Client API
Generated public TypeScript reference for @relkit/client.
Common APIs
For configuration and examples, read generated clients, streaming, jobs.
For a complete workflow, follow connect react.
Frontend usage
Connect a React frontend shows the client side of this capability.
Public imports
@relkit/client— 11 exports@relkit/client/server— 1 exports@relkit/client/server/tanstack-query— 4 exports@relkit/client/tanstack-query— 2 exports@relkit/client/react— 117 exports@relkit/client/jobs— 60 exports@relkit/client/build/next— 1 exports@relkit/client/build/vite— 2 exports
All exported APIs
Names link to their complete contracts. Re-exports share their original contract; legacy exports keep their separate identity. Examples link to the API’s inline sample, a maintained repository usage, or the shared module walkthrough.
| API | Kind | Import from | Example |
|---|---|---|---|
| AgentBase | Type | @relkit/client/react |
Source example |
| AgentContent | Type | @relkit/client/react |
Module example |
| AgentMessage | Type | @relkit/client/react |
Module example |
| AgentNestedExecution | Type | @relkit/client/react |
Module example |
| AgentOutput | Type | @relkit/client/react |
Module example |
| AgentProgress | Type | @relkit/client/react |
Module example |
| AgentRegistry | Type | @relkit/client/react |
Module example |
| AgentResumeOptions | Type | @relkit/client/react |
Module example |
| AgentRunOptions | Type | @relkit/client/react |
Module example |
| AgentSelector | Type | @relkit/client/react |
Module example |
| AgentStopOptions | Type | @relkit/client/react |
Module example |
| AgentThreadOptions | Type | @relkit/client/react |
Module example |
| AgentTimelineItem | Type | @relkit/client/react |
Module example |
| AgentToolCall | Type | @relkit/client/react |
Module example |
| ChannelHandlers | Type | @relkit/client/react |
Module example |
| ChannelRegistry | Type | @relkit/client/react |
Module example |
| ChannelSelector | Type | @relkit/client/react |
Module example |
| clearPendingOperations | Value | @relkit/client/react |
Source example |
| ClientAgentContract | Type | @relkit/client/react |
Source example |
| ClientAgentDynamic | Type | @relkit/client/react |
Source example |
| ClientChannelContract | Type | @relkit/client/react |
Source example |
| ClientHeaders | Type | @relkit/client |
Module example |
| ClientHeadersInit | Type | @relkit/client |
Module example |
| ClientRegistry | Type | @relkit/client/react |
Module example |
| ClientRouteContract | Type | @relkit/client/react |
Source example |
| ClientSelector | Type | @relkit/client/react |
Module example |
| ClientStreamContract | Type | @relkit/client/react |
Source example |
| ContractFor | Type | @relkit/client/react |
Module example |
| CountPresence | Type | @relkit/client/react |
API example |
| createAutoClient | Value | @relkit/client |
Source example |
| CreateAutoClientOptions | Type | @relkit/client |
Module example |
| createClient | Value | @relkit/client |
API example |
| CreateClientOptions | Type | @relkit/client |
Source example |
| createRelkitServerContext | Value | @relkit/client/server/tanstack-query |
Source example |
| CreateRelkitServerContextOptions | Type | @relkit/client/server/tanstack-query |
Module example |
| createServerClient | Value | @relkit/client/server |
Source example |
| createTanstackQueryUtils | Value | @relkit/client/tanstack-query |
Source example |
| createWebSocketClient | Value | @relkit/client |
Source example |
| CreateWebSocketClientOptions | Type | @relkit/client |
Source example |
| DefaultContract | Type | @relkit/client |
Module example |
| DefaultContractRegistry | Type | @relkit/client |
Module example |
| digestPendingRequest | Value | @relkit/client/react |
Source example |
| ErrorFor | Type | @relkit/client/react |
Module example |
| FiniteSelector | Type | @relkit/client/react |
Module example |
| forgetPending | Value | @relkit/client/react |
Module example |
| InputFor | Type | @relkit/client/react |
Module example |
| isJobUnknownOutcome | Value | @relkit/client/react |
Source example |
| ItemFor | Type | @relkit/client/react |
Module example |
| JobCancelInput | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobCancelInputFor | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobCancelName | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobCancelOutputFor | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobClientField | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobClientOperation | Type | @relkit/client/jobs |
Module example |
| JobContract | Type | @relkit/client/react, @relkit/client/jobs |
Source example |
| JobErrorEnvelope | Type | @relkit/client/jobs |
Module example |
| JobFailureFor | Type | @relkit/client/jobs |
Module example |
| JobFor | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobGetInput | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobListInput | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobListQuery | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobMutationOptions | Type | @relkit/client/react |
Module example |
| JobProcedureContract | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobProcedureSelector | Type | @relkit/client/react, @relkit/client/jobs |
Source example |
| JobRegistry | Type | @relkit/client/react, @relkit/client/jobs |
Source example |
| JobRetryInput | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobRetryInputFor | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobRetryName | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobRetryOutputFor | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobRunFor | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobRunSelector | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobRunStatus | Type | @relkit/client/jobs |
Module example |
| JobRunWatchController | Value | @relkit/client/jobs |
Module example |
| JobSelector | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobSnapshotFor | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobStreamGapError | Value | @relkit/client/jobs |
Source example |
| JobStreamInput | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobStreamOptions | Type | @relkit/client/jobs |
Module example |
| JobStreamOverflowError | Value | @relkit/client/jobs |
Source example |
| JobStreamProcedureContract | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobTriggerInput | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobTriggerInputFor | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobTriggerName | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobTriggerOptions | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobTriggerOutputFor | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobTriggerSelector | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| jobUnknownOutcome | Value | @relkit/client/react |
Source example |
| JobWatchAbortedError | Value | @relkit/client/jobs |
Source example |
| JobWatchController | Type | @relkit/client/jobs |
Module example |
| JobWatchDisposedError | Value | @relkit/client/jobs |
Module example |
| JobWatchFrame | Type | @relkit/client/jobs |
Module example |
| JobWatchFrameFor | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobWatchInput | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobWatchListener | Type | @relkit/client/jobs |
Module example |
| JobWatchName | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| JobWatchOptions | Type | @relkit/client/jobs |
Source example |
| JobWatchReadTimeoutError | Value | @relkit/client/jobs |
Source example |
| JobWatchState | Type | @relkit/client/jobs |
Module example |
| JobWatchUnavailableError | Value | @relkit/client/jobs |
Module example |
| matchesPendingRequest | Value | @relkit/client/react |
Source example |
| MemberPresence | Type | @relkit/client/react |
API example |
| MutationSelector | Type | @relkit/client/react |
Module example |
| NamedStreamFrame | Type | @relkit/client/jobs |
Module example |
| ORPCError | Value | @relkit/client |
Source example |
| OutputFor | Type | @relkit/client/react |
Module example |
| PendingCapacityError | Value | @relkit/client/react |
Source example |
| pendingOperations | Value | @relkit/client/react |
Source example |
| PendingRecoveryUnavailableError | Value | @relkit/client/react |
Module example |
| PendingRememberOptions | Type | @relkit/client/react |
Module example |
| pendingRequest | Value | @relkit/client/react |
Source example |
| PendingRequestMismatchError | Value | @relkit/client/react |
Module example |
| pendingScopeKey | Value | @relkit/client/react |
Module example |
| QuerySelector | Type | @relkit/client/react |
Module example |
| reconcileAgentRun | Value | @relkit/client/react |
Source example |
| relkit | Value | @relkit/client/build/vite |
Source example |
| RelkitClientProvider | Value | @relkit/client/react |
Source example |
| RelkitClientProviderProps | Type | @relkit/client/react |
Module example |
| RelkitClientRuntime | Type | @relkit/client/react |
Module example |
| RelkitHydrationState | Type | @relkit/client/react |
Module example |
| relkitJobKey | Value | @relkit/client/react |
Module example |
| RelkitJobKeyOptions | Type | @relkit/client/react |
Module example |
| relkitKey | Value | @relkit/client/react |
Source example |
| RelkitKeyScope | Type | @relkit/client/react |
Module example |
| RelkitServerContext | Type | @relkit/client/server/tanstack-query |
Module example |
| RelkitServerHydrationState | Type | @relkit/client/server/tanstack-query |
Module example |
| RelkitVitePlugin | Type | @relkit/client/build/vite |
Module example |
| RelkitWriteError | Value | @relkit/client/react |
Module example |
| rememberJobPending | Value | @relkit/client/react |
Source example |
| rememberPending | Value | @relkit/client/react |
Source example |
| RunCancellationReceipt | Type | @relkit/client/jobs |
Module example |
| RunHandle | Type | @relkit/client/jobs |
Source example |
| RunListQuery | Type | @relkit/client/jobs |
Module example |
| RunPage | Type | @relkit/client/jobs |
Source example |
| RunRetryReceipt | Type | @relkit/client/jobs |
Module example |
| RunSnapshot | Type | @relkit/client/jobs |
Source example |
| RunWatchFrame | Type | @relkit/client/jobs |
Source example |
| SelectedJobField | Type | @relkit/client/react, @relkit/client/jobs |
Module example |
| StreamSelector | Type | @relkit/client/react |
Module example |
| StreamState | Type | @relkit/client/react |
Module example |
| TanstackQueryOperationContext | Type | @relkit/client/tanstack-query |
Module example |
| updatePending | Value | @relkit/client/react |
Source example |
| useAgent | Value | @relkit/client/react |
Source example |
| UseAgentResult | Type | @relkit/client/react |
Module example |
| useChannel | Value | @relkit/client/react |
Source example |
| UseChannelOptions | Type | @relkit/client/react |
Module example |
| UseChannelResult | Type | @relkit/client/react |
Module example |
| useInfiniteRoute | Value | @relkit/client/react |
Module example |
| useJobCancel | Value | @relkit/client/react |
Source example |
| useJobRetry | Value | @relkit/client/react |
Source example |
| useJobRun | Value | @relkit/client/react |
Source example |
| UseJobRunOptions | Type | @relkit/client/react |
Module example |
| UseJobRunResult | Type | @relkit/client/react |
Module example |
| useJobTrigger | Value | @relkit/client/react |
Source example |
| useRealtime | Value | @relkit/client/react |
Module example |
| UseRealtimeResult | Type | @relkit/client/react |
Module example |
| useRelkitClient | Value | @relkit/client/react |
Source example |
| useRoute | Value | @relkit/client/react |
Source example |
| useRouteMutation | Value | @relkit/client/react |
Source example |
| useRouteUtils | Value | @relkit/client/react |
Module example |
| useStream | Value | @relkit/client/react |
Source example |
| UseStreamResult | Type | @relkit/client/react |
Module example |
| useSuspenseRoute | Value | @relkit/client/react |
Module example |
| watchJobRun | Value | @relkit/client/jobs |
Source example |
| watchJobStream | Value | @relkit/client/jobs |
Source example |
| withRelkit | Value | @relkit/client/build/next |
Source example |
manifest.ts
readPublicFingerprint
Reads the generated manifest fingerprint and rejects malformed generated output.
Signature
declare const readPublicFingerprint: (root?: string) => string;
next.ts
withRelkit
Adds the generated public fingerprint and linked-workspace root to Next configuration.
Signature
declare const withRelkit: (config?: NextConfig, options?: { readonly root?: string }) => NextConfig;
next.types.ts
The Next configuration shape accepted and returned by the client build adapter.
NextConfig (type alias)
The Next configuration shape accepted and returned by the client build adapter.
Signature
type NextConfig = Readonly<Record<string, unknown>> & {
readonly env?: Readonly<Record<string, string | undefined>>;
readonly turbopack?: Readonly<Record<string, unknown>> & { readonly root?: string };
};
vite.ts
RelkitVitePlugin
Signature
declare const RelkitVitePlugin: RelkitVitePlugin;
relkit
Creates the Vite adapter that defines the generated client fingerprint.
Signature
declare const relkit: (options?: { readonly root?: string }) => RelkitVitePlugin;
vite.types.ts
The minimal Vite plugin contract defining the generated client fingerprint.
RelkitVitePlugin (interface)
The minimal Vite plugin contract defining the generated client fingerprint.
Signature
export interface RelkitVitePlugin {
readonly name: "relkit";
config(): {
readonly define: Readonly<Record<string, string>>;
};
}
client-owner.ts
acquireClientOwner
Acquires one synchronous Layer context and an independently closable fiber scope.
Signature
declare const acquireClientOwner: <Service, Shape>(
layer: Layer.Layer<Service>,
key: Context.Key<Service, Shape>,
) => ClientOwner<Shape>;
client-owner.types.ts
ClientOwner (interface)
Once-acquired domain context with independent asynchronous lifetime ownership.
Signature
export interface ClientOwner<Shape> {
/** Stable service identity; invoking it does not acquire another Layer. */
readonly service: Shape;
/** Runs one child owned by this context and joins its scoped finalizers.
* @typeParam A - Successful operation result.
* @typeParam E - Original typed failure, preserved at the Promise boundary.
* @param effect - Lazy resource-owning service workflow.
* @returns The original result or rejection after child cleanup. */
readonly run: <A, E>(effect: Effect.Effect<A, E>) => Promise<A>;
/** Interrupts active children and joins acquired-resource finalizers once.
* @returns The same settlement Promise on concurrent or repeated closure. */
readonly close: () => Promise<void>;
}
client-runtime.ts
runClient
Runs fully provided client work at a Promise adapter, retaining original failures.
Signature
declare const runClient: <A, E>(effect: Effect.Effect<A, E>, signal?: AbortSignal) => Promise<A>;
runClientSync
Runs a fully provided synchronous state decision at its compatibility edge.
Signature
declare const runClientSync: <A, E>(effect: Effect.Effect<A, E>) => A;
index.ts
Exposes transport clients and the generated contract augmentation authority. Install @relkit/client for HTTP/WebSocket clients; React and TanStack peers are needed only by their explicit integration entrypoints.
ClientHeaders
Signature
declare const ClientHeaders: ClientHeaders;
ClientHeadersInit
Signature
declare const ClientHeadersInit: ClientHeadersInit;
CreateAutoClientOptions
Signature
declare const CreateAutoClientOptions: CreateAutoClientOptions;
CreateClientOptions
Signature
declare const CreateClientOptions: CreateClientOptions;
CreateWebSocketClientOptions
Signature
declare const CreateWebSocketClientOptions: CreateWebSocketClientOptions;
DefaultContract (type alias)
Contract inferred from the preserved public registry augmentation.
Signature
type DefaultContract = DefaultContractRegistry extends {
readonly contract: infer Contract extends RouterContract;
}
? Contract
: RouterContract;
DefaultContractRegistry (interface)
Original augmentation authority; generated applications extend this exact module.
Signature
export interface DefaultContractRegistry {}
ORPCError
Signature
declare const ORPCError: typeof ORPCError;
createAutoClient
Signature
declare const createAutoClient: <Contract extends RouterContract = RouterContract>(
options: CreateAutoClientOptions,
) => RouterContractClient<Contract>;
createClient
Signature
declare const createClient: <Contract extends RouterContract = RouterContract>(
options: CreateClientOptions,
) => RouterContractClient<Contract>;
createWebSocketClient
Signature
declare const createWebSocketClient: <Contract extends RouterContract = RouterContract>(
options: CreateWebSocketClientOptions,
) => RouterContractClient<Contract>;
index.types.ts
Native header inputs accepted without copying mutable Headers at construction.
ClientHeaders (type alias)
Static headers or a provider evaluated for each future request.
Signature
type ClientHeaders = ClientHeadersInit | (() => ClientHeadersInit | Promise<ClientHeadersInit>);
ClientHeadersInit (type alias)
Native header inputs accepted without copying mutable Headers at construction.
Signature
type ClientHeadersInit =
Headers | Readonly<Record<string, string>> | readonly (readonly [string, string])[];
CreateAutoClientOptions (interface)
Combined transport options; fallback applies only to WebSocket establishment failure.
Signature
export interface CreateAutoClientOptions
extends CreateClientOptions, CreateWebSocketClientOptions {}
CreateClientOptions (interface)
HTTP client configuration preserving browser credentials and caller transport overrides.
Signature
export interface CreateClientOptions {
/** Application HTTP origin and optional base path. */
readonly baseUrl: string;
/** Request-time headers, including asynchronous providers. */
readonly headers?: ClientHeaders;
/** Browser fetch credentials policy; the live adapter supplies the existing default. */
readonly credentials?: RequestInit["credentials"];
/** Borrowed fetch implementation used for all HTTP requests. */
readonly fetch?: typeof globalThis.fetch;
}
CreateWebSocketClientOptions (interface)
WebSocket configuration whose establishment timeout leaves accepted streams independent.
Signature
export interface CreateWebSocketClientOptions {
/** Application origin converted to its corresponding WebSocket protocol. */
readonly baseUrl: string;
/** Maximum time allowed for initial connection establishment. */
readonly establishmentTimeoutMs?: number;
/** Headers retained with the existing WebSocket transport contract. */
readonly headers?: ClientHeaders;
/** Borrowed WebSocket constructor, or the browser implementation when omitted. */
readonly websocket?: typeof WebSocket;
}
content.service.ts
JobContent (class)
Named job content lifetime and bounded continuity contract.
Signature
declare class JobContent
JobContentLive
Provides named-content acquisition with scoped native pulls and bounded continuity.
See
- packages/client/tests/compatibility/jobs-watch.test.ts for continuity assertions.
Signature
declare const JobContentLive: Layer.Layer<JobContent, never, never>;
content.types.ts
JobContentService (interface)
Named stream acquisition, continuity and memory-bound ownership.
Signature
export interface JobContentService {
/** Acquires named content and transfers native cleanup to the returned iterator.
* @param client - Borrowed generated job transport.
* @param job - Declared job key.
* @param options - Existing stream identity, cursor, cancellation and bounds.
* @returns Lazy acquisition of bounded frames or the original native failure. */
readonly open: (
client: unknown,
job: string,
options: JobStreamOptions,
) => Effect.Effect<AsyncIterable<NamedStreamFrame<JsonValue>>, unknown>;
}
contracts.types.ts
JobCancelInput (type alias)
Cancellation request with caller-owned operation identity.
Signature
type JobCancelInput = {
readonly runId: string;
readonly operationId: OperationId | string;
readonly reason?: string;
readonly expectedIdentity?: ExpectedClientIdentity;
};
JobClientField (type alias)
Client-visible run projection fields.
Signature
type JobClientField = "status" | "input" | "progress" | "output" | "error";
JobGetInput (type alias)
Authoritative run lookup and expected application identity.
Signature
type JobGetInput = {
readonly runId: string;
readonly expectedIdentity?: ExpectedClientIdentity;
};
JobListInput (type alias)
Job-specific listing filters and expected application identity.
Signature
type JobListInput = {
readonly query?: JobListQuery;
readonly expectedIdentity?: ExpectedClientIdentity;
};
JobListQuery (type alias)
Filters accepted by a generated job-specific list; ownership is server-derived.
Signature
type JobListQuery = Omit<RunListQuery, "jobId" | "service">;
JobProcedureContract (interface)
Generated finite procedure shape preserving input, output and failure inference.
Signature
export interface JobProcedureContract<Input, Output, Failure = Error> {
readonly input: Input;
readonly output: Output;
readonly error: Failure;
readonly operation: "query" | "mutation";
readonly stream: false;
}
JobRetryInput (type alias)
Retry request with caller-owned operation identity.
Signature
type JobRetryInput = {
readonly runId: string;
readonly operationId: OperationId | string;
readonly expectedIdentity?: ExpectedClientIdentity;
};
JobStreamInput (type alias)
Named content observation cursor and expected application identity.
Signature
type JobStreamInput<StreamName extends string = string> = {
readonly runId: string;
readonly name: StreamName;
readonly after?: string;
readonly expectedIdentity?: ExpectedClientIdentity;
};
JobStreamProcedureContract (interface)
Generated stream procedure shape preserving item and failure inference.
Signature
export interface JobStreamProcedureContract<Input, Item, Failure = Error> {
readonly input: Input;
readonly output: AsyncIterable<Item>;
readonly item: Item;
readonly error: Failure;
readonly operation: "query" | "mutation";
readonly stream: true;
}
JobTriggerInput (type alias)
Job trigger request and expected application identity.
Signature
type JobTriggerInput<Input> = {
readonly input: Input;
readonly options?: JobTriggerOptions;
readonly expectedIdentity?: ExpectedClientIdentity;
};
JobTriggerOptions (interface)
Browser-safe options accepted by a generated job trigger.
Signature
export interface JobTriggerOptions {
readonly operationId?: OperationId | string;
readonly idempotencyKey?: string;
readonly delay?: string;
readonly at?: string;
readonly tags?: readonly string[];
readonly correlationId?: string;
}
JobWatchInput (type alias)
Run observation cursor and expected application identity.
Signature
type JobWatchInput = {
readonly runId: string;
readonly after?: string;
readonly expectedIdentity?: ExpectedClientIdentity;
};
controller-state.ts
stateFromFeedEvent
Projects observation status or frames into the existing external-store state.
Signature
declare const stateFromFeedEvent: <Run>(
current: JobWatchState<Run>,
event: FeedEvent<Run>,
source: JobWatchOptions["source"],
) => JobWatchState<Run>;
controller-support.ts
freeze
Deep-freezes external-store state without cloning its identity.
Signature
declare const freeze: <T>(value: T) => T;
notify
Isolates one external-store callback from observation ownership.
Signature
declare const notify: <Run>(listener: JobWatchListener<Run>, state: JobWatchState<Run>) => void;
reconnectAfterTeardown
Waits for interrupted setup and cleanup before admitting the next connection.
Signature
declare const reconnectAfterTeardown: (
previous: Promise<void> | undefined,
teardown: Promise<void> | undefined,
start: () => Promise<void>,
) => Promise<void>;
resumedOptions
Adds the retained snapshot cursor to the existing observation options.
Signature
declare const resumedOptions: <Run>(
options: JobWatchOptions,
state: JobWatchState<Run>,
) => JobWatchOptions;
controller.service.ts
JobControllers (class)
Creates passive external-store views over scoped physical observation services.
Signature
declare class JobControllers
JobControllersLive
Acquires the controller factory once without opening native requests.
Example
import { Layer, ManagedRuntime } from "effect";
import { runExecutionSync } from "@relkit/contracts/operation";
import { JobControllers, JobControllersLive } from "./controller.service.js";
import { JobFeedRegistryLive } from "./feed-registry.service.js";
export async function observeJob(client: unknown): Promise<void> {
const owner = ManagedRuntime.make(JobControllersLive.pipe(Layer.provide(JobFeedRegistryLive)));
try {
const factory = runExecutionSync(owner, JobControllers);
const view = factory.view(client, "job", { runId: "run" });
try {
await view.connect();
} finally {
await view.dispose();
}
} finally {
await owner.dispose();
}
}
Signature
declare const JobControllersLive: Layer.Layer<JobControllers, never, JobFeedRegistry>;
controller.service.types.ts
JobControllerFactory (interface)
Once-acquired state factory sharing only complete-key physical observations.
Signature
export interface JobControllerFactory {
readonly view: (client: unknown, name: string, options: JobWatchOptions) => JobControllerView;
}
JobControllerView (interface)
Passive external-store state; asynchronous native work belongs to the feed service.
Signature
export interface JobControllerView {
readonly snapshot: () => JobWatchState<unknown>;
readonly subscribe: (listener: JobWatchListener<unknown>) => () => void;
readonly assertLive: () => void;
readonly isDisconnected: () => boolean;
readonly connect: () => Promise<void>;
readonly disconnect: () => Promise<void>;
readonly dispose: () => Promise<void>;
readonly refetch: () => Promise<void>;
}
controller.ts
JobRunWatchController (class)
Passive synchronous external-store facade over scoped physical feed services.
Signature
declare class JobRunWatchController<Run> {
constructor(client: unknown, name: string, options: JobWatchOptions);
}
getSnapshot (method)
Signature
declare const getSnapshot: () => JobWatchState<Run>;
subscribe (method)
Borrows controller state publication without acquiring native work.
Signature
declare const subscribe: (listener: JobWatchListener<Run>) => () => void;
connect (method)
Signature
declare const connect: () => Promise<void>;
disconnect (method)
Signature
declare const disconnect: () => Promise<void>;
dispose (method)
Signature
declare const dispose: () => Promise<void>;
refetch (method)
Signature
declare const refetch: () => Promise<void>;
watchJobRun
Creates an idle, independently disposable external-store watch owner.
Signature
declare const watchJobRun: <Name extends string>(
client: unknown,
name: Name,
options: JobWatchOptions,
) => JobWatchController<JobRunFor<Name>>;
feed-registry.service.ts
JobFeedRegistry (class)
Reference-counted native observation ownership, independent of controller state.
Signature
declare class JobFeedRegistry
JobFeedRegistryLive
Provides reference-counted feed sharing within complete security/protocol keys.
Example
import { Effect, ManagedRuntime } from "effect";
import { runExecutionSync } from "@relkit/contracts/operation";
import { JobFeedRegistry, JobFeedRegistryLive } from "./feed-registry.service.js";
export async function borrowJobFeed(client: unknown): Promise<void> {
const owner = ManagedRuntime.make(JobFeedRegistryLive);
try {
const registry = runExecutionSync(owner, JobFeedRegistry);
const borrow = await owner.runPromise(registry.borrow(client, "job", { runId: "run" }));
try {
await borrow.feed.addLease("view", () => undefined);
} finally {
await Effect.runPromise(borrow.release);
}
} finally {
await owner.dispose();
}
}
See
- tests/jobs/registry.test.ts for checked scoped native cleanup.
Signature
declare const JobFeedRegistryLive: Layer.Layer<JobFeedRegistry, never, never>;
feed-registry.types.ts
JobFeedRegistryService (interface)
Reference-counted observation registry, with complete request authority.
Signature
export interface JobFeedRegistryService {
/** Registers a passive external-store view without another Layer acquisition. */
readonly borrowView: (client: unknown, name: string, options: JobWatchOptions) => WatchFeedBorrow;
readonly borrow: (
client: unknown,
name: string,
options: JobWatchOptions,
) => Effect.Effect<WatchFeedBorrow>;
}
WatchFeedBorrow (interface)
One independently closable reference to a shared feed.
Signature
export interface WatchFeedBorrow {
readonly feed: SharedWatchFeed<unknown>;
/** Excludes a final retiring group before native callbacks can reconnect. */
readonly retire: Effect.Effect<void>;
readonly release: Effect.Effect<void>;
/** Passive view retirement; this boundary never awaits native work. */
readonly retireView: () => void;
/** Joins the shared native borrow after passive view retirement. */
readonly releaseView: () => Promise<void>;
}
WatchFeedGroup (interface)
One native RcMap borrow shared by independently retired passive view leases.
Signature
export interface WatchFeedGroup {
readonly feed: SharedWatchFeed<unknown>;
readonly scope: Scope.Closeable;
readonly references: Ref.Ref<number>;
}
index.ts
“./contracts.types.js” (namespace export)
Re-exports all named exports from the “./contracts.types.js” module.
Signature
export * from "./contracts.types.js";
JobCancelInputFor
Signature
declare const JobCancelInputFor: JobCancelInputFor<Name>;
JobCancelName
Signature
declare const JobCancelName: never;
JobCancelOutputFor
Signature
declare const JobCancelOutputFor: JobCancelOutputFor<Name>;
JobClientOperation
Signature
declare const JobClientOperation: JobClientOperation;
JobContract
Signature
declare const JobContract: JobContract<
Name,
JobId,
Input,
Output,
Failure,
Progress,
Streams,
Operations,
Fields
>;
JobErrorEnvelope
Signature
declare const JobErrorEnvelope: JobErrorEnvelope;
JobFailureFor
Signature
declare const JobFailureFor: JobFailureFor<Name>;
JobFor
Signature
declare const JobFor: JobFor<Name>;
JobProcedureSelector
Signature
declare const JobProcedureSelector: JobProcedureSelector<Name>;
JobRegistry
Signature
declare const JobRegistry: JobRegistry;
JobRetryInputFor
Signature
declare const JobRetryInputFor: JobRetryInputFor<Name>;
JobRetryName
Signature
declare const JobRetryName: never;
JobRetryOutputFor
Signature
declare const JobRetryOutputFor: JobRetryOutputFor<Name>;
JobRunFor
Signature
declare const JobRunFor: JobRunFor<Name>;
JobRunSelector
Signature
declare const JobRunSelector: JobRunSelector<Name>;
JobRunStatus
Signature
declare const JobRunStatus: JobRunStatus;
JobRunWatchController
Signature
declare const JobRunWatchController: typeof JobRunWatchController;
JobSelector
Signature
declare const JobSelector: never;
JobSnapshotFor
Signature
declare const JobSnapshotFor: JobSnapshotFor<Input, Output, Progress, Failure, Fields>;
JobStreamGapError
Signature
declare const JobStreamGapError: typeof JobStreamGapError;
JobStreamOptions
Signature
declare const JobStreamOptions: JobStreamOptions;
JobStreamOverflowError
Signature
declare const JobStreamOverflowError: typeof JobStreamOverflowError;
JobTriggerInputFor
Signature
declare const JobTriggerInputFor: JobTriggerInputFor<Name>;
JobTriggerName
Signature
declare const JobTriggerName: never;
JobTriggerOutputFor
Signature
declare const JobTriggerOutputFor: JobTriggerOutputFor<Name>;
JobTriggerSelector
Signature
declare const JobTriggerSelector: JobTriggerSelector<Name>;
JobWatchAbortedError
Signature
declare const JobWatchAbortedError: typeof JobWatchAbortedError;
JobWatchController
Signature
declare const JobWatchController: JobWatchController<Run>;
JobWatchDisposedError
Signature
declare const JobWatchDisposedError: typeof JobWatchDisposedError;
JobWatchFrame
Signature
declare const JobWatchFrame: JobWatchFrame<Run>;
JobWatchFrameFor
Signature
declare const JobWatchFrameFor: JobWatchFrameFor<Name>;
JobWatchListener
Signature
declare const JobWatchListener: JobWatchListener<Run>;
JobWatchName
Signature
declare const JobWatchName: never;
JobWatchOptions
Signature
declare const JobWatchOptions: JobWatchOptions;
JobWatchReadTimeoutError
Signature
declare const JobWatchReadTimeoutError: typeof JobWatchReadTimeoutError;
JobWatchState
Signature
declare const JobWatchState: JobWatchState<Run>;
JobWatchUnavailableError
Signature
declare const JobWatchUnavailableError: typeof JobWatchUnavailableError;
NamedStreamFrame
Signature
declare const NamedStreamFrame: NamedStreamFrame<Item>;
RunCancellationReceipt
Signature
declare const RunCancellationReceipt: RunCancellationReceipt;
RunHandle
Signature
declare const RunHandle: RunHandle;
RunListQuery
Signature
declare const RunListQuery: RunListQuery;
RunPage
Signature
declare const RunPage: RunPage<Run>;
RunRetryReceipt
Signature
declare const RunRetryReceipt: RunRetryReceipt;
RunSnapshot
Signature
declare const RunSnapshot: RunSnapshot<Input, Output, Progress, Failure>;
RunWatchFrame
Signature
declare const RunWatchFrame: RunWatchFrame<Run>;
SelectedJobField
Signature
declare const SelectedJobField: SelectedJobField<Fields, Field>;
watchJobRun
Signature
declare const watchJobRun: <Name extends string>(
client: unknown,
name: Name,
options: JobWatchOptions,
) => JobWatchController<JobRunFor<Name>>;
watchJobStream
Signature
declare const watchJobStream: <Item extends JsonValue = JsonValue>(
client: unknown,
job: string,
options: JobStreamOptions,
) => Promise<AsyncIterable<NamedStreamFrame<Item>>>;
job-registry-derived.ts
“./job-registry-derived.types.js” (namespace export)
Re-exports all named exports from the “./job-registry-derived.types.js” module.
Signature
export * from "./job-registry-derived.types.js";
job-registry-derived.types.ts
JobCancelInputFor (type alias)
Infers the exact cancellation request or its dynamic fallback.
Signature
type JobCancelInputFor<Name extends string> = Name extends JobSelector
? JobFor<Name> extends { readonly runs: infer Runs }
? Runs extends { readonly cancel: infer Cancel }
? Cancel extends { readonly input: infer Input }
? Input
: never
: never
: never
: JobCancelInput;
JobCancelName (type alias)
Names of jobs exposing cancellation receipts.
Signature
type JobCancelName = JobRunName<"cancel">;
JobCancelOutputFor (type alias)
Infers the declared cancellation receipt or its standard fallback.
Signature
type JobCancelOutputFor<Name extends string> = Name extends JobSelector
? JobFor<Name> extends { readonly runs: infer Runs }
? Runs extends { readonly cancel: infer Cancel }
? Cancel extends { readonly output: infer Output }
? Output
: RunCancellationReceipt
: RunCancellationReceipt
: RunCancellationReceipt
: RunCancellationReceipt;
JobFailureFor (type alias)
Infers declared job failures while preserving the standard error envelope fallback.
Signature
type JobFailureFor<Name extends string> = Name extends JobSelector
? JobFor<Name> extends { readonly trigger: infer Trigger }
? Trigger extends { readonly error: infer Failure }
? Failure
: JobErrorEnvelope
: JobErrorEnvelope
: JobErrorEnvelope;
JobRetryInputFor (type alias)
Infers the exact retry request or its dynamic fallback.
Signature
type JobRetryInputFor<Name extends string> = Name extends JobSelector
? JobFor<Name> extends { readonly runs: infer Runs }
? Runs extends { readonly retry: infer Retry }
? Retry extends { readonly input: infer Input }
? Input
: never
: never
: never
: JobRetryInput;
JobRetryName (type alias)
Names of jobs exposing retry receipts.
Signature
type JobRetryName = JobRunName<"retry">;
JobRetryOutputFor (type alias)
Infers the declared retry receipt or its standard fallback.
Signature
type JobRetryOutputFor<Name extends string> = Name extends JobSelector
? JobFor<Name> extends { readonly runs: infer Runs }
? Runs extends { readonly retry: infer Retry }
? Retry extends { readonly output: infer Output }
? Output
: RunRetryReceipt
: RunRetryReceipt
: RunRetryReceipt
: RunRetryReceipt;
JobRunFor (type alias)
Infers authoritative run payloads from get or watch contracts.
Signature
type JobRunFor<Name extends string> = Name extends JobSelector
? JobFor<Name> extends { readonly runs: infer Runs }
? Runs extends { readonly get: infer Get }
? Get extends { readonly output: infer Output }
? Output
: RunSnapshot
: Runs extends { readonly watch: infer Watch }
? Watch extends { readonly output: AsyncIterable<infer Frame> }
? Frame extends { readonly run: infer Run }
? Run
: RunSnapshot
: RunSnapshot
: RunSnapshot
: RunSnapshot
: RunSnapshot;
JobRunName (type alias)
Names of jobs exposing the selected run operation.
Signature
type JobRunName<Operation extends JobRunOperation> = {
[Name in JobSelector]: JobFor<Name> extends { readonly runs: infer Runs }
? Operation extends keyof Runs
? Name
: never
: never;
}[JobSelector];
JobTriggerInputFor (type alias)
Infers the declared trigger input while preserving the dynamic fallback.
Signature
type JobTriggerInputFor<Name extends string> = Name extends JobSelector
? JobFor<Name> extends { readonly trigger: infer Trigger }
? Trigger extends { readonly input: infer Input }
? Input
: never
: never
: unknown;
JobTriggerName (type alias)
Names of jobs exposing a declared trigger procedure.
Signature
type JobTriggerName = {
[Name in JobSelector]: JobFor<Name> extends { readonly trigger: unknown } ? Name : never;
}[JobSelector];
JobTriggerOutputFor (type alias)
Infers the declared trigger receipt while preserving RunHandle fallback.
Signature
type JobTriggerOutputFor<Name extends string> = Name extends JobSelector
? JobFor<Name> extends { readonly trigger: infer Trigger }
? Trigger extends { readonly output: infer Output }
? Output
: never
: never
: RunHandle;
JobWatchFrameFor (type alias)
Wraps the inferred authoritative run payload in its native watch frame.
Signature
type JobWatchFrameFor<Name extends string> = RunWatchFrame<JobRunFor<Name>>;
JobWatchName (type alias)
Names of jobs exposing native run observation.
Signature
type JobWatchName = JobRunName<"watch">;
job-registry-types.ts
Augmentable registry of application-declared job contracts.
“./job-registry.types.js” (namespace export)
Re-exports all named exports from the “./job-registry.types.js” module.
Signature
export * from "./job-registry.types.js";
JobRegistry (interface)
Augmentable registry of application-declared job contracts.
Signature
export interface JobRegistry {}
job-registry.types.ts
JobContract (type alias)
Generated job declaration retaining operation availability and selective field inference.
Signature
type JobContract<
Name extends string = string,
JobId extends string = string,
Input = unknown,
Output = unknown,
Failure = JobErrorEnvelope,
Progress = unknown,
Streams extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,
Operations extends readonly JobClientOperation[] = readonly JobClientOperation[],
Fields extends readonly JobClientField[] = readonly [],
> = {
readonly name: Name;
readonly jobId: JobId;
} & TriggerMember<Input, Failure, Operations> &
RunMembers<Input, Output, Progress, Failure, Streams, Operations, Fields>;
JobFor (type alias)
Looks up one declared job contract without widening its members.
Signature
type JobFor<Name extends JobSelector> = JobRegistry[Name];
JobProcedureSelector (type alias)
Union of exact procedure selectors exposed by one declared job.
Signature
type JobProcedureSelector<Name extends JobSelector = JobSelector> =
JobTriggerSelector<Name> | JobRunSelector<Name>;
JobRunSelector (type alias)
Produces exact selectors for the declared run operations.
Signature
type JobRunSelector<Name extends JobSelector> =
JobFor<Name> extends { readonly runs: infer Runs }
? {
[
Operation in "get" | "list" | "watch" | "stream" | "cancel" | "retry"
]: Runs extends Record<Operation, unknown>
? Runs[Operation] extends never
? never
: `${Name}.runs.${Operation}`
: never;
}["get" | "list" | "watch" | "stream" | "cancel" | "retry"]
: never;
JobSelector (type alias)
String keys of the application-declared job registry.
Signature
type JobSelector = Extract<keyof JobRegistry, string>;
JobSnapshotFor (type alias)
Projects run payload fields according to the declared client visibility contract.
Signature
type JobSnapshotFor<
Input,
Output,
Progress,
Failure,
Fields extends readonly JobClientField[],
> = RunSnapshot<
SelectedJobField<Fields, "input"> extends true ? Input : never,
SelectedJobField<Fields, "output"> extends true ? Output : never,
SelectedJobField<Fields, "progress"> extends true ? Progress : never,
SelectedJobField<Fields, "error"> extends true ? Failure : never
>;
JobTriggerSelector (type alias)
Produces the exact trigger selector only for trigger-capable jobs.
Signature
type JobTriggerSelector<Name extends JobSelector> =
JobFor<Name> extends { readonly trigger: unknown } ? `${Name}.trigger` : never;
SelectedJobField (type alias)
Tests whether a projection field belongs to the declared visible field set.
Signature
type SelectedJobField<
Fields extends readonly JobClientField[],
Field extends JobClientField,
> = Field extends Fields[number] ? true : false;
observation.service.ts
JobObservation (class)
Cohesive native/polling observation workflow, replaceable at the feed owner.
Signature
declare class JobObservation
JobObservationLive
Acquires the live observation workflow; native dependencies are supplied by each feed.
See
- tests/jobs/quality.test.ts for checked observation, recovery and interruption cases.
Signature
declare const JobObservationLive: Layer.Layer<JobObservation, never, never>;
observation.types.ts
JobObservationService (interface)
Live/test contract for one independently cancellable shared observation lifetime.
Signature
export interface JobObservationService {
/** Observes one physical feed until confirmed completion or retirement.
* @typeParam Run - Application-declared run payload.
* @param feed - Native dependency and authoritative observation state.
* @param generation - Active worker generation rejecting stale callbacks.
* @returns A lazy observed and interruptible workflow preserving native failures. */
readonly consume: <Run>(
feed: WatchFeedLoop<Run>,
generation: number,
) => Effect.Effect<void, unknown>;
}
read-timeout.ts
readWatchNext
Bounds one native iterator pull using the caller’s cancellation authority.
Signature
declare const readWatchNext: (
iterator: AsyncIterator<unknown>,
signal: AbortSignal,
timeoutMs?: number,
) => Promise<IteratorResult<unknown>>;
timedCall
Races one native boundary call against cancellation and the existing bounded read deadline.
Signature
declare const timedCall: <T>(
signal: AbortSignal,
timeoutMs: number,
operation: (signal: AbortSignal) => Promise<T> | T,
) => Promise<T>;
reconcile-boundary.ts
asWatchFrame
Checks the existing selective watch-frame envelope and retains original fields.
Signature
declare const asWatchFrame: (value: unknown) => RunWatchFrame;
isProcedureNotFound
Recognizes the existing missing-procedure envelope used for safe read fallback.
Signature
declare const isProcedureNotFound: (value: unknown) => boolean;
isRunSnapshot
Checks the existing selective run-snapshot authority without stricter payload validation.
Signature
declare const isRunSnapshot: (value: unknown) => value is RunSnapshot;
optionalJobProcedure
Resolves an optional generated procedure while preserving unrelated lookup defects.
Signature
declare const optionalJobProcedure: (
root: unknown,
name: string,
operation: string,
) => Procedure | undefined;
ownJobProcedure
Finds a concrete job procedure while avoiding synthesized proxy properties.
Signature
declare const ownJobProcedure: (
root: unknown,
name: string,
operation: string,
) => Procedure | undefined;
resolveJobProcedure
Resolves a generated job procedure or preserves the existing missing-procedure error.
Signature
declare const resolveJobProcedure: (root: unknown, name: string, operation: string) => Procedure;
throwIfAborted
Preserves the public watch-aborted failure at a native compatibility edge.
Signature
declare const throwIfAborted: (signal: AbortSignal) => void;
toAsyncIterator
Checks and transfers a native iterable or iterator without cloning its payloads.
Signature
declare const toAsyncIterator: (value: unknown) => AsyncIterator<unknown>;
reconcile-support.ts
closeIterator
Bounds a native iterator’s return without changing an existing public failure.
Signature
declare const closeIterator: (iterator: AsyncIterator<unknown>) => Promise<void>;
newEpoch
Creates the existing local epoch used for synthesized authoritative snapshots.
Signature
declare const newEpoch: () => string;
reconcile.ts
WatchRequest
Signature
declare const WatchRequest: WatchRequest;
authoritativeFrame
Reads authoritative run state, falling back to watch only for a missing get procedure.
Signature
declare const authoritativeFrame: (
client: unknown,
name: string,
options: JobWatchOptions,
signal: AbortSignal,
) => Promise<RunWatchFrame | undefined>;
closeIterator
Signature
declare const closeIterator: (iterator: AsyncIterator<unknown>) => Promise<void>;
frameFromRun
Projects an authoritative run into the existing frozen snapshot frame.
Signature
declare const frameFromRun: (run: RunSnapshot) => RunWatchFrame;
newEpoch
Signature
declare const newEpoch: () => string;
openWatchIterator
Bounds native watch establishment and preserves the supplied lifetime signal.
Signature
declare const openWatchIterator: (
client: unknown,
name: string,
request: WatchRequest,
signal: AbortSignal,
timeoutMs?: number,
) => Promise<AsyncIterator<unknown>>;
ownJobProcedure
Signature
declare const ownJobProcedure: (
root: unknown,
name: string,
operation: string,
) => Procedure | undefined;
readFirstWatchFrame
Reads and closes a temporary native watch used for authoritative fallback.
Signature
declare const readFirstWatchFrame: (
client: unknown,
name: string,
request: WatchRequest,
signal: AbortSignal,
timeoutMs?: number,
) => Promise<RunWatchFrame | undefined>;
resolveJobProcedure
Signature
declare const resolveJobProcedure: (root: unknown, name: string, operation: string) => Procedure;
watchRequest
Builds the existing run observation request without widening identity authority.
Signature
declare const watchRequest: (options: JobWatchOptions, after?: string | undefined) => WatchRequest;
reconcile.types.ts
Procedure (type alias)
A native job procedure callable preserving unknown request and result authority.
Signature
type Procedure = (...args: readonly unknown[]) => unknown;
WatchRequest (interface)
Run identity, retained cursor and optional expected application identity.
Signature
export interface WatchRequest {
readonly runId: string;
readonly after?: string;
readonly expectedIdentity?: ExpectedClientIdentity;
}
stream-errors.ts
JobStreamGapError (class)
Signature
declare class JobStreamGapError { constructor(
readonly expected: number,
readonly received: number,
) }
code (property)
Signature
readonly code: "RELKIT_JOB_STREAM_GAP"
JobStreamOverflowError (class)
Signature
declare class JobStreamOverflowError { constructor(readonly limit: "frames" | "bytes" | "item-bytes") }
code (property)
Signature
readonly code: "RELKIT_JOB_STREAM_OVERFLOW"
stream-support.ts
byteLength
Measures the existing UTF-8 JSON representation used by content memory limits.
Signature
declare const byteLength: (value: unknown) => number;
streamIdentity
Combines every existing named-content generation boundary into its continuity key.
Signature
declare const streamIdentity: (frame: NamedStreamFrame) => string;
toAsyncIterator
Checks and transfers a native iterable or iterator without cloning its payloads.
Signature
declare const toAsyncIterator: (value: unknown) => AsyncIterator<unknown>;
validateFrame
Validates the existing selective named-content frame and chunk authority.
Signature
declare const validateFrame: (value: unknown) => NamedStreamFrame;
stream.ts
JobStreamGapError
Signature
declare const JobStreamGapError: typeof JobStreamGapError;
JobStreamOptions
Signature
declare const JobStreamOptions: JobStreamOptions;
JobStreamOverflowError
Signature
declare const JobStreamOverflowError: typeof JobStreamOverflowError;
watchJobStream
Opens one bounded named-content iterator with existing continuity guarantees.
Signature
declare const watchJobStream: <Item extends JsonValue = JsonValue>(
client: unknown,
job: string,
options: JobStreamOptions,
) => Promise<AsyncIterable<NamedStreamFrame<Item>>>;
stream.types.ts
JobStreamOptions (interface)
Existing content bounds and request authority for one named stream.
Signature
export interface JobStreamOptions {
readonly runId: string;
readonly name: string;
readonly after?: string;
readonly expectedIdentity?: ExpectedClientIdentity;
readonly signal?: AbortSignal;
readonly readTimeoutMs?: number;
readonly maxFrames?: number;
readonly maxBytes?: number;
readonly maxItemBytes?: number;
}
types.ts
JobWatchAbortedError (class)
Signature
declare class JobWatchAbortedError {
constructor();
}
code (property)
Signature
readonly code: "RELKIT_JOB_WATCH_ABORTED"
JobWatchController
Signature
declare const JobWatchController: JobWatchController<Run>;
JobWatchDisposedError (class)
Signature
declare class JobWatchDisposedError {
constructor();
}
code (property)
Signature
readonly code: "RELKIT_JOB_WATCH_DISPOSED"
JobWatchFrame
Signature
declare const JobWatchFrame: JobWatchFrame<Run>;
JobWatchListener
Signature
declare const JobWatchListener: JobWatchListener<Run>;
JobWatchOptions
Signature
declare const JobWatchOptions: JobWatchOptions;
JobWatchReadTimeoutError (class)
Signature
declare class JobWatchReadTimeoutError {
constructor();
}
code (property)
Signature
readonly code: "RELKIT_JOB_WATCH_READ_TIMEOUT"
JobWatchState
Signature
declare const JobWatchState: JobWatchState<Run>;
JobWatchUnavailableError (class)
Signature
declare class JobWatchUnavailableError {
constructor();
}
code (property)
Signature
readonly code: "RELKIT_JOB_WATCH_UNAVAILABLE"
isTerminalRun
Recognizes only the existing terminal run statuses.
Signature
declare const isTerminalRun: (run: unknown) => boolean;
watch-feed-loop.ts
WatchFeedLoop
Signature
declare const WatchFeedLoop: WatchFeedLoop<Run>;
runWatchFeed
Runs the native observation/reconciliation/retry state machine in its owner fiber.
Signature
declare const runWatchFeed: <Run>(
feed: WatchFeedLoop<Run>,
generation: number,
) => Effect.Effect<void, unknown, never>;
watch-feed-loop.types.ts
WatchFeedLoop (interface)
State authority shared by native and polling observation workflows.
Signature
export interface WatchFeedLoop<Run> {
readonly client: unknown;
readonly name: string;
readonly options: JobWatchOptions;
readonly isActive: (generation: number) => boolean;
readonly lastCursor: () => string | undefined;
readonly setAbort: (controller: AbortController | undefined) => void;
readonly setIterator: (iterator: AsyncIterator<unknown> | undefined) => void;
readonly acceptFrame: (value: unknown) => RunWatchFrame<Run> | undefined;
readonly emit: (event: FeedEvent<Run>) => void;
readonly verifyTerminal: (
frame: RunWatchFrame<Run>,
signal: AbortSignal,
) => Promise<boolean | undefined>;
readonly releaseTerminal: () => void;
readonly resolveFirsts: () => void;
readonly rejectFirsts: (error: unknown) => void;
readonly failureCount: () => number;
readonly setFailureCount: (value: number) => void;
}
watch-feed-observers.ts
WatchFeedObservers
Signature
declare const WatchFeedObservers: WatchFeedObservers<Run>;
emitObservers
Publishes to each observer while isolating synchronous view failures.
Signature
declare const emitObservers: <Run>(
observers: WatchFeedObservers<Run>,
event: FeedEvent<Run>,
) => void;
rejectObserverFirsts
Rejects pending first-snapshot Promises with the original failure object.
Signature
declare const rejectObserverFirsts: <Run>(
observers: WatchFeedObservers<Run>,
error: unknown,
) => void;
releaseWatchFeedTerminal
Aborts the observer request and clears leases after authoritative completion.
Signature
declare const releaseWatchFeedTerminal: <Run>(
observers: Map<string, { readonly observer: FeedObserver<Run>; readonly first: Pending }>,
abort: AbortController | undefined,
onEmpty: () => void,
) => void;
resolveObserverFirsts
Settles each pending first-snapshot Promise after authoritative evidence.
Signature
declare const resolveObserverFirsts: <Run>(observers: WatchFeedObservers<Run>) => void;
watch-feed-observers.types.ts
WatchFeedObservers (type alias)
Each feed lease’s callback and shared first-snapshot settlement authority.
Signature
type WatchFeedObservers<Run> = ReadonlyMap<
string,
{ readonly observer: FeedObserver<Run>; readonly first: Pending }
>;
watch-feed-polling.ts
runPollingFeed
Observes authoritative snapshots with the injected Clock and unchanged retry policy.
Signature
declare const runPollingFeed: <Run>(
feed: WatchFeedLoop<Run>,
generation: number,
) => Effect.Effect<void, unknown, never>;
watch-feed-recovery.ts
recoverWatchFeed
Applies the bounded, idempotent observation retry policy without retrying server work.
Signature
declare const recoverWatchFeed: <Run>(
feed: WatchFeedLoop<Run>,
generation: number,
error: unknown,
controller: AbortController,
) => Effect.Effect<void, unknown>;
watch-feed-refetch.ts
refetchSharedWatchFeed
Owns a temporary authoritative read while respecting borrowed cancellation.
Signature
declare const refetchSharedWatchFeed: <Run>(
client: unknown,
name: string,
options: JobWatchOptions,
lastCursor: string | undefined,
signal?: AbortSignal,
) => Promise<RunWatchFrame<Run> | undefined>;
watch-feed-state.ts
WatchFeedState
Signature
declare const WatchFeedState: WatchFeedState<Run>;
acceptWatchFrame
Applies epoch changes and duplicate suppression without losing retained cursor authority.
Signature
declare const acceptWatchFrame: <Run>(
state: WatchFeedState<Run>,
value: unknown,
) => { readonly state: WatchFeedState<Run>; readonly frame: RunWatchFrame<Run> | undefined };
emptyWatchFeedState
Creates the initial empty observation cache with no native resources.
Signature
declare const emptyWatchFeedState: <Run>() => WatchFeedState<Run>;
watch-feed-state.types.ts
WatchFeedState (interface)
Accepted frame, epoch, sequence and cursor retained by one shared observation feed.
Signature
export interface WatchFeedState<Run> {
readonly lastFrame: RunWatchFrame<Run> | undefined;
readonly lastCursor: string | undefined;
readonly lastSequence: number;
readonly nativeEpoch: string | undefined;
}
watch-feed-support.ts
Pending
Signature
declare const Pending: Pending;
backoff
Calculates the existing bounded observation reconnect delay.
Signature
declare const backoff: (attempt: number, options: JobWatchOptions) => number;
closeEmptyIterator
Provides the existing already-completed native iterator.
Signature
declare const closeEmptyIterator: () => AsyncIterator<unknown>;
deferred
Creates one settled-once first-snapshot Promise with explicit resolution authority.
Signature
declare const deferred: () => Pending;
isFrame
Checks the existing selective observation-frame shape.
Signature
declare const isFrame: (value: unknown) => value is RunWatchFrame;
isUnauthorized
Recognizes existing nested authorization denial envelopes.
Signature
declare const isUnauthorized: (value: unknown) => boolean;
offline
Waits for browser online recovery while owning its listener and borrowed signal.
Signature
declare const offline: (signal: AbortSignal) => Promise<boolean>;
resetFrame
Marks reconnect continuity without fabricating cursor or terminal evidence.
Signature
declare const resetFrame: (value: unknown) => unknown;
wait
Owns a native delay and removes its timer and borrowed abort listener on settlement.
Signature
declare const wait: (milliseconds: number, signal: AbortSignal) => Promise<void>;
withAfter
Adds a retained cursor only when one exists.
Signature
declare const withAfter: (options: JobWatchOptions, after: string | undefined) => JobWatchOptions;
watch-feed-support.types.ts
Settled-once first-snapshot Promise with explicit resolve and reject functions.
Pending (type alias)
Settled-once first-snapshot Promise with explicit resolve and reject functions.
Signature
type Pending = {
readonly promise: Promise<void>;
readonly resolve: () => void;
readonly reject: (error: unknown) => void;
};
watch-feed-teardown.ts
Joins native feed completion within the public teardown deadline.
joinFeedTeardown
Joins native feed completion within the public teardown deadline.
Signature
declare const joinFeedTeardown: (
interrupted: Promise<void>,
running: Promise<void>,
) => Promise<void>;
watch-feed-terminal.ts
verifyWatchTerminal
Confirms terminal evidence and publishes the authoritative frame.
Signature
declare const verifyWatchTerminal: <Run>(
client: unknown,
name: string,
options: JobWatchOptions,
frame: RunWatchFrame<Run>,
signal: AbortSignal,
accept: (value: unknown) => RunWatchFrame<Run> | undefined,
emit: (event: FeedEvent<Run>) => void,
) => Promise<boolean | undefined>;
watch-feed-types.ts
“./watch-feed.types.js” (namespace export)
Re-exports all named exports from the “./watch-feed.types.js” module.
Signature
export * from "./watch-feed.types.js";
watch-feed.ts
FeedEvent
Signature
declare const FeedEvent: FeedEvent<Run>;
FeedStatus
Signature
declare const FeedStatus: FeedStatus;
SharedWatchFeed (class)
Scoped physical native observation shared by independently retired view leases.
Signature
declare class SharedWatchFeed<Run> { constructor(
private readonly client: unknown,
private readonly name: string,
private readonly options: JobWatchOptions,
private readonly onEmpty: () => void = () => undefined,
) }
addLease (method)
Registers one observer and its first-snapshot Promise without duplicating shared native work.
Signature
declare const addLease: (id: string, observer: FeedObserver<Run>) => Promise<void>;
removeLease (method)
Releases one observer and joins bounded native teardown only for the final observer.
Signature
declare const removeLease: (id: string, error?: unknown) => Promise<void>;
refetch (method)
Reads authoritative evidence without changing observation lease ownership.
Signature
declare const refetch: (signal?: AbortSignal) => Promise<RunWatchFrame<Run> | undefined>;
close (method)
Closes the service owner after the sharing registry removes its final entry.
Signature
declare const close: () => Promise<void>;
ensureRunning (method)
Starts one supervised observation worker only when live observers require it.
Signature
declare const ensureRunning: () => void;
loop (method)
Projects the facade’s observer and epoch authority into the owned observation workflow.
Signature
declare const loop: (generation: number) => {
client: unknown;
name: string;
options: JobWatchOptions;
isActive: (generation: number) => boolean;
lastCursor: () => string | undefined;
setAbort: (controller: AbortController | undefined) => void;
setIterator: () => void;
acceptFrame: (value: unknown) => RunWatchFrame<Run> | undefined;
emit: (event: FeedEvent<Run>) => void;
verifyTerminal: (frame: RunWatchFrame<Run>, signal: AbortSignal) => Promise<boolean | undefined>;
releaseTerminal: () => void;
resolveFirsts: () => void;
rejectFirsts: (error: unknown) => void;
failureCount: () => number;
setFailureCount: (value: number) => void;
};
releaseTerminal (method)
Retires terminal observer authority and invalidates the shared registry entry.
Signature
declare const releaseTerminal: () => void;
acceptFrame (method)
Applies epoch, sequence and cursor duplicate rules to the cached observer snapshot.
Signature
declare const acceptFrame: (value: unknown) => RunWatchFrame<Run> | undefined;
emit (method)
Publishes an observation without allowing one callback to fail another observer.
Signature
declare const emit: (event: FeedEvent<Run>) => void;
watch-feed.types.ts
FeedEvent (type alias)
Canonical native frame or physical observation lifecycle publication.
Signature
type FeedEvent<Run> =
| { readonly kind: "frame"; readonly frame: RunWatchFrame<Run> }
| { readonly kind: "status"; readonly status: FeedStatus; readonly error?: unknown };
FeedObserver (type alias)
Synchronous observer isolated from another view and the native worker lifetime.
Signature
type FeedObserver<Run> = (event: FeedEvent<Run>) => void;
FeedStatus (type alias)
Physical observation states projected into each passive external-store view.
Signature
type FeedStatus =
"connecting" | "connected" | "reconnecting" | "completed" | "unauthorized" | "error";
watch-key.ts
WatchFeedKey (class)
Complete immutable sharing identity with borrowed transport/configuration.
Signature
declare class WatchFeedKey { constructor(
readonly client: unknown,
readonly name: string,
readonly options: JobWatchOptions,
) }
[Equal.symbol] (method)
Signature
declare const [Equal.symbol]: (that: Equal.Equal) => boolean
[Hash.symbol] (method)
Signature
declare const [Hash.symbol]: () => number
value (property)
Signature
readonly value: string
watch.ts
FeedEvent
Signature
declare const FeedEvent: FeedEvent<Run>;
FeedStatus
Signature
declare const FeedStatus: FeedStatus;
JobFeedRegistryDefault
Borrowed browser registry; each controller closes its explicit RcMap borrow.
Signature
declare const JobFeedRegistryDefault: Layer.Layer<JobFeedRegistry, never, never>;
SharedWatchFeed
Signature
declare const SharedWatchFeed: typeof SharedWatchFeed;
jobFeedRegistry
Once-acquired reference-counted registry used by controller operations.
Signature
declare const jobFeedRegistry: JobFeedRegistryService;
watch.types.ts
JobWatchController (interface)
Reusable public watch owner with synchronous state and explicit Promise cleanup.
Signature
export interface JobWatchController<Run = RunSnapshot> {
getSnapshot(): JobWatchState<Run>;
subscribe(listener: JobWatchListener<Run>): () => void;
connect(): Promise<void>;
disconnect(): Promise<void>;
dispose(): Promise<void>;
refetch(): Promise<void>;
}
JobWatchFrame (type alias)
Declared job run observation frame.
Signature
type JobWatchFrame<Run = RunSnapshot> = RunWatchFrame<Run>;
JobWatchListener (type alias)
Borrowed synchronous observer of frozen job watch state.
Signature
type JobWatchListener<Run = RunSnapshot> = (state: JobWatchState<Run>) => void;
JobWatchOptions (interface)
Complete watch sharing authority, cursor/projection fields and retry/read bounds.
Signature
export interface JobWatchOptions {
readonly runId: string;
readonly jobId?: string;
readonly after?: string;
readonly expectedIdentity?: ExpectedClientIdentity;
readonly identityKey?: string | null;
readonly applicationId?: string;
readonly environment?: string;
readonly grantScope?: string;
readonly projection?: string;
readonly schemaVersion?: string;
readonly protocolVersion?: number;
readonly source?: "native" | "polling";
readonly pollIntervalMs?: number;
readonly maxReconnectAttempts?: number;
readonly reconnectMinDelayMs?: number;
readonly reconnectMaxDelayMs?: number;
readonly readTimeoutMs?: number;
}
JobWatchState (interface)
Frozen external-store snapshot of connection, run and continuity evidence.
Signature
export interface JobWatchState<Run = RunSnapshot> {
readonly run?: Run;
readonly connection: RunConnection;
readonly isStale: boolean;
readonly lastObservedAt?: string;
readonly connectionError?: unknown;
readonly continuity?: "state" | "history";
readonly resetReason?: "reconnected" | "cursor-expired" | "history-unavailable" | "overflow";
readonly source?: "native" | "polling";
readonly epoch?: string;
readonly sequence?: number;
readonly cursor?: string;
}
native-stream.ts
nativeCall
Suspends native work and passes the owning fiber’s cancellation signal.
Signature
declare const nativeCall: <A>(
execute: (signal: AbortSignal) => PromiseLike<A>,
) => Effect.Effect<A, unknown>;
nativeStream
Owns an iterator and its request through all pulls, EOF and early return.
Signature
declare const nativeStream: <A>(
operation: string,
open: (signal: AbortSignal) => PromiseLike<AsyncIterator<A>>,
caller?: AbortSignal,
opened?: Effect.Effect<void>,
read?: (iterator: AsyncIterator<A>, signal: AbortSignal) => PromiseLike<IteratorResult<A>>,
) => Stream.Stream<A, unknown>;
agent-continuation.ts
prepareAgentContinuation
Binds a continuation to the authoritative waiting revision for its thread.
Signature
declare const prepareAgentContinuation: (
client: unknown,
agentId: string,
threadId: string,
payload: unknown,
current?: ThreadSnapshot,
) => Promise<PreparedContinuation>;
requiredThreadId
Validates the existing caller-supplied thread boundary.
Throws
Error when the existing thread validation fails.
Signature
declare const requiredThreadId: (options: AgentThreadOptions | undefined) => string;
agent-contract-selection.ts
“./agent-contract-selection.types.js” (namespace export)
Re-exports all named exports from the “./agent-contract-selection.types.js” module.
Signature
export * from "./agent-contract-selection.types.js";
agent-contract-selection.types.ts
AgentChat (type alias)
Infers whether the declared agent accepts chat send.
Signature
type AgentChat<Name extends AgentSelector> =
AgentFor<Name> extends { readonly chat: infer Value } ? Value : false;
AgentControls (type alias)
Infers the declared agent control capabilities.
Signature
type AgentControls<Name extends AgentSelector> =
AgentFor<Name> extends { readonly controls: infer Value } ? Value : never;
AgentCustomEvent (type alias)
Infers the declared custom observation event payload.
Signature
type AgentCustomEvent<Name extends AgentSelector> =
AgentFor<Name> extends { readonly customEvent: infer Value } ? Value : never;
AgentInput (type alias)
Infers the declared agent run input.
Signature
type AgentInput<Name extends AgentSelector> =
AgentFor<Name> extends { readonly input: infer Value } ? Value : never;
AgentOutput (type alias)
Infers the declared terminal agent output.
Signature
type AgentOutput<Name extends AgentSelector> =
AgentFor<Name> extends { readonly output: infer Value } ? Value : never;
AgentPublicState (type alias)
Infers the public values projected into observed thread state.
Signature
type AgentPublicState<Name extends AgentSelector> =
AgentFor<Name> extends { readonly publicState: infer Value } ? Value : never;
AgentResume (type alias)
Infers the declared continuation input.
Signature
type AgentResume<Name extends AgentSelector> =
AgentFor<Name> extends { readonly resume: infer Value } ? Value : never;
AgentScope (type alias)
Infers declared nested execution scope identities.
Signature
type AgentScope<Name extends AgentSelector> =
AgentFor<Name> extends { readonly scope: infer Value } ? Value : never;
AgentTool (type alias)
Infers the declared tool input and output contract.
Signature
type AgentTool<Name extends AgentSelector> =
AgentFor<Name> extends { readonly tool: infer Value } ? Value : never;
AgentWaiting (type alias)
Infers supported waiting request payloads.
Signature
type AgentWaiting<Name extends AgentSelector> =
AgentFor<Name> extends { readonly waiting: infer Value } ? Value : never;
agent-execution-observation.ts
AgentExecutionProjection
Signature
declare const AgentExecutionProjection: AgentExecutionProjection<Output>;
clientEventProjection
Projects canonical client events into the existing browser execution event shape.
Signature
declare const clientEventProjection: (event: AgentClientEvent) => unknown;
executionProjection
Projects authoritative execution state into the existing browser agent shape.
Signature
declare const executionProjection: <Output>(
current: AgentExecutionProjection<Output>,
event: AgentExecutionEvent,
) => AgentExecutionProjection<Output>;
snapshotProjection
Projects a thread snapshot through its canonical executions.
Signature
declare const snapshotProjection: <Output>(
snapshot: ThreadSnapshot,
) => AgentExecutionProjection<Output>;
terminalProjection
Projects a native terminal envelope without fabricating missing output.
Signature
declare const terminalProjection: <Output>(value: unknown) => {
output?: Output;
status: "failed" | "cancelled" | "succeeded";
};
updateSnapshotProjection
Updates the browser snapshot projection without widening authority.
Signature
declare const updateSnapshotProjection: <Snapshot extends ThreadSnapshot>(
snapshot: Snapshot,
projection: AgentExecutionProjection,
event: AgentClientEvent,
) => Snapshot;
agent-execution-observation.types.ts
AgentExecutionProjection (interface)
Browser agent lifecycle and content projected from authoritative execution state.
Signature
export interface AgentExecutionProjection<Output = unknown> {
readonly values?: unknown;
readonly output?: Output;
readonly executions: readonly AgentExecutionSnapshot[];
}
agent-hook-contract.ts
“./agent-hook-contract.types.js” (namespace export)
Re-exports all named exports from the “./agent-hook-contract.types.js” module.
Signature
export * from "./agent-hook-contract.types.js";
agent-hook-contract.types.ts
AgentNestedExecution (type alias)
Projects nested execution identity and public values from the declared scope.
Signature
type AgentNestedExecution<Scope, PublicState> = Omit<
AgentExecutionSnapshot,
"agent" | "node" | "values"
> & {
readonly agent?: ScopeId<Scope, "agent" | "subagent">;
readonly node?: ScopeId<Scope, "node">;
readonly values?: PublicState;
};
AgentObservedEvent (type alias)
Canonical observed events with declared tool and custom payload inference.
Signature
type AgentObservedEvent<Tool, CustomEvent> =
| Exclude<AgentClientEvent, AgentToolEvent>
| TypedToolEvent<AgentToolEvent, Tool>
| ObservedCustomEvent<CustomEvent>;
AgentToolCall (interface)
Stable browser projection of canonical tool identity, state, input and output.
Signature
export interface AgentToolCall {
readonly toolCallId: string;
readonly messageId: string;
readonly partId: string;
readonly runId?: string;
readonly toolId: string;
readonly state: ToolPartState;
readonly inputText?: string;
readonly input?: unknown;
readonly output?: unknown;
readonly createdAt: string;
readonly updatedAt: string;
}
TypedAgentToolCall (type alias)
Specializes observed tool identity and payloads when a tool contract is declared.
Signature
type TypedAgentToolCall<Tool> = Tool extends ToolContract
? Omit<AgentToolCall, "toolId" | "input" | "output"> & {
readonly toolId: Tool["id"];
readonly input?: Tool["input"];
readonly output?: Tool["output"];
}
: AgentToolCall;
TypedThreadSnapshot (type alias)
Authoritative thread snapshot with declaration-derived output, scope, values and waiting requests.
Signature
type TypedThreadSnapshot<Output, PublicState, Scope, Waiting> = Omit<
ThreadSnapshot,
"executions" | "output" | "values" | "waiting"
> & {
readonly executions: readonly AgentNestedExecution<Scope, PublicState>[];
readonly output?: Output;
readonly values?: PublicState;
readonly waiting?: [Waiting] extends [never] ? never : TypedWaitingState<Waiting>;
};
TypedWaitingState (type alias)
Projects waiting requests using the declared supported waiting union.
Signature
type TypedWaitingState<Waiting> = Omit<AgentWaitingState, "requests"> & {
readonly requests: readonly (Waiting extends AgentWaitingRequest ? Waiting : never)[];
};
agent-hook-types.ts
“./agent-hook-types.types.js” (namespace export)
Re-exports all named exports from the “./agent-hook-types.types.js” module.
Signature
export * from "./agent-hook-types.types.js";
agent-hook-types.types.ts
AgentBase (interface)
Observed durable thread state with declaration-derived payload and control contracts.
Signature
export interface AgentBase<
Output,
Tool = ClientAgentDynamic,
PublicState = unknown,
CustomEvent = never,
Scope = ClientAgentDynamic,
Waiting = AgentWaitingRequest,
> extends AgentContent<Tool> {
readonly status:
| "idle"
| "loading"
| "running"
| "waiting"
| "approval-interrupted"
| "stopping"
| "worker-interrupted"
| "succeeded"
| "failed"
| "cancelled"
| "error";
readonly threadId?: string;
readonly events: readonly AgentObservedEvent<Tool, CustomEvent>[];
readonly values?: PublicState;
readonly executions: readonly AgentNestedExecution<Scope, PublicState>[];
readonly output?: Output;
readonly snapshot?: ThreadSnapshot;
readonly waiting?: ([Waiting] extends [never] ? never : TypedWaitingState<Waiting>) | undefined;
readonly error?: unknown;
}
AgentContent (interface)
Indexed browser content supporting ordered timeline and direct identity lookup.
Signature
export interface AgentContent<Tool = ClientAgentDynamic> {
readonly timeline: readonly AgentTimelineItem<Tool>[];
readonly timelineById: ReadonlyMap<string, AgentTimelineItem<Tool>>;
readonly messages: readonly AgentMessage[];
readonly messagesById: ReadonlyMap<string, AgentMessage>;
readonly toolCalls: readonly TypedAgentToolCall<Tool>[];
readonly toolCallsById: ReadonlyMap<string, TypedAgentToolCall<Tool>>;
readonly progress: readonly AgentProgress[];
readonly progressById: ReadonlyMap<string, AgentProgress>;
}
AgentMessage (interface)
Browser projection of canonical user or assistant text message parts.
Signature
export interface AgentMessage {
readonly messageId: string;
readonly runId?: string;
readonly role: "user" | "assistant";
readonly parts: readonly Extract<BrowserMessagePart, { readonly kind: "text" }>[];
readonly createdAt: string;
}
AgentNestedExecution
Signature
declare const AgentNestedExecution: AgentNestedExecution<Scope, PublicState>;
AgentOutput
Signature
declare const AgentOutput: AgentOutput<Name>;
AgentProgress (type alias)
Browser progress projection with its canonical run or tool scope.
Signature
type AgentProgress = AgentProgressBase & import("@relkit/contracts").AgentProgressScope;
AgentResumeOptions (interface)
Continuation options requiring explicit resume mode.
Signature
export interface AgentResumeOptions extends AgentThreadOptions {
readonly resume: true;
}
AgentRunOptions (interface)
Fresh run options excluding continuation mode.
Signature
export interface AgentRunOptions extends AgentThreadOptions {
readonly resume?: false;
}
AgentStopOptions (interface)
Durable thread stop policy preserving graceful and immediate alternatives.
Signature
export interface AgentStopOptions extends AgentThreadOptions {
readonly mode?: "graceful" | "immediate";
}
AgentThreadOptions (interface)
Caller-owned durable thread identity used by observation and controls.
Signature
export interface AgentThreadOptions {
readonly threadId: string;
}
AgentTimelineItem (type alias)
Ordered browser timeline member retaining stable message, tool and progress identity.
Signature
type AgentTimelineItem<Tool = ClientAgentDynamic> =
| { readonly key: string; readonly kind: "message"; readonly message: AgentMessage }
| { readonly key: string; readonly kind: "tool"; readonly toolCall: TypedAgentToolCall<Tool> }
| { readonly key: string; readonly kind: "progress"; readonly progress: AgentProgress };
AgentToolCall
Signature
declare const AgentToolCall: AgentToolCall;
UseAgentResult (type alias)
Public agent hook state and declaration-derived execution, observation and controls.
Signature
type UseAgentResult<Name extends AgentSelector> = Omit<ContractBase<Name>, "snapshot"> & {
readonly snapshot?: TypedThreadSnapshot<
AgentOutput<Name>,
AgentPublicState<Name>,
AgentScope<Name>,
AgentWaiting<Name>
>;
} & Execution<Name> &
Observation &
Controls<Name>;
agent-hook.ts
“./agent-hook-types.js” (namespace export)
Re-exports all named exports from the “./agent-hook-types.js” module.
Signature
export * from "./agent-hook-types.js";
useAgent
Adapts the agent service into React state while keeping accepted work independent of view cleanup.
Signature
declare const useAgent: <Name extends AgentSelector>(name: Name) => UseAgentResult<Name>;
agent-hook.types.ts
InvocationOptions (type alias)
Explicit caller thread authority for an agent submission.
Signature
type InvocationOptions = AgentThreadOptions & { readonly resume?: boolean };
ObservationRequest (type alias)
The thread selected for the view’s current agent observation.
Signature
type ObservationRequest = { readonly threadId: string; readonly revision: number };
agent-methods.ts
agentMethods
Projects declared agent methods over the view’s borrowed invocation and observation adapters.
Signature
declare const agentMethods: <Output>(
state: AgentBase<Output>,
invoke: Invoke,
observe: (options: AgentThreadOptions) => Promise<void>,
) => {
observe: (options: AgentThreadOptions) => Promise<void>;
run: (input: unknown, options: AgentThreadOptions) => Promise<void>;
send: (message: string, options: AgentThreadOptions) => Promise<void>;
steer: (message: string, options: AgentThreadOptions) => Promise<void>;
followUp: (message: string, options: AgentThreadOptions) => Promise<void>;
stop: (options: AgentStopOptions) => Promise<void>;
approve: (approvalId: string, options: AgentThreadOptions) => Promise<void>;
deny: (approvalId: string, options: AgentThreadOptions) => Promise<void>;
status:
| "idle"
| "loading"
| "running"
| "waiting"
| "approval-interrupted"
| "stopping"
| "worker-interrupted"
| "succeeded"
| "failed"
| "cancelled"
| "error";
threadId?: string;
events: ReadonlyArray<AgentObservedEvent<ClientAgentDynamic, never>>;
values?: unknown;
executions: ReadonlyArray<AgentNestedExecution<ClientAgentDynamic, unknown>>;
output?: Output;
snapshot?: ThreadSnapshot;
waiting?: TypedWaitingState<AgentWaitingRequest> | undefined;
error?: unknown;
timeline: ReadonlyArray<AgentTimelineItem<ClientAgentDynamic>>;
timelineById: ReadonlyMap<string, AgentTimelineItem<ClientAgentDynamic>>;
messages: readonly AgentMessage[];
messagesById: ReadonlyMap<string, AgentMessage>;
toolCalls: ReadonlyArray<AgentToolCall>;
toolCallsById: ReadonlyMap<string, AgentToolCall>;
progress: readonly AgentProgress[];
progressById: ReadonlyMap<string, AgentProgress>;
};
agent-methods.types.ts
Invoke (type alias)
Borrowed agent submission callback preserving its declared receipt Promise.
Signature
type Invoke = (
kind: string,
payload: unknown,
options: AgentThreadOptions & { readonly resume?: boolean },
) => Promise<void>;
agent-observation-effect.ts
observeAgent
Restores the authoritative snapshot and owns every subsequent observation attempt.
Signature
declare const observeAgent: <Output>(
client: unknown,
streamClient: unknown,
agentId: string,
threadId: string,
identity: AgentIdentity | undefined,
signal: AbortSignal,
update: AgentUpdate<Output>,
) => Effect.Effect<void, unknown, never>;
agent-observation-index.ts
upsertMessage
Replaces or appends one message while preserving its timeline position.
Signature
declare const upsertMessage: (content: AgentContent, value: AgentMessage) => AgentContent;
upsertProgress
Replaces or appends one scoped progress item while preserving its timeline position.
Signature
declare const upsertProgress: (content: AgentContent, value: AgentProgress) => AgentContent;
upsertTool
Replaces or appends one tool call while preserving its timeline position.
Signature
declare const upsertTool: (content: AgentContent, value: AgentToolCall) => AgentContent;
agent-observation.ts
agentContentFromMessages
Projects authoritative messages into indexed browser content.
Signature
declare const agentContentFromMessages: (messages: readonly BrowserMessage[]) => AgentContent;
applyAgentEvent
Applies one canonical agent observation while preserving lifecycle and journal authority.
Signature
declare const applyAgentEvent: <Output>(
current: AgentBase<Output>,
event: AgentClientEvent,
) => AgentBase<Output>;
emptyAgentContent
Creates empty indexed browser agent content without native resources.
Signature
declare const emptyAgentContent: () => AgentContent;
agent-observer.ts
restoreAndObserve
Restores and observes one caller-owned thread until terminal evidence or cleanup.
Signature
declare const restoreAndObserve: <Output>(
client: unknown,
streamClient: unknown,
agentId: string,
threadId: string,
identity: AgentIdentity | undefined,
signal: AbortSignal,
update: AgentUpdate<Output>,
) => Promise<void>;
agent-operations.service.ts
AgentOperations (class)
Agent observation, continuation and accepted-work ownership contract.
Signature
declare class AgentOperations
AgentOperationsLive
Provides agent operations using the existing pending receipt authority.
Example
import { Layer } from "effect";
import { AgentOperationsLive } from "./agent-operations.service.js";
import { pendingOperationsLayer } from "./pending.service.js";
export const live = AgentOperationsLive.pipe(Layer.provide(pendingOperationsLayer()));
Signature
declare const AgentOperationsLive: Layer.Layer<AgentOperations, never, PendingOperations>;
isAcceptedAgentRun
Retains the existing weak receipt predicate used by agent dispatch.
Signature
declare const isAcceptedAgentRun: (value: unknown) => value is { readonly threadId: string };
agent-operations.types.ts
AgentIdentity (interface)
Complete identity authority supplied to an observation or submission.
Signature
export interface AgentIdentity {
readonly identityScope: string;
readonly sessionEpoch: string;
}
AgentObservationCursor (interface)
Checkpoint state belongs to one observation fiber.
Signature
export interface AgentObservationCursor {
checkpoint: JournalCheckpoint;
runId: string | undefined;
}
AgentOperationsService (interface)
Cohesive agent recovery and accepted-work contract, independent of React.
Signature
export interface AgentOperationsService {
/** Observes durable thread snapshots and ordered frames until view retirement.
* @typeParam Output - Application-declared terminal output payload.
* @param client - Borrowed finite procedure transport.
* @param streamClient - Borrowed native observation transport.
* @param agentId - Declared agent key.
* @param threadId - Caller-owned durable thread identity.
* @param identity - Complete authorization and session boundary.
* @param signal - View lifetime propagated to native observations.
* @param update - Isolated external-store publication.
* @returns A lazy scoped recovery workflow preserving native errors. */
readonly observe: <Output>(
client: unknown,
streamClient: unknown,
agentId: string,
threadId: string,
identity: AgentIdentity | undefined,
signal: AbortSignal,
update: AgentUpdate<Output>,
) => Effect.Effect<void, unknown>;
/** Binds continuation input to an authoritative waiting revision.
* @param client - Borrowed finite procedure transport.
* @param agentId - Declared agent key.
* @param threadId - Caller-owned durable thread identity.
* @param payload - Original transmitted continuation payload.
* @param current - Matching authoritative snapshot when already available.
* @returns A lazy observed revision and digest input or original native failure. */
readonly continuation: (
client: unknown,
agentId: string,
threadId: string,
payload: unknown,
current?: ThreadSnapshot,
) => Effect.Effect<PreparedContinuation, unknown>;
/** Reconciles stored receipts with durable thread identity.
* @param client - Borrowed receipt lookup transport.
* @param scopeKey - Complete pending isolation scope.
* @param agentId - Declared agent key.
* @param signal - View lifetime for receipt observations.
* @returns A lazy observed restored thread identity or original native failure. */
readonly reconcile: (
client: unknown,
scopeKey: string,
agentId: string,
signal: AbortSignal,
) => Effect.Effect<string | undefined, unknown>;
/** Dispatches accepted agent work independently of observation cancellation.
* @param request - Complete identity, input, continuation and pending authority.
* @returns A lazy observed original receipt or original native rejection. */
readonly submit: (request: AgentSubmission) => Effect.Effect<unknown, unknown>;
}
AgentReceiptLookup (type alias)
Receipt lookup preserves the existing finite recovery alternatives.
Signature
type AgentReceiptLookup =
| { readonly status: "found"; readonly receipt: { readonly threadId: string } }
| { readonly status: "not-found" | "expired" | "state-lost" };
AgentSubmission (interface)
Request state for a single accepted-work submission.
Signature
export interface AgentSubmission {
readonly client: unknown;
readonly scopeKey: string;
readonly agentId: string;
readonly threadId: string;
readonly identity: AgentIdentity | undefined;
readonly kind: string;
readonly payload: unknown;
readonly resume?: boolean;
readonly snapshot?: ThreadSnapshot;
readonly activeRunId?: string;
}
AgentUpdate (type alias)
State publication remains borrowed from the calling view.
Signature
type AgentUpdate<Output> = (
value: AgentBase<Output> | ((current: AgentBase<Output>) => AgentBase<Output>),
) => void;
PreparedContinuation (interface)
A continuation digest binds input to the authoritative waiting revision.
Signature
export interface PreparedContinuation {
readonly waitingRevision: string;
readonly digestValue: { readonly payload: unknown; readonly waitingRevision: string };
}
agent-reconcile.ts
reconcileAgentRun
Reconciles recorded submissions using authoritative receipt lookup.
Signature
declare const reconcileAgentRun: (
client: unknown,
scopeKey: string,
agentId: string,
signal: AbortSignal,
) => Promise<string | undefined>;
agent-runtime.ts
agentOperations
Once-acquired service used by synchronous constructors and Promise adapters.
Signature
declare const agentOperations: AgentOperationsService;
agentRuntime
Signature
declare const agentRuntime: ManagedRuntime.ManagedRuntime<AgentOperations, never>;
agent-snapshot-observation.ts
applyAgentSnapshot
Replaces authoritative agent state and reconciles its browser projection.
Signature
declare const applyAgentSnapshot: <Output>(
current: AgentBase<Output>,
snapshot: ThreadSnapshot,
) => AgentBase<Output>;
agent-sse-client.ts
createAgentSseClient
Creates the native SSE edge used by the agent observation service.
Signature
declare const createAgentSseClient: (options: AgentSseClientOptions, fallback?: object) => unknown;
agent-sse-stream.ts
agentSseObservations
Transfers a native response reader into a scoped Effect parser and iterator edge.
Signature
declare const agentSseObservations: (
body: ReadableStream<Uint8Array>,
controller: AbortController,
borrowed?: AbortSignal,
) => AsyncIterable<AgentObservation>;
agent-sse.types.ts
AgentSseClientOptions (interface)
Native HTTP configuration for the browser-safe agent SSE edge.
Signature
export interface AgentSseClientOptions {
readonly baseUrl: string;
readonly credentials: NonNullable<RequestInit["credentials"]>;
readonly headers?: ClientHeaders;
readonly fetch: typeof globalThis.fetch;
}
AgentSseObserveInput (interface)
Existing selective observation input authority.
Signature
export interface AgentSseObserveInput {
readonly agentId: string;
readonly threadId: string;
readonly runId?: string;
readonly after: JournalCheckpoint;
}
context-support.ts
browserOrigin
Reads the current browser backend origin or the existing local fallback.
Signature
declare const browserOrigin: () => string;
compiledFingerprint
Reads the existing browser or Next public fingerprint binding.
Signature
declare const compiledFingerprint: () => string | undefined;
finiteFetcher
Creates the finite native fetch edge with combined caller and deadline signals.
Signature
declare const finiteFetcher: (timeoutMs: number) => typeof fetch;
identityHeaders
Attaches existing identity, jobs protocol and CSRF authority to current headers.
Signature
declare const identityHeaders: (
value: ClientHeaders | undefined,
identity: ClientIdentityDocument | undefined,
) => Promise<Headers>;
isRelkitQuery
Selects query entries owned by RELKIT’s existing key prefix.
Signature
declare const isRelkitQuery: (query: { readonly queryKey: readonly unknown[] }) => boolean;
loadIdentity
Reads the existing backend identity document with caller-owned cancellation.
Signature
declare const loadIdentity: (
baseUrl: string,
credentials: NonNullable<RequestInit["credentials"]>,
signal: AbortSignal,
) => Promise<ClientIdentityDocument>;
sameScope
Compares every existing query and hydration isolation boundary.
Signature
declare const sameScope: (left: RelkitKeyScope, right: RelkitKeyScope) => boolean;
scopeFor
Constructs the complete existing backend and identity hydration/query scope.
Signature
declare const scopeFor: (
backend: string,
identity: ClientIdentityDocument,
identityKey: string | null | undefined,
environment?: string,
) => RelkitKeyScope;
streamClientFor
Selects the existing HTTP, WebSocket, auto or SSE procedure adapter.
Signature
declare const streamClientFor: (options: {
readonly baseUrl: string;
readonly credentials: NonNullable<RequestInit["credentials"]>;
readonly headers: ClientHeaders | undefined;
readonly transport: "auto" | "websocket" | "http-stream" | "sse" | undefined;
readonly timeoutMs: number;
readonly identity: ClientIdentityDocument | undefined;
}) => ReturnType<typeof createClient>;
streamFetcher
Bounds native stream establishment without timing out the subsequent live stream.
Signature
declare const streamFetcher: (timeoutMs: number) => typeof fetch;
context-types.ts
“./context.types.js” (namespace export)
Re-exports all named exports from the “./context.types.js” module.
Signature
export * from "./context.types.js";
context.tsx
RelkitClientProvider
Provides configured clients, query hydration, identity isolation and realtime ownership.
See
Signature
declare const RelkitClientProvider: (props: RelkitClientProviderProps) => ReactNode;
RelkitClientProviderProps
Signature
declare const RelkitClientProviderProps: RelkitClientProviderProps;
RelkitClientRuntime
Signature
declare const RelkitClientRuntime: RelkitClientRuntime;
RelkitHydrationState
Signature
declare const RelkitHydrationState: RelkitHydrationState;
useRelkitClient
Reads the required existing React client provider context.
Throws
Error when called outside RelkitClientProvider.
See
Signature
declare const useRelkitClient: () => RelkitClientRuntime;
context.types.ts
RelkitClientProviderProps (interface)
React provider configuration retaining borrowed clients and hydration authority.
Signature
export interface RelkitClientProviderProps {
readonly baseUrl?: string;
readonly environment?: string;
readonly credentials?: RequestInit["credentials"];
readonly headers?: ClientHeaders;
readonly queryClient?: QueryClient;
readonly identityKey?: string | null;
readonly hydratedState?: RelkitHydrationState;
readonly transport?: "auto" | "websocket" | "http-stream" | "sse";
readonly requestTimeoutMs?: number;
readonly streamEstablishmentTimeoutMs?: number;
readonly children: ReactNode;
}
RelkitClientRuntime (interface)
Provider-owned client and identity state shared by React boundary adapters.
Signature
export interface RelkitClientRuntime {
readonly client: ReturnType<typeof createClient>;
readonly streamClient: ReturnType<typeof createClient>;
readonly queryClient: QueryClient;
readonly utils: unknown;
readonly identity?: ClientIdentityDocument;
readonly identityKey?: string | null;
readonly status: "loading" | "ready" | "application-updated" | "error";
readonly scope?: RelkitKeyScope;
readonly transport: "auto" | "websocket" | "http-stream" | "sse";
readonly streamEstablishmentTimeoutMs: number;
readonly environment?: string;
readonly realtime: RealtimeManager;
}
RelkitHydrationState (interface)
Server-supplied ready identity and application contract hydration.
Signature
export interface RelkitHydrationState {
readonly scope: RelkitKeyScope;
readonly dehydrated: unknown;
}
finite-hooks.ts
RelkitWriteError
Signature
declare const RelkitWriteError: typeof RelkitWriteError;
useInfiniteRoute
Adapts a declared paginated route while retaining page and scope inference.
Signature
declare const useInfiniteRoute: <
Name extends QuerySelector,
PageParam,
Selected = InfiniteData<OutputFor<Name>, PageParam>,
>(
name: Name,
options: Omit<
UseInfiniteQueryOptions<
OutputFor<Name>,
ErrorFor<Name>,
Selected,
readonly unknown[],
PageParam
>,
"queryKey" | "queryFn"
> & { readonly input: (page: PageParam) => InputFor<Name> },
) => UseInfiniteQueryResult<Selected, ErrorFor<Name>>;
useRoute
Adapts a declared finite route into a scope-bound TanStack query.
Signature
declare const useRoute: <Name extends QuerySelector, Selected = OutputFor<Name>>(
name: Name,
options: QueryInput<Name, Selected>,
) => UseQueryResult<Selected, ErrorFor<Name>>;
useRouteMutation
Adapts a declared accepted-work operation into TanStack mutation state.
Signature
declare const useRouteMutation: <Name extends MutationSelector, Context = unknown>(
name: Name,
options?: Omit<
UseMutationOptions<OutputFor<Name>, ErrorFor<Name>, InputFor<Name>, Context>,
"mutationKey" | "mutationFn"
>,
) => UseMutationResult<OutputFor<Name>, ErrorFor<Name>, InputFor<Name>, Context>;
useRouteUtils
Returns the existing generated query/mutation utilities for a declared selector.
Signature
declare const useRouteUtils: <Name extends QuerySelector | MutationSelector>(
name: Name,
) => ProcedureUtilsLike;
useSuspenseRoute
Adapts a ready declared route into a scope-bound suspense query.
Signature
declare const useSuspenseRoute: <Name extends QuerySelector, Selected = OutputFor<Name>>(
name: Name,
options: Omit<
UseSuspenseQueryOptions<OutputFor<Name>, ErrorFor<Name>, Selected>,
"queryKey" | "queryFn"
> & {
readonly input: InputFor<Name>;
},
) => UseSuspenseQueryResult<Selected, ErrorFor<Name>>;
finite-hooks.types.ts
QueryInput (type alias)
Declared route input or the existing skip-token readiness sentinel.
Signature
type QueryInput<Name extends QuerySelector, Selected> = Omit<
UseQueryOptions<OutputFor<Name>, ErrorFor<Name>, Selected>,
"queryKey" | "queryFn"
> & { readonly input: InputFor<Name> };
index.ts
Exposes React providers and hooks backed by the selected query adapter. Install react, @tanstack/react-query@^5, @tanstack/query-core@^5 and
“./agent-hook.js” (namespace export)
Re-exports all named exports from the “./agent-hook.js” module.
Signature
export * from "./agent-hook.js";
“./agent-reconcile.js” (namespace export)
Re-exports all named exports from the “./agent-reconcile.js” module.
Signature
export * from "./agent-reconcile.js";
“./context.js” (namespace export)
Re-exports all named exports from the “./context.js” module.
Signature
export * from "./context.js";
“./finite-hooks.js” (namespace export)
Re-exports all named exports from the “./finite-hooks.js” module.
Signature
export * from "./finite-hooks.js";
“./job-hooks.js” (namespace export)
Re-exports all named exports from the “./job-hooks.js” module.
Signature
export * from "./job-hooks.js";
“./keys.js” (namespace export)
Re-exports all named exports from the “./keys.js” module.
Signature
export * from "./keys.js";
“./pending.js” (namespace export)
Re-exports all named exports from the “./pending.js” module.
Signature
export * from "./pending.js";
“./realtime-hook.js” (namespace export)
Re-exports all named exports from the “./realtime-hook.js” module.
Signature
export * from "./realtime-hook.js";
“./registry.js” (namespace export)
Re-exports all named exports from the “./registry.js” module.
Signature
export * from "./registry.js";
“./stream-hook.js” (namespace export)
Re-exports all named exports from the “./stream-hook.js” module.
Signature
export * from "./stream-hook.js";
CountPresence
Signature
declare const CountPresence: CountPresence;
JobCancelInput
Signature
declare const JobCancelInput: JobCancelInput;
JobCancelInputFor
Signature
declare const JobCancelInputFor: JobCancelInputFor<Name>;
JobCancelName
Signature
declare const JobCancelName: never;
JobCancelOutputFor
Signature
declare const JobCancelOutputFor: JobCancelOutputFor<Name>;
JobClientField
Signature
declare const JobClientField: JobClientField;
JobContract
Signature
declare const JobContract: JobContract<
Name,
JobId,
Input,
Output,
Failure,
Progress,
Streams,
Operations,
Fields
>;
JobFor
Signature
declare const JobFor: JobFor<Name>;
JobGetInput
Signature
declare const JobGetInput: JobGetInput;
JobListInput
Signature
declare const JobListInput: JobListInput;
JobListQuery
Signature
declare const JobListQuery: JobListQuery;
JobProcedureContract
Signature
declare const JobProcedureContract: JobProcedureContract<Input, Output, Failure>;
JobProcedureSelector
Signature
declare const JobProcedureSelector: JobProcedureSelector<Name>;
JobRegistry
Signature
declare const JobRegistry: JobRegistry;
JobRetryInput
Signature
declare const JobRetryInput: JobRetryInput;
JobRetryInputFor
Signature
declare const JobRetryInputFor: JobRetryInputFor<Name>;
JobRetryName
Signature
declare const JobRetryName: never;
JobRetryOutputFor
Signature
declare const JobRetryOutputFor: JobRetryOutputFor<Name>;
JobRunFor
Signature
declare const JobRunFor: JobRunFor<Name>;
JobRunSelector
Signature
declare const JobRunSelector: JobRunSelector<Name>;
JobSelector
Signature
declare const JobSelector: never;
JobSnapshotFor
Signature
declare const JobSnapshotFor: JobSnapshotFor<Input, Output, Progress, Failure, Fields>;
JobStreamInput
Signature
declare const JobStreamInput: JobStreamInput<StreamName>;
JobStreamProcedureContract
Signature
declare const JobStreamProcedureContract: JobStreamProcedureContract<Input, Item, Failure>;
JobTriggerInput
Signature
declare const JobTriggerInput: JobTriggerInput<Input>;
JobTriggerInputFor
Signature
declare const JobTriggerInputFor: JobTriggerInputFor<Name>;
JobTriggerName
Signature
declare const JobTriggerName: never;
JobTriggerOptions
Signature
declare const JobTriggerOptions: JobTriggerOptions;
JobTriggerOutputFor
Signature
declare const JobTriggerOutputFor: JobTriggerOutputFor<Name>;
JobTriggerSelector
Signature
declare const JobTriggerSelector: JobTriggerSelector<Name>;
JobWatchFrameFor
Signature
declare const JobWatchFrameFor: JobWatchFrameFor<Name>;
JobWatchInput
Signature
declare const JobWatchInput: JobWatchInput;
JobWatchName
Signature
declare const JobWatchName: never;
MemberPresence
Signature
declare const MemberPresence: MemberPresence<Member>;
SelectedJobField
Signature
declare const SelectedJobField: SelectedJobField<Fields, Field>;
job-hooks-support.ts
PreparedJobRequest
Signature
declare const PreparedJobRequest: PreparedJobRequest;
generatedJobTriggerName
Recognizes a generated trigger selector without rewriting other route names.
Signature
declare const generatedJobTriggerName: (name: string) => string | undefined;
isRecord
Checks whether the existing property-access boundary accepts a supplied value.
Signature
declare const isRecord: (value: unknown) => value is Record<string, unknown>;
prepareJobRequest
Binds a transmitted job request to caller identity and explicit receipt authority.
Signature
declare const prepareJobRequest: (
value: unknown,
expectedIdentity: ExpectedClientIdentity,
mutationContext?: object,
) => PreparedJobRequest;
readOperationId
Selects a caller-supplied operation ID from the existing request shape.
Signature
declare const readOperationId: (value: unknown) => string | undefined;
readRunId
Selects the existing run identity from a request.
Signature
declare const readRunId: (value: unknown) => string | undefined;
job-hooks-support.types.ts
Transmitted job input and its operation/run receipt references.
PreparedJobRequest (interface)
Transmitted job input and its operation/run receipt references.
Signature
export interface PreparedJobRequest {
readonly value: unknown;
readonly operationId: string;
readonly idempotencyKey?: string;
}
job-hooks.ts
JobMutationOptions
Signature
declare const JobMutationOptions: JobMutationOptions<Output, Failure, Input, Context>;
UseJobRunOptions
Signature
declare const UseJobRunOptions: UseJobRunOptions;
UseJobRunResult
Signature
declare const UseJobRunResult: UseJobRunResult<Run>;
useJobCancel
Signature
declare const useJobCancel: <Name extends JobCancelName, Context = unknown>(
name: Name,
options?: JobMutationOptions<
JobCancelOutputFor<Name>,
JobFailureFor<Name>,
JobCancelInputFor<Name>,
Context
>,
) => UseMutationResult<
JobCancelOutputFor<Name>,
JobFailureFor<Name>,
JobCancelInputFor<Name>,
Context
>;
useJobRetry
Signature
declare const useJobRetry: <Name extends JobRetryName, Context = unknown>(
name: Name,
options?: JobMutationOptions<
JobRetryOutputFor<Name>,
JobFailureFor<Name>,
JobRetryInputFor<Name>,
Context
>,
) => UseMutationResult<
JobRetryOutputFor<Name>,
JobFailureFor<Name>,
JobRetryInputFor<Name>,
Context
>;
useJobRun
Borrows an idle scoped job controller and exposes its frozen external-store state.
Signature
declare const useJobRun: <Name extends JobWatchName>(
name: Name,
options?: UseJobRunOptions,
) => UseJobRunResult<JobRunFor<Name>>;
useJobTrigger
Signature
declare const useJobTrigger: <Name extends JobTriggerName, Context = unknown>(
name: Name,
options?: JobMutationOptions<
JobTriggerOutputFor<Name>,
JobFailureFor<Name>,
JobTriggerInputFor<Name>,
Context
>,
) => UseMutationResult<
JobTriggerOutputFor<Name>,
JobFailureFor<Name>,
JobTriggerInputFor<Name>,
Context
>;
job-hooks.types.ts
UseJobRunOptions (interface)
Watch request authority and explicit connection/recovery policy for the declared job.
Signature
export interface UseJobRunOptions extends Omit<
JobWatchOptions,
"runId" | "expectedIdentity" | "identityKey" | "applicationId" | "protocolVersion"
> {
readonly runId?: string;
readonly enabled?: boolean;
readonly autoConnect?: boolean;
readonly expectedIdentity?: ExpectedClientIdentity;
}
UseJobRunResult (interface)
Frozen job run state plus connection, refetch and disposal controls.
Signature
export interface UseJobRunResult<Run = RunSnapshot> extends JobWatchState<Run> {
readonly connect: () => Promise<void>;
readonly disconnect: () => Promise<void>;
readonly refetch: () => Promise<void>;
}
job-mutation-hooks.ts
JobMutationOptions
Signature
declare const JobMutationOptions: JobMutationOptions<Output, Failure, Input, Context>;
useJobCancel
Adapts an idempotent job cancellation request into TanStack mutation state.
Signature
declare const useJobCancel: <Name extends JobCancelName, Context = unknown>(
name: Name,
options?: JobMutationOptions<
JobCancelOutputFor<Name>,
JobFailureFor<Name>,
JobCancelInputFor<Name>,
Context
>,
) => UseMutationResult<
JobCancelOutputFor<Name>,
JobFailureFor<Name>,
JobCancelInputFor<Name>,
Context
>;
useJobRetry
Adapts an explicit job retry request into TanStack mutation state.
Signature
declare const useJobRetry: <Name extends JobRetryName, Context = unknown>(
name: Name,
options?: JobMutationOptions<
JobRetryOutputFor<Name>,
JobFailureFor<Name>,
JobRetryInputFor<Name>,
Context
>,
) => UseMutationResult<
JobRetryOutputFor<Name>,
JobFailureFor<Name>,
JobRetryInputFor<Name>,
Context
>;
useJobTrigger
Adapts a declared job trigger and its pending authority into TanStack mutation state.
Signature
declare const useJobTrigger: <Name extends JobTriggerName, Context = unknown>(
name: Name,
options?: JobMutationOptions<
JobTriggerOutputFor<Name>,
JobFailureFor<Name>,
JobTriggerInputFor<Name>,
Context
>,
) => UseMutationResult<
JobTriggerOutputFor<Name>,
JobFailureFor<Name>,
JobTriggerInputFor<Name>,
Context
>;
job-mutation-hooks.types.ts
JobMutationOptions (type alias)
Job mutation options preserving operation identity, retry and TanStack callback inference.
Signature
type JobMutationOptions<Output, Failure, Input, Context> = Omit<
UseMutationOptions<Output, Failure, Input, Context>,
"mutationKey" | "mutationFn"
> & { readonly jobId?: string };
job-mutation-support.ts
controlReferences
Retains the existing run reference in a job control receipt.
Signature
declare const controlReferences: (input: unknown) => { readonly runId?: string };
offline
Reads the browser online hint synchronously without acquiring resources.
Signature
declare const offline: () => boolean;
settlePending
Applies the existing authoritative or unknown receipt settlement policy.
Signature
declare const settlePending: (
scopeKey: string,
pending: PendingOperationMetadata,
error: unknown,
) => void;
writableScope
Requires ready identity authority before an accepted-work dispatch.
Signature
declare const writableScope: (
runtime: RelkitClientRuntime,
) => NonNullable<RelkitClientRuntime["scope"]>;
keys.ts
RelkitJobKeyOptions
Signature
declare const RelkitJobKeyOptions: RelkitJobKeyOptions;
RelkitKeyScope
Signature
declare const RelkitKeyScope: RelkitKeyScope;
relkitJobKey
Constructs the canonical scope-complete job observation or mutation key.
Signature
declare const relkitJobKey: (
scope: RelkitKeyScope,
operation: "trigger" | "run" | "cancel" | "retry",
options: RelkitJobKeyOptions,
input?: unknown,
) => readonly unknown[];
relkitKey
Constructs the canonical scope-complete finite query or mutation key.
Signature
declare const relkitKey: (
scope: RelkitKeyScope,
kind: "query" | "mutation" | "stream" | "agent" | "channel",
procedureId: string,
input?: unknown,
) => readonly unknown[];
keys.types.ts
Backend, fingerprint, transport, identity and session boundaries of cached client work.
RelkitJobKeyOptions (interface)
Run, cursor, named-content and projection fields participating in a job cache key.
Signature
export interface RelkitJobKeyOptions {
readonly jobId: string;
readonly runId?: string;
readonly projection?: string;
readonly schemaVersion?: string;
readonly environment?: string;
readonly jobsProtocolVersion?: number;
}
RelkitKeyScope (interface)
Backend, fingerprint, transport, identity and session boundaries of cached client work.
Signature
export interface RelkitKeyScope {
readonly backend: string;
readonly applicationId: string;
readonly identityScope: string;
readonly sessionEpoch: string;
readonly identityKey: string | null | undefined;
readonly publicFingerprint: string;
readonly environment?: string;
readonly jobsProtocolVersion?: number;
}
mutation-runtime.ts
mutationOperations
Once-acquired submission service at the Promise/React compatibility boundary.
Signature
declare const mutationOperations: MutationOperationsService;
mutationRuntime
Signature
declare const mutationRuntime: ManagedRuntime.ManagedRuntime<MutationOperations, never>;
mutation.service.ts
MutationOperations (class)
Accepted-work dispatch and authoritative pending settlement contract.
Signature
declare class MutationOperations
MutationOperationsLive
Acquires accepted-work submission and pending-outcome settlement.
See
- tests/compatibility/pending.test.ts for checked metadata and recovery behavior.
Signature
declare const MutationOperationsLive: Layer.Layer<MutationOperations, never, PendingOperations>;
mutation.service.types.ts
MutationOperationsService (interface)
Accepted-work submission authority shared by finite and job React adapters.
Signature
export interface MutationOperationsService {
/** Dispatches accepted work independently of the submitting view lifetime.
* @param scope - Complete pending receipt isolation scope.
* @param kind - Existing submission category.
* @param resource - Declared route or job identity.
* @param input - Transmitted input retained only in opted-in memory.
* @param references - Existing receipt references.
* @param options - Existing idempotency, reuse and retention policy.
* @param execute - Native server submission boundary.
* @returns A lazy observed original result or rejection after metadata settlement. */
readonly submit: (
scope: string,
kind: PendingOperationMetadata["kind"],
resource: string,
input: unknown,
references: PendingReferences,
options: PendingRememberOptions,
execute: () => PromiseLike<unknown>,
) => Effect.Effect<unknown, unknown>;
/** Applies the existing unknown-outcome policy to receipt metadata.
* @param scope - Complete pending receipt isolation scope.
* @param pending - Previously stored metadata.
* @param error - Original native rejection.
* @returns A lazy observed metadata update; submission preserves the original rejection. */
readonly settle: (
scope: string,
pending: PendingOperationMetadata,
error: unknown,
) => Effect.Effect<void>;
}
pending-errors.ts
MAX_JOB_INTENTS
Signature
declare const MAX_JOB_INTENTS: 100;
PendingCapacityError (class)
Signature
declare class PendingCapacityError {
constructor();
}
code (property)
Signature
readonly code: "RELKIT_PENDING_CAPACITY"
PendingRecoveryUnavailableError (class)
Signature
declare class PendingRecoveryUnavailableError {
constructor();
}
code (property)
Signature
readonly code: "RELKIT_PENDING_RECOVERY_UNAVAILABLE"
PendingRequestMismatchError (class)
Signature
declare class PendingRequestMismatchError {
constructor();
}
code (property)
Signature
readonly code: "RELKIT_PENDING_REQUEST_MISMATCH"
pending-outcome.ts
jobUnknownOutcome
Extracts recognized recovery authority without manufacturing successful outcomes.
Signature
declare const jobUnknownOutcome: (value: unknown) => JobUnknownOutcome | undefined;
pending-store.ts
PENDING_PREFIX
Signature
declare const PENDING_PREFIX: "relkit.pending.";
clearPendingStorage
Retires all persisted receipt metadata in one complete identity scope.
Signature
declare const clearPendingStorage: (scopeKey: string) => void;
pendingEntryKey
Constructs the existing persistence key for one scoped receipt.
Signature
declare const pendingEntryKey: (scopeKey: string, operationId: string) => string;
pendingMemory
Signature
declare const pendingMemory: Map<
string,
{ readonly metadata: PendingOperationMetadata; readonly request?: unknown }
>;
readPendingStorage
Recovers selectively validated metadata while isolating malformed entries.
Signature
declare const readPendingStorage: (scopeKey: string) => Map<string, PendingOperationMetadata>;
removePendingStorage
Removes persisted receipt metadata without surfacing unavailable browser storage.
Signature
declare const removePendingStorage: (key: string) => void;
writePendingStorage
Persists metadata best-effort without persisting transmitted requests.
Signature
declare const writePendingStorage: (key: string, value: PendingOperationMetadata) => void;
pending-support.ts
Enumerates only the existing nested public recovery envelopes.
candidates
Enumerates only the existing nested public recovery envelopes.
Signature
declare const candidates: (value: unknown) => readonly unknown[];
isRecord
Checks whether the existing property-access boundary accepts a supplied value.
Signature
declare const isRecord: (value: unknown) => value is Record<string, unknown>;
pending.schemas.ts
PersistedPendingMetadata
Legacy persisted metadata authority: only operationId was required on recovery.
Signature
declare const PersistedPendingMetadata: Schema.Struct<{ readonly operationId: Schema.String }>;
isPersistedPendingMetadata
Validates the recovery discriminator without stripping other legacy fields.
Signature
declare const isPersistedPendingMetadata: <I>(
input: I,
) => input is I & { readonly operationId: string };
pending.service.ts
PendingOperations (class)
Submission receipts, recovery authority and memory-only transmitted requests.
Signature
declare class PendingOperations
pendingOperationsLayer
Acquires pending state once; storage remains a best-effort native persistence edge.
Example
import { Effect, ManagedRuntime } from "effect";
import { PendingOperations, pendingOperationsLayer } from "./pending.service.js";
export async function pendingOwner(): Promise<void> {
const owner = ManagedRuntime.make(pendingOperationsLayer(new Map()));
try {
await owner.runPromise(
Effect.flatMap(PendingOperations, (service) => service.digest({ input: 1 })),
);
} finally {
await owner.dispose();
}
}
See
- packages/client/tests/transport/examples.test.ts for the checked live Layer example.
Signature
declare const pendingOperationsLayer: (
memory?: Map<string, { readonly metadata: PendingOperationMetadata; readonly request?: unknown }>,
) => Layer.Layer<PendingOperations>;
pending.ts
PendingCapacityError
Signature
declare const PendingCapacityError: typeof PendingCapacityError;
PendingRecoveryUnavailableError
Signature
declare const PendingRecoveryUnavailableError: typeof PendingRecoveryUnavailableError;
PendingRememberOptions
Signature
declare const PendingRememberOptions: PendingRememberOptions;
PendingRequestMismatchError
Signature
declare const PendingRequestMismatchError: typeof PendingRequestMismatchError;
clearPendingOperations
Clears every receipt in an explicitly retired identity scope.
Signature
declare const clearPendingOperations: (scopeKey: string) => void;
digestPendingRequest
Hashes the existing canonical transmitted request representation.
Signature
declare const digestPendingRequest: (value: unknown) => Promise<string>;
forgetPending
Removes memory and best-effort persisted metadata after a known outcome.
Signature
declare const forgetPending: (scopeKey: string, operationId: string) => void;
isJobUnknownOutcome
Checks nested public error envelopes for an unknown job outcome.
Signature
declare const isJobUnknownOutcome: (value: unknown) => value is JobUnknownOutcome;
jobUnknownOutcome
Signature
declare const jobUnknownOutcome: (value: unknown) => JobUnknownOutcome | undefined;
matchesPendingRequest
Compares a proposed retry against its recorded transmitted request digest.
Signature
declare const matchesPendingRequest: (
scopeKey: string,
operationId: string,
request: unknown,
) => Promise<boolean>;
pendingOperations
Merges recovered metadata with newer in-memory values without discarding authority.
Signature
declare const pendingOperations: (scopeKey: string) => readonly PendingOperationMetadata[];
pendingRequest
Reads a transmitted request; restored session metadata never recreates input.
Signature
declare const pendingRequest: (scopeKey: string, operationId: string) => unknown;
pendingScopeKey
Preserves the complete existing scope serialization used by query and receipt keys.
Signature
declare const pendingScopeKey: (scope: RelkitKeyScope) => string;
rememberJobPending
Remembers a job intent and retains its transmitted request only in memory.
Signature
declare const rememberJobPending: (
scopeKey: string,
resourceId: string,
request: unknown,
options?: PendingRememberOptions,
) => Promise<PendingOperationMetadata>;
rememberPending
Records a submission before dispatch without persisting its sensitive request.
Signature
declare const rememberPending: (
scopeKey: string,
kind: PendingOperationMetadata["kind"],
resourceId: string,
value: unknown,
references?: PendingReferences,
options?: PendingRememberOptions,
) => Promise<PendingOperationMetadata>;
updatePending
Updates metadata while preserving a previously retained in-memory request.
Signature
declare const updatePending: (scopeKey: string, value: PendingOperationMetadata) => void;
pending.types.ts
PendingOperationService (interface)
One browser’s pending-operation state with isolated live/test implementations.
Signature
export interface PendingOperationService {
/** Records validated metadata while retaining original input only in opted-in memory.
* @param scope - Complete application and identity isolation scope.
* @param kind - Existing submission category.
* @param resource - Declared job, route or agent key.
* @param value - Original transmitted request payload.
* @param references - Existing durable receipt references.
* @param options - Existing operation identity, reuse and retention policy.
* @returns Lazy observed metadata creation or the original hashing/capacity failure. */
readonly remember: (
scope: string,
kind: PendingOperationMetadata["kind"],
resource: string,
value: unknown,
references: PendingReferences,
options: PendingRememberOptions,
) => Effect.Effect<PendingOperationMetadata, unknown>;
/** Replaces persisted metadata without persisting request inputs.
* @param scope - Complete pending isolation scope.
* @param value - Existing receipt metadata with its updated outcome.
* @returns A synchronous observed best-effort metadata update. */
readonly update: (scope: string, value: PendingOperationMetadata) => Effect.Effect<void>;
/** Removes one settled receipt and its memory-only request.
* @param scope - Complete pending isolation scope.
* @param id - Existing operation identity.
* @returns A synchronous observed state update. */
readonly forget: (scope: string, id: string) => Effect.Effect<void>;
/** Lists metadata using the existing selective persistence validation.
* @param scope - Complete pending isolation scope.
* @returns A synchronous observed metadata snapshot. */
readonly list: (scope: string) => Effect.Effect<readonly PendingOperationMetadata[]>;
/** Reads opted-in memory input without recovering payloads from persisted metadata.
* @param scope - Complete pending isolation scope.
* @param id - Existing operation identity.
* @returns A synchronous observed original input when retained. */
readonly request: (scope: string, id: string) => Effect.Effect<unknown>;
/** Clears receipt metadata and retained memory input for one isolation scope.
* @param scope - Complete pending isolation scope.
* @returns A synchronous observed state update. */
readonly clear: (scope: string) => Effect.Effect<void>;
/** Checks a request digest against stored receipt metadata.
* @param scope - Complete pending isolation scope.
* @param id - Existing operation identity.
* @param value - Original request payload whose digest is compared.
* @returns A lazy observed match decision or the original hashing failure. */
readonly matches: (scope: string, id: string, value: unknown) => Effect.Effect<boolean, unknown>;
/** Hashes canonical JSON through the existing WebCrypto boundary.
* @param value - Original payload whose canonical representation is hashed.
* @returns A lazy observed SHA-256 digest or the original serialization/crypto failure. */
readonly digest: (value: unknown) => Effect.Effect<string, unknown>;
}
PendingReferences (type alias)
References persisted with metadata; transmitted inputs remain memory-only.
Signature
type PendingReferences = Pick<PendingOperationMetadata, "threadId" | "runId">;
PendingRememberOptions (interface)
Submission/recovery authority retained from the existing pending API.
Signature
export interface PendingRememberOptions {
readonly operationId?: string;
readonly idempotencyKey?: string;
readonly recovery?: JobUnknownOutcome["recovery"];
readonly retainRequest?: boolean;
}
procedure.ts
ProcedureUtilsLike
Signature
declare const ProcedureUtilsLike: ProcedureUtilsLike;
procedureCall
Resolves a callable generated procedure using exact selector semantics.
Signature
declare const procedureCall: (
root: unknown,
selector: string | readonly string[],
) => (...args: unknown[]) => unknown;
procedureUtils
Resolves generated TanStack utilities using exact selector semantics.
Signature
declare const procedureUtils: (
root: unknown,
selector: string | readonly string[],
) => ProcedureUtilsLike;
resolveProcedure
Resolves generated paths without changing exact dotted route-key semantics.
Signature
declare const resolveProcedure: (root: unknown, selector: string | readonly string[]) => unknown;
procedure.types.ts
ProcedureUtilsLike (interface)
Generated TanStack query/mutation options and keys resolved by exact selector.
Signature
export interface ProcedureUtilsLike {
queryOptions(options: object): object;
infiniteOptions(options: object): object;
mutationOptions(options?: object): object;
queryKey(options?: object): QueryKey;
infiniteKey(options?: object): QueryKey;
mutationKey(options?: object): QueryKey;
}
realtime-hook.ts
ChannelHandlers
Signature
declare const ChannelHandlers: Partial<{
readonly [Event in keyof EventsFor<Name>]: (payload: EventsFor<Name>[Event]) => void;
}>;
UseChannelOptions
Signature
declare const UseChannelOptions: UseChannelOptions<Name>;
UseChannelResult
Signature
declare const UseChannelResult: UseChannelResult<Name>;
UseRealtimeResult
Signature
declare const UseRealtimeResult: UseRealtimeResult;
useChannel
Borrows one shared channel session and projects ordered frames into React state.
Signature
declare const useChannel: <Name extends ChannelSelector>(
name: Name,
options: UseChannelOptions<Name>,
) => UseChannelResult<Name>;
useRealtime
Adapts manager status and explicit subscription leases into React’s external store.
Signature
declare const useRealtime: () => UseRealtimeResult;
realtime-hook.types.ts
ChannelFor (type alias)
The channel registry entry inferred from its declared name.
Signature
type ChannelFor<Name extends ChannelSelector> = ChannelRegistry[Name];
ChannelHandlers (type alias)
Typed handlers keyed by the declared channel’s event names.
Signature
type ChannelHandlers<Name extends ChannelSelector> = Partial<{
readonly [Event in keyof EventsFor<Name>]: (payload: EventsFor<Name>[Event]) => void;
}>;
ChannelState (interface)
Current checkpoint, connection status, events and presence projection.
Signature
export interface ChannelState {
readonly status: RealtimeStatus;
readonly checkpoint?: ChannelCheckpoint;
readonly caughtUp: boolean;
readonly gap?: string;
readonly presence?: unknown;
}
EventsFor (type alias)
Event payloads inferred from the declared channel.
Signature
type EventsFor<Name extends ChannelSelector> =
ChannelFor<Name> extends { readonly events: infer Events } ? Events : never;
ParamsFor (type alias)
Channel parameter input inferred from the declared channel.
Signature
type ParamsFor<Name extends ChannelSelector> =
ChannelFor<Name> extends { readonly params: infer Params } ? Params : never;
PresenceFor (type alias)
Presence state inferred from the declared channel.
Signature
type PresenceFor<Name extends ChannelSelector> =
ChannelFor<Name> extends { readonly presence: infer Presence } ? Presence : never;
UseChannelOptions (interface)
Channel parameters and current-view event handlers.
Signature
export interface UseChannelOptions<Name extends ChannelSelector> {
readonly params: ParamsFor<Name>;
readonly on?: ChannelHandlers<Name>;
readonly onCaughtUp?: () => void | Promise<void>;
readonly onGap?: (reason: string) => void | Promise<void>;
}
UseChannelResult (type alias)
Typed channel projection and explicit realtime controls.
Signature
type UseChannelResult<Name extends ChannelSelector> = Omit<ChannelState, "presence"> &
([PresenceFor<Name>] extends [never] ? {} : { readonly presence: PresenceFor<Name> });
UseRealtimeResult (interface)
Realtime connection state with explicit channel observer controls.
Signature
export interface UseRealtimeResult {
readonly status: RealtimeStatus;
readonly subscribe: <Name extends ChannelSelector>(
name: Name,
params: ParamsFor<Name>,
listener: (frame: RealtimeFrame) => void,
) => () => void;
readonly bind: UseRealtimeResult["subscribe"];
readonly unbind: (unsubscribe: () => void) => void;
readonly unsubscribe: (unsubscribe: () => void) => void;
}
realtime-manager.ts
RealtimeFrame
Signature
declare const RealtimeFrame: RealtimeFrame;
RealtimeManager (class)
Synchronous external-store adapter over one scoped realtime session owner.
Signature
declare class RealtimeManager {
constructor(
client: unknown,
identity?: Pick<ClientIdentityDocument, "identityScope" | "sessionEpoch">,
);
}
subscribe (method)
Borrows a shared channel without letting one observer close another’s request.
Signature
declare const subscribe: (
channel: string,
params: unknown,
listener: (frame: RealtimeFrame) => void,
statusListener?: (status: RealtimeStatus) => void,
) => () => void;
listenStatus (method)
Subscribes to manager status changes for React’s synchronous external store.
Signature
declare const listenStatus: (listener: () => void) => () => void;
dispose (method)
Initiates disposal synchronously; close joins native iterator cleanup.
Signature
declare const dispose: () => void;
close (method)
Joins the manager’s finalization, including pending native pulls and retries.
Signature
declare const close: () => Promise<void>;
RealtimeStatus
Signature
declare const RealtimeStatus: RealtimeStatus;
realtimeSubscriptionKey
Signature
declare const realtimeSubscriptionKey: (channel: string, params: unknown) => string;
realtime-manager.types.ts
RealtimeFrame (type alias)
Public channel frames retained without changing wire schemas.
Signature
type RealtimeFrame =
| {
readonly kind: "event";
readonly event: string;
readonly payload: unknown;
readonly checkpoint: ChannelCheckpoint;
}
| { readonly kind: "caught-up"; readonly checkpoint: ChannelCheckpoint }
| { readonly kind: "gap"; readonly reason: string; readonly checkpoint: ChannelCheckpoint }
| { readonly kind: "presence"; readonly presence: PresenceSnapshot };
RealtimeSessionService (interface)
Realtime state and scoped workflows supplied by live and test Layers.
Signature
export interface RealtimeSessionService {
readonly feeds: Map<string, SharedSubscription>;
readonly statusListeners: Set<() => void>;
/** Reads the current pure external-store status.
* @returns A synchronous state read without native acquisition. */
readonly snapshot: () => Effect.Effect<RealtimeStatus>;
/** Registers a manager-local view over a complete-key scoped native connection.
* @param channel - Declared channel key.
* @param params - Complete native channel parameters.
* @param listener - Isolated synchronous frame publication.
* @param statusListener - Optional isolated lifecycle publication.
* @returns A synchronous registration Effect yielding independently releasable view ownership. */
readonly subscribe: (
channel: string,
params: unknown,
listener: (frame: RealtimeFrame) => void,
statusListener?: (status: RealtimeStatus) => void,
) => Effect.Effect<Effect.Effect<void>>;
/** Initiates cancellation of all scoped native connections and resets idle state.
* @returns A synchronous cancellation request; owner closure joins native workers. */
readonly stop: () => Effect.Effect<void>;
}
RealtimeStatus (type alias)
Existing realtime external-store states.
Signature
type RealtimeStatus = "idle" | "connecting" | "connected" | "stale" | "error";
SharedSubscription (interface)
One connection shared inside its manager’s authorization identity.
Signature
export interface SharedSubscription {
readonly controller: AbortController;
readonly listeners: Set<(frame: RealtimeFrame) => void>;
readonly statusListeners: Set<(status: RealtimeStatus) => void>;
status: RealtimeStatus;
checkpoint?: ChannelCheckpoint;
fiber?: Fiber.Fiber<void, unknown>;
}
realtime-session-key.ts
Constructs a manager-local sharing key without losing parameter distinctions.
realtimeSubscriptionKey
Constructs a manager-local sharing key without losing parameter distinctions.
Signature
declare const realtimeSubscriptionKey: (channel: string, params: unknown) => string;
realtime-session.service.ts
RealtimeSessions (class)
One manager’s sharing registry, checkpoints and reconnect workers.
Signature
declare class RealtimeSessions
realtimeSessionsLayer
Acquires one synchronous registry with scoped, lazy native workers.
Example
import { ManagedRuntime } from "effect";
import { runExecutionSync } from "@relkit/contracts/operation";
import { RealtimeSessions, realtimeSessionsLayer } from "./realtime-session.service.js";
export async function realtimeOwner(): Promise<void> {
const owner = ManagedRuntime.make(realtimeSessionsLayer({}));
try {
const sessions = runExecutionSync(owner, RealtimeSessions);
} finally {
await owner.dispose();
}
}
See
- packages/client/tests/transport/examples.test.ts for the checked live Layer example.
Signature
declare const realtimeSessionsLayer: (
client: unknown,
identity?: Pick<ClientIdentityDocument, "identityScope" | "sessionEpoch">,
) => Layer.Layer<RealtimeSessions>;
registry.ts
Augmentable application registry of exact procedure contracts.
“./registry.types.js” (namespace export)
Re-exports all named exports from the “./registry.types.js” module.
Signature
export * from "./registry.types.js";
AgentRegistry (interface)
Augmentable application registry of declared agent contracts.
Signature
export interface AgentRegistry {}
ChannelRegistry (interface)
Augmentable application registry of declared channel contracts.
Signature
export interface ChannelRegistry {}
ClientRegistry (interface)
Augmentable application registry of exact procedure contracts.
Signature
export interface ClientRegistry {}
registry.types.ts
AgentSelector (type alias)
String keys of the declared agent registry.
Signature
type AgentSelector = Extract<keyof AgentRegistry, string>;
ChannelSelector (type alias)
String keys of the declared channel registry.
Signature
type ChannelSelector = Extract<keyof ChannelRegistry, string>;
ClientAgentContract (interface)
Generated agent declaration preserving execution, payload and control capabilities.
Signature
export interface ClientAgentContract<
Input = unknown,
Output = unknown,
Controls extends string = never,
Chat extends boolean = false,
Resume = never,
Tool = never,
PublicState = Readonly<Record<never, never>>,
CustomEvent = never,
Scope = ClientAgentDynamic,
Waiting = never,
> {
readonly input: Input;
readonly output: Output;
readonly controls: Controls;
readonly chat: Chat;
readonly resume: Resume;
readonly tool: Tool;
readonly publicState: PublicState;
readonly customEvent: CustomEvent;
readonly scope: Scope;
readonly waiting: Waiting;
}
ClientAgentDynamic (interface)
Dynamic agent capability marker retaining the existing broad compatibility contract.
Signature
export interface ClientAgentDynamic {
readonly kind: "dynamic";
readonly data: unknown;
}
ClientChannelContract (interface)
Generated channel declaration preserving params, event and presence inference.
Signature
export interface ClientChannelContract<
Params = unknown,
Events extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,
Presence = never,
> {
readonly params: Params;
readonly events: Events;
readonly presence: Presence;
}
ClientRouteContract (interface)
Generated finite route declaration preserving payload and failure inference.
Signature
export interface ClientRouteContract<
Input = unknown,
Output = unknown,
Failure = globalThis.Error,
> {
readonly input: Input;
readonly output: Output;
readonly error: Failure;
readonly operation: "query" | "mutation";
readonly stream: false;
}
ClientSelector (type alias)
String keys of the declared procedure registry.
Signature
type ClientSelector = Extract<keyof ClientRegistry, string>;
ClientStreamContract (interface)
Generated route stream declaration preserving item and failure inference.
Signature
export interface ClientStreamContract<Input = unknown, Item = unknown, Failure = globalThis.Error> {
readonly input: Input;
readonly output: AsyncIterable<Item>;
readonly item: Item;
readonly error: Failure;
readonly operation: "query" | "mutation";
readonly stream: true;
}
ContractFor (type alias)
Looks up one exact application procedure contract.
Signature
type ContractFor<Name extends ClientSelector> = ClientRegistry[Name];
ErrorFor (type alias)
Infers the declared failure of one exact application procedure.
Signature
type ErrorFor<Name extends ClientSelector> =
ContractFor<Name> extends {
readonly error: infer Error;
}
? Error
: never;
FiniteSelector (type alias)
Declared procedure keys whose result is finite.
Signature
type FiniteSelector = {
[Name in ClientSelector]: ClientRegistry[Name] extends { readonly stream: false } ? Name : never;
}[ClientSelector];
InputFor (type alias)
Infers the input of one exact application procedure.
Signature
type InputFor<Name extends ClientSelector> =
ContractFor<Name> extends {
readonly input: infer Input;
}
? Input
: never;
ItemFor (type alias)
Infers the item payload of one exact application stream.
Signature
type ItemFor<Name extends StreamSelector> =
ContractFor<Name> extends {
readonly item: infer Item;
}
? Item
: never;
JobCancelInput
Signature
declare const JobCancelInput: JobCancelInput;
JobClientField
Signature
declare const JobClientField: JobClientField;
JobContract
Signature
declare const JobContract: JobContract<
Name,
JobId,
Input,
Output,
Failure,
Progress,
Streams,
Operations,
Fields
>;
JobFor
Signature
declare const JobFor: JobFor<Name>;
JobGetInput
Signature
declare const JobGetInput: JobGetInput;
JobListInput
Signature
declare const JobListInput: JobListInput;
JobListQuery
Signature
declare const JobListQuery: JobListQuery;
JobProcedureContract
Signature
declare const JobProcedureContract: JobProcedureContract<Input, Output, Failure>;
JobProcedureSelector
Signature
declare const JobProcedureSelector: JobProcedureSelector<Name>;
JobRegistry
Signature
declare const JobRegistry: JobRegistry;
JobRetryInput
Signature
declare const JobRetryInput: JobRetryInput;
JobRunSelector
Signature
declare const JobRunSelector: JobRunSelector<Name>;
JobSelector
Signature
declare const JobSelector: never;
JobSnapshotFor
Signature
declare const JobSnapshotFor: JobSnapshotFor<Input, Output, Progress, Failure, Fields>;
JobStreamInput
Signature
declare const JobStreamInput: JobStreamInput<StreamName>;
JobStreamProcedureContract
Signature
declare const JobStreamProcedureContract: JobStreamProcedureContract<Input, Item, Failure>;
JobTriggerInput
Signature
declare const JobTriggerInput: JobTriggerInput<Input>;
JobTriggerOptions
Signature
declare const JobTriggerOptions: JobTriggerOptions;
JobTriggerSelector
Signature
declare const JobTriggerSelector: JobTriggerSelector<Name>;
JobWatchInput
Signature
declare const JobWatchInput: JobWatchInput;
MutationSelector (type alias)
Declared finite mutation procedure keys.
Signature
type MutationSelector = {
[Name in FiniteSelector]: ClientRegistry[Name] extends { readonly operation: "mutation" }
? Name
: never;
}[FiniteSelector];
OutputFor (type alias)
Infers the successful output of one exact application procedure.
Signature
type OutputFor<Name extends ClientSelector> =
ContractFor<Name> extends {
readonly output: infer Output;
}
? Output
: never;
QuerySelector (type alias)
Declared finite query procedure keys.
Signature
type QuerySelector = {
[Name in FiniteSelector]: ClientRegistry[Name] extends { readonly operation: "query" }
? Name
: never;
}[FiniteSelector];
SelectedJobField
Signature
declare const SelectedJobField: SelectedJobField<Fields, Field>;
StreamSelector (type alias)
Declared procedure keys whose result is streamed.
Signature
type StreamSelector = {
[Name in ClientSelector]: ClientRegistry[Name] extends { readonly stream: true } ? Name : never;
}[ClientSelector];
stream-hook.ts
StreamState
Signature
declare const StreamState: StreamState<Item, Error>;
UseStreamResult
Signature
declare const UseStreamResult: UseStreamResult<Input, Item, Error>;
useStream
Adapts a declared scoped stream into React state and explicit cancellation controls.
Signature
declare const useStream: <Name extends StreamSelector>(
name: Name,
options?: { readonly autoStart?: boolean; readonly input?: InputFor<Name> },
) => UseStreamResult<InputFor<Name>, ItemFor<Name>, ErrorFor<Name>>;
stream-hook.types.ts
Current stream lifecycle, latest item, retained item history and original failure.
StreamState (interface)
Current stream lifecycle, latest item, retained item history and original failure.
Signature
export interface StreamState<Item, Error> {
readonly status: "idle" | "starting" | "streaming" | "completed" | "cancelled" | "error";
readonly items: readonly Item[];
readonly error?: Error;
}
UseStreamResult (interface)
Typed stream state with explicit start and cancellation controls.
Signature
export interface UseStreamResult<Input, Item, Error> extends StreamState<Item, Error> {
readonly start: (input: Input) => Promise<void>;
readonly cancel: () => void;
readonly reset: () => void;
}
stream-runtime.ts
clientStreams
Once-acquired stream service whose call fibers own all native requests.
Signature
declare const clientStreams: ClientStreamService;
streamRuntime
Signature
declare const streamRuntime: ManagedRuntime.ManagedRuntime<ClientStreams, never>;
stream.service.ts
ClientStreams (class)
Arbitrary declared procedure observation lifetime, independent of React.
Signature
declare class ClientStreams
ClientStreamsLive
Supplies declared procedure streams with scoped native pulls.
See
- tests/transport/native.test.ts for checked pending-pull cancellation at the Bun boundary.
Signature
declare const ClientStreamsLive: Layer.Layer<ClientStreams, never, never>;
stream.service.types.ts
ClientStreamService (interface)
Declared procedure observation with borrowed external-store callbacks.
Signature
export interface ClientStreamService {
/** Owns declared native pulls and external-store publication until cancellation.
* @param client - Borrowed generated transport.
* @param name - Exact declared procedure key.
* @param input - Original request payload.
* @param signal - View lifetime propagated to the native transport.
* @param opened - Synchronous establishment publication.
* @param publish - Isolated synchronous item publication.
* @returns A lazy scoped observation preserving native errors and joining cleanup. */
readonly consume: (
client: unknown,
name: string,
input: unknown,
signal: AbortSignal,
opened: () => void,
publish: (item: unknown) => void,
) => Effect.Effect<void, unknown>;
}
view-owner.ts
Retains an owner across React’s synchronous development cleanup/setup replay.
borrowViewOwner
Retains an owner across React’s synchronous development cleanup/setup replay.
Signature
declare const borrowViewOwner: (
owner: object,
close: () => void,
leases: WeakMap<object, object>,
) => () => void;
write-error.ts
RelkitWriteError (class)
Signature
declare class RelkitWriteError { constructor(
readonly outcome: "not-sent" | "unknown",
message: string,
) }
server-context.ts
Implements the opt-in Bun server query context and identity-bound hydration. Install @orpc/tanstack-query@2.0.0-beta.31 and @tanstack/query-core@^5 alongside
CreateRelkitServerContextOptions
Signature
declare const CreateRelkitServerContextOptions: CreateRelkitServerContextOptions;
RelkitServerContext
Signature
declare const RelkitServerContext: RelkitServerContext;
RelkitServerHydrationState
Signature
declare const RelkitServerHydrationState: RelkitServerHydrationState;
createRelkitServerContext
Forwards request identity into a server client and scope-bound hydration state.
Signature
declare const createRelkitServerContext: (
options: CreateRelkitServerContextOptions,
) => Promise<RelkitServerContext>;
server-context.types.ts
Describes server query hydration using query-core types alone. The React provider accepts this structural hydration result without making its own declarations part of the server integration’s dependency graph.
CreateRelkitServerContextOptions (interface)
Server request, backend and query-client configuration for one hydration context.
Signature
export interface CreateRelkitServerContextOptions {
readonly baseUrl: string;
readonly request: Request;
readonly queryClient: QueryClient;
readonly identityKey?: string | null;
}
RelkitServerContext (interface)
Typed finite client, TanStack utilities and dehydrated server query state.
Signature
export interface RelkitServerContext {
readonly client: ReturnType<typeof createClient<DefaultContract>>;
readonly utils: ReturnType<typeof createTanstackQueryUtils<RelkitServerContext["client"]>>;
readonly identity: ClientIdentityDocument;
readonly dehydrate: () => RelkitServerHydrationState;
}
RelkitServerHydrationState (interface)
Identity-bound query snapshot accepted by the React provider on hydration.
Signature
export interface RelkitServerHydrationState {
/** Backend, application and session authority attached to the cached data. */
readonly scope: RelkitKeyScope;
/** Native query-core snapshot, preserving query and mutation metadata. */
readonly dehydrated: DehydratedState;
}
server.ts
Adds request-time tracing to the Bun server transport without loading frontend bindings. TanStack hydration is exposed by @relkit/client/server/tanstack-query and requires that integration’s documented frontend peers.
createServerClient
Bun server client with operation-time W3C propagation. Response bodies remain untouched.
Signature
declare const createServerClient: <Contract extends RouterContract = RouterContract>(
options: CreateClientOptions,
) => RouterContractClient<Contract>;
tanstack-query.ts
Reexports oRPC’s query adapter without adding it to the transport dependency graph. Install @orpc/tanstack-query@2.0.0-beta.31 and @tanstack/query-core@^5 alongside @relkit/client when selecting this entrypoint.
TanstackQueryOperationContext
Signature
declare const TanstackQueryOperationContext: OperationContext;
createTanstackQueryUtils
Signature
declare const createTanstackQueryUtils: <T extends AnyNestedClient>(
client: T,
options?: NoInfer<RouterUtilsOptions<T>>,
) => RouterUtils<T>;
transport-native.ts
httpLink
Builds the native HTTP oRPC link with lazy headers and owned iterator cancellation.
Signature
declare const httpLink: (options: CreateClientOptions) => RPCLink<Record<PropertyKey, unknown>>;
webSocketEndpoint
Resolves the RPC WebSocket endpoint and canonical agent capability query.
Signature
declare const webSocketEndpoint: (baseUrl: string) => URL;
webSocketLink
Builds the native oRPC WebSocket link while retaining SDK reconnect ownership.
Signature
declare const webSocketLink: (
options: CreateWebSocketClientOptions,
Socket: typeof WebSocket,
connect?: () => Promise<WebSocket>,
) => WebSocketRPCLink<Record<PropertyKey, unknown>>;
transport-socket.ts
connectSocket
Establishes a socket through an interruptible Clock deadline and native callback.
Signature
declare const connectSocket: (
Socket: typeof WebSocket,
endpoint: URL,
timeoutMs: number,
) => Promise<WebSocket>;
connectSocketEffect
Owns establishment callbacks until socket ownership transfers to oRPC.
Signature
declare const connectSocketEffect: (
Socket: {
new (url: string | URL, options?: Bun.WebSocketOptions): WebSocket;
new (url: string | URL, protocols?: string | string[]): WebSocket;
prototype: WebSocket;
readonly CONNECTING: 0;
readonly OPEN: 1;
readonly CLOSING: 2;
readonly CLOSED: 3;
},
endpoint: URL,
timeoutMs: number,
) => Effect.Effect<WebSocket, unknown, never>;
transport.service.ts
ClientTransport (class)
Configured transport selection and invocation authority, without server dependencies.
Signature
declare class ClientTransport
clientTransportLayer
Acquires one link owner with a lazy, shared transport-selection decision.
Example
import { Effect, ManagedRuntime } from "effect";
import { runExecutionSync } from "@relkit/contracts/operation";
import { ClientTransport, clientTransportLayer } from "./transport.service.js";
export async function transportOwner(): Promise<void> {
const owner = ManagedRuntime.make(clientTransportLayer(Effect.succeed({ call: async () => 1 })));
try {
const transport = runExecutionSync(owner, ClientTransport);
} finally {
await owner.dispose();
}
}
See
- packages/client/tests/transport/examples.test.ts for executable ownership examples.
Signature
declare const clientTransportLayer: (
select: Effect.Effect<TransportLink, unknown, Scope.Scope>,
) => Layer.Layer<ClientTransport>;
selectAutoTransport
Selects WebSocket once, falling back only when initial establishment fails.
Signature
declare const selectAutoTransport: (
options: CreateAutoClientOptions,
) => Effect.Effect<
RPCLink<Record<PropertyKey, unknown>> | RPCLink<Record<PropertyKey, unknown>>,
never,
Scope.Scope
>;
transport.ts
createClient
Creates the generated contract’s synchronous HTTP proxy with a configured service owner.
Example
import { createClient } from "@relkit/client";
export const makeClient = () => createClient({ baseUrl: "http://127.0.0.1:3000" });
Signature
declare const createClient: <Contract extends RouterContract = RouterContract>(
options: CreateClientOptions,
) => RouterContractClient<Contract>;
Since v0.1.0
createAutoClient
Creates a lazy proxy whose first transport choice is shared by concurrent calls.
Signature
declare const createAutoClient: <Contract extends RouterContract = RouterContract>(
options: CreateAutoClientOptions,
) => RouterContractClient<Contract>;
createWebSocketClient
Creates a synchronous lazy WebSocket proxy, retaining constructor availability errors.
Signature
declare const createWebSocketClient: <Contract extends RouterContract = RouterContract>(
options: CreateWebSocketClientOptions,
) => RouterContractClient<Contract>;
transport.types.ts
ClientTransportService (interface)
One configured link-selection and invocation owner.
Signature
export interface ClientTransportService {
/** Selects the owned link and invokes one declared procedure.
* @param path - Exact generated procedure path segments.
* @param input - Original request payload passed to the native link.
* @param options - Existing oRPC context, cancellation and request options.
* @returns A lazy observed invocation preserving the native result and error identity. */
readonly invoke: (
path: string[],
input: unknown,
options: ClientOptions<TransportContext>,
) => Effect.Effect<unknown, unknown>;
}
TransportContext (type alias)
Existing oRPC context retained without translating native error objects.
Signature
type TransportContext = Record<PropertyKey, unknown>;
TransportLink (type alias)
Native link dependency supplied at transport acquisition.
Signature
type TransportLink = ClientLink<TransportContext>;