LangChain API
Generated public TypeScript reference for @relkit/langchain.
For configuration and examples, read ai, tools, function tools.
Frontend usage
Observe an agent and send controls shows the client side of this capability.
Public imports
@relkit/langchain— 298 exports@relkit/langchain/runtime— 20 exports@relkit/langchain/continuation-validation— 3 exports@relkit/langchain/testing— 19 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.
client-contract-metadata.ts
Projects native agent and graph schemas into serializable client metadata; SDK-specific inspection remains inside this integration before the generic contract is published.
“./client-contract-metadata.types.js” (namespace export)
Re-exports all named exports from the “./client-contract-metadata.types.js” module.
Signature
export * from "./client-contract-metadata.types.js";
agentClientContractMetadata
Builds native agent metadata for existing synchronous callers.
Throws
The original invalid metadata error.
Example
agentClientContractMetadata(options);
Signature
declare const agentClientContractMetadata: (
options: AgentClientMetadataOptions,
) => AgentClientContractMetadata;
agentClientContractMetadataEffect
Builds client contract metadata for a native agent.
Example
Effect.runSync(agentClientContractMetadataEffect(options));
Signature
declare const agentClientContractMetadataEffect: (
options: AgentClientMetadataOptions,
) => Effect.Effect<AgentClientContractMetadata, AgentDefinitionFailure, never>;
graphClientContractMetadata
Builds graph metadata for existing synchronous callers.
Throws
The original invalid graph metadata error.
Example
graphClientContractMetadata(options);
Signature
declare const graphClientContractMetadata: (
options: GraphClientMetadataOptions,
) => AgentClientContractMetadata;
graphClientContractMetadataEffect
Builds client contract metadata for a native graph.
Example
Effect.runSync(graphClientContractMetadataEffect(options));
Signature
declare const graphClientContractMetadataEffect: (
options: GraphClientMetadataOptions,
) => Effect.Effect<AgentClientContractMetadata, GraphDefinitionFailure, never>;
client-contract-metadata.types.ts
Projects native agent and graph schemas into serializable client metadata; SDK-specific inspection remains inside this integration before the generic contract is published. This companion preserves the native input and output types without starting runtime work.
AgentClientContractMetadata (interface)
Complete metadata needed to generate an agent client contract.
Signature
export interface AgentClientContractMetadata {
readonly tools: readonly ClientToolMetadata[];
readonly state: readonly ClientTypeField[];
readonly events: readonly ClientEventMetadata[];
readonly scopes: readonly ClientScopeMetadata[];
readonly waiting: readonly ClientWaitingMetadata[];
}
AgentClientMetadataOptions (interface)
Inputs for native agent client metadata.
Signature
export interface AgentClientMetadataOptions {
readonly id: string;
readonly tools: readonly AgentTool[];
readonly middleware: readonly AgentMiddleware[];
readonly client?: AgentClientPolicy;
readonly subagents?: readonly SubagentMetadataSource[];
readonly interruptOn?: Readonly<Record<string, unknown>>;
}
ClientEventMetadata (type alias)
Client visible event schema or dynamic event marker.
Signature
type ClientEventMetadata = ClientTypeField | { readonly kind: "dynamic" };
ClientScopeMetadata (interface)
Client visible agent, subagent, or graph node scope.
Signature
export interface ClientScopeMetadata {
readonly kind: "agent" | "subagent" | "node" | "dynamic";
readonly id?: string;
}
ClientToolMetadata (type alias)
Client visible tool schema or dynamic tool marker.
Signature
type ClientToolMetadata =
| {
readonly id: string;
readonly input: ClientSchemaMetadata;
readonly output: ClientSchemaMetadata;
}
| { readonly kind: "dynamic" };
ClientWaitingMetadata (interface)
Client visible continuation response schema.
Signature
export interface ClientWaitingMetadata {
readonly scope: ClientScopeMetadata;
readonly response: ClientSchemaMetadata;
}
GraphClientMetadataOptions (interface)
Inputs for graph client metadata.
Signature
export interface GraphClientMetadataOptions {
readonly id: string;
readonly state: { readonly getJsonSchema: () => unknown };
readonly client?: AgentClientPolicy;
readonly workflow: GraphWorkflow;
}
SubagentMetadataSource (interface)
Source of nested subagent scope identities.
Signature
export interface SubagentMetadataSource {
readonly id: string;
readonly subagents?: readonly SubagentMetadataSource[];
}
client-contract-schema.ts
Inspects native schema adapters to describe client-visible inputs and outputs; unsupported shapes produce the existing contract errors before execution.
ClientSchemaMetadata
Signature
declare const ClientSchemaMetadata: ClientSchemaMetadata;
ClientTypeField
Signature
declare const ClientTypeField: ClientTypeField;
clientSchemaMetadata
Synchronously projects schema metadata for existing descriptor callers.
Example
const metadata = clientSchemaMetadata({ type: "string" });
Signature
declare const clientSchemaMetadata: (value: unknown) => ClientSchemaMetadata;
clientSchemaMetadataEffect
Projects a schema-like value to safe client metadata.
Example
const metadata = Effect.runSync(clientSchemaMetadataEffect({ type: "string" }));
Signature
declare const clientSchemaMetadataEffect: (
value: unknown,
) => Effect.Effect<ClientSchemaMetadata, never, never>;
dynamicClientSchema
Marker for a schema that cannot be represented in the client contract.
Signature
declare const dynamicClientSchema: Readonly<{ kind: "dynamic" }>;
mergeClientSchemas
Synchronously merges client schemas for existing descriptor callers.
Example
const schema = mergeClientSchemas([{ type: "object" }]);
Signature
declare const mergeClientSchemas: (values: readonly unknown[]) => ClientSchemaMetadata;
mergeClientSchemasEffect
Merges projected object schemas while preserving input order.
Example
const schema = Effect.runSync(mergeClientSchemasEffect([{ type: "object" }]));
Signature
declare const mergeClientSchemasEffect: (
values: ReadonlyArray<unknown>,
) => Effect.Effect<JsonValue, never, never>;
selectedClientFields
Synchronously selects client fields for existing descriptor callers.
Example
const fields = selectedClientFields({ type: "object" }, ["name"]);
Signature
declare const selectedClientFields: (
schema: ClientSchemaMetadata,
keys?: readonly string[],
) => readonly ClientTypeField[];
selectedClientFieldsEffect
Selects named client state fields from a projected object schema.
Example
const fields = Effect.runSync(selectedClientFieldsEffect({ type: "object" }, ["name"]));
Signature
declare const selectedClientFieldsEffect: (
schema: ClientSchemaMetadata,
keys?: ReadonlyArray<string> | undefined,
) => Effect.Effect<ReadonlyArray<ClientTypeField>, never, never>;
continuation-validation.ts
Exposes graph identity and continuation validators to transport adapters without importing the agent execution barrel. Validation remains owned by its existing implementations and preserves their public failure and reply contracts.
isGraphDescriptor
Signature
declare const isGraphDescriptor: (value: unknown) => value is GraphDescriptor;
validateGraphResumeInput
Signature
declare const validateGraphResumeInput: (
descriptor: GraphDescriptor,
requests: readonly AgentWaitingRequest[],
value: unknown,
) => Promise<unknown>;
validateNativeAgentResumeInput
Signature
declare const validateNativeAgentResumeInput: (
requests: readonly AgentWaitingRequest[],
value: unknown,
) => unknown;
deepagent-bucket-backend.ts
Adapts a configured RELKIT bucket to the DeepAgents file backend, sharing the invocation scope and preserving bucket failures at the native adapter.
DeepAgentBucketBackendOptions
Signature
declare const DeepAgentBucketBackendOptions: DeepAgentBucketBackendOptions;
createDeepAgentBucketBackend
Creates a backend for existing synchronous callers.
Throws
The original invalid bucket or prefix error.
Example
const backend = createDeepAgentBucketBackend(bucket);
Signature
declare const createDeepAgentBucketBackend: (
bucket: DeepAgentBucketClient,
options?: DeepAgentBucketBackendOptions,
) => BackendProtocolV2;
createDeepAgentBucketBackendEffect
Builds a DeepAgents backend from a RELKIT bucket client.
Example
Effect.runSync(createDeepAgentBucketBackendEffect(bucket));
Signature
declare const createDeepAgentBucketBackendEffect: (
bucket: DeepAgentBucketClient,
options?: DeepAgentBucketBackendOptions | undefined,
) => Effect.Effect<
Readonly<{
ls: (path: string) => Promise<LsResult>;
read: (path: string, offset?: number, limit?: number) => Promise<ReadResult>;
readRaw: (path: string) => Promise<ReadRawResult>;
write: (path: string, content: string) => Promise<WriteResult>;
edit: (
path: string,
oldText: string,
newText: string,
replaceAll?: boolean,
) => Promise<EditResult>;
grep: (
pattern: string,
path?: string | null,
glob?: string | null,
maxCount?: number | null,
) => Promise<GrepResult>;
glob: (pattern: string, path?: string) => Promise<GlobResult>;
delete: (path: string) => Promise<DeleteResult>;
uploadFiles: (files: Array<[string, Uint8Array]>) => Promise<Array<FileUploadResponse>>;
downloadFiles: (paths: string[]) => Promise<Array<FileDownloadResponse>>;
}>,
DeepAgentBucketFailure,
never
>;
deepagent-bucket-backend.types.ts
Configuration for a DeepAgents backend bound to a RELKIT bucket.
DeepAgentBucketBackendOptions (interface)
Configuration for a DeepAgents backend bound to a RELKIT bucket.
Signature
export interface DeepAgentBucketBackendOptions {
/** Key prefix owned by this backend instance. */
readonly prefix?: string;
}
deepagent-bucket-client.types.ts
Bucket client and prefix bound to one DeepAgents backend.
DeepAgentBucketClient (interface)
IO operations required by the DeepAgents bucket bridge.
Signature
export interface DeepAgentBucketClient {
readonly put: (
key: string,
bytes: Uint8Array,
options?: {
readonly contentType?: string;
readonly metadata?: Readonly<Record<string, string>>;
},
) => Promise<void>;
readonly get: (key: string) => Promise<Uint8Array | undefined>;
readonly head: (key: string) => Promise<DeepAgentBucketMetadata | undefined>;
readonly delete: (key: string) => Promise<void>;
readonly exists: (key: string) => Promise<boolean>;
readonly list: (prefix?: string) => Promise<readonly string[]>;
}
DeepAgentBucketContext (interface)
Bucket client and prefix bound to one DeepAgents backend.
Signature
export interface DeepAgentBucketContext {
readonly bucket: DeepAgentBucketClient;
readonly prefix: string;
}
DeepAgentBucketMetadata (interface)
Metadata needed to expose a bucket object as a virtual file.
Signature
export interface DeepAgentBucketMetadata {
readonly contentType?: string;
readonly size?: number;
readonly metadata?: Readonly<Record<string, string>>;
}
deepagent-bucket-delete.ts
Deletes normalized DeepAgents file paths through the selected bucket service and reports native file-operation results without changing unrelated keys.
removeBucketPath
Removes a bucket path for existing DeepAgents Promise callers.
Throws
A cancellation or timeout failure from the bucket client.
Example
await removeBucketPath(context, "/notes");
Signature
declare const removeBucketPath: (
context: DeepAgentBucketContext,
path: string,
) => Promise<DeleteResult>;
removeBucketPathEffect
Removes a virtual file or directory with at most eight bucket requests in flight.
Example
Effect.runPromise(Effect.provide(removeBucketPathEffect("/notes"), deepAgentBucketLayer(context)));
Signature
declare const removeBucketPathEffect: (
path: string,
) => Effect.Effect<
| { error: string; path?: never; filesUpdate?: never }
| { path: string; filesUpdate: null; error?: never },
DeepAgentBucketFailure,
DeepAgentBucket
>;
deepagent-bucket-error.ts
Translates bucket operation failures into the DeepAgents backend error format while retaining the affected operation and path.
DeepAgentBucketFailure (class)
Typed bucket validation or IO failure for DeepAgents operations.
Signature
declare class DeepAgentBucketFailure
deepAgentBucketFailure
Captures a bucket error while preserving its original cause.
Example
deepAgentBucketFailure(new Error("not found"));
Signature
declare const deepAgentBucketFailure: (cause: unknown) => DeepAgentBucketFailure;
deepagent-bucket-file-data.ts
Encodes and decodes DeepAgents file records stored in bucket objects, preserving file content and timestamps across backend operations.
putFileData
Writes a file for existing Promise callers.
Throws
The original bucket or path failure.
Example
await putFileData(context, "/a.md", "hi");
Signature
declare const putFileData: (
context: DeepAgentBucketContext,
path: string,
content: string | Uint8Array,
) => Promise<void>;
putFileDataEffect
Writes file content with timestamps from the Effect clock.
Example
Effect.runPromise(Effect.provide(putFileDataEffect("/a.md", "hi"), deepAgentBucketLayer(context)));
Signature
declare const putFileDataEffect: (
path: string,
content: string | Uint8Array<ArrayBufferLike>,
) => Effect.Effect<void, DeepAgentBucketFailure, DeepAgentBucket>;
readFileData
Reads a file for existing Promise callers.
Throws
The original bucket or path failure.
Example
await readFileData(context, "/a.md");
Signature
declare const readFileData: (
context: DeepAgentBucketContext,
path: string,
) => Promise<DeepAgentBucketFileData | undefined>;
readFileDataEffect
Reads bytes and metadata together from the current bucket service.
Example
Effect.runPromise(Effect.provide(readFileDataEffect("/a.md"), deepAgentBucketLayer(context)));
Signature
declare const readFileDataEffect: (path: string) => Effect.Effect<
| {
content: string | Uint8Array<ArrayBufferLike>;
mimeType: string;
created_at: string;
modified_at: string;
}
| undefined,
DeepAgentBucketFailure,
DeepAgentBucket
>;
deepagent-bucket-file-index.ts
Maintains the invocation file index used by bucket-backed listing and lookup; reads and mutations share the same backend state.
infoFor
Reads metadata for existing Promise callers.
Throws
The original bucket or path failure.
Example
await infoFor(context, "deepagents/a.md");
Signature
declare const infoFor: (
context: DeepAgentBucketContext,
key: string,
) => Promise<FileInfo | undefined>;
infoForEffect
Reads metadata for one bucket key.
Example
Effect.runPromise(Effect.provide(infoForEffect("deepagents/a.md"), deepAgentBucketLayer(context)));
Signature
declare const infoForEffect: (
key: string,
) => Effect.Effect<FileInfo | undefined, DeepAgentBucketFailure, DeepAgentBucket>;
scopedKeys
Lists keys for existing Promise callers.
Throws
The original bucket or path failure.
Example
await scopedKeys(context, "/notes");
Signature
declare const scopedKeys: (
context: DeepAgentBucketContext,
path: string | null | undefined,
) => Promise<readonly string[]>;
scopedKeysEffect
Lists sorted keys in a virtual file or directory.
Example
Effect.runPromise(Effect.provide(scopedKeysEffect("/notes"), deepAgentBucketLayer(context)));
Signature
declare const scopedKeysEffect: (
path: string | null | undefined,
) => Effect.Effect<Array<string>, DeepAgentBucketFailure, DeepAgentBucket>;
deepagent-bucket-files.ts
Collects bucket-backed file entries for native filesystem operations after path normalization, keeping metadata separate from fetched file content.
“./deepagent-bucket-files.types.js” (namespace export)
Re-exports all named exports from the “./deepagent-bucket-files.types.js” module.
Signature
export * from "./deepagent-bucket-files.types.js";
bucketKey
Signature
declare const bucketKey: (context: DeepAgentBucketContext, path: string) => string;
bucketKeyEffect
Signature
declare const bucketKeyEffect: (
context: DeepAgentBucketContext,
path: string,
) => Effect<string, DeepAgentBucketFailure, never>;
createBucketContext
Signature
declare const createBucketContext: (
bucket: DeepAgentBucketClient,
prefix?: string,
) => DeepAgentBucketContext;
createBucketContextEffect
Signature
declare const createBucketContextEffect: (
bucket: DeepAgentBucketClient,
prefix?: any,
) => Effect<
Readonly<{ bucket: DeepAgentBucketClient; prefix: string }>,
DeepAgentBucketFailure,
never
>;
errorMessage
Signature
declare const errorMessage: (cause: unknown) => string;
errorMessageEffect
Signature
declare const errorMessageEffect: (cause: unknown) => Effect<string, never, never>;
filePath
Signature
declare const filePath: (context: DeepAgentBucketContext, key: string) => string;
filePathEffect
Signature
declare const filePathEffect: (
context: DeepAgentBucketContext,
key: string,
) => Effect<string, DeepAgentBucketFailure, never>;
isControlFailure
Signature
declare const isControlFailure: (cause: unknown) => boolean;
isControlFailureEffect
Signature
declare const isControlFailureEffect: (cause: unknown) => Effect<boolean, never, never>;
isTextMimeType
Signature
declare const isTextMimeType: (mimeType: string) => boolean;
isTextMimeTypeEffect
Signature
declare const isTextMimeTypeEffect: (mimeType: string) => Effect<boolean, never, never>;
normalizedPage
Signature
declare const normalizedPage: (
offset?: number,
limit?: number,
) => { offset: number; limit: number };
normalizedPageEffect
Signature
declare const normalizedPageEffect: (
offset: number,
limit: number,
) => Effect<{ offset: number; limit: number }, never, never>;
virtualPath
Signature
declare const virtualPath: (value: string, directory?: boolean) => string;
virtualPathEffect
Signature
declare const virtualPathEffect: (
value: string,
directory?: any,
) => Effect<string, DeepAgentBucketFailure, never>;
deepagent-bucket-files.types.ts
Collects bucket-backed file entries for native filesystem operations after path normalization, keeping metadata separate from fetched file content. This companion preserves the native input and output types without starting runtime work.
“./deepagent-bucket-client.types.js” (namespace export)
Re-exports all named exports from the “./deepagent-bucket-client.types.js” module.
Signature
export * from "./deepagent-bucket-client.types.js";
DeepAgentBucketFileData (type alias)
DeepAgents file payload that carries a concrete MIME type.
Signature
type DeepAgentBucketFileData = Extract<FileData, { readonly mimeType: string }>;
deepagent-bucket-format.ts
Formats bucket file records into the native DeepAgents listing and content shapes consumed by backend callers.
errorMessage
Reads a failure message for existing synchronous callers.
Example
errorMessage(error);
Signature
declare const errorMessage: (cause: unknown) => string;
errorMessageEffect
Reads a failure message without requiring an Error instance.
Example
Effect.runSync(errorMessageEffect(error));
Signature
declare const errorMessageEffect: (cause: unknown) => Effect.Effect<string, never, never>;
isControlFailure
Classifies a control failure for existing synchronous callers.
Example
isControlFailure(error);
Signature
declare const isControlFailure: (cause: unknown) => boolean;
isControlFailureEffect
Classifies cancellation and timeout control failures.
Example
Effect.runSync(isControlFailureEffect(error));
Signature
declare const isControlFailureEffect: (cause: unknown) => Effect.Effect<boolean, never, never>;
isTextMimeType
Checks a text MIME type for existing synchronous callers.
Example
isTextMimeType("text/plain");
Signature
declare const isTextMimeType: (mimeType: string) => boolean;
isTextMimeTypeEffect
Checks whether a MIME type should be decoded as text.
Example
Effect.runSync(isTextMimeTypeEffect("text/plain"));
Signature
declare const isTextMimeTypeEffect: (mimeType: string) => Effect.Effect<boolean, never, never>;
normalizedPage
Normalizes paging for existing synchronous callers.
Example
normalizedPage(0, 500);
Signature
declare const normalizedPage: (
offset?: number,
limit?: number,
) => { offset: number; limit: number };
normalizedPageEffect
Normalizes paging arguments to nonnegative integers.
Example
Effect.runSync(normalizedPageEffect(0, 500));
Signature
declare const normalizedPageEffect: (
offset: number,
limit: number,
) => Effect.Effect<{ offset: number; limit: number }, never, never>;
deepagent-bucket-glob.ts
Matches normalized bucket paths against DeepAgents glob patterns so search traverses only the backend’s visible file namespace.
compileGlob
Validates and normalizes a user glob without changing match semantics.
Signature
declare const compileGlob: (pattern: string) => string;
globFiles
Finds files for existing DeepAgents Promise callers.
Throws
A cancellation or timeout failure from the bucket client.
Example
await globFiles(context, "*.md", "/notes");
Signature
declare const globFiles: (
context: DeepAgentBucketContext,
pattern: string,
path?: string,
) => Promise<GlobResult>;
globFilesEffect
Finds matching bucket files and orders them by modification time.
Example
Effect.runPromise(Effect.provide(globFilesEffect("*.md"), deepAgentBucketLayer(context)));
Signature
declare const globFilesEffect: (
pattern: string,
path?: any,
) => Effect.Effect<{ files: Array<FileInfo> }, DeepAgentBucketFailure, DeepAgentBucket>;
deepagent-bucket-grep.ts
Searches bucket file content for native grep requests and projects matching lines into DeepAgents results.
grepFiles
Searches text files for existing DeepAgents Promise callers.
Throws
A cancellation or timeout failure from the bucket client.
Example
await grepFiles(context, "TODO", "/notes", "*.md", 10);
Signature
declare const grepFiles: (
context: DeepAgentBucketContext,
pattern: string,
path?: string | null,
globPattern?: string | null,
maxCount?: number | null,
) => Promise<GrepResult>;
grepFilesEffect
Searches text files in key order and stops as soon as the match cap is exceeded.
Example
Effect.runPromise(Effect.provide(grepFilesEffect("TODO"), deepAgentBucketLayer(context)));
Signature
declare const grepFilesEffect: (
pattern: string,
path?: string | null | undefined,
globPattern?: string | null | undefined,
maxCount?: number | null | undefined,
) => Effect.Effect<
| { matches: Array<GrepMatch>; truncated: boolean }
| { matches: Array<GrepMatch>; truncated?: never },
DeepAgentBucketFailure,
DeepAgentBucket
>;
deepagent-bucket-path.ts
Normalizes native file paths into scoped bucket keys and rejects paths that would escape the configured backend prefix.
bucketKey
Converts a virtual path to a bucket key for synchronous callers.
Throws
The original invalid path error.
Example
bucketKey(context, "/readme.md");
Signature
declare const bucketKey: (context: DeepAgentBucketContext, path: string) => string;
bucketKeyEffect
Converts a virtual path to its bucket key.
Example
Effect.runSync(bucketKeyEffect(context, "/readme.md"));
Signature
declare const bucketKeyEffect: (
context: DeepAgentBucketContext,
path: string,
) => Effect.Effect<string, DeepAgentBucketFailure, never>;
createBucketContext
Creates a bucket context for existing synchronous callers.
Throws
The original invalid bucket or prefix error.
Example
createBucketContext(bucket, "agents");
Signature
declare const createBucketContext: (
bucket: DeepAgentBucketClient,
prefix?: string,
) => DeepAgentBucketContext;
createBucketContextEffect
Validates a bucket client and creates its private prefix context.
Example
Effect.runSync(createBucketContextEffect(bucket));
Signature
declare const createBucketContextEffect: (
bucket: DeepAgentBucketClient,
prefix?: any,
) => Effect.Effect<
Readonly<{ bucket: DeepAgentBucketClient; prefix: string }>,
DeepAgentBucketFailure,
never
>;
filePath
Converts a scoped bucket key for existing synchronous callers.
Throws
Error for a key outside the context prefix.
Example
filePath(context, "agents/readme.md");
Signature
declare const filePath: (context: DeepAgentBucketContext, key: string) => string;
filePathEffect
Converts a scoped bucket key to a virtual path.
Example
Effect.runSync(filePathEffect(context, "agents/readme.md"));
Signature
declare const filePathEffect: (
context: DeepAgentBucketContext,
key: string,
) => Effect.Effect<string, DeepAgentBucketFailure, never>;
virtualPath
Normalizes a virtual path for existing synchronous callers.
Throws
Error for empty, unsafe, or traversing paths.
Example
virtualPath("docs/readme.md");
Signature
declare const virtualPath: (value: string, directory?: boolean) => string;
virtualPathEffect
Normalizes a virtual backend path and rejects traversal.
Example
Effect.runSync(virtualPathEffect("/docs/readme.md"));
Signature
declare const virtualPathEffect: (
value: string,
directory?: any,
) => Effect.Effect<string, DeepAgentBucketFailure, never>;
deepagent-bucket-read.ts
Reads normalized native files from the selected bucket, applying the backend’s content and missing-file conventions.
readBucket
Reads a file for existing DeepAgents Promise callers.
Throws
A cancellation or timeout failure from the bucket client.
Example
await readBucket(context, "/a.md", 0, 50);
Signature
declare const readBucket: (
context: DeepAgentBucketContext,
path: string,
offset?: number,
limit?: number,
) => Promise<ReadResult>;
readBucketEffect
Reads a paged text file or an unmodified binary payload.
Example
Effect.runPromise(Effect.provide(readBucketEffect("/a.md", 0, 50), deepAgentBucketLayer(context)));
Signature
declare const readBucketEffect: (
path: string,
offset?: any,
limit?: any,
) => Effect.Effect<
| { error: string; content?: never; mimeType?: never }
| { content: string | Uint8Array<ArrayBufferLike>; mimeType: string; error?: never }
| {
nextOffset?: number;
content: string;
mimeType: string;
totalLines: number;
startLine: number;
endLine: number;
error?: never;
},
DeepAgentBucketFailure,
DeepAgentBucket
>;
readBucketRaw
Reads the full file payload for existing DeepAgents Promise callers.
Throws
A cancellation or timeout failure from the bucket client.
Example
await readBucketRaw(context, "/a.md");
Signature
declare const readBucketRaw: (
context: DeepAgentBucketContext,
path: string,
) => Promise<ReadRawResult>;
readBucketRawEffect
Reads the full file payload from the current bucket service.
Example
Effect.runPromise(Effect.provide(readBucketRawEffect("/a.md"), deepAgentBucketLayer(context)));
Signature
declare const readBucketRawEffect: (path: string) => Effect.Effect<
| { error: string; data?: never }
| {
data: {
content: string | Uint8Array<ArrayBufferLike>;
mimeType: string;
created_at: string;
modified_at: string;
};
error?: never;
},
DeepAgentBucketFailure,
DeepAgentBucket
>;
deepagent-bucket-scope.ts
Owns bucket backend access for an agent invocation and closes acquired resources only after the scoped operation settles.
createThreadBucketBackend
Creates a private thread backend for existing synchronous callers.
Throws
The original invalid bucket or thread error.
Example
const backend = createThreadBucketBackend(bucket, "agent", "thread");
Signature
declare const createThreadBucketBackend: (
bucket: DeepAgentBucketClient,
agentId: string,
threadId: string,
) => Readonly<{
ls: (path: string) => Promise<LsResult>;
read: (path: string, offset?: number, limit?: number) => Promise<ReadResult>;
readRaw: (path: string) => Promise<ReadRawResult>;
write: (path: string, content: string) => Promise<WriteResult>;
edit: (
path: string,
oldText: string,
newText: string,
replaceAll?: boolean,
) => Promise<EditResult>;
grep: (
pattern: string,
path?: string | null,
glob?: string | null,
maxCount?: number | null,
) => Promise<GrepResult>;
glob: (pattern: string, path?: string) => Promise<GlobResult>;
delete: (path: string) => Promise<DeleteResult>;
uploadFiles: (files: Array<[string, Uint8Array]>) => Promise<Array<FileUploadResponse>>;
downloadFiles: (paths: string[]) => Promise<Array<FileDownloadResponse>>;
}>;
createThreadBucketBackendEffect
Creates a private filesystem partition for one exact agent thread.
Example
Effect.runSync(createThreadBucketBackendEffect(bucket, "agent", "thread"));
Signature
declare const createThreadBucketBackendEffect: (
bucket: DeepAgentBucketClient,
agentId: string,
threadId: string,
) => Effect.Effect<
Readonly<{
ls: (path: string) => Promise<LsResult>;
read: (path: string, offset?: number, limit?: number) => Promise<ReadResult>;
readRaw: (path: string) => Promise<ReadRawResult>;
write: (path: string, content: string) => Promise<WriteResult>;
edit: (
path: string,
oldText: string,
newText: string,
replaceAll?: boolean,
) => Promise<EditResult>;
grep: (
pattern: string,
path?: string | null,
glob?: string | null,
maxCount?: number | null,
) => Promise<GrepResult>;
glob: (pattern: string, path?: string) => Promise<GlobResult>;
delete: (path: string) => Promise<DeleteResult>;
uploadFiles: (files: Array<[string, Uint8Array]>) => Promise<Array<FileUploadResponse>>;
downloadFiles: (paths: string[]) => Promise<Array<FileDownloadResponse>>;
}>,
DeepAgentBucketFailure,
never
>;
deepagent-bucket-search.ts
Coordinates native bucket listing and content search, sharing normalized paths and file metadata with the read backend.
listDirectory
Lists a virtual directory for existing DeepAgents Promise callers.
Throws
A cancellation or control failure.
Example
await listDirectory(context, "/notes");
Signature
declare const listDirectory: (context: DeepAgentBucketContext, path: string) => Promise<LsResult>;
listDirectoryEffect
Lists direct files and child directories through bounded metadata IO.
Example
Effect.runPromise(Effect.provide(listDirectoryEffect("/"), deepAgentBucketLayer(context)));
Signature
declare const listDirectoryEffect: (
path: string,
) => Effect.Effect<{ files: Array<FileInfo> }, DeepAgentBucketFailure, DeepAgentBucket>;
deepagent-bucket-service.ts
Provides the Effect service used by native bucket operations, translating selected provider access into the backend’s typed operation boundary.
DeepAgentBucket (class)
Injectable bucket context for DeepAgents filesystem operations.
Example
Effect.provide(listDirectoryEffect("/"), deepAgentBucketLayer(context));
Signature
declare class DeepAgentBucket
deepAgentBucketLayer
Provides one bucket client and path prefix to an Effect operation.
Example
deepAgentBucketLayer({ bucket, prefix: "threads/one" });
Signature
declare const deepAgentBucketLayer: (
context: DeepAgentBucketContext,
) => Layer.Layer<DeepAgentBucket, never, never>;
deepagent-bucket-transfer.ts
Transfers native file content between backend requests and bucket objects while retaining per-file success and failure results.
downloadBucketFiles
Downloads files for existing DeepAgents Promise callers.
Throws
A cancellation or timeout failure from the bucket client.
Example
await downloadBucketFiles(context, ["/a"]);
Signature
declare const downloadBucketFiles: (
context: DeepAgentBucketContext,
paths: string[],
) => Promise<FileDownloadResponse[]>;
downloadBucketFilesEffect
Downloads files in input order with a result for each path.
Example
Effect.runPromise(Effect.provide(downloadBucketFilesEffect(["/a"]), deepAgentBucketLayer(context)));
Signature
declare const downloadBucketFilesEffect: (
paths: Array<string>,
) => Effect.Effect<
Array<
| { path: string; content: null; error: "file_not_found" }
| { path: string; content: Uint8Array<ArrayBufferLike>; error: null }
| { path: string; content: null; error: "invalid_path" }
>,
DeepAgentBucketFailure,
DeepAgentBucket
>;
uploadBucketFiles
Uploads files for existing DeepAgents Promise callers.
Throws
A cancellation or timeout failure from the bucket client.
Example
await uploadBucketFiles(context, [["/a", bytes]]);
Signature
declare const uploadBucketFiles: (
context: DeepAgentBucketContext,
files: Array<[string, Uint8Array]>,
) => Promise<FileUploadResponse[]>;
uploadBucketFilesEffect
Uploads files in input order so repeated paths retain last-write behavior.
Example
Effect.runPromise(
Effect.provide(uploadBucketFilesEffect([["/a", bytes]]), deepAgentBucketLayer(context)),
);
Signature
declare const uploadBucketFilesEffect: (
files: Array<[string, Uint8Array<ArrayBufferLike>]>,
) => Effect.Effect<
Array<{ path: string; error: null } | { path: string; error: "invalid_path" }>,
DeepAgentBucketFailure,
DeepAgentBucket
>;
deepagent-bucket-write.ts
Applies native file writes and edits to the selected bucket and updates the shared file index after successful storage mutations.
editBucket
Edits text for existing DeepAgents Promise callers.
Throws
A cancellation or timeout failure from the bucket client.
Example
await editBucket(context, "/a.md", "old", "new", true);
Signature
declare const editBucket: (
context: DeepAgentBucketContext,
path: string,
oldText: string,
newText: string,
replaceAll?: boolean,
) => Promise<EditResult>;
editBucketEffect
Replaces text with the existing DeepAgents edit rules.
Example
Effect.runPromise(
Effect.provide(editBucketEffect("/a.md", "old", "new"), deepAgentBucketLayer(context)),
);
Signature
declare const editBucketEffect: (
path: string,
oldText: string,
newText: string,
replaceAll?: any,
) => Effect.Effect<
| { error: string; path?: never; filesUpdate?: never; occurrences?: never }
| { path: string; filesUpdate: null; occurrences: number; error?: never },
DeepAgentBucketFailure,
DeepAgentBucket
>;
writeBucket
Writes text for existing DeepAgents Promise callers.
Throws
A cancellation or timeout failure from the bucket client.
Example
await writeBucket(context, "/a.md", "hi");
Signature
declare const writeBucket: (
context: DeepAgentBucketContext,
path: string,
content: string,
) => Promise<WriteResult>;
writeBucketEffect
Writes a text file through the current bucket service.
Example
Effect.runPromise(Effect.provide(writeBucketEffect("/a.md", "hi"), deepAgentBucketLayer(context)));
Signature
declare const writeBucketEffect: (
path: string,
content: string,
) => Effect.Effect<{ path: string; filesUpdate: null }, DeepAgentBucketFailure, DeepAgentBucket>;
define-agent-build.ts
Assembles validated native agent configuration into a RELKIT descriptor, preserving native model, tools and execution metadata for runtime selection.
prepareAgentDescriptor
Validates agent options and returns an assembler for a resolved identity.
Throws
Validation errors from fields and client policy.
Example
prepareAgentDescriptor(options)("support");
Signature
declare const prepareAgentDescriptor: <
const Id extends string,
const InputSchema extends StandardSchemaV1,
const OutputSchema extends StandardSchemaV1,
const Middleware extends readonly AgentMiddleware[],
const Tools extends readonly AgentTool[],
>(
options: DefineAgentOptions<Id, InputSchema, OutputSchema, Middleware, Tools>,
) => (
id: Id,
) => AgentDescriptor<
Id,
InferInput<InputSchema>,
InferOutput<OutputSchema>,
InputSchema,
OutputSchema,
Middleware,
Tools
>;
define-agent-deep.ts
Normalizes optional DeepAgents authoring fields without loading the DeepAgents runtime; the same defined-field selection controls the graph marker.
“./define-agent-deep.types.js” (namespace export)
Re-exports all named exports from the “./define-agent-deep.types.js” module.
Signature
export * from "./define-agent-deep.types.js";
copyDeepAgentCapabilities
Copies DeepAgents options for existing synchronous authoring callers.
Throws
The original invalid capability error.
Example
const options = copyDeepAgentCapabilities({ skills: ["/skills"] });
Signature
declare const copyDeepAgentCapabilities: (value: DeepAgentCapabilities) => DeepAgentCapabilities;
copyDeepAgentCapabilitiesEffect
Validates and freezes native DeepAgents options.
Example
Effect.runSync(copyDeepAgentCapabilitiesEffect({ skills: ["/skills"] }));
Signature
declare const copyDeepAgentCapabilitiesEffect: (
value: DeepAgentCapabilities,
) => Effect.Effect<DeepAgentCapabilities, AgentDefinitionFailure, never>;
hasDeepAgentCapabilities
Checks capabilities for existing synchronous authoring callers.
Example
if (hasDeepAgentCapabilities(options)) enableDeep();
Signature
declare const hasDeepAgentCapabilities: (value: DeepAgentCapabilities) => boolean;
hasDeepAgentCapabilitiesEffect
Checks whether a descriptor enables native DeepAgents capabilities.
Example
Effect.runSync(hasDeepAgentCapabilitiesEffect({ skills: ["/skills"] }));
Signature
declare const hasDeepAgentCapabilitiesEffect: (
value: DeepAgentCapabilities,
) => Effect.Effect<boolean, never, never>;
define-agent-deep.types.ts
Normalizes optional DeepAgents authoring fields without loading the DeepAgents runtime; the same defined-field selection controls the graph marker. This companion preserves the native input and output types without starting runtime work.
AgentFilesystemBackend (type alias)
DeepAgents filesystem backend or a state-bound backend factory.
Signature
type AgentFilesystemBackend =
object | ((context: { readonly state: unknown; readonly store?: unknown }) => object);
AgentSubagent (type alias)
Agent descriptor nested under a DeepAgent.
Signature
type AgentSubagent = AgentDescriptor<string, unknown, unknown>;
DeepAgentCapabilities (interface)
Optional capabilities enabled for a DeepAgent.
Signature
export interface DeepAgentCapabilities {
readonly subagents?: readonly AgentSubagent[];
readonly skills?: readonly string[];
readonly memory?: readonly string[];
readonly backend?: AgentFilesystemBackend;
readonly checkpointer?: BaseCheckpointSaver | CheckpointerResource;
readonly store?: BaseStore | MemoryResource;
readonly interruptOn?: Readonly<Record<string, boolean | InterruptOnConfig>>;
}
define-agent-native-middleware.ts
Validates and retains SDK middleware supplied by native agent authors so runtime construction receives the original middleware objects.
copyAgentMiddleware
Copies middleware for existing synchronous authoring callers.
Throws
The original invalid middleware error.
Example
const middleware = copyAgentMiddleware([]);
Signature
declare const copyAgentMiddleware: <Middleware extends readonly AgentMiddleware[]>(
value: Middleware | undefined,
) => Middleware;
copyAgentMiddlewareEffect
Validates middleware names and brands, retaining input order.
Example
Effect.runSync(copyAgentMiddlewareEffect([]));
Signature
declare const copyAgentMiddlewareEffect: <Middleware extends readonly AgentMiddleware[]>(
value: Middleware | undefined,
) => Effect.Effect<Middleware, AgentDefinitionFailure, never>;
middlewareStateKeys
Collects state keys for existing synchronous authoring callers.
Throws
The original schema access error.
Example
const keys = middlewareStateKeys([]);
Signature
declare const middlewareStateKeys: <Middleware extends readonly AgentMiddleware[]>(
middleware: Middleware,
) => ReadonlySet<AgentClientStateKey<Middleware>>;
middlewareStateKeysEffect
Collects public state keys declared by middleware schemas.
Example
Effect.runSync(middlewareStateKeysEffect([]));
Signature
declare const middlewareStateKeysEffect: <Middleware extends readonly AgentMiddleware[]>(
middleware: Middleware,
) => Effect.Effect<
ReadonlySet<MiddlewareStateKey<Middleware[number]>>,
AgentDefinitionFailure,
never
>;
define-agent-native-model.ts
Accepts native chat-model instances or supported model selectors and preserves the model’s inference contract for descriptor construction.
isAgentModel
Checks a model for existing synchronous authoring callers.
Example
if (isAgentModel(value)) use(value);
Signature
declare const isAgentModel: (value: unknown) => value is AgentModel;
isAgentModelEffect
Checks whether a value can select or provide a native agent model.
Example
Effect.runSync(isAgentModelEffect("openai:gpt"));
Signature
declare const isAgentModelEffect: (value: unknown) => Effect.Effect<boolean, never, never>;
define-agent-native-tools.ts
Separates native SDK tools from RELKIT callable references while retaining native identity and serializable generic tool references.
copyAgentTools
Copies tools for existing synchronous authoring callers.
Throws
The original invalid or duplicate tool error.
Example
const tools = copyAgentTools([]);
Signature
declare const copyAgentTools: <Tools extends readonly AgentTool[]>(value: Tools) => Tools;
copyAgentToolsEffect
Validates and freezes RELKIT and native agent tools in input order.
Example
Effect.runSync(copyAgentToolsEffect([]));
Signature
declare const copyAgentToolsEffect: <Tools extends readonly AgentTool[]>(
value: Tools,
) => Effect.Effect<Tools, AgentDefinitionFailure, never>;
relkitToolRefs
Selects RELKIT references for existing synchronous authoring callers.
Example
const refs = relkitToolRefs(tools);
Signature
declare const relkitToolRefs: (tools: readonly AgentTool[]) => readonly ToolRefAny[];
relkitToolRefsEffect
Selects RELKIT tool references from a mixed native tool list.
Example
Effect.runSync(relkitToolRefsEffect([]));
Signature
declare const relkitToolRefsEffect: (
tools: ReadonlyArray<AgentTool>,
) => Effect.Effect<Array<ToolRefAny>, never, never>;
define-agent-native.ts
Builds the native execution payload from model, tool and middleware inputs after validation, without starting model execution during authoring.
“./define-agent-native-middleware.js” (namespace export)
Re-exports all named exports from the “./define-agent-native-middleware.js” module.
Signature
export * from "./define-agent-native-middleware.js";
“./define-agent-native-model.js” (namespace export)
Re-exports all named exports from the “./define-agent-native-model.js” module.
Signature
export * from "./define-agent-native-model.js";
“./define-agent-native-tools.js” (namespace export)
Re-exports all named exports from the “./define-agent-native-tools.js” module.
Signature
export * from "./define-agent-native-tools.js";
“./define-agent-native.types.js” (namespace export)
Re-exports all named exports from the “./define-agent-native.types.js” module.
Signature
export * from "./define-agent-native.types.js";
define-agent-native.types.ts
Builds the native execution payload from model, tool and middleware inputs after validation, without starting model execution during authoring. This companion preserves the native input and output types without starting runtime work.
AgentClientStateKey (type alias)
Public state keys selected from each middleware schema without erasing tuples.
Signature
type AgentClientStateKey<Middleware extends readonly AgentMiddleware[]> = MiddlewareStateKey<
Middleware[number]
>;
AgentLanguageModel (interface)
Native model object accepted by an agent descriptor.
Signature
export interface AgentLanguageModel {
readonly invoke: (...args: never[]) => unknown;
}
AgentMiddleware (type alias)
SDK fields RELKIT inspects; each descriptor retains its complete inferred middleware tuple, including native hooks, tools and phantom schema data. Runtime validation checks the SDK brand.
Signature
type AgentMiddleware = Pick<NativeAgentMiddleware, "name" | "stateSchema">;
AgentMiddlewareState (type alias)
Public state composed from middleware state schemas.
Signature
type AgentMiddlewareState<Middleware extends readonly AgentMiddleware[]> =
Middleware extends readonly [infer First, ...infer Rest]
? First extends AgentMiddleware
? Rest extends readonly AgentMiddleware[]
? MiddlewareState<First> & AgentMiddlewareState<Rest>
: MiddlewareState<First>
: {}
: {};
AgentModel (type alias)
Model selector, native model, or model factory.
Signature
type AgentModel = string | AgentLanguageModel | AgentModelFactory;
AgentModelFactory (type alias)
Environment-bound factory for a native model.
Signature
type AgentModelFactory<Environment = Readonly<Record<string, unknown>>> = (
environment: Environment,
) => MaybePromise<AgentLanguageModel>;
AgentTool (type alias)
RELKIT reference or native LangChain tool.
Signature
type AgentTool = ToolRefAny | NativeAgentTool;
NativeAgentTool (type alias)
LangChain client or server tool.
Signature
type NativeAgentTool = ClientTool | ServerTool;
define-agent-validation.ts
Validates shared and native agent configuration before descriptor assembly, keeping invalid authoring failures out of the invocation path.
assertAgentDescriptor
Requires a descriptor for existing synchronous authoring callers.
Throws
TypeError when the descriptor is invalid.
Example
assertAgentDescriptor(candidate);
Signature
declare const assertAgentDescriptor: (value: unknown) => asserts value is AgentAny;
assertAgentDescriptorEffect
Requires a valid agent descriptor.
Example
Effect.runSync(assertAgentDescriptorEffect(agent));
Signature
declare const assertAgentDescriptorEffect: (
value: unknown,
) => Effect.Effect<void, AgentDefinitionFailure, never>;
isAgentDescriptor
Checks a descriptor for existing synchronous authoring callers.
Example
if (isAgentDescriptor(candidate)) use(candidate);
Signature
declare const isAgentDescriptor: (value: unknown) => value is AgentAny;
isAgentDescriptorEffect
Checks the complete runtime shape of an agent descriptor.
Example
Effect.runSync(isAgentDescriptorEffect(candidate));
Signature
declare const isAgentDescriptorEffect: (value: unknown) => Effect.Effect<boolean, never, never>;
normalizeAgentModel
Normalizes a model for existing synchronous authoring callers.
Throws
The original invalid selector error.
Example
const model = normalizeAgentModel("openai:gpt");
Signature
declare const normalizeAgentModel: (value: AgentModel | undefined) => AgentModel | undefined;
normalizeAgentModelEffect
Normalizes the selector of a string model definition.
Example
Effect.runSync(normalizeAgentModelEffect("openai:gpt"));
Signature
declare const normalizeAgentModelEffect: (
value: AgentModel | undefined,
) => Effect.Effect<
string | AgentLanguageModel | AgentModelFactory<Readonly<Record<string, unknown>>> | undefined,
AgentDefinitionFailure,
never
>;
define-agent.ts
Exposes SDK-native agent authoring with inferred input and output types; validation and descriptor assembly are delegated to the integration’s owning helpers.
defineAgent
Defines a native agent for existing synchronous authoring callers.
Throws
The original invalid authoring or identity error.
Example
import { defineAgent } from "@relkit/langchain";
import { z } from "@relkit/app/schema";
const support = defineAgent({
id: "support",
input: z.object({ message: z.string() }),
output: z.object({ answer: z.string() }),
instructions: "Reply briefly.",
tools: [],
limits: { maxSteps: 4, maxToolCalls: 2, timeoutMs: 30_000 },
});
void support;
Signature
declare const defineAgent: <
const Id extends string,
const InputSchema extends StandardSchemaV1,
const OutputSchema extends StandardSchemaV1,
const Middleware extends readonly AgentMiddleware[] = readonly [],
const Tools extends readonly AgentTool[] = ReadonlyArray<AgentTool>,
>(
options: DefineAgentOptions<Id, InputSchema, OutputSchema, Middleware, Tools>,
) => AgentDescriptor<
Id,
InferInput<InputSchema>,
InferOutput<OutputSchema>,
InputSchema,
OutputSchema,
Middleware,
Tools
>;
Since v0.4.0
Backend and frontend example
Backend — these maintained files define the operation used by the frontend below.
/** Runs an offline greeting agent with RELKIT/native tools, todo middleware and public state observation. */
import { defineAgent } from "@relkit/langchain";
import { z } from "@relkit/app/schema";
import { FakeToolCallingModel, todoListMiddleware, tool } from "langchain";
import lookup from "@app/services/hello/tools/lookup.tool.js";
export const uppercase = tool(async ({ text }: { readonly text: string }) => text.toUpperCase(), {
name: "uppercase",
description: "Uppercase text without leaving the process",
schema: z.object({ text: z.string() }),
});
export default defineAgent({
id: "hello.assistant",
input: z.object({ message: z.string().min(1) }),
output: z.object({ answer: z.string() }),
model: new FakeToolCallingModel({
toolCalls: [
[
{
name: "write_todos",
args: { todos: [{ content: "Answer the greeting", status: "completed" }] },
id: "todo-1",
},
],
[
{
name: "relkit_output",
args: { value: { answer: "Hello from the offline LangChain model." } },
id: "output-1",
},
],
],
}),
instructions: "Answer greeting questions with the available tools.",
tools: [lookup, uppercase],
middleware: [todoListMiddleware()],
stateProfile: "default",
client: {
public: true,
state: ["todos"],
events: { notice: z.object({ message: z.string() }) },
},
chat: { input: "message", output: "answer" },
controls: ["stop"],
limits: {
maxSteps: 4,
maxToolCalls: 4,
timeoutMs: 10_000,
},
});
Frontend
After frontend setup and pulling the greeting agent’s contract,
render this component under the provider. Supply a stable business threadId owned by your
application, such as the ID of the conversation the user opened:
"use client";
/** Sends one greeting to the documented hello.assistant agent and observes its typed answer. */
import { useAgent, useRelkitClient } from "@relkit/client/react";
import { useState } from "react";
/** Keeps the application-owned thread identity stable across rendering and observation.
* @param props - Authorized conversation identity retained by the application.
* @returns A greeting action, the observed answer, and explicit submission failure. */
export function Assistant({ threadId }: { readonly threadId: string }) {
const { status } = useRelkitClient();
const assistant = useAgent("hello.assistant");
const [failure, setFailure] = useState("");
/** Submits once and preserves uncertain outcomes for explicit recovery.
* @returns Completion after acceptance or displaying the failure. */
async function sendGreeting() {
try {
await assistant.send("Hello, RELKIT!", { threadId });
} catch (error) {
setFailure(String(error));
}
}
return (
<section>
<button
disabled={status !== "ready" || assistant.status !== "idle" || failure !== ""}
onClick={sendGreeting}
>
Say hello
</button>
<p role="status">{assistant.output?.answer ?? assistant.status}</p>
{failure && <p role="alert">{failure}. Check this thread before submitting again.</p>}
</section>
);
}
This is the same hello.assistant declaration: client.public exposes it, chat.input: "message"
makes send accept a string, and chat.output: "answer" selects its typed answer. Mounting
useAgent does not start a run. The backend owns models, credentials, tools, and authorization.
Reference: useAgent.
Continue with streaming and controls or
thread recovery.
AgentChatMapping
Signature
declare const AgentChatMapping: AgentChatMapping;
AgentClientPolicy
Signature
declare const AgentClientPolicy: AgentClientPolicy<Guard, StateKey, Events>;
AgentClientStateKey
Signature
declare const AgentClientStateKey: AgentClientStateKey<Middleware>;
AgentControl
Signature
declare const AgentControl: AgentControl;
AgentDescriptor
Signature
declare const AgentDescriptor: AgentDescriptor<
Id,
Input,
Output,
InputSchema,
OutputSchema,
Middleware,
Tools
>;
AgentFilesystemBackend
Signature
declare const AgentFilesystemBackend: AgentFilesystemBackend;
AgentInstructions
Signature
declare const AgentInstructions: AgentInstructions;
AgentLimits
Signature
declare const AgentLimits: AgentLimits;
AgentMiddleware
Signature
declare const AgentMiddleware: AgentMiddleware;
AgentMiddlewareState
Signature
declare const AgentMiddlewareState: AgentMiddlewareState<Middleware>;
AgentModel
Signature
declare const AgentModel: AgentModel;
AgentModelFactory
Signature
declare const AgentModelFactory: AgentModelFactory<Environment>;
AgentSubagent
Signature
declare const AgentSubagent: AgentSubagent;
AgentTool
Signature
declare const AgentTool: AgentTool;
DeepAgentCapabilities
Signature
declare const DeepAgentCapabilities: DeepAgentCapabilities;
DefineAgentOptions
Signature
declare const DefineAgentOptions: DefineAgentOptions<
Id,
InputSchema,
OutputSchema,
Middleware,
Tools
>;
NativeAgentTool
Signature
declare const NativeAgentTool: NativeAgentTool;
PromptInstructions
Signature
declare const PromptInstructions: PromptInstructions;
PromptTemplate
Signature
declare const PromptTemplate: PromptTemplate;
assertAgentDescriptor
Signature
declare const assertAgentDescriptor: (value: unknown) => asserts value is AgentAny;
copyAgentLimits
Signature
declare const copyAgentLimits: (value: unknown) => AgentLimits;
copyAgentLimitsEffect
Signature
declare const copyAgentLimitsEffect: (
value: unknown,
) => Effect.Effect<
Readonly<{ maxSteps: number; maxToolCalls: number; timeoutMs: number }>,
import("@relkit/agents/internal/define-agent-error").AgentDefinitionFailure,
never
>;
defineAgentEffect
Defines a native agent with validated authoring options and substitutable identity generation.
Example
Effect.runSync(
defineAgentEffect({ id: "support", input, output, instructions: "Reply.", tools: [], limits }),
);
Signature
declare const defineAgentEffect: <
const Id extends string,
const InputSchema extends StandardSchemaV1,
const OutputSchema extends StandardSchemaV1,
const Middleware extends readonly AgentMiddleware[] = readonly [],
const Tools extends readonly AgentTool[] = ReadonlyArray<AgentTool>,
>(
options: DefineAgentOptions<Id, InputSchema, OutputSchema, Middleware, Tools>,
) => Effect.Effect<
AgentDescriptor<
Id,
InferInput<InputSchema>,
InferOutput<OutputSchema>,
InputSchema,
OutputSchema,
Middleware,
Tools
>,
AgentDefinitionFailure,
never
>;
isAgentDescriptor
Signature
declare const isAgentDescriptor: (value: unknown) => value is AgentAny;
define-agent.types.ts
Exposes SDK-native agent authoring with inferred input and output types; validation and descriptor assembly are delegated to the integration’s owning helpers. This companion preserves the native input and output types without starting runtime work.
AgentDescriptor (interface)
Signature
export interface AgentDescriptor<
Id extends string,
Input,
Output,
InputSchema extends StandardSchemaV1 = StandardSchemaV1,
OutputSchema extends StandardSchemaV1 = StandardSchemaV1,
Middleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[],
Tools extends readonly AgentTool[] = readonly AgentTool[],
>
extends
DescriptorBase<"agent", Id>,
AgentRef<Id, InputSchema, OutputSchema>,
DeepAgentCapabilities {
readonly model?: AgentModel;
readonly instructions: AgentInstructions;
readonly tools: Tools;
readonly middleware: Middleware;
readonly limits: AgentLimits;
readonly stateProfile?: string;
readonly client?: AgentClientPolicy<(...args: any[]) => unknown, AgentClientStateKey<Middleware>>;
readonly chat?: AgentChatMapping;
readonly controls?: readonly AgentControl[];
readonly clientContract: AgentClientContractMetadata;
}
AgentInstructions (type alias)
Signature
type AgentInstructions = string | PromptTemplate | PromptInstructions;
AgentLimits (interface)
Signature
export interface AgentLimits {
readonly maxSteps: number;
readonly maxToolCalls: number;
readonly timeoutMs: number;
}
DefineAgentOptions (interface)
Signature
export interface DefineAgentOptions<
Id extends string,
InputSchema extends StandardSchemaV1,
OutputSchema extends StandardSchemaV1,
Middleware extends readonly AgentMiddleware[],
Tools extends readonly AgentTool[],
>
extends DescriptorMetadata, DeepAgentCapabilities {
readonly id?: Id;
readonly input: InputSchema;
readonly output: OutputSchema;
readonly model?: AgentModel;
readonly instructions: AgentInstructions;
readonly tools: Tools;
readonly middleware?: Middleware;
readonly limits: AgentLimits;
readonly stateProfile?: string;
readonly client?: AgentClientPolicy<(...args: any[]) => unknown, AgentClientStateKey<Middleware>>;
readonly chat?: AgentChatMapping;
readonly controls?: readonly AgentControl[];
}
PromptInstructions (interface)
Signature
export interface PromptInstructions {
readonly kind: "prompt";
readonly id: string;
readonly ref: { readonly kind: "prompt"; readonly id: string };
readonly value: string | readonly string[];
}
PromptTemplate (interface)
Signature
export interface PromptTemplate {
readonly template: string;
readonly variables?: readonly string[];
}
define-graph-build.ts
Assembles graph nodes, edges, state and persistence into the authored native descriptor that compilation consumes without invoking graph nodes.
prepareGraphDescriptor
Validates graph authoring options and returns an assembler for its identity.
Throws
Invalid schema, node, edge, or client policy errors.
Example
prepareGraphDescriptor(options)("support.graph");
Signature
declare const prepareGraphDescriptor: <
const Id extends string,
const InputSchema extends StandardSchemaV1,
const OutputSchema extends StandardSchemaV1,
const State extends AnyStateSchema,
const Nodes extends readonly GraphNodeLike[],
>(
options: DefineGraphOptions<Id, InputSchema, OutputSchema, State, Nodes>,
) => (id: Id) => GraphDescriptor<Id, InputSchema, OutputSchema, State, Nodes>;
define-graph-error.ts
Defines graph authoring failures reported before native compilation, retaining the invalid graph field and actionable diagnostic.
GraphDefinitionFailure (class)
Tagged invalid graph authoring options or descriptor construction.
Signature
declare class GraphDefinitionFailure
graphDefinitionFailure
Preserves a graph authoring error for Effect callers.
Example
graphDefinitionFailure(new TypeError("invalid graph"));
Signature
declare const graphDefinitionFailure: (cause: unknown) => GraphDefinitionFailure;
define-graph-node.ts
Creates typed native graph node descriptors from author callbacks and records their execution metadata for later graph compilation.
“./define-graph-node.types.js” (namespace export)
Re-exports all named exports from the “./define-graph-node.types.js” module.
Signature
export * from "./define-graph-node.types.js";
assertGraphNodeDestinations
Signature
declare const assertGraphNodeDestinations: (
node: Pick<GraphNodeAny, "id" | "ends">,
registeredNodeIds: ReadonlySet<string> | readonly string[],
) => void;
defineGraphNode
Defines a graph node for existing synchronous authoring callers.
Throws
The original authoring error for invalid options.
Example
const node = defineGraphNode({ id: "step", input, output, handler });
Signature
declare const defineGraphNode: <
const Id extends string,
const InputSchema extends StandardSchemaV1,
const OutputSchema extends StandardSchemaV1,
const ResumeSchema extends StandardSchemaV1 | undefined = undefined,
const Ends extends readonly string[] = readonly [],
>(
options: DefineGraphNodeOptions<Id, InputSchema, OutputSchema, ResumeSchema, Ends>,
) => GraphNodeDescriptor<Id, InputSchema, OutputSchema, ResumeSchema, Ends>;
defineGraphNodeEffect
Defines a native LangGraph node with RELKIT schemas and declared dynamic routes.
Example
Effect.runSync(defineGraphNodeEffect({ id: "step", input, output, handler }));
Signature
declare const defineGraphNodeEffect: <
const Id extends string,
const InputSchema extends StandardSchemaV1,
const OutputSchema extends StandardSchemaV1,
const ResumeSchema extends StandardSchemaV1 | undefined = undefined,
const Ends extends readonly string[] = readonly [],
>(
options: DefineGraphNodeOptions<Id, InputSchema, OutputSchema, ResumeSchema, Ends>,
) => Effect.Effect<
GraphNodeDescriptor<Id, InputSchema, OutputSchema, ResumeSchema, Ends>,
GraphNodeValidationFailure,
never
>;
isGraphNodeDescriptor
Checks a graph node descriptor for existing synchronous callers.
Example
if (isGraphNodeDescriptor(value)) useNode(value);
Signature
declare const isGraphNodeDescriptor: (value: unknown) => value is GraphNodeAny;
isGraphNodeDescriptorEffect
Checks whether a value is a native graph node descriptor.
Example
Effect.runSync(isGraphNodeDescriptorEffect(value));
Signature
declare const isGraphNodeDescriptorEffect: (value: unknown) => Effect.Effect<boolean, never, never>;
runGraphNodeHandlerEffect
Runs input validation, the user handler, and output validation in one Effect.
Example
await Effect.runPromise(runGraphNodeHandlerEffect(options, [], input));
Signature
declare const runGraphNodeHandlerEffect: <
InputSchema extends StandardSchemaV1,
OutputSchema extends StandardSchemaV1,
Ends extends readonly string[],
>(
options: Pick<
DefineGraphNodeOptions<
string,
InputSchema,
OutputSchema,
StandardSchemaV1<unknown, unknown> | undefined,
Ends
>,
"input" | "output" | "handler"
>,
ends: Ends,
input: unknown,
config?: LangGraphRunnableConfig<Record<string, any>> | undefined,
) => Effect.Effect<GraphNodeResult<OutputSchema, Ends>, GraphNodeValidationFailure, never>;
define-graph-node.types.ts
Creates typed native graph node descriptors from author callbacks and records their execution metadata for later graph compilation. This companion preserves the native input and output types without starting runtime work.
DefineGraphNodeOptions (interface)
Authoring options for a native LangGraph node.
Signature
export interface DefineGraphNodeOptions<
Id extends string,
InputSchema extends StandardSchemaV1,
OutputSchema extends StandardSchemaV1,
ResumeSchema extends StandardSchemaV1 | undefined,
Ends extends readonly string[],
> extends DescriptorMetadata {
readonly id: Id;
readonly input: InputSchema;
readonly output: OutputSchema;
readonly resume?: ResumeSchema;
readonly ends?: Ends;
readonly handler: GraphNodeImplementation<InputSchema, OutputSchema, Ends>;
}
GraphNodeAny (type alias)
Erased graph node descriptor for runtime validation.
Signature
type GraphNodeAny = GraphNodeDescriptor<
string,
StandardSchemaV1,
StandardSchemaV1,
StandardSchemaV1 | undefined,
readonly string[]
>;
GraphNodeDescriptor (interface)
Immutable native graph node descriptor.
Signature
export interface GraphNodeDescriptor<
Id extends string = string,
InputSchema extends StandardSchemaV1 = StandardSchemaV1,
OutputSchema extends StandardSchemaV1 = StandardSchemaV1,
ResumeSchema extends StandardSchemaV1 | undefined = StandardSchemaV1 | undefined,
Ends extends readonly string[] = readonly string[],
> extends DescriptorMetadata {
readonly [RELKIT_GRAPH_NODE]: true;
readonly kind: "graph-node";
readonly id: Id;
readonly input: InputSchema;
readonly output: OutputSchema;
readonly resume?: ResumeSchema;
readonly ends: Ends;
readonly handler: GraphNodeHandler<InputSchema, OutputSchema, Ends>;
}
GraphNodeHandler (type alias)
Validated handler stored on a graph node descriptor.
Signature
type GraphNodeHandler<
InputSchema extends StandardSchemaV1,
OutputSchema extends StandardSchemaV1,
Ends extends readonly string[],
> = (
input: InferOutput<InputSchema>,
config?: LangGraphRunnableConfig,
) => MaybePromise<GraphNodeResult<OutputSchema, Ends>>;
GraphNodeImplementation (type alias)
User implementation before RELKIT input and output validation.
Signature
type GraphNodeImplementation<
InputSchema extends StandardSchemaV1,
OutputSchema extends StandardSchemaV1,
Ends extends readonly string[],
> = (
input: InferOutput<InputSchema>,
config?: LangGraphRunnableConfig,
) => MaybePromise<
| NodeUpdateInput<OutputSchema>
| Command<unknown, NodeUpdateInput<OutputSchema>, CommandNodes<Ends>>
>;
GraphNodeResult (type alias)
Validated graph node result or native routing command.
Signature
type GraphNodeResult<OutputSchema extends StandardSchemaV1, Ends extends readonly string[]> =
NodeUpdate<OutputSchema> | Command<unknown, NodeUpdate<OutputSchema>, CommandNodes<Ends>>;
define-graph.ts
Exposes typed LangGraph authoring and delegates descriptor validation and construction before any graph execution can begin.
“./define-graph.types.js” (namespace export)
Re-exports all named exports from the “./define-graph.types.js” module.
Signature
export * from "./define-graph.types.js";
defineGraph
Defines a graph for existing synchronous authoring callers.
Throws
The original invalid graph authoring or identity error.
Example
const graph = defineGraph({ id: "flow", state, input, output, nodes, edges, limits });
Signature
declare const defineGraph: <
const Id extends string,
const InputSchema extends StandardSchemaV1,
const OutputSchema extends StandardSchemaV1,
const State extends AnyStateSchema,
const Nodes extends readonly GraphNodeLike[],
>(
options: DefineGraphOptions<Id, InputSchema, OutputSchema, State, Nodes>,
) => GraphDescriptor<Id, InputSchema, OutputSchema, State, Nodes>;
Backend and frontend example
Backend — these maintained files define the operation used by the frontend below.
const orderReview = defineGraph({
state,
input: z.object({ orderId: z.string() }),
output: z.object({ result: z.string() }),
nodes: [inventory, risk, retry, review, finish],
edges: (edge) =>
edge
.addEdge(START, "load-inventory")
.addEdge(START, "assess-risk")
.addEdge(["load-inventory", "assess-risk"], "retry")
.addConditionalEdges("retry", ({ attempts }) => (attempts === 1 ? "again" : "ready"), {
again: "retry",
ready: "review",
})
.addEdge("finish", END),
checkpointer: orderCheckpoints,
store: orderMemory,
limits: { maxSteps: 10, maxToolCalls: 1, timeoutMs: 20_000 },
stateProfile: "agents",
client: {
public: true,
state: ["inventory", "risk", "attempts", "approved", "result"],
},
controls: ["stop"],
});
Frontend
After frontend setup and pulling the commerce contract, render
this component under the provider with your application’s stable business threadId:
"use client";
/** Starts the commerce review graph and answers its boolean interrupt on the same business thread. */
import { useAgent, useRelkitClient } from "@relkit/client/react";
import { useState } from "react";
/** Keeps initial input and a waiting reply distinct while rendering the graph's final result.
* @param props - Authorized order-review thread retained by the application.
* @returns Start/approve actions, current result, and visible submission failure. */
export function OrderReview({ threadId }: { readonly threadId: string }) {
const { status } = useRelkitClient();
const review = useAgent("orders.order-review");
const [failure, setFailure] = useState("");
/** Starts one review; uncertain acceptance is left for explicit thread recovery.
* @returns Completion after acceptance or displaying the failure. */
async function startReview() {
try {
await review.run({ orderId: "demo-1" }, { threadId });
} catch (error) {
setFailure(String(error));
}
}
/** Replies with the review node's declared boolean on the original thread.
* @returns Completion after the continuation is accepted or its failure is displayed. */
async function approve() {
try {
await review.run(true, { threadId, resume: true });
} catch (error) {
setFailure(String(error));
}
}
return (
<section>
<button
disabled={status !== "ready" || review.status !== "idle" || failure !== ""}
onClick={startReview}
>
Start review
</button>
<button
disabled={status !== "ready" || review.status !== "waiting" || failure !== ""}
onClick={approve}
>
Approve order
</button>
<p role="status">{review.output?.result ?? review.status}</p>
{failure && <p role="alert">{failure}. Check this thread before submitting again.</p>}
</section>
);
}
defineGraph generates an agent client too. The initial run receives { orderId }; the review
node’s resume: z.boolean() makes the continuation accept a boolean. Resume the same thread with
{ resume: true }, and show the final output.result. Do not send a replacement initial run to
answer an interrupt or replay an uncertain submission.
Reference: useAgent.
Continue with threads and recovery.
defineGraphEffect
Defines an inspectable agent backed by native LangGraph.
Example
Effect.runSync(defineGraphEffect({ id: "flow", state, input, output, nodes, edges, limits }));
Signature
declare const defineGraphEffect: <
const Id extends string,
const InputSchema extends StandardSchemaV1,
const OutputSchema extends StandardSchemaV1,
const State extends AnyStateSchema,
const Nodes extends readonly GraphNodeLike[],
>(
options: DefineGraphOptions<Id, InputSchema, OutputSchema, State, Nodes>,
) => Effect.Effect<
GraphDescriptor<Id, InputSchema, OutputSchema, State, Nodes>,
GraphDefinitionFailure,
never
>;
graphExecution
Reads graph runtime state for existing synchronous callers.
Example
graphExecution(graph);
Signature
declare const graphExecution: (value: GraphDescriptor) => GraphExecution;
graphExecutionEffect
Reads the hidden runtime state of an authored graph.
Example
Effect.runSync(graphExecutionEffect(graph));
Signature
declare const graphExecutionEffect: (
value: GraphDescriptor<
string,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
AnyStateSchema,
ReadonlyArray<GraphNodeLike>
>,
) => Effect.Effect<GraphExecution<InferStateSchemaValue<any>>, never, never>;
isGraphDescriptor
Checks a graph descriptor for existing synchronous callers.
Example
if (isGraphDescriptor(candidate)) invokeGraph(candidate);
Signature
declare const isGraphDescriptor: (value: unknown) => value is GraphDescriptor;
isGraphDescriptorEffect
Checks whether a value is a native graph descriptor.
Example
Effect.runSync(isGraphDescriptorEffect(candidate));
Signature
declare const isGraphDescriptorEffect: (value: unknown) => Effect.Effect<boolean, never, never>;
define-graph.types.ts
Exposes typed LangGraph authoring and delegates descriptor validation and construction before any graph execution can begin. This companion preserves the native input and output types without starting runtime work.
DefineGraphOptions (interface)
Authoring options for a native LangGraph agent descriptor.
Signature
export interface DefineGraphOptions<
Id extends string,
InputSchema extends StandardSchemaV1,
OutputSchema extends StandardSchemaV1,
State extends AnyStateSchema,
Nodes extends readonly GraphNodeLike[],
> extends DescriptorMetadata {
readonly id?: Id;
readonly state: State;
readonly input: InputSchema;
readonly output: OutputSchema;
readonly nodes: Nodes & UniqueNodes<Nodes>;
readonly edges: (
graph: GraphEdgeBuilder<NoInfer<Extract<GraphNodeId<Nodes>, string>>, GraphState<State>>,
) => unknown;
readonly limits: AgentLimits;
readonly stateProfile?: string;
readonly client?: AgentClientPolicy<(...args: any[]) => unknown, GraphStateKey<State>>;
readonly controls?: readonly AgentControl[];
readonly checkpointer?: BaseCheckpointSaver | CheckpointerResource;
readonly store?: BaseStore | MemoryResource;
}
GraphDescriptor (interface)
Inspectable agent descriptor backed by a native LangGraph graph.
Signature
export interface GraphDescriptor<
Id extends string = string,
InputSchema extends StandardSchemaV1 = StandardSchemaV1,
OutputSchema extends StandardSchemaV1 = StandardSchemaV1,
State extends AnyStateSchema = AnyStateSchema,
Nodes extends readonly GraphNodeLike[] = readonly GraphNodeLike[],
>
extends DescriptorBase<"agent", Id>, AgentRef<Id, InputSchema, OutputSchema> {
readonly execution: "graph";
readonly input: InputSchema;
readonly output: OutputSchema;
readonly nodes: Nodes;
readonly workflow: GraphWorkflow;
readonly instructions: "";
readonly tools: readonly [];
readonly middleware: readonly [];
readonly limits: AgentLimits;
readonly stateProfile?: string;
readonly client?: AgentClientPolicy<(...args: any[]) => unknown, GraphStateKey<State>>;
readonly controls?: readonly AgentControl[];
readonly clientContract: AgentClientContractMetadata;
readonly [GRAPH_EXECUTION]: GraphExecution<GraphState<State>>;
readonly asGraphNode: <const NodeId extends string = Id>(
options?: GraphAsNodeOptions<NodeId>,
) => SubgraphNodeDescriptor<NodeId, InputSchema, OutputSchema>;
}
GraphExecution (interface)
Runtime state and persistence declarations hidden on a graph descriptor.
Signature
export interface GraphExecution<State = any> {
readonly state: AnyStateSchema;
readonly operations: readonly GraphEdgeOperation<string, State>[];
readonly checkpointer?: BaseCheckpointSaver | CheckpointerResource;
readonly store?: BaseStore | MemoryResource;
}
GraphInput (type alias)
Input inferred from a graph descriptor.
Signature
type GraphInput<Graph extends GraphDescriptor> = InferInput<Graph["input"]>;
GraphNodeId (type alias)
ID union of a graph’s authored nodes.
Signature
type GraphNodeId<Nodes extends readonly GraphNodeLike[]> = Nodes[number]["id"];
GraphNodeLike (type alias)
Authored node accepted by a graph descriptor.
Signature
type GraphNodeLike = GraphNodeAny | FunctionGraphNodeDescriptor | SubgraphNodeDescriptor;
GraphOutput (type alias)
Output inferred from a graph descriptor.
Signature
type GraphOutput<Graph extends GraphDescriptor> = InferOutput<Graph["output"]>;
GraphState (type alias)
State value inferred from a LangGraph StateSchema.
Signature
type GraphState<State extends AnyStateSchema> = State["State"];
GraphStateKey (type alias)
Public state keys selected from a LangGraph StateSchema.
Signature
type GraphStateKey<State extends AnyStateSchema> = Extract<keyof GraphState<State>, string>;
define-persistence-guards.ts
Recognizes supported native checkpointer and store shapes before persistence descriptors accept them, preserving SDK identity rather than cloning resources.
assertPersistenceProtocol
Validates a resolved handle for existing synchronous callers.
Throws
The original protocol TypeError.
Example
assertPersistenceProtocol("memory", store);
Signature
declare const assertPersistenceProtocol: (
resource: "checkpointer" | "memory",
value: unknown,
) => asserts value is BaseCheckpointSaver | BaseStore;
assertPersistenceProtocolEffect
Validates a resolved LangGraph checkpointer or memory store.
Example
Effect.runSync(assertPersistenceProtocolEffect("memory", store));
Signature
declare const assertPersistenceProtocolEffect: (
resource: "checkpointer" | "memory",
value: unknown,
) => Effect.Effect<void, AgentPersistenceFailure, never>;
isPersistenceResource
Checks a resource for existing synchronous callers.
Example
if (isPersistenceResource(value)) await value.acquire(context);
Signature
declare const isPersistenceResource: (value: unknown) => value is PersistenceResource<any, any>;
isPersistenceResourceEffect
Checks whether a value is a RELKIT persistence resource descriptor.
Example
Effect.runSync(isPersistenceResourceEffect(candidate));
Signature
declare const isPersistenceResourceEffect: (value: unknown) => Effect.Effect<boolean, never, never>;
define-persistence.ts
Creates native persistence descriptors around authored checkpointers and stores; runtime acquisition and release remain owned by the invocation scope.
“./define-persistence.types.js” (namespace export)
Re-exports all named exports from the “./define-persistence.types.js” module.
Signature
export * from "./define-persistence.types.js";
assertPersistenceProtocol
Signature
declare const assertPersistenceProtocol: (
resource: "checkpointer" | "memory",
value: unknown,
) => asserts value is BaseCheckpointSaver | BaseStore;
assertPersistenceProtocolEffect
Signature
declare const assertPersistenceProtocolEffect: (
resource: "checkpointer" | "memory",
value: unknown,
) => Effect.Effect<void, AgentPersistenceFailure, never>;
defineCheckpointerDb
Defines a checkpointer for existing synchronous authoring callers.
Throws
The original invalid options error.
Example
const resource = defineCheckpointerDb({ id: "db", client: saver });
Signature
declare const defineCheckpointerDb: <Value extends BaseCheckpointSaver>(
options: PersistenceOptions<Value>,
) => CheckpointerResource<Value>;
defineCheckpointerDbEffect
Defines a lazily acquired checkpointer resource.
Example
Effect.runSync(defineCheckpointerDbEffect({ id: "db", client: saver }));
Signature
declare const defineCheckpointerDbEffect: <Value extends BaseCheckpointSaver>(
options: PersistenceOptions<Value>,
) => Effect.Effect<PersistenceResource<"checkpointer", Value>, AgentPersistenceFailure, never>;
defineMemoryDb
Defines a memory store for existing synchronous authoring callers.
Throws
The original invalid options error.
Example
const resource = defineMemoryDb({ id: "memory", client: store });
Signature
declare const defineMemoryDb: <Value extends BaseStore>(
options: PersistenceOptions<Value>,
) => MemoryResource<Value>;
defineMemoryDbEffect
Defines a lazily acquired memory store resource.
Example
Effect.runSync(defineMemoryDbEffect({ id: "memory", client: store }));
Signature
declare const defineMemoryDbEffect: <Value extends BaseStore>(
options: PersistenceOptions<Value>,
) => Effect.Effect<PersistenceResource<"memory", Value>, AgentPersistenceFailure, never>;
isPersistenceResource
Signature
declare const isPersistenceResource: (value: unknown) => value is PersistenceResource<any, any>;
isPersistenceResourceEffect
Signature
declare const isPersistenceResourceEffect: (value: unknown) => Effect.Effect<boolean, never, never>;
define-persistence.types.ts
Creates native persistence descriptors around authored checkpointers and stores; runtime acquisition and release remain owned by the invocation scope. This companion preserves the native input and output types without starting runtime work.
CheckpointerResource (type alias)
Checkpointer resource passed to a LangGraph runtime.
Signature
type CheckpointerResource<Value extends BaseCheckpointSaver = BaseCheckpointSaver> =
PersistenceResource<"checkpointer", Value>;
MemoryResource (type alias)
Memory store resource passed to a LangGraph runtime.
Signature
type MemoryResource<Value extends BaseStore = BaseStore> = PersistenceResource<"memory", Value>;
PersistenceContext (interface)
Environment made available while acquiring persistence.
Signature
export interface PersistenceContext {
readonly env: Readonly<Record<string, unknown>>;
}
PersistenceOptions (interface)
Acquisition and disposal configuration for an agent persistence resource.
Signature
export interface PersistenceOptions<Value> {
readonly id: string;
readonly client: Value | ((context: PersistenceContext) => MaybePromise<Value>);
readonly ownership?: "owned" | "borrowed";
readonly dispose?: (value: Value) => MaybePromise<void>;
}
PersistenceResource (interface)
Lazily acquired, explicitly released persistence descriptor.
Signature
export interface PersistenceResource<Kind extends "checkpointer" | "memory", Value> {
readonly [RELKIT_PERSISTENCE]: true;
readonly kind: "agent-persistence";
readonly resource: Kind;
readonly id: string;
readonly ownership: "owned" | "borrowed";
readonly acquire: (context: PersistenceContext) => Promise<Value>;
readonly release: () => Promise<void>;
}
graph-compile-error.ts
Defines typed failures for native graph compilation, preserving the graph identity and underlying native compile cause.
GraphCompilationFailure (class)
Tagged graph compilation or route execution failure.
Signature
declare class GraphCompilationFailure
graphCompilationFailure
Preserves a graph compilation or route error for Effect callers.
Example
graphCompilationFailure(new TypeError("invalid route"));
Signature
declare const graphCompilationFailure: (cause: unknown) => GraphCompilationFailure;
graph-compile.ts
Compiles validated RELKIT graph descriptors into LangGraph execution objects using the authored nodes, edges, state and persistence options.
compileGraph
Compiles a graph for existing synchronous runtime callers.
Throws
The original compilation error.
Example
const runnable = compileGraph(graph);
Signature
declare const compileGraph: (
descriptor: GraphDescriptor,
persistence?: ResolvedGraphPersistence,
) => any;
compileGraphEffect
Compiles a graph descriptor and its resolved persistence resources.
Example
Effect.runSync(compileGraphEffect(graph));
Signature
declare const compileGraphEffect: (
descriptor: GraphDescriptor<
string,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
AnyStateSchema,
ReadonlyArray<GraphNodeLike>
>,
persistence?: ResolvedGraphPersistence | undefined,
) => Effect.Effect<any, GraphCompilationFailure, never>;
runGraphRouteEffect
Runs a user route and validates its destination with linked cancellation.
Example
await Effect.runPromise(runGraphRouteEffect(route, state, config, ids));
Signature
declare const runGraphRouteEffect: <Id extends string>(
route: (state: unknown, config: LangGraphRunnableConfig) => MaybePromise<unknown>,
state: unknown,
config: LangGraphRunnableConfig<Record<string, any>>,
nodeIds: ReadonlySet<Id>,
destinations?: Readonly<Record<string, "__end__" | Id>> | undefined,
) => Effect.Effect<unknown, GraphCompilationFailure, never>;
graph-continuation-error.ts
Defines continuation failures for persisted native graphs so invalid or unavailable resume state remains distinct from invocation failures.
GraphContinuationFailure (class)
Tagged validation or state failure while resuming a graph.
Signature
declare class GraphContinuationFailure
graphContinuationFailure
Preserves the original graph continuation error.
Example
graphContinuationFailure(new TypeError("invalid reply"));
Signature
declare const graphContinuationFailure: (cause: unknown) => GraphContinuationFailure;
graph-continuation-validation.ts
Checks persisted graph continuation input and identity before native resume admission, preventing execution against a mismatched thread or graph.
validateGraphResumeInput
Validates graph continuation replies for existing Promise callers.
Throws
The original continuation validation error.
Example
await validateGraphResumeInput(graph, requests, reply);
Signature
declare const validateGraphResumeInput: (
descriptor: GraphDescriptor,
requests: readonly AgentWaitingRequest[],
value: unknown,
) => Promise<unknown>;
validateGraphResumeInputEffect
Validates one or more graph continuation replies with bounded concurrency.
Example
Effect.runPromise(validateGraphResumeInputEffect(graph, requests, reply));
Signature
declare const validateGraphResumeInputEffect: (
descriptor: GraphDescriptor<
string,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
AnyStateSchema,
ReadonlyArray<GraphNodeLike>
>,
requests: ReadonlyArray<AgentWaitingRequest>,
value: unknown,
) => Effect.Effect<unknown, GraphContinuationFailure, never>;
graph-continuation-waiting.ts
Projects native graph interrupts into durable waiting state used by the RELKIT continuation protocol before returning control to callers.
waitingInterrupts
Reads waiting interrupts for existing Promise callers.
Throws
The original graph state or schema failure.
Example
await waitingInterrupts(graph, descriptor, config);
Signature
declare const waitingInterrupts: (
graph: CompiledGraph,
descriptor: GraphDescriptor,
config: GraphConfig,
) => Promise<readonly GraphWaitingInterrupt[]>;
waitingInterruptsEffect
Reads waiting interrupts from the graph state snapshot.
Example
Effect.runPromise(waitingInterruptsEffect(graph, descriptor, config));
Signature
declare const waitingInterruptsEffect: (
graph: any,
descriptor: GraphDescriptor<
string,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
AnyStateSchema,
ReadonlyArray<GraphNodeLike>
>,
config: GraphConfig,
) => Effect.Effect<ReadonlyArray<GraphWaitingInterrupt>, GraphContinuationFailure, never>;
graph-continuation.ts
Coordinates native graph resume requests with persisted waiting state and the invocation scope, preserving continuation failures and thread identity.
GraphConfig
Signature
declare const GraphConfig: GraphConfig;
graphConfig
Builds graph run configuration for existing synchronous callers.
Throws
The original missing thread error.
Example
const config = graphConfig(graph, "thread");
Signature
declare const graphConfig: (descriptor: GraphDescriptor, threadId?: string) => GraphConfig;
graphConfigEffect
Builds a persistent graph run configuration.
Example
Effect.runSync(graphConfigEffect(graph, "thread"));
Signature
declare const graphConfigEffect: (
descriptor: GraphDescriptor<
string,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
AnyStateSchema,
ReadonlyArray<GraphNodeLike>
>,
threadId?: string | undefined,
) => Effect.Effect<GraphConfig, GraphContinuationFailure, never>;
resumeCommand
Constructs a native resume command for existing Promise callers.
Throws
The original state or continuation validation error.
Example
await resumeCommand(graph, descriptor, config, reply);
Signature
declare const resumeCommand: (
graph: CompiledGraph,
descriptor: GraphDescriptor,
config: GraphConfig,
value: unknown,
) => Promise<Command>;
resumeCommandEffect
Validates a reply and constructs a native LangGraph resume command.
Example
Effect.runPromise(resumeCommandEffect(graph, descriptor, config, reply));
Signature
declare const resumeCommandEffect: (
graph: any,
descriptor: GraphDescriptor<
string,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
AnyStateSchema,
ReadonlyArray<GraphNodeLike>
>,
config: GraphConfig,
value: unknown,
) => Effect.Effect<
Command<unknown, Record<string, unknown>, string>,
GraphContinuationFailure,
never
>;
validateGraphResumeInput
Signature
declare const validateGraphResumeInput: (
descriptor: GraphDescriptor,
requests: readonly AgentWaitingRequest[],
value: unknown,
) => Promise<unknown>;
validateGraphResumeInputEffect
Signature
declare const validateGraphResumeInputEffect: (
descriptor: GraphDescriptor<
string,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
AnyStateSchema,
ReadonlyArray<GraphNodeLike>
>,
requests: ReadonlyArray<AgentWaitingRequest>,
value: unknown,
) => Effect.Effect<unknown, GraphContinuationFailure, never>;
waitingInterrupts
Signature
declare const waitingInterrupts: (
graph: CompiledGraph,
descriptor: GraphDescriptor,
config: GraphConfig,
) => Promise<readonly GraphWaitingInterrupt[]>;
waitingInterruptsEffect
Signature
declare const waitingInterruptsEffect: (
graph: any,
descriptor: GraphDescriptor<
string,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
AnyStateSchema,
ReadonlyArray<GraphNodeLike>
>,
config: GraphConfig,
) => Effect.Effect<ReadonlyArray<GraphWaitingInterrupt>, GraphContinuationFailure, never>;
graph-continuation.types.ts
Coordinates native graph resume requests with persisted waiting state and the invocation scope, preserving continuation failures and thread identity. This companion preserves the native input and output types without starting runtime work.
CompiledGraph (type alias)
Compiled graph accepted by continuation helpers.
Signature
type CompiledGraph = ReturnType<typeof compileGraph>;
GraphConfig (type alias)
LangGraph run configuration with an optional persistent thread identity.
Signature
type GraphConfig = {} | { readonly configurable: { readonly thread_id: string } };
graph-definition.ts
Validates graph structure and resolves authored node identities before native compilation, reporting missing or inconsistent graph definitions.
prepareGraphDefinition
Validates graph authoring for existing synchronous callers.
Throws
The original graph authoring error.
Example
const prepared = prepareGraphDefinition(state, input, output, nodes, edges);
Signature
declare const prepareGraphDefinition: (
state: AnyStateSchema,
input: StandardSchemaV1,
output: StandardSchemaV1,
sourceNodes: readonly GraphNodeLike[],
edges: (builder: GraphEdgeBuilder<string, any>) => unknown,
) => {
readonly nodes: readonly GraphNodeLike[];
readonly operations: readonly GraphEdgeOperation<string, any>[];
readonly stateKeys: Set<string>;
};
prepareGraphDefinitionEffect
Validates graph state, nodes, and edge declarations.
Example
Effect.runSync(prepareGraphDefinitionEffect(state, input, output, nodes, edges));
Signature
declare const prepareGraphDefinitionEffect: (
state: AnyStateSchema,
input: StandardSchemaV1<unknown, unknown>,
output: StandardSchemaV1<unknown, unknown>,
sourceNodes: ReadonlyArray<GraphNodeLike>,
edges: (builder: GraphEdgeBuilder<string, any>) => unknown,
) => Effect.Effect<
{
readonly nodes: readonly GraphNodeLike[];
readonly operations: readonly GraphEdgeOperation<string, any>[];
readonly stateKeys: Set<string>;
},
GraphDefinitionFailure,
never
>;
graph-edge-destinations.ts
Validates native graph endpoints and conditional route results before execution. Mutation builders reuse the same endpoint and duplicate-edge rules.
addUnique
Signature
declare const addUnique: (signatures: Set<string>, signature: string) => void;
assertEndpoint
Signature
declare const assertEndpoint: <Id extends string>(
value: unknown,
nodeIds: ReadonlySet<Id>,
source: boolean,
) => asserts value is Id | typeof START | typeof END;
assertGraphDestination
Checks native route targets for existing synchronous callers.
Throws
The original invalid destination error.
Example
assertGraphDestination("next", ids);
Signature
declare const assertGraphDestination: <Id extends string>(
value: unknown,
nodeIds: ReadonlySet<Id>,
) => void;
assertGraphDestinationEffect
Checks native route targets against registered nodes.
Example
Effect.runSync(assertGraphDestinationEffect("next", ids));
Signature
declare const assertGraphDestinationEffect: <Id extends string>(
value: unknown,
nodeIds: ReadonlySet<Id>,
) => Effect.Effect<void, GraphDefinitionFailure, never>;
copyDestinations
Signature
declare const copyDestinations: <Id extends string>(
value: Readonly<Record<string, Id | typeof END>>,
nodeIds: ReadonlySet<Id>,
) => Readonly<Record<string, Id | typeof END>>;
validateGraphRoute
Validates dynamic routes for existing synchronous callers.
Throws
The original invalid route error.
Example
validateGraphRoute("yes", ids, { yes: "next" });
Signature
declare const validateGraphRoute: <Id extends string>(
value: unknown,
nodeIds: ReadonlySet<Id>,
destinations?: Readonly<Record<string, Id | typeof END>>,
) => void;
validateGraphRouteEffect
Validates dynamic route labels or node destinations.
Example
Effect.runSync(validateGraphRouteEffect("yes", ids, { yes: "next" }));
Signature
declare const validateGraphRouteEffect: <Id extends string>(
value: unknown,
nodeIds: ReadonlySet<Id>,
destinations?: Readonly<Record<string, "__end__" | Id>> | undefined,
) => Effect.Effect<void, GraphDefinitionFailure, never>;
graph-edge-mutations.ts
Applies validated edge mutations to one builder-owned operation log. Factories retain that builder’s closure so duplicate checks and mutation order stay local.
conditionalEdgeMutation
Creates conditional mutations sharing one checked operation log.
Signature
declare const conditionalEdgeMutation: <Id extends string, State>(
context: GraphEdgeMutationContext<Id, State>,
) => (
source: "__start__" | Id,
route: (state: State, config: LangGraphRunnableConfig) => MaybePromise<unknown>,
destinations?: Readonly<Record<string, "__end__" | Id>> | undefined,
) => Effect.Effect<GraphEdgeBuilder<Id, State>, GraphDefinitionFailure, never>;
edgeMutation
Creates direct/join mutations sharing the same checked operation log.
Signature
declare const edgeMutation: <Id extends string, State>(
context: GraphEdgeMutationContext<Id, State>,
) => (
start: "__start__" | Id | ReadonlyArray<Id>,
end: "__end__" | Id,
) => Effect.Effect<GraphEdgeBuilder<Id, State>, GraphDefinitionFailure, never>;
graph-edge-mutations.types.ts
One graph builder’s private ordered mutation authority.
GraphEdgeMutationContext (interface)
Signature
export interface GraphEdgeMutationContext<Id extends string, State> {
readonly nodeIds: ReadonlySet<Id>;
readonly operations: GraphEdgeOperation<Id, State>[];
readonly signatures: Set<string>;
readonly builder: () => GraphEdgeBuilder<Id, State>;
}
graph-edges.ts
Defines typed native graph edge and routing descriptors whose endpoints are checked during graph assembly and compilation.
“./graph-edges.types.js” (namespace export)
Re-exports all named exports from the “./graph-edges.types.js” module.
Signature
export * from "./graph-edges.types.js";
assertGraphDestination
Signature
declare const assertGraphDestination: <Id extends string>(
value: unknown,
nodeIds: ReadonlySet<Id>,
) => void;
assertGraphDestinationEffect
Signature
declare const assertGraphDestinationEffect: <Id extends string>(
value: unknown,
nodeIds: ReadonlySet<Id>,
) => Effect.Effect<void, GraphDefinitionFailure, never>;
createGraphEdgeBuilder
Creates an edge builder for existing synchronous graph authoring.
Example
const { builder, operations } = createGraphEdgeBuilder(ids);
Signature
declare const createGraphEdgeBuilder: <Id extends string, State>(
nodeIds: ReadonlySet<Id>,
) => {
readonly builder: GraphEdgeBuilder<Id, State>;
readonly operations: readonly GraphEdgeOperation<Id, State>[];
};
createGraphEdgeBuilderEffect
Creates an edge builder whose mutations run through Effect.
Example
Effect.runSync(createGraphEdgeBuilderEffect(ids));
Signature
declare const createGraphEdgeBuilderEffect: <Id extends string, State>(
nodeIds: ReadonlySet<Id>,
) => Effect.Effect<
{
builder: Readonly<GraphEdgeBuilder<Id, State>>;
operations: Array<GraphEdgeOperation<Id, State>>;
},
never,
never
>;
validateGraphRoute
Signature
declare const validateGraphRoute: <Id extends string>(
value: unknown,
nodeIds: ReadonlySet<Id>,
destinations?: Readonly<Record<string, Id | typeof END>>,
) => void;
validateGraphRouteEffect
Signature
declare const validateGraphRouteEffect: <Id extends string>(
value: unknown,
nodeIds: ReadonlySet<Id>,
destinations?: Readonly<Record<string, "__end__" | Id>> | undefined,
) => Effect.Effect<void, GraphDefinitionFailure, never>;
graph-edges.types.ts
Defines typed native graph edge and routing descriptors whose endpoints are checked during graph assembly and compilation. This companion preserves the native input and output types without starting runtime work.
GraphConditionalRoute (type alias)
Label based graph conditional route callback.
Signature
type GraphConditionalRoute<Id extends string, State, Key extends string> = (
state: State,
config: LangGraphRunnableConfig,
) => MaybePromise<Key | Send<Id, Partial<State>> | readonly (Key | Send<Id, Partial<State>>)[]>;
GraphEdgeBuilder (interface)
Mutable graph edge authoring interface backed by Effect operations.
Signature
export interface GraphEdgeBuilder<Id extends string, State> {
/** Adds a static or join edge.
* @param start - One or more source nodes.
* @param end - Destination node.
* @returns This builder.
* @throws TypeError for invalid or duplicate edges.
* @example edge.addEdge("start", "finish");
*/
addEdge(
start: typeof START | NoInfer<Id> | readonly NoInfer<Id>[],
end: NoInfer<Id> | typeof END,
): GraphEdgeBuilder<Id, State>;
/** Adds a dynamic edge.
* @param source - Source node.
* @param route - Route callback.
* @returns This builder.
* @throws TypeError for invalid or duplicate routes.
* @example edge.addConditionalEdges("start", () => "finish");
*/
addConditionalEdges(
source: typeof START | NoInfer<Id>,
route: GraphRoute<NoInfer<Id>, State>,
): GraphEdgeBuilder<Id, State>;
/** Adds a labeled dynamic edge.
* @param source - Source node.
* @param route - Route callback.
* @param destinations - Label to destination mapping.
* @returns This builder.
* @throws TypeError for invalid or duplicate routes.
* @example edge.addConditionalEdges("start", () => "yes", { yes: "finish" });
*/
addConditionalEdges<const Key extends string>(
source: typeof START | NoInfer<Id>,
route: GraphConditionalRoute<NoInfer<Id>, State, Key>,
destinations: Readonly<Record<Key, NoInfer<Id> | typeof END>>,
): GraphEdgeBuilder<Id, State>;
}
GraphEdgeOperation (type alias)
Recorded edge operation consumed by the LangGraph compiler.
Signature
type GraphEdgeOperation<Id extends string, State> =
| {
readonly kind: "edge";
readonly start: typeof START | Id | readonly Id[];
readonly end: Id | typeof END;
}
| {
readonly kind: "conditional";
readonly source: typeof START | Id;
readonly route: (state: State, config: LangGraphRunnableConfig) => MaybePromise<unknown>;
readonly destinations?: Readonly<Record<string, Id | typeof END>>;
};
GraphRoute (type alias)
Native graph conditional route callback.
Signature
type GraphRoute<Id extends string, State> = (
state: State,
config: LangGraphRunnableConfig,
) => MaybePromise<Id | typeof END | Send<Id> | readonly (Id | Send<Id>)[]>;
graph-execution-symbol.ts
Private nonenumerable slot holding compiled graph authoring data.
GRAPH_EXECUTION
Private nonenumerable slot holding compiled graph authoring data.
Signature
declare const GRAPH_EXECUTION: unique symbol;
graph-interruption.ts
Converts native graph interrupt observations into RELKIT continuation data while preserving the interrupt identifiers needed for resume.
GraphInterruptedError (class)
Internal control result used by the server to publish a durable waiting snapshot.
Example
throw new GraphInterruptedError("thread-1", interrupts);
Signature
declare class GraphInterruptedError { constructor(
readonly threadId: string,
readonly interrupts: readonly GraphWaitingInterrupt[],
) }
code (property)
Signature
readonly code: "RELKIT_GRAPH_INTERRUPTED"
GraphWaitingInterrupt
Signature
declare const GraphWaitingInterrupt: GraphWaitingInterrupt;
GraphWaitingResponseError (class)
No pending request is available to form a graph interruption response.
Signature
declare class GraphWaitingResponseError
graphWaitingResponse
Combines pending graph responses for synchronous runtime callers.
Throws
TypeError when no request is pending.
Example
const response = graphWaitingResponse([{ node: "review", response: true }]);
Signature
declare const graphWaitingResponse: (interrupts: readonly GraphWaitingInterrupt[]) => JsonValue;
graphWaitingResponseEffect
Combines pending graph responses into one JSON schema.
Example
const response = Effect.runSync(graphWaitingResponseEffect([{ node: "review", response: true }]));
Signature
declare const graphWaitingResponseEffect: (
interrupts: ReadonlyArray<GraphWaitingInterrupt>,
) => Effect.Effect<JsonValue, GraphWaitingResponseError, never>;
isGraphInterruptedError
Recognizes graph interruption errors for synchronous callers.
Example
if (isGraphInterruptedError(error)) console.log(error.threadId);
Signature
declare const isGraphInterruptedError: (value: unknown) => value is GraphInterruptedError;
isGraphInterruptedErrorEffect
Recognizes the internal graph interruption control result.
Example
const interrupted = Effect.runSync(isGraphInterruptedErrorEffect(error));
Signature
declare const isGraphInterruptedErrorEffect: (
value: unknown,
) => Effect.Effect<boolean, never, never>;
publicWaitingRequests
Returns public waiting requests for synchronous runtime callers.
Example
const requests = publicWaitingRequests(interrupts);
Signature
declare const publicWaitingRequests: (
interrupts: readonly GraphWaitingInterrupt[],
) => readonly AgentWaitingRequest[];
publicWaitingRequestsEffect
Removes internal identifiers while retaining public waiting request order.
Example
const requests = Effect.runSync(publicWaitingRequestsEffect(interrupts));
Signature
declare const publicWaitingRequestsEffect: (
interrupts: ReadonlyArray<GraphWaitingInterrupt>,
) => Effect.Effect<Array<{ response: JsonValue; value?: {} | null; node: string }>, never, never>;
graph-interruption.types.ts
Converts native graph interrupt observations into RELKIT continuation data while preserving the interrupt identifiers needed for resume. This companion preserves the native input and output types without starting runtime work.
GraphWaitingInterrupt (interface)
Pending graph interruption and its public response schema. The optional ID is internal and omitted from published waiting requests.
Example
const interrupt: GraphWaitingInterrupt = { node: "review", response: true };
Signature
export interface GraphWaitingInterrupt {
readonly id?: string;
readonly node: string;
readonly value?: unknown;
readonly response: JsonValue;
}
graph-node-schema-validation.ts
Validates native node input, output and optional resume schemas in authoring order before handler or identity construction; schema failures retain their existing graph-node boundary.
validateGraphNodeSchemasEffect
Validates each authored schema without invoking the user’s node handler.
Signature
declare const validateGraphNodeSchemasEffect: (
options: Pick<GraphNodeAny, "input" | "output" | "resume">,
) => Effect.Effect<void, GraphNodeValidationFailure, never>;
graph-node-symbol.ts
Private brand identifying a validated RELKIT graph node.
RELKIT_GRAPH_NODE
Private brand identifying a validated RELKIT graph node.
Signature
declare const RELKIT_GRAPH_NODE: unique symbol;
graph-node-validation-error.ts
Defines authoring failures for native graph nodes and retains the invalid field for focused descriptor diagnostics.
GraphNodeValidationFailure (class)
Tagged graph node validation failure.
Signature
declare class GraphNodeValidationFailure
graphNodeValidationFailure
Preserves a graph node validation error for Effect callers.
Example
graphNodeValidationFailure(new TypeError("invalid"));
Signature
declare const graphNodeValidationFailure: (cause: unknown) => GraphNodeValidationFailure;
graph-node-validation-value.ts
Checks graph node authoring values and callable shapes before construction, keeping runtime callbacks untouched after validation.
commandUpdate
Converts a native command update for existing synchronous callers.
Throws
TypeError for malformed entry lists.
Example
commandUpdate([["count", 1]]);
Signature
declare const commandUpdate: (value: unknown) => unknown;
commandUpdateEffect
Converts a native command update entry list into an object.
Example
Effect.runSync(commandUpdateEffect([["count", 1]]));
Signature
declare const commandUpdateEffect: (
value: unknown,
) => Effect.Effect<unknown, GraphNodeValidationFailure, never>;
validateDestinations
Checks native command destinations for existing synchronous callers.
Throws
TypeError for invalid or undeclared destinations.
Example
validateDestinations(["next"], "next");
Signature
declare const validateDestinations: (ends: readonly string[], value: unknown) => void;
validateDestinationsEffect
Checks that native command destinations were declared by the node.
Example
Effect.runSync(validateDestinationsEffect(["next"], "next"));
Signature
declare const validateDestinationsEffect: (
ends: ReadonlyArray<string>,
value: unknown,
) => Effect.Effect<void, GraphNodeValidationFailure, never>;
validatedUpdate
Validates a node output for existing Promise callers.
Throws
The original schema or record error.
Example
await validatedUpdate(schema, output);
Signature
declare const validatedUpdate: <Schema extends StandardSchemaV1>(
schema: Schema,
value: unknown,
) => Promise<Extract<InferOutput<Schema>, Record<string, unknown>>>;
validatedUpdateEffect
Validates a graph node output as a record.
Example
await Effect.runPromise(validatedUpdateEffect(schema, output));
Signature
declare const validatedUpdateEffect: <Schema extends StandardSchemaV1>(
schema: Schema,
value: unknown,
) => Effect.Effect<
Extract<InferOutput<Schema>, Record<string, unknown>>,
GraphNodeValidationFailure,
never
>;
validatedValue
Validates a node value for existing Promise callers.
Throws
The original schema validation error.
Example
await validatedValue(schema, input, "input");
Signature
declare const validatedValue: <Schema extends StandardSchemaV1>(
schema: Schema,
value: unknown,
phase: "input" | "output",
) => Promise<InferOutput<Schema>>;
validatedValueEffect
Validates a graph node input or output through its Standard Schema.
Example
await Effect.runPromise(validatedValueEffect(schema, input, "input"));
Signature
declare const validatedValueEffect: <Schema extends StandardSchemaV1>(
schema: Schema,
value: unknown,
phase: "input" | "output",
) => Effect.Effect<InferOutput<Schema>, GraphNodeValidationFailure, never>;
graph-node-validation.ts
Validates native graph node contracts and execution configuration before the node descriptor is published to graph assembly.
assertGraphNodeDestinations
Checks destinations for existing synchronous graph callers.
Throws
The original unknown destination error.
Example
assertGraphNodeDestinations(node, ids);
Signature
declare const assertGraphNodeDestinations: (
node: Pick<GraphNodeAny, "id" | "ends">,
registeredNodeIds: ReadonlySet<string> | readonly string[],
) => void;
assertGraphNodeDestinationsEffect
Checks that every declared node destination exists in the graph.
Example
Effect.runSync(assertGraphNodeDestinationsEffect(node, ids));
Signature
declare const assertGraphNodeDestinationsEffect: (
node: Pick<GraphNodeAny, "id" | "ends">,
registeredNodeIds: ReadonlyArray<string> | ReadonlySet<string>,
) => Effect.Effect<void, GraphNodeValidationFailure, never>;
copyGraphNodeEnds
Copies destinations for existing synchronous graph callers.
Throws
The original invalid or duplicate destination error.
Example
const ends = copyGraphNodeEnds([END]);
Signature
declare const copyGraphNodeEnds: (value: readonly string[] | undefined) => readonly string[];
copyGraphNodeEndsEffect
Validates and freezes a node’s static destination list.
Example
Effect.runSync(copyGraphNodeEndsEffect([END]));
Signature
declare const copyGraphNodeEndsEffect: (
value: ReadonlyArray<string> | undefined,
) => Effect.Effect<ReadonlyArray<string>, GraphNodeValidationFailure, never>;
validateGraphNodeResult
Validates a node result for existing Promise graph callers.
Throws
The original schema, update, or destination error.
Example
await validateGraphNodeResult(schema, [], value);
Signature
declare const validateGraphNodeResult: <
OutputSchema extends StandardSchemaV1,
Ends extends readonly string[],
>(
output: OutputSchema,
ends: Ends,
result: unknown,
) => Promise<GraphNodeResult<OutputSchema, Ends>>;
validateGraphNodeResultEffect
Validates a node result and any native command update.
Example
Effect.runPromise(validateGraphNodeResultEffect(schema, [], value));
Signature
declare const validateGraphNodeResultEffect: <
OutputSchema extends StandardSchemaV1,
Ends extends readonly string[],
>(
output: OutputSchema,
ends: Ends,
result: unknown,
) => Effect.Effect<GraphNodeResult<OutputSchema, Ends>, GraphNodeValidationFailure, never>;
validatedGraphNodeInput
Validates graph node input for existing Promise graph callers.
Throws
The original schema validation error.
Example
await validatedGraphNodeInput(schema, value);
Signature
declare const validatedGraphNodeInput: <Schema extends StandardSchemaV1>(
schema: Schema,
value: unknown,
) => Promise<InferOutput<Schema>>;
validatedGraphNodeInputEffect
Validates graph node input against its standard schema.
Example
Effect.runPromise(validatedGraphNodeInputEffect(schema, value));
Signature
declare const validatedGraphNodeInputEffect: <Schema extends StandardSchemaV1>(
schema: Schema,
value: unknown,
) => Effect.Effect<InferOutput<Schema>, GraphNodeValidationFailure, never>;
graph-persistence-release.ts
Releases native graph persistence resources through their supported close protocol after graph work has settled.
releaseAgentPersistence
Releases persistence resources for existing Promise callers.
Throws
The first release error in descriptor order.
Example
await releaseAgentPersistence([agent]);
Signature
declare const releaseAgentPersistence: (descriptors: readonly unknown[]) => Promise<void>;
releaseAgentPersistenceEffect
Releases declared persistence resources with bounded concurrency.
Example
Effect.runPromise(releaseAgentPersistenceEffect([agent]));
Signature
declare const releaseAgentPersistenceEffect: (
descriptors: ReadonlyArray<unknown>,
) => Effect.Effect<undefined, AgentPersistenceFailure, never>;
graph-persistence.ts
Acquires native graph checkpointer and store configuration for invocation and supplies the release action to the owning graph scope.
AgentPersistenceDeclaration
Signature
declare const AgentPersistenceDeclaration: AgentPersistenceDeclaration;
ResolvedGraphPersistence
Signature
declare const ResolvedGraphPersistence: ResolvedGraphPersistence;
releaseAgentPersistence
Signature
declare const releaseAgentPersistence: (descriptors: readonly unknown[]) => Promise<void>;
releaseAgentPersistenceEffect
Signature
declare const releaseAgentPersistenceEffect: (
descriptors: ReadonlyArray<unknown>,
) => Effect.Effect<undefined, AgentPersistenceFailure, never>;
resolveAgentPersistence
Resolves agent persistence for existing Promise callers.
Throws
The original factory or protocol error.
Example
await resolveAgentPersistence(agent, {});
Signature
declare const resolveAgentPersistence: (
descriptor: AgentPersistenceDeclaration,
env: Readonly<Record<string, unknown>>,
signal?: AbortSignal,
) => Promise<ResolvedGraphPersistence>;
resolveAgentPersistenceEffect
Resolves an agent’s declared persistence handles.
Example
Effect.runPromise(resolveAgentPersistenceEffect(agent, {}));
Signature
declare const resolveAgentPersistenceEffect: (
descriptor: AgentPersistenceDeclaration,
env: Readonly<Record<string, unknown>>,
) => Effect.Effect<ResolvedGraphPersistence, AgentPersistenceFailure, never>;
resolveGraphPersistence
Resolves graph persistence for existing Promise callers.
Throws
The original factory or protocol error.
Example
await resolveGraphPersistence(graph, {});
Signature
declare const resolveGraphPersistence: (
descriptor: GraphDescriptor,
env: Readonly<Record<string, unknown>>,
signal?: AbortSignal,
) => Promise<ResolvedGraphPersistence>;
resolveGraphPersistenceEffect
Resolves a graph’s declared persistence handles.
Example
Effect.runPromise(resolveGraphPersistenceEffect(graph, {}));
Signature
declare const resolveGraphPersistenceEffect: (
descriptor: GraphDescriptor<
string,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
AnyStateSchema,
ReadonlyArray<GraphNodeLike>
>,
env: Readonly<Record<string, unknown>>,
) => Effect.Effect<ResolvedGraphPersistence, AgentPersistenceFailure, never>;
graph-persistence.types.ts
Acquires native graph checkpointer and store configuration for invocation and supplies the release action to the owning graph scope. This companion preserves the native input and output types without starting runtime work.
AgentPersistenceDeclaration (interface)
Optional checkpointer and store declarations on an agent.
Signature
export interface AgentPersistenceDeclaration {
readonly checkpointer?: unknown;
readonly store?: unknown;
}
AnyPersistenceResource (type alias)
A persistence descriptor being resolved for one invocation.
Signature
type AnyPersistenceResource = PersistenceResource<"checkpointer" | "memory", unknown>;
ResolutionState (interface)
Pending and committed resolution state for one shared resource.
Signature
export interface ResolutionState {
pending: number;
committed: boolean;
}
ResolvedGraphPersistence (interface)
Resolved handles passed to a compiled graph.
Signature
export interface ResolvedGraphPersistence {
readonly checkpointer?: BaseCheckpointSaver;
readonly store?: BaseStore;
}
graph-runtime-error.ts
Translates native graph execution failures into the RELKIT graph error boundary while preserving their original causes.
GraphInvocationFailure (class)
Tagged graph invocation failure with the original runtime cause.
Signature
declare class GraphInvocationFailure
graphInvocationFailure
Preserves a graph invocation failure for Effect callers.
Example
graphInvocationFailure(new Error("graph failed"));
Signature
declare const graphInvocationFailure: (cause: unknown) => GraphInvocationFailure;
graph-runtime-execution.ts
Runs a compiled graph within the invocation context, coordinating input, continuation and persistence before projecting final output.
runCompiledGraph
Runs a compiled graph for existing Promise callers.
Throws
The original graph, persistence, output, or cancellation error.
Example
await runCompiledGraph(options, input, signal, id, trace, 1024);
Signature
declare const runCompiledGraph: (
options: GraphRuntimeOptions,
input: unknown,
signal: AbortSignal,
invocationId: string,
traceId: string,
maxOutputBytes: number,
) => Promise<unknown>;
runCompiledGraphEffect
Runs one compiled graph with persistence and a linked invocation scope.
Example
await Effect.runPromise(runCompiledGraphEffect(options, input, signal, id, trace, 1024));
Signature
declare const runCompiledGraphEffect: (
options: GraphRuntimeOptions,
input: unknown,
signal: AbortSignal,
invocationId: string,
traceId: string,
maxOutputBytes: number,
) => Effect.Effect<JsonValue, GraphInvocationFailure, never>;
graph-runtime-identity.ts
Derives graph invocation, thread and checkpoint identity used consistently by native execution and persisted continuation lookup.
GraphInvocationIdentity (class)
Substitutable random source for graph invocation IDs.
Example
Effect.provide(invokeGraphEffect(options), GraphInvocationIdentityLive);
Signature
declare class GraphInvocationIdentity
GraphInvocationIdentityLive
Live graph invocation identity source.
Example
Effect.runPromise(Effect.provide(invokeGraphEffect(options), GraphInvocationIdentityLive));
Signature
declare const GraphInvocationIdentityLive: Layer.Layer<GraphInvocationIdentity, never, never>;
graph-runtime-identity.types.ts
Random identity source used by graph invocation Effects.
GraphInvocationIdentityService (interface)
Random identity source used by graph invocation Effects.
Signature
export interface GraphInvocationIdentityService {
readonly randomUUID: () => string;
}
graph-runtime-stream-state.ts
Collects graph state, waiting requests and validated output from an already acquired native stream. Its caller retains stream abort/finalization ownership.
collectCompiledGraphStateEffect
Collects the original native events before settling public graph state.
Signature
declare const collectCompiledGraphStateEffect: (
context: CompiledGraphStreamContext,
) => Effect.Effect<JsonValue, GraphInvocationFailure, never>;
graph-runtime-stream.ts
Consumes native graph streams and publishes RELKIT execution events, finalizing the native iterator before settling the invocation.
streamCompiledGraphEffect
Streams one compiled graph and validates its final public output.
Example
await Effect.runPromise(streamCompiledGraphEffect(options, graph, config, input, signal, 1024));
Signature
declare const streamCompiledGraphEffect: (
options: GraphRuntimeOptions,
graph: any,
config: GraphConfig,
input: unknown,
signal: AbortSignal,
maxOutputBytes: number,
) => Effect.Effect<JsonValue, GraphInvocationFailure, never>;
graph-runtime-stream.types.ts
Acquired native stream and public sinks retained by one graph invocation.
CompiledGraphStreamContext (interface)
Signature
export interface CompiledGraphStreamContext {
readonly options: GraphRuntimeOptions;
readonly graph: ReturnType<typeof compileGraph>;
readonly config: GraphConfig;
readonly signal: AbortSignal;
readonly maxOutputBytes: number;
readonly run: Awaited<ReturnType<ReturnType<typeof compileGraph>["streamEvents"]>>;
}
graph-runtime.ts
Composes graph compilation, scoped persistence and execution into the native invocation entrypoint, retaining stream and continuation behavior.
GraphInvocationFailure
Signature
declare const GraphInvocationFailure: typeof GraphInvocationFailure;
GraphInvocationIdentity
Signature
declare const GraphInvocationIdentity: typeof GraphInvocationIdentity;
GraphInvocationIdentityLive
Signature
declare const GraphInvocationIdentityLive: Layer<GraphInvocationIdentity, never, never>;
GraphRuntimeOptions
Signature
declare const GraphRuntimeOptions: GraphRuntimeOptions;
invokeGraph
Invokes a graph for existing Promise runtime callers.
Throws
The original graph, provider, validation, or cancellation error.
Example
await invokeGraph(options);
Signature
declare const invokeGraph: (options: GraphRuntimeOptions) => Promise<unknown>;
invokeGraphEffect
Invokes a graph with scoped signal cleanup and linked Effect cancellation.
Example
Effect.runPromise(Effect.provide(invokeGraphEffect(options), GraphInvocationIdentityLive));
Signature
declare const invokeGraphEffect: (
options: GraphRuntimeOptions,
) => Effect.Effect<unknown, GraphInvocationFailure, GraphInvocationIdentity>;
graph-runtime.types.ts
Composes graph compilation, scoped persistence and execution into the native invocation entrypoint, retaining stream and continuation behavior. This companion preserves the native input and output types without starting runtime work.
GraphRuntimeOptions (type alias)
Runtime options for invoking a compiled graph descriptor.
Signature
type GraphRuntimeOptions = AgentRuntimeOptions &
AgentInvocationOptions & { readonly agent: GraphDescriptor };
graph-state-schema.ts
Adapts authored state schemas to the native graph state contract and preserves the reducers and validated channel shapes required by compilation.
GraphStateSelectionError (class)
Expected graph state projection failure in the Effect error channel.
Signature
declare class GraphStateSelectionError
selectGraphState
Projects graph state for existing synchronous graph definition callers.
Throws
AgentRuntimeError when the selection or one of its fields is unavailable.
Example
const projected = selectGraphState(state, z.object({ answer: z.string() }));
Signature
declare const selectGraphState: (
state: AnyStateSchema,
selection: StandardSchemaV1,
) => AnyStateSchema;
selectGraphStateEffect
Projects a graph state to the fields declared by a client selection schema.
Throws
A defect if LangGraph rejects an otherwise valid StateSchema construction.
Example
const projected = Effect.runSync(selectGraphStateEffect(state, z.object({ answer: z.string() })));
Signature
declare const selectGraphStateEffect: (
state: AnyStateSchema,
selection: StandardSchemaV1<unknown, unknown>,
) => Effect.Effect<StateSchema<Record<string, any>>, GraphStateSelectionError, never>;
graph-subgraph-symbol.ts
Marker for a graph embedded as a native node.
RELKIT_SUBGRAPH
Hidden reference to the embedded graph descriptor.
Signature
declare const RELKIT_SUBGRAPH: unique symbol;
RELKIT_SUBGRAPH_NODE
Marker for a graph embedded as a native node.
Signature
declare const RELKIT_SUBGRAPH_NODE: unique symbol;
graph-subgraph.ts
Creates nested graph descriptors with their native execution metadata so parent compilation can retain subgraph state and interruption semantics.
“./graph-subgraph.types.js” (namespace export)
Re-exports all named exports from the “./graph-subgraph.types.js” module.
Signature
export * from "./graph-subgraph.types.js";
createSubgraphNode
Creates an embedded graph node for existing synchronous callers.
Throws
The original invalid options or destination error.
Example
const node = createSubgraphNode(graph, { id: "nested" });
Signature
declare const createSubgraphNode: <
const Id extends string,
InputSchema extends StandardSchemaV1,
OutputSchema extends StandardSchemaV1,
>(
graph: GraphDescriptor<string, InputSchema, OutputSchema>,
options?: GraphAsNodeOptions<Id>,
) => SubgraphNodeDescriptor<Id, InputSchema, OutputSchema>;
createSubgraphNodeEffect
Creates a native node backed by another graph.
Example
Effect.runSync(createSubgraphNodeEffect(graph, { id: "nested" }));
Signature
declare const createSubgraphNodeEffect: <
const Id extends string,
InputSchema extends StandardSchemaV1,
OutputSchema extends StandardSchemaV1,
>(
graph: GraphDescriptor<
string,
InputSchema,
OutputSchema,
AnyStateSchema,
ReadonlyArray<GraphNodeLike>
>,
options?: GraphAsNodeOptions<Id> | undefined,
) => Effect.Effect<
SubgraphNodeDescriptor<Id, InputSchema, OutputSchema>,
GraphNodeValidationFailure,
never
>;
isSubgraphNode
Checks embedded graph nodes for existing synchronous callers.
Example
if (isSubgraphNode(value)) subgraphForNode(value);
Signature
declare const isSubgraphNode: (value: unknown) => value is SubgraphNodeDescriptor;
isSubgraphNodeEffect
Checks whether a value is an embedded graph node.
Example
Effect.runSync(isSubgraphNodeEffect(value));
Signature
declare const isSubgraphNodeEffect: (value: unknown) => Effect.Effect<boolean, never, never>;
subgraphForNode
Reads the source graph for existing synchronous callers.
Example
const nested = subgraphForNode(node);
Signature
declare const subgraphForNode: (value: SubgraphNodeDescriptor) => GraphDescriptor;
subgraphForNodeEffect
Reads the source graph from a subgraph node.
Example
Effect.runSync(subgraphForNodeEffect(node));
Signature
declare const subgraphForNodeEffect: (
value: SubgraphNodeDescriptor<
string,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>
>,
) => Effect.Effect<
GraphDescriptor<
string,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
AnyStateSchema,
ReadonlyArray<GraphNodeLike>
>,
never,
never
>;
graph-subgraph.types.ts
Creates nested graph descriptors with their native execution metadata so parent compilation can retain subgraph state and interruption semantics. This companion preserves the native input and output types without starting runtime work.
GraphAsNodeOptions (interface)
Authoring options for a graph embedded as a node.
Signature
export interface GraphAsNodeOptions<Id extends string = string> {
readonly id?: Id;
readonly ends?: readonly string[];
}
SubgraphNodeDescriptor (interface)
Native graph node whose action is another graph.
Signature
export interface SubgraphNodeDescriptor<
Id extends string = string,
InputSchema extends StandardSchemaV1 = StandardSchemaV1,
OutputSchema extends StandardSchemaV1 = StandardSchemaV1,
> {
readonly [RELKIT_SUBGRAPH_NODE]: true;
readonly kind: "subgraph-node";
readonly id: Id;
readonly input: InputSchema;
readonly output: OutputSchema;
readonly ends: readonly string[];
readonly [RELKIT_SUBGRAPH]: GraphDescriptor;
}
graph-workflow-error.ts
Defines graph workflow failures at the RELKIT execution boundary, preserving graph identity and the native failure cause.
GraphWorkflowFailure (class)
Tagged graph workflow projection failure.
Signature
declare class GraphWorkflowFailure
graphWorkflowFailure
Preserves a graph workflow projection error.
Example
graphWorkflowFailure(new TypeError("invalid node"));
Signature
declare const graphWorkflowFailure: (cause: unknown) => GraphWorkflowFailure;
graph-workflow.ts
Adapts native graph execution to the RELKIT workflow contract, carrying invocation context and scoped persistence through completion.
“./graph-workflow.types.js” (namespace export)
Re-exports all named exports from the “./graph-workflow.types.js” module.
Signature
export * from "./graph-workflow.types.js";
graphWorkflow
Projects a workflow for existing synchronous graph callers.
Throws
The original node or schema projection error.
Example
graphWorkflow(nodes, edges);
Signature
declare const graphWorkflow: <Id extends string, State>(
nodes: readonly (GraphNodeAny | FunctionGraphNodeDescriptor | SubgraphNodeDescriptor)[],
edges: readonly GraphEdgeOperation<Id, State>[],
) => GraphWorkflow;
graphWorkflowEffect
Projects a frozen serializable graph workflow from authoring nodes and edges.
Example
Effect.runSync(graphWorkflowEffect(nodes, edges));
Signature
declare const graphWorkflowEffect: <Id extends string, State>(
nodes: ReadonlyArray<
| GraphNodeAny
| SubgraphNodeDescriptor<
string,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>
>
| FunctionGraphNodeDescriptor<
string,
string,
unknown,
unknown,
ReadonlyArray<ErrorDescriptorAny>,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
FunctionDependencies
>
>,
edges: ReadonlyArray<GraphEdgeOperation<Id, State>>,
) => Effect.Effect<GraphWorkflow, GraphWorkflowFailure, never>;
graphWorkflowRequiresPersistence
Checks persistence needs for existing synchronous graph callers.
Example
graphWorkflowRequiresPersistence(workflow);
Signature
declare const graphWorkflowRequiresPersistence: (workflow: GraphWorkflow) => boolean;
graphWorkflowRequiresPersistenceEffect
Checks whether any graph node has a resumable continuation.
Example
Effect.runSync(graphWorkflowRequiresPersistenceEffect(workflow));
Signature
declare const graphWorkflowRequiresPersistenceEffect: (
workflow: GraphWorkflow,
) => Effect.Effect<boolean, never, never>;
graph-workflow.types.ts
Adapts native graph execution to the RELKIT workflow contract, carrying invocation context and scoped persistence through completion. This companion preserves the native input and output types without starting runtime work.
GraphWorkflow (interface)
Immutable serializable graph topology for runtime and clients.
Signature
export interface GraphWorkflow {
readonly version: 1;
readonly start: typeof START;
readonly end: typeof END;
readonly nodes: readonly GraphWorkflowNode[];
readonly edges: readonly GraphWorkflowEdge[];
}
GraphWorkflowEdge (type alias)
Serializable static, join, or conditional graph edge.
Signature
type GraphWorkflowEdge =
| { readonly kind: "edge"; readonly from: string; readonly to: string }
| { readonly kind: "join"; readonly from: readonly string[]; readonly to: string }
| {
readonly kind: "conditional";
readonly from: string;
readonly routes: readonly { readonly label: string; readonly to: string }[];
readonly dynamic: boolean;
};
GraphWorkflowNode (interface)
Serializable node entry in an agent graph workflow.
Signature
export interface GraphWorkflowNode {
readonly id: string;
readonly kind: "node" | "function" | "subgraph";
readonly input: JsonValue;
readonly output: JsonValue;
readonly resume?: JsonValue;
readonly ends: readonly string[];
readonly targetFunctionId?: string;
readonly workflow?: GraphWorkflow;
}
index.ts
Publishes the explicit LangChain integration authoring and execution surface; generic application imports remain owned by the SDK-free agents package.
“./define-agent.js” (namespace export)
Re-exports all named exports from the “./define-agent.js” module.
Signature
export * from "./define-agent.js";
“./define-graph-node.js” (namespace export)
Re-exports all named exports from the “./define-graph-node.js” module.
Signature
export * from "./define-graph-node.js";
“./define-graph.js” (namespace export)
Re-exports all named exports from the “./define-graph.js” module.
Signature
export * from "./define-graph.js";
“./define-persistence.js” (namespace export)
Re-exports all named exports from the “./define-persistence.js” module.
Signature
export * from "./define-persistence.js";
“./graph-edges.js” (namespace export)
Re-exports all named exports from the “./graph-edges.js” module.
Signature
export * from "./graph-edges.js";
“./graph-interruption.js” (namespace export)
Re-exports all named exports from the “./graph-interruption.js” module.
Signature
export * from "./graph-interruption.js";
“./graph-persistence.js” (namespace export)
Re-exports all named exports from the “./graph-persistence.js” module.
Signature
export * from "./graph-persistence.js";
“./graph-runtime.js” (namespace export)
Re-exports all named exports from the “./graph-runtime.js” module.
Signature
export * from "./graph-runtime.js";
“./graph-subgraph.js” (namespace export)
Re-exports all named exports from the “./graph-subgraph.js” module.
Signature
export * from "./graph-subgraph.js";
“./graph-workflow.js” (namespace export)
Re-exports all named exports from the “./graph-workflow.js” module.
Signature
export * from "./graph-workflow.js";
“./runtime-service.js” (namespace export)
Re-exports all named exports from the “./runtime-service.js” module.
Signature
export * from "./runtime-service.js";
“./runtime.js” (namespace export)
Re-exports all named exports from the “./runtime.js” module.
Signature
export * from "./runtime.js";
“@relkit/agents/internal/agent-client” (namespace export)
Re-exports all named exports from the “@relkit/agents/internal/agent-client” module.
Signature
export * from "@relkit/agents/internal/agent-client";
“@relkit/agents/internal/agent-telemetry” (namespace export)
Re-exports all named exports from the “@relkit/agents/internal/agent-telemetry” module.
Signature
export * from "@relkit/agents/internal/agent-telemetry";
“@relkit/agents/internal/approval” (namespace export)
Re-exports all named exports from the “@relkit/agents/internal/approval” module.
Signature
export * from "@relkit/agents/internal/approval";
“@relkit/agents/internal/client-events” (namespace export)
Re-exports all named exports from the “@relkit/agents/internal/client-events” module.
Signature
export * from "@relkit/agents/internal/client-events";
“@relkit/agents/internal/generated-function” (namespace export)
Re-exports all named exports from the “@relkit/agents/internal/generated-function” module.
Signature
export * from "@relkit/agents/internal/generated-function";
“@relkit/agents/internal/model-selection” (namespace export)
Re-exports all named exports from the “@relkit/agents/internal/model-selection” module.
Signature
export * from "@relkit/agents/internal/model-selection";
“@relkit/agents/internal/observability” (namespace export)
Re-exports all named exports from the “@relkit/agents/internal/observability” module.
Signature
export * from "@relkit/agents/internal/observability";
“@relkit/agents/internal/runtime-events” (namespace export)
Re-exports all named exports from the “@relkit/agents/internal/runtime-events” module.
Signature
export * from "@relkit/agents/internal/runtime-events";
“@relkit/agents/internal/state-control-requests.types” (namespace export)
Re-exports all named exports from the “@relkit/agents/internal/state-control-requests.types” module.
Signature
export * from "@relkit/agents/internal/state-control-requests.types";
“@relkit/agents/internal/state-provider.types” (namespace export)
Re-exports all named exports from the “@relkit/agents/internal/state-provider.types” module.
Signature
export * from "@relkit/agents/internal/state-provider.types";
“@relkit/agents/internal/state-receipts.types” (namespace export)
Re-exports all named exports from the “@relkit/agents/internal/state-receipts.types” module.
Signature
export * from "@relkit/agents/internal/state-receipts.types";
“@relkit/agents/internal/state-thread-requests.types” (namespace export)
Re-exports all named exports from the “@relkit/agents/internal/state-thread-requests.types” module.
Signature
export * from "@relkit/agents/internal/state-thread-requests.types";
“@relkit/agents/internal/state.types” (namespace export)
Re-exports all named exports from the “@relkit/agents/internal/state.types” module.
Signature
export * from "@relkit/agents/internal/state.types";
“@relkit/agents/internal/thread-transition” (namespace export)
Re-exports all named exports from the “@relkit/agents/internal/thread-transition” module.
Signature
export * from "@relkit/agents/internal/thread-transition";
assertAgentRuntimeDependencies
Signature
declare const assertAgentRuntimeDependencies: (
agents: readonly AgentDescriptor<string, unknown, unknown>[],
) => Promise<void>;
createGeneratedAgentFunction
Signature
declare const createGeneratedAgentFunction: (
agentId: unknown,
executor?: GeneratedAgentExecutor,
) => GeneratedAgentFunction;
validateGraphResumeInput
Signature
declare const validateGraphResumeInput: (
descriptor: GraphDescriptor,
requests: readonly AgentWaitingRequest[],
value: unknown,
) => Promise<unknown>;
validateNativeAgentResumeInput
Signature
declare const validateNativeAgentResumeInput: (
requests: readonly AgentWaitingRequest[],
value: unknown,
) => unknown;
native-agent-interruption-error.ts
Defines failures for native agent interrupt handling so malformed interruption data stays distinct from normal approval suspension.
NativeAgentInterruptionFailure (class)
Tagged native agent continuation or state failure.
Signature
declare class NativeAgentInterruptionFailure
nativeAgentInterruptionFailure
Wraps a native continuation failure for Effect callers.
Example
nativeAgentInterruptionFailure(new TypeError("invalid reply"));
Signature
declare const nativeAgentInterruptionFailure: (cause: unknown) => NativeAgentInterruptionFailure;
native-agent-interruption-schema.ts
Declares executable schemas for native interruption payloads before they cross the durable RELKIT continuation boundary.
“./native-agent-interruption-schema.types.js” (namespace export)
Re-exports all named exports from the “./native-agent-interruption-schema.types.js” module.
Signature
export * from "./native-agent-interruption-schema.types.js";
hitlResponseSchema
Constructs the response schema for existing synchronous callers.
Example
const schema = hitlResponseSchema(configs);
Signature
declare const hitlResponseSchema: (configs: readonly ReviewConfig[]) => JsonValue;
hitlResponseSchemaEffect
Constructs the exact response schema for pending reviews.
Example
Effect.runSync(hitlResponseSchemaEffect(configs));
Signature
declare const hitlResponseSchemaEffect: (
configs: ReadonlyArray<ReviewConfig>,
) => Effect.Effect<JsonValue, never, never>;
isDecision
Checks a decision label for existing synchronous callers.
Example
if (isDecision(value)) useDecision(value);
Signature
declare const isDecision: (value: unknown) => value is DecisionType;
isDecisionEffect
Checks one native human decision label.
Example
Effect.runSync(isDecisionEffect("approve"));
Signature
declare const isDecisionEffect: (value: unknown) => Effect.Effect<boolean, never, never>;
isHitlRequest
Checks a native human review request for existing synchronous callers.
Example
if (isHitlRequest(value)) handle(value);
Signature
declare const isHitlRequest: (value: unknown) => value is HitlRequest;
isHitlRequestEffect
Validates the native human review request shape.
Example
Effect.runSync(isHitlRequestEffect(value));
Signature
declare const isHitlRequestEffect: (value: unknown) => Effect.Effect<boolean, never, never>;
isRecord
Checks a record for existing synchronous callers.
Example
if (isRecord(value)) read(value.name);
Signature
declare const isRecord: (value: unknown) => value is Record<string, unknown>;
isRecordEffect
Checks a non-null, non-array record.
Example
Effect.runSync(isRecordEffect({ name: "tool" }));
Signature
declare const isRecordEffect: (value: unknown) => Effect.Effect<boolean, never, never>;
publicHitlRequest
Projects a review request for existing synchronous callers.
Example
const request = publicHitlRequest(nativeRequest);
Signature
declare const publicHitlRequest: (value: HitlRequest) => HitlRequest;
publicHitlRequestEffect
Projects a review request to public action fields.
Example
Effect.runSync(publicHitlRequestEffect(request));
Signature
declare const publicHitlRequestEffect: (
value: HitlRequest,
) => Effect.Effect<HitlRequest, never, never>;
native-agent-interruption-schema.types.ts
Declares executable schemas for native interruption payloads before they cross the durable RELKIT continuation boundary. This companion preserves the native input and output types without starting runtime work.
DecisionType (type alias)
Human review decision accepted by a native agent.
Signature
type DecisionType = "approve" | "edit" | "reject";
HitlRequest (interface)
Public set of actions awaiting human review.
Signature
export interface HitlRequest {
readonly actionRequests: readonly Record<string, unknown>[];
readonly reviewConfigs: readonly ReviewConfig[];
}
ReviewConfig (interface)
Review policy for one pending action.
Signature
export interface ReviewConfig {
readonly actionName: string;
readonly allowedDecisions: readonly DecisionType[];
readonly argsSchema?: JsonValue;
}
native-agent-interruption-validation.ts
Decodes native agent interruption data and rejects invalid continuation payloads before approval or resume processing.
snapshotInterrupts
Extracts public native interruptions from nested graph state.
Example
const requests = snapshotInterrupts(snapshot, []);
Signature
declare const snapshotInterrupts: (
snapshot: unknown,
path: readonly string[],
) => GraphWaitingInterrupt[];
validateNativeAgentResumeInputCore
Validates one or more replies against pending native reviews.
Throws
TypeError for absent, mismatched, or invalid replies.
Example
const replies = validateNativeAgentResumeInputCore(requests, input);
Signature
declare const validateNativeAgentResumeInputCore: (
requests: readonly AgentWaitingRequest[],
value: unknown,
) => unknown;
native-agent-interruption.ts
Projects native agent interruption state into RELKIT approval and continuation records without losing native interrupt identity.
nativeAgentResumeCommand
Builds a native resume command for existing Promise callers.
Throws
The original state or validation error.
Example
await nativeAgentResumeCommand(agent, config, reply);
Signature
declare const nativeAgentResumeCommand: (
agent: NativeAgent,
config: NativeAgentConfig,
value: unknown,
) => Promise<Command>;
nativeAgentResumeCommandEffect
Reads native pending requests and constructs a resume command.
Example
await Effect.runPromise(nativeAgentResumeCommandEffect(agent, config, reply));
Signature
declare const nativeAgentResumeCommandEffect: (
agent: NativeAgent,
config: RunnableConfig<Record<string, any>>,
value: unknown,
) => Effect.Effect<
Command<{ [k: string]: unknown }, Record<string, unknown>, string>,
NativeAgentInterruptionFailure,
never
>;
nativeAgentWaitingInterrupts
Reads waiting native interruptions for existing Promise callers.
Throws
The original native state provider error.
Example
await nativeAgentWaitingInterrupts(agent, config);
Signature
declare const nativeAgentWaitingInterrupts: (
agent: NativeAgent,
config: NativeAgentConfig,
) => Promise<readonly import("./graph-interruption.js").GraphWaitingInterrupt[]>;
nativeAgentWaitingInterruptsEffect
Reads and projects waiting native interruptions.
Example
await Effect.runPromise(nativeAgentWaitingInterruptsEffect(agent, config));
Signature
declare const nativeAgentWaitingInterruptsEffect: (
agent: NativeAgent,
config: RunnableConfig<Record<string, any>>,
) => Effect.Effect<Array<GraphWaitingInterrupt>, NativeAgentInterruptionFailure, never>;
validateNativeAgentResumeInput
Validates native continuation replies for existing synchronous callers.
Throws
The original invalid continuation error.
Example
const reply = validateNativeAgentResumeInput(requests, value);
Signature
declare const validateNativeAgentResumeInput: (
requests: readonly AgentWaitingRequest[],
value: unknown,
) => unknown;
validateNativeAgentResumeInputEffect
Validates native continuation replies against pending requests.
Example
Effect.runSync(validateNativeAgentResumeInputEffect(requests, reply));
Signature
declare const validateNativeAgentResumeInputEffect: (
requests: ReadonlyArray<AgentWaitingRequest>,
value: unknown,
) => Effect.Effect<unknown, NativeAgentInterruptionFailure, never>;
native-agent-interruption.types.ts
Native LangGraph agent state access used by continuation operations.
NativeAgent (type alias)
Native LangGraph agent state access used by continuation operations.
Signature
type NativeAgent = Pick<ReturnType<typeof import("langchain").createAgent>, "getState">;
NativeAgentConfig (type alias)
State lookup configuration accepted by a native agent.
Signature
type NativeAgentConfig = Parameters<NativeAgent["getState"]>[0];
persistence-error.ts
Defines typed failures for native persistence acquisition and release, retaining the selected resource and underlying cause.
AgentPersistenceFailure (class)
A typed persistence acquire, validation, or release failure.
Signature
declare class AgentPersistenceFailure
agentPersistenceFailure
Retains the original failure for compatibility callers.
Example
agentPersistenceFailure(new Error("store unavailable"));
Signature
declare const agentPersistenceFailure: (cause: unknown) => AgentPersistenceFailure;
persistence-symbol.ts
Shared marker used to recognize RELKIT persistence descriptors.
RELKIT_PERSISTENCE
Shared marker used to recognize RELKIT persistence descriptors.
Signature
declare const RELKIT_PERSISTENCE: unique symbol;
runtime-approval-decision.ts
Converts supported approval reply forms to the canonical record while keeping approval policy, tracing and tool lifecycle in their existing owners.
resolveApprovalDecisionEffect
Normalizes the supported reply forms without changing approval semantics.
Signature
declare const resolveApprovalDecisionEffect: (
approval: PendingApproval,
response: ApprovalDecision,
) => Effect.Effect<ApprovalRecord, AgentInvocationFailure, never>;
runtime-dependencies.ts
Exposes dependency preflight without making optional DeepAgents declarations part of ordinary native authoring.
assertAgentRuntimeDependencies
Checks selected native capabilities and preserves the original loader failure and lifecycle.
Signature
declare const assertAgentRuntimeDependencies: (
agents: readonly AgentDescriptor<string, unknown, unknown>[],
) => Promise<void>;
runtime-effect-error.ts
Normalizes Effect failures from native invocation adapters while retaining the original failure cause at the public runtime boundary.
AgentInvocationFailure (class)
A typed Effect failure that retains the public invocation error as its cause.
Signature
declare class AgentInvocationFailure
agentInvocationFailure
Captures an invocation failure without losing compatibility error details.
Example
agentInvocationFailure(new Error("model unavailable"));
Signature
declare const agentInvocationFailure: (cause: unknown) => AgentInvocationFailure;
runtime-errors.ts
Constructs invocation failures with agent identity and native causes, including selected dependency failures and execution errors.
AgentRuntimeError (class)
Safe public failure fields; a non-enumerable native cause is private diagnostic data.
Signature
declare class AgentRuntimeError { constructor(
readonly code: string,
message: string,
readonly issues?: readonly StandardIssue[],
options?: ErrorOptions,
) }
runtime-failure-diagnostics.ts
Records bounded failure categories at the invocation boundary; native causes remain private and are never logged raw.
logAgentFailure
Logs one safe diagnostic before public failure mapping, without retrying execution.
Signature
declare const logAgentFailure: (
failure: AgentInvocationFailure,
options: AgentRuntimeOptions & AgentInvocationOptions,
) => Effect.Effect<void, never, never>;
runtime-integration.ts
Advertises native execution registrations to the existing verified integration plan. Provider acquisition skips these execution-only capabilities.
runtimeIntegration
Signature
declare const runtimeIntegration: Readonly<{
kind: "runtime-integration";
integrationId: "langchain";
registrations: ReadonlyArray<{ capability: string; adapterId: string; protocolVersion: number }>;
}>;
runtime-invoke.ts
Resolves model and invocation identities before acquiring the scoped native signal; stream work inherits the same tracing and cancellation context.
invokeNativeWithContextEffect
Runs native work inside the original scoped signal and trace boundary.
Signature
declare const invokeNativeWithContextEffect: (
options: NativeAgentRuntimeOptions,
service: AgentExecutionService,
invocation: {
capture: AgentCapturePolicy;
invocationId: StableId;
traceId: StableId;
runtimeModel: ResolvedRuntimeModel;
},
) => Effect.Effect<unknown, AgentInvocationFailure, never>;
resolveNativeInvocationEffect
Resolves validated invocation identity, capture policy and native model.
Signature
declare const resolveNativeInvocationEffect: (
options: NativeAgentRuntimeOptions,
service: AgentExecutionService,
) => Effect.Effect<
{
capture: AgentCapturePolicy;
invocationId: StableId;
traceId: StableId;
runtimeModel: ResolvedRuntimeModel;
},
AgentInvocationFailure,
never
>;
runtime-loop-context.types.ts
Carries one native loop’s already acquired runnable, identity, state selection and signal to stream/settlement helpers without allocating another lifetime.
NativeAgentLoopContext (interface)
Signature
export interface NativeAgentLoopContext {
readonly options: AgentLoopOptions;
readonly native: Awaited<ReturnType<typeof createNativeAgent>>;
readonly config: { readonly configurable?: { readonly thread_id: string } };
readonly input: unknown;
readonly signal: AbortSignal;
readonly maxInputBytes: number;
readonly maxOutputBytes: number;
readonly observe: ReturnType<typeof createLoopTelemetry>;
}
runtime-loop-execution.ts
Executes one native agent stream while retaining model failure precedence. Public wrappers own Effect interruption; state helpers use the same signal.
runAgentLoopCore
Signature
declare const runAgentLoopCore: (
options: AgentLoopOptions,
model: NativeModel,
modelId: string,
signal: AbortSignal,
input: unknown,
maxInputBytes: number,
maxOutputBytes: number,
invocationId: string,
traceId: string,
capture: AgentCapturePolicy,
) => Promise<unknown>;
runtime-loop-state.ts
Streams one already acquired native runnable and settles its public output or interruption using the same checkpoint identity, byte limits and content sink.
settleNativeAgentLoop
Publishes waiting state or validated output without changing persistence identity.
Signature
declare const settleNativeAgentLoop: (
context: NativeAgentLoopContext,
state: unknown,
) => Promise<unknown>;
streamNativeAgentLoop
Collects the native stream under its caller’s existing trace and signal.
Signature
declare const streamNativeAgentLoop: (context: NativeAgentLoopContext) => Promise<any>;
runtime-loop-telemetry.ts
Publishes native invocation loop observations to RELKIT telemetry using the current execution context and stable agent identifiers.
createLoopTelemetry
Signature
declare const createLoopTelemetry: (
runtime: AgentRuntimeOptions,
modelId: string,
) => (event: ProtocolEvent) => void;
runtime-loop-values.ts
Extracts validated loop input and output values for native execution, keeping schema failure handling at the invocation boundary.
nativeMessages
Builds native messages for existing synchronous callers.
Throws
The original input JSON or byte limit error.
Example
nativeMessages(options, input, 1024);
Signature
declare const nativeMessages: (
options: AgentLoopOptions,
input: unknown,
maxInputBytes: number,
) => Array<{ role: "user" | "assistant"; content: string }>;
nativeMessagesEffect
Builds the native message list from prior turns and validated input.
Example
Effect.runSync(nativeMessagesEffect(options, input, 1024));
Signature
declare const nativeMessagesEffect: (
options: AgentLoopOptions,
input: unknown,
maxInputBytes: number,
) => Effect.Effect<
Array<{ role: "user" | "assistant"; content: string }>,
AgentInvocationFailure,
never
>;
responseValue
Extracts structured output for existing synchronous callers.
Throws
AgentRuntimeError when structured output is absent.
Example
responseValue(state);
Signature
declare const responseValue: (state: unknown) => unknown;
responseValueEffect
Extracts the structured model output value.
Example
Effect.runSync(responseValueEffect(state));
Signature
declare const responseValueEffect: (
state: unknown,
) => Effect.Effect<unknown, AgentInvocationFailure, never>;
unwrapNativeCause
Unwraps native causes for existing synchronous callers.
Example
unwrapNativeCause(error);
Signature
declare const unwrapNativeCause: (value: unknown) => unknown;
unwrapNativeCauseEffect
Unwraps nested native provider causes without looping on cyclic causes.
Example
Effect.runSync(unwrapNativeCauseEffect(error));
Signature
declare const unwrapNativeCauseEffect: (value: unknown) => Effect.Effect<unknown, never, never>;
runtime-loop.ts
Exposes native loop execution as an observed Effect and Promise facade. Cancellation remains linked to the caller and the native stream owner.
AgentLoopOptions
Signature
declare const AgentLoopOptions: AgentLoopOptions;
NativeModel
Signature
declare const NativeModel: NativeModel;
runAgentLoop
Runs the native model loop for existing Promise callers.
Throws
The original model, tool, validation, or cancellation error.
Example
await runAgentLoop(options, model, id, signal, input, 1024, 1024, invocation, trace, capture);
Signature
declare const runAgentLoop: (
options: AgentLoopOptions,
model: NativeModel,
modelId: string,
signal: AbortSignal,
input: unknown,
maxInputBytes: number,
maxOutputBytes: number,
invocationId: string,
traceId: string,
capture: AgentCapturePolicy,
) => Promise<unknown>;
runAgentLoopEffect
Runs one native model loop with linked Effect cancellation.
Example
await Effect.runPromise(
runAgentLoopEffect(options, model, id, signal, input, 1024, 1024, invocation, trace, capture),
);
Signature
declare const runAgentLoopEffect: (
options: AgentLoopOptions,
model: NativeModel,
modelId: string,
signal: AbortSignal,
input: unknown,
maxInputBytes: number,
maxOutputBytes: number,
invocationId: string,
traceId: string,
capture: AgentCapturePolicy,
) => Effect.Effect<unknown, AgentInvocationFailure, never>;
runtime-loop.types.ts
Coordinates native invocation steps, output validation and settlement while retaining tool, interruption and stream finalization order. This companion preserves the native input and output types without starting runtime work.
AgentLoopOptions (type alias)
Runtime and invocation options consumed by the native model loop.
Signature
type AgentLoopOptions = AgentRuntimeOptions & AgentInvocationOptions;
NativeModel (type alias)
Resolved native model or provider selector.
Signature
type NativeModel = string | LanguageModelLike;
runtime-model-error.ts
Defines model selection and initialization failures with the selected model identifier and underlying SDK cause.
AgentModelResolutionFailure (class)
Tagged model resolution or content limit failure.
Signature
declare class AgentModelResolutionFailure
agentModelResolutionFailure
Preserves a model provider or limit error for Effect callers.
Example
agentModelResolutionFailure(new Error("unavailable"));
Signature
declare const agentModelResolutionFailure: (cause: unknown) => AgentModelResolutionFailure;
runtime-model.ts
Resolves authored model selectors or native model instances for an invocation without replacing the caller’s model resource identity.
AgentContentLimits
Signature
declare const AgentContentLimits: AgentContentLimits;
ResolvedRuntimeModel
Signature
declare const ResolvedRuntimeModel: ResolvedRuntimeModel;
RuntimeModelOptions
Signature
declare const RuntimeModelOptions: RuntimeModelOptions;
resolveAgentContentLimits
Validates content byte limits for existing synchronous runtime callers.
Throws
The original AgentRuntimeError for invalid limits.
Example
resolveAgentContentLimits({ maxInputBytes: 1024 });
Signature
declare const resolveAgentContentLimits: (
options: Pick<RuntimeModelOptions, "maxInputBytes" | "maxOutputBytes">,
) => AgentContentLimits;
resolveAgentContentLimitsEffect
Validates content byte limits against fixed package maximums.
Example
Effect.runSync(resolveAgentContentLimitsEffect({ maxInputBytes: 1024 }));
Signature
declare const resolveAgentContentLimitsEffect: (
options: Pick<RuntimeModelOptions, "maxOutputBytes" | "maxInputBytes">,
) => Effect.Effect<AgentContentLimits, AgentModelResolutionFailure, never>;
resolveRuntimeModel
Resolves a model for existing Promise runtime callers.
Throws
The original provider or AgentRuntimeError cause.
Example
await resolveRuntimeModel({ model: "test", registry: null, environment: {} });
Signature
declare const resolveRuntimeModel: (options: RuntimeModelOptions) => Promise<ResolvedRuntimeModel>;
resolveRuntimeModelEffect
Resolves a model factory, native model, registry selection, or string selector.
Example
Effect.runPromise(resolveRuntimeModelEffect({ model: "test", registry: null, environment: {} }));
Signature
declare const resolveRuntimeModelEffect: (
options: RuntimeModelOptions,
) => Effect.Effect<ResolvedRuntimeModel, AgentModelResolutionFailure, never>;
runtime-model.types.ts
Resolves authored model selectors or native model instances for an invocation without replacing the caller’s model resource identity. This companion preserves the native input and output types without starting runtime work.
AgentContentLimits (interface)
Validated maximum byte counts for agent input and output.
Signature
export interface AgentContentLimits {
readonly maxInputBytes: number;
readonly maxOutputBytes: number;
}
ResolvedRuntimeModel (interface)
Selected native model and validated content limits.
Signature
export interface ResolvedRuntimeModel extends AgentContentLimits {
readonly id: string;
readonly model: string | LanguageModelLike;
}
RuntimeModelOptions (interface)
Inputs used to select a native model and content limits.
Signature
export interface RuntimeModelOptions {
readonly model?: AgentModel;
readonly registry: unknown;
readonly environment: Readonly<Record<string, unknown>>;
readonly maxInputBytes?: number;
readonly maxOutputBytes?: number;
}
runtime-native-agent-build.ts
Constructs the native agent from resolved model, tools, middleware and optional DeepAgents configuration immediately before invocation.
childModelEffect
Resolves a child model or inherits its parent model.
Example
await Effect.runPromise(childModelEffect(child, model, runtime));
Signature
declare const childModelEffect: (
child: AgentDescriptor<
string,
unknown,
unknown,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
ReadonlyArray<AgentMiddleware>,
ReadonlyArray<AgentTool>
>,
inherited: string | LanguageModelLike,
runtime: NativeAgentRuntimeOptions,
) => Effect.Effect<string | LanguageModelLike, AgentInvocationFailure, never>;
createSubagentsEffect
Builds child and nested DeepAgents declarations in authored order.
Example
await Effect.runPromise(
createSubagentsEffect(children, model, backend, runtime, options, groups, deepagents, limits),
);
Signature
declare const createSubagentsEffect: (
children: ReadonlyArray<
AgentDescriptor<
string,
unknown,
unknown,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
ReadonlyArray<AgentMiddleware>,
ReadonlyArray<AgentTool>
>
>,
inheritedModel: string | LanguageModelLike,
inheritedBackend: unknown,
runtime: NativeAgentRuntimeOptions,
options: CreateNativeAgentOptions,
groups: Array<NativeTools>,
deepagents: typeof import("deepagents"),
limitMiddleware: AnyAgentMiddleware,
) => Effect.Effect<Array<unknown>, AgentInvocationFailure, NativeToolIdentity>;
createToolsForAgentEffect
Materializes tools for a root or child agent.
Example
Effect.runSync(createToolsForAgentEffect(runtime, options, child));
Signature
declare const createToolsForAgentEffect: (
runtime: NativeAgentRuntimeOptions,
options: CreateNativeAgentOptions,
agent: AgentDescriptor<
string,
unknown,
unknown,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
ReadonlyArray<AgentMiddleware>,
ReadonlyArray<AgentTool>
>,
) => Effect.Effect<NativeTools, AgentInvocationFailure, NativeToolIdentity>;
responseFormatEffect
Signature
declare const responseFormatEffect: (
schema: StandardSchemaV1<unknown, unknown>,
model?: NativeModel | undefined,
) => Effect.Effect<
ProviderStrategy<Record<string, unknown>> | TypedToolStrategy<Record<string, unknown>>,
AgentInvocationFailure,
never
>;
runtime-native-agent.ts
Owns native agent construction and invocation adaptation, retaining the authored SDK configuration and selected persistence context.
CreateNativeAgentOptions
Signature
declare const CreateNativeAgentOptions: CreateNativeAgentOptions;
NativeAgent
Signature
declare const NativeAgent: ReactAgent<
AgentTypeConfig<
Record<string, any>,
StateDefinitionInit | undefined,
InteropZodObject | AnyAnnotationRoot,
ReadonlyArray<AnyAgentMiddleware>,
ReadonlyArray<ClientTool | ServerTool>,
ReadonlyArray<() => StreamTransformer<any>>
>
>;
StructuredOutputParsingError
Signature
declare const StructuredOutputParsingError: typeof StructuredOutputParsingError;
createNativeAgent
Builds a native agent for existing Promise callers.
Throws
The original model, schema, persistence, or dependency error.
Example
await createNativeAgent(options);
Signature
declare const createNativeAgent: (
options: CreateNativeAgentOptions,
) => Promise<{ readonly agent: NativeAgent; readonly tools: NativeTools }>;
createNativeAgentEffect
Builds a native LangChain or DeepAgents runnable for one invocation.
Example
await Effect.runPromise(
Effect.provide(
createNativeAgentEffect(options),
Layer.merge(DeepAgentsLoaderLive, NativeToolIdentityLive),
),
);
Signature
declare const createNativeAgentEffect: (options: CreateNativeAgentOptions) => Effect.Effect<
| {
agent: ReactAgent<
AgentTypeConfig<
ResponseFormatUndefined,
undefined,
AnyAnnotationRoot,
Array<AnyAgentMiddleware>,
ReadonlyArray<
| ClientTool
| ServerTool
| DynamicStructuredTool<
InteropZodObject | JsonSchema7Type | InteropZodType<string>,
unknown,
unknown,
unknown,
unknown,
string
>
| DynamicTool<unknown, unknown>
>,
readonly []
>
>;
tools: NativeTools;
}
| {
agent: ReactAgent<
AgentTypeConfig<
Record<string, any>,
StateDefinitionInit | undefined,
InteropZodObject | AnyAnnotationRoot,
ReadonlyArray<AnyAgentMiddleware>,
ReadonlyArray<ClientTool | ServerTool>,
ReadonlyArray<() => StreamTransformer<any>>
>
>;
tools: NativeTools;
},
AgentInvocationFailure,
NativeToolIdentity | DeepAgentsLoader
>;
runtime-native-agent.types.ts
Owns native agent construction and invocation adaptation, retaining the authored SDK configuration and selected persistence context. This companion preserves the native input and output types without starting runtime work.
CreateNativeAgentOptions (interface)
Inputs required to build one native agent invocation.
Signature
export interface CreateNativeAgentOptions {
readonly runtime: NativeAgentRuntimeOptions;
readonly model: string | LanguageModelLike;
readonly signal: AbortSignal;
readonly maxOutputBytes: number;
readonly invocationId: string;
readonly traceId: string;
}
NativeAgent (type alias)
Native LangChain agent runnable.
Signature
type NativeAgent = ReturnType<typeof createAgent>;
NativeAgentRuntimeOptions (type alias)
Runtime options narrowed to a native agent descriptor.
Signature
type NativeAgentRuntimeOptions = Omit<AgentRuntimeOptions, "agent"> &
AgentInvocationOptions & {
readonly agent: AgentDescriptor<string, unknown, unknown>;
};
runtime-native-event-tools.ts
Projects native tool events into RELKIT tool lifecycle observations while preserving tool call identifiers and status order.
emitToolEvent
Emits a native tool event for existing Promise callers.
Throws
The original sink or cancellation error.
Example
await emitToolEvent(event, sink, ids, names, calls, signal);
Signature
declare const emitToolEvent: (
event: ProtocolEvent,
sink: AgentContentSink | undefined,
toolIds: ReadonlyMap<string, string>,
relkitNames: ReadonlySet<string>,
toolNames: Map<string, string>,
signal: AbortSignal,
) => Promise<void>;
emitToolEventEffect
Emits public lifecycle updates for a native tool event.
Example
await Effect.runPromise(emitToolEventEffect(event, sink, ids, names, calls, signal));
Signature
declare const emitToolEventEffect: (
event: ProtocolEvent,
sink: AgentContentSink | undefined,
toolIds: ReadonlyMap<string, string>,
relkitNames: ReadonlySet<string>,
toolNames: Map<string, string>,
signal: AbortSignal,
) => Effect.Effect<void, AgentInvocationFailure, never>;
runtime-native-events-helpers.ts
Extracts native event identifiers and payload fragments shared by stream adapters, retaining the SDK’s event identity conventions.
executionContext
Resolves the nearest execution context for a nested event.
Example
executionContext(event, contexts);
Signature
declare const executionContext: (
event: ProtocolEvent,
contexts: ReadonlyMap<string, NativeExecutionContext>,
) => NativeExecutionContext;
isModelStart
Checks whether an event starts a model call.
Example
isModelStart(event);
Signature
declare const isModelStart: (event: ProtocolEvent) => boolean;
isToolStart
Checks whether an event starts a tool call.
Example
isToolStart(event);
Signature
declare const isToolStart: (event: ProtocolEvent) => boolean;
trackExecutionContext
Tracks agent and subagent identity from native protocol events.
Example
trackExecutionContext(event, contexts);
Signature
declare const trackExecutionContext: (
event: ProtocolEvent,
contexts: Map<string, NativeExecutionContext>,
) => void;
runtime-native-events.ts
Maps the native event stream into RELKIT execution events and public observations in the order delivered by the native iterator.
collectNativeEvents
Collects native events for existing Promise runtime callers.
Throws
The original stream, sink, validation, or cancellation error.
Example
await collectNativeEvents(
events,
sink,
ids,
names,
signal,
limits,
schemas,
failure,
observe,
abort,
);
Signature
declare const collectNativeEvents: (
events: AsyncIterable<ProtocolEvent>,
sink: AgentContentSink | undefined,
toolIds: ReadonlyMap<string, string>,
relkitNames: ReadonlySet<string>,
signal: AbortSignal,
limits: { readonly maxSteps: number; readonly maxToolCalls: number },
stateSchemas: ReadonlyMap<string, StandardSchemaV1>,
failure: () => unknown,
observe: ((event: ProtocolEvent) => void) | undefined,
abort: (reason: unknown) => void,
eventSchemas?: Readonly<Record<string, StandardSchemaV1>>,
) => Promise<void>;
collectNativeEventsEffect
Collects native events with linked Effect interruption.
Example
await Effect.runPromise(
collectNativeEventsEffect(
events,
sink,
ids,
names,
signal,
limits,
schemas,
failure,
observe,
abort,
),
);
Signature
declare const collectNativeEventsEffect: (
events: AsyncIterable<ProtocolEvent>,
sink: AgentContentSink | undefined,
toolIds: ReadonlyMap<string, string>,
relkitNames: ReadonlySet<string>,
signal: AbortSignal,
limits: { readonly maxSteps: number; readonly maxToolCalls: number },
stateSchemas: ReadonlyMap<string, StandardSchemaV1<unknown, unknown>>,
failure: () => unknown,
observe: ((event: ProtocolEvent) => void) | undefined,
abort: (reason: unknown) => void,
eventSchemas?: Readonly<Record<string, StandardSchemaV1<unknown, unknown>>> | undefined,
) => Effect.Effect<undefined, AgentInvocationFailure, never>;
runtime-native-limits.ts
Applies authored step, tool-call and timeout limits at native invocation boundaries and reports the existing limit failures.
createNativeLimitMiddleware
Creates native invocation guards for existing synchronous callers.
Throws
The original middleware creation error.
Example
createNativeLimitMiddleware(limits);
Signature
declare const createNativeLimitMiddleware: (limits: AgentLimits) => AnyAgentMiddleware;
createNativeLimitMiddlewareEffect
Creates per-invocation model and tool call guards.
Example
Effect.runSync(createNativeLimitMiddlewareEffect(limits));
Signature
declare const createNativeLimitMiddlewareEffect: (
limits: AgentLimits,
) => Effect.Effect<AnyAgentMiddleware, AgentInvocationFailure, never>;
runtime-native-messages.ts
Converts invocation messages into native LangChain message shapes while preserving content, tool calls and reply correlation.
NativeMessageAccumulator (class)
Per-invocation accumulator of streamed native assistant message parts.
Example
const messages = new NativeMessageAccumulator();
Signature
declare class NativeMessageAccumulator
update (method)
Applies one event for existing synchronous callers.
Example
messages.update(event);
Signature
declare const update: (event: AgentExecutionEvent) => BrowserMessage | undefined;
updateCore (method)
Signature
declare const updateCore: (event: AgentExecutionEvent) => BrowserMessage | undefined;
updateEffect (property)
Applies one public event to the message accumulator.
Example
Effect.runSync(messages.updateEffect(event));
Signature
readonly updateEffect: (event: AgentExecutionEvent) => Effect.Effect<BrowserMessage | undefined, never, never>
runtime-native-messages.types.ts
Mutable text parts for one native assistant message.
MessageState (interface)
Mutable text parts for one native assistant message.
Signature
export interface MessageState {
readonly messageId: string;
readonly createdAt: string;
readonly parts: Map<number, string>;
}
runtime-native-public-state.ts
Projects permitted native state values for public client events using the agent’s declared visibility policy.
selectEffect
Validates selected fields from one state object with bounded concurrency.
Example
await Effect.runPromise(selectEffect(state, schemas));
Signature
declare const selectEffect: (
value: Record<string, unknown>,
schemas: ReadonlyMap<string, StandardSchemaV1<unknown, unknown>>,
) => Effect.Effect<{ [k: string]: unknown }, AgentInvocationFailure, never>;
selectedStateEffect
Projects selected state keys from direct or nested native updates.
Example
await Effect.runPromise(selectedStateEffect(update, schemas));
Signature
declare const selectedStateEffect: (
value: unknown,
schemas: ReadonlyMap<string, StandardSchemaV1<unknown, unknown>>,
) => Effect.Effect<{ [k: string]: unknown } | undefined, AgentInvocationFailure, never>;
runtime-native-public-tools.ts
Projects native tool activity into client-visible tool events after applying the declared public visibility contract.
publicToolValue
Projects a native tool result for existing synchronous callers.
Example
publicToolValue(result);
Signature
declare const publicToolValue: (value: unknown) => unknown;
publicToolValueEffect
Projects a native tool result to its public value.
Example
Effect.runSync(publicToolValueEffect(result));
Signature
declare const publicToolValueEffect: (value: unknown) => Effect.Effect<unknown, never, never>;
runtime-native-public.ts
Coordinates native state and tool projection for public execution sinks without exposing undeclared private state.
NativeExecutionContext
Signature
declare const NativeExecutionContext: NativeExecutionContext;
nativePublicEvent
Projects a native event for existing Promise callers.
Throws
The original schema or timestamp error.
Example
await nativePublicEvent(event, schemas);
Signature
declare const nativePublicEvent: (
event: ProtocolEvent,
stateSchemas: ReadonlyMap<string, StandardSchemaV1>,
context?: NativeExecutionContext,
eventSchemas?: Readonly<Record<string, StandardSchemaV1>>,
) => Promise<AgentExecutionEvent>;
nativePublicEventEffect
Projects a native protocol event to its public, validated form.
Example
await Effect.runPromise(nativePublicEventEffect(event, schemas));
Signature
declare const nativePublicEventEffect: (
event: ProtocolEvent,
stateSchemas: ReadonlyMap<string, StandardSchemaV1<unknown, unknown>>,
context?: NativeExecutionContext | undefined,
eventSchemas?: Readonly<Record<string, StandardSchemaV1<unknown, unknown>>> | undefined,
) => Effect.Effect<AgentExecutionEvent, AgentInvocationFailure, never>;
publicToolValue
Signature
declare const publicToolValue: (value: unknown) => unknown;
publicToolValueEffect
Signature
declare const publicToolValueEffect: (value: unknown) => Effect.Effect<unknown, never, never>;
runtime-native-public.types.ts
Coordinates native state and tool projection for public execution sinks without exposing undeclared private state. This companion preserves the native input and output types without starting runtime work.
NativeExecutionContext (type alias)
Agent and parent context attached to a public native event.
Signature
type NativeExecutionContext = Pick<AgentExecutionEvent, "agent" | "parent">;
runtime-native-response-format.ts
Converts a validated RELKIT output schema to the native structured response strategy, preserving schema failures and disabling native silent recovery.
responseFormatEffect
Creates the native structured output strategy.
Example
Effect.runSync(responseFormatEffect(output));
Signature
declare const responseFormatEffect: (
schema: StandardSchemaV1<unknown, unknown>,
model?: NativeModel | undefined,
) => Effect.Effect<
ProviderStrategy<Record<string, unknown>> | TypedToolStrategy<Record<string, unknown>>,
AgentInvocationFailure,
never
>;
runtime-native-subagents.ts
Builds native child configurations and nested runnables after model, tools and persistence have been resolved by the existing ordered subagent traversal.
childAgentCommon
Projects an already resolved child’s native runnable configuration.
Signature
declare const childAgentCommon: (
child: AgentDescriptor<string, unknown, unknown>,
model: string | LanguageModelLike,
instructions: string,
format: Effect.Success<ReturnType<typeof responseFormatEffect>>,
childTools: NativeTools,
limitMiddleware: AnyAgentMiddleware,
) => {
name: string;
model: string | LanguageModelLike;
systemPrompt: string;
tools: Array<
| ClientTool
| ServerTool
| DynamicStructuredTool<
InteropZodObject | JsonSchema7Type | InteropZodType<string>,
unknown,
unknown,
unknown,
unknown,
string
>
| DynamicTool<unknown, unknown>
>;
middleware: Array<AnyAgentMiddleware>;
responseFormat:
ProviderStrategy<Record<string, unknown>> | TypedToolStrategy<Record<string, unknown>>;
};
nestedChildAgentEffect
Constructs one nested runnable with the existing native exception boundary.
Signature
declare const nestedChildAgentEffect: (
child: AgentDescriptor<
string,
unknown,
unknown,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
ReadonlyArray<AgentMiddleware>,
ReadonlyArray<AgentTool>
>,
common: {
name: string;
model: string | LanguageModelLike;
systemPrompt: string;
tools: Array<
| ClientTool
| ServerTool
| DynamicStructuredTool<
InteropZodObject | JsonSchema7Type | InteropZodType<string>,
unknown,
unknown,
unknown,
unknown,
string
>
| DynamicTool<unknown, unknown>
>;
middleware: Array<AnyAgentMiddleware>;
responseFormat:
ProviderStrategy<Record<string, unknown>> | TypedToolStrategy<Record<string, unknown>>;
},
persistence: ResolvedGraphPersistence,
nested: Array<unknown>,
backend: unknown,
deepagents: typeof import("deepagents"),
) => Effect.Effect<NativeNestedSubagent, AgentInvocationFailure, never>;
runtime-native-subagents.types.ts
Native nested subagent declaration consumed by DeepAgents construction.
NativeNestedSubagent (interface)
Native nested subagent declaration consumed by DeepAgents construction.
Signature
export interface NativeNestedSubagent {
readonly name: string;
readonly description: string;
readonly runnable: ReturnType<typeof import("deepagents").createDeepAgent>;
}
runtime-native-support.ts
Resolves native execution support, including optional DeepAgents loading, preserving initialization and nested dependency errors as invocation causes.
DeepAgentsLoader (class)
Substitutable loader for the optional DeepAgents dependency.
Example
Effect.provide(loadDeepAgentsEffect(), DeepAgentsLoaderLive);
Signature
declare class DeepAgentsLoader
DeepAgentsLoaderLive
Live dynamic import of the optional DeepAgents dependency.
Example
Effect.runPromise(Effect.provide(loadDeepAgentsEffect(), DeepAgentsLoaderLive));
Signature
declare const DeepAgentsLoaderLive: Layer.Layer<DeepAgentsLoader, never, never>;
DeepAgentsLoaderService
Signature
declare const DeepAgentsLoaderService: DeepAgentsLoaderService;
assertAgentRuntimeDependencies
Verifies optional runtime dependencies for existing Promise callers.
Throws
AgentRuntimeError for an unavailable dependency.
Example
await assertAgentRuntimeDependencies(agents);
Signature
declare const assertAgentRuntimeDependencies: (
agents: readonly AgentDescriptor<string, unknown, unknown>[],
) => Promise<void>;
assertAgentRuntimeDependenciesEffect
Verifies optional runtime dependencies for authored agents.
Example
await Effect.runPromise(
Effect.provide(assertAgentRuntimeDependenciesEffect(agents), DeepAgentsLoaderLive),
);
Signature
declare const assertAgentRuntimeDependenciesEffect: (
agents: ReadonlyArray<
AgentDescriptor<
string,
unknown,
unknown,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
ReadonlyArray<AgentMiddleware>,
ReadonlyArray<AgentTool>
>
>,
) => Effect.Effect<void, AgentInvocationFailure, DeepAgentsLoader>;
combineNativeTools
Combines tool groups for existing synchronous callers.
Throws
The original invalid group error.
Example
combineNativeTools(groups);
Signature
declare const combineNativeTools: (groups: readonly NativeTools[]) => NativeTools;
combineNativeToolsEffect
Combines public IDs and failures from native tool groups.
Example
Effect.runSync(combineNativeToolsEffect(groups));
Signature
declare const combineNativeToolsEffect: (
groups: ReadonlyArray<NativeTools>,
) => Effect.Effect<NativeTools, AgentInvocationFailure, never>;
loadDeepAgents
Loads DeepAgents for existing Promise callers.
Throws
AgentRuntimeError when the module is unavailable.
Example
await loadDeepAgents();
Signature
declare const loadDeepAgents: () => Promise<typeof import("deepagents")>;
loadDeepAgentsEffect
Loads the optional DeepAgents module through a replaceable service.
Example
await Effect.runPromise(Effect.provide(loadDeepAgentsEffect(), DeepAgentsLoaderLive));
Signature
declare const loadDeepAgentsEffect: () => Effect.Effect<
typeof import("deepagents"),
AgentInvocationFailure,
DeepAgentsLoader
>;
nativeInstructions
Projects native instructions for existing synchronous callers.
Throws
The original invalid instructions error.
Example
nativeInstructions(agent);
Signature
declare const nativeInstructions: (agent: AgentDescriptor<string, unknown, unknown>) => string;
nativeInstructionsEffect
Projects authored instructions to native system prompt text.
Example
Effect.runSync(nativeInstructionsEffect(agent));
Signature
declare const nativeInstructionsEffect: (
agent: AgentDescriptor<
string,
unknown,
unknown,
StandardSchemaV1<unknown, unknown>,
StandardSchemaV1<unknown, unknown>,
ReadonlyArray<AgentMiddleware>,
ReadonlyArray<AgentTool>
>,
) => Effect.Effect<string, AgentInvocationFailure, never>;
runtime-native-support.types.ts
Replaceable loader for the optional DeepAgents runtime dependency.
DeepAgentsLoaderService (interface)
Replaceable loader for the optional DeepAgents runtime dependency.
Signature
export interface DeepAgentsLoaderService {
/** Loads the optional runtime module.
* @returns The DeepAgents module.
* @example await loader.load();
*/
readonly load: () => Promise<typeof import("deepagents")>;
}
runtime-native-tool-build.ts
Converts one checked reference into a native tool while preserving common-engine execution, trace context and the deferred approval failure reader.
nativeToolEntry
Resolves one authored tool and records its public native mapping.
Signature
declare const nativeToolEntry: (
entry: AgentTool,
index: number,
context: NativeToolBuildContext,
) => ClientTool | ServerTool | ReturnType<typeof tool>;
runtime-native-tool-build.types.ts
Invocation-owned tool identity maps and deferred native failure authority.
NativeToolBuildContext (interface)
Signature
export interface NativeToolBuildContext {
readonly options: NativeToolRuntimeOptions;
readonly signal: AbortSignal;
readonly maxOutputBytes: number;
readonly invocationId: string;
readonly traceId: string;
readonly identity: NativeToolIdentityService;
readonly publicIds: Map<string, string>;
readonly relkitNames: Set<string>;
readonly setFailure: (cause: unknown) => void;
}
runtime-native-tools-identity.ts
Derives stable native tool identities used by descriptor adaptation and runtime dispatch without cloning the SDK tool instances.
NativeToolIdentity (class)
Substitutable native tool call identity source.
Example
Effect.provide(createNativeToolsEffect(options, signal, 1024, id, trace), NativeToolIdentityLive);
Signature
declare class NativeToolIdentity
NativeToolIdentityLive
Live UUID source for native tool calls.
Example
Effect.runSync(Effect.provide(effect, NativeToolIdentityLive));
Signature
declare const NativeToolIdentityLive: Layer.Layer<NativeToolIdentity, never, never>;
runtime-native-tools.ts
Combines authored native tools and RELKIT callable adapters for invocation, retaining input schemas and native dispatch identity.
NativeToolIdentity
Signature
declare const NativeToolIdentity: typeof NativeToolIdentity;
NativeToolIdentityLive
Signature
declare const NativeToolIdentityLive: Layer<NativeToolIdentity, never, never>;
NativeTools
Signature
declare const NativeTools: NativeTools;
createNativeTools
Materializes native tools for existing synchronous callers.
Throws
The original unknown tool or schema error.
Example
createNativeTools(options, signal, 1024, id, trace);
Signature
declare const createNativeTools: (
options: NativeToolRuntimeOptions,
signal: AbortSignal,
maxOutputBytes: number,
invocationId: string,
traceId: string,
) => NativeTools;
createNativeToolsEffect
Materializes LangChain tools with public IDs and an invocation failure reader.
Example
Effect.runSync(
Effect.provide(createNativeToolsEffect(options, signal, 1024, id, trace), NativeToolIdentityLive),
);
Signature
declare const createNativeToolsEffect: (
options: NativeToolRuntimeOptions,
signal: AbortSignal,
maxOutputBytes: number,
invocationId: string,
traceId: string,
) => Effect.Effect<NativeTools, AgentInvocationFailure, NativeToolIdentity>;
runtime-native-tools.types.ts
Combines authored native tools and RELKIT callable adapters for invocation, retaining input schemas and native dispatch identity. This companion preserves the native input and output types without starting runtime work.
NativeToolIdentityService (interface)
Replaceable identity source for native tool calls.
Signature
export interface NativeToolIdentityService {
/** Creates a call identity when LangChain does not supply one.
* @returns A UUID.
* @example identity.randomUUID();
*/
readonly randomUUID: () => string;
}
NativeToolRuntimeOptions (type alias)
Runtime context used to materialize native tools.
Signature
type NativeToolRuntimeOptions = AgentRuntimeOptions & AgentInvocationOptions;
NativeTools (interface)
Native tools and public identity mapping for one invocation.
Signature
export interface NativeTools {
readonly values: readonly (
ClientTool | ServerTool | ReturnType<typeof import("langchain").tool>
)[];
readonly publicIds: ReadonlyMap<string, string>;
readonly relkitNames: ReadonlySet<string>;
readonly failure: () => unknown;
}
runtime-service.ts
Provides the Effect runtime service that composes native model resolution, tools and loop execution under the invocation owner.
AgentExecution (class)
Injectable model, graph, loop, and identity boundary.
Example
Effect.provide(invokeAgentEffect(options), AgentExecutionLive);
Signature
declare class AgentExecution
AgentExecutionLive
Live agent integrations used by the Promise compatibility API.
Example
Effect.runPromise(Effect.provide(invokeAgentEffect(options), AgentExecutionLive));
Signature
declare const AgentExecutionLive: Layer.Layer<AgentExecution, never, never>;
AgentExecutionService
Signature
declare const AgentExecutionService: AgentExecutionService;
runtime-service.types.ts
Provides the Effect runtime service that composes native model resolution, tools and loop execution under the invocation owner. This companion preserves the native input and output types without starting runtime work.
AgentExecutionService (interface)
Substitutable integrations used while invoking an agent.
Signature
export interface AgentExecutionService {
readonly resolveModel: typeof resolveRuntimeModel;
readonly runLoop: typeof runAgentLoop;
readonly invokeGraph: typeof invokeGraph;
readonly randomUUID: () => string;
}
runtime-state-schemas.ts
Decodes invocation state and output values at the native runtime boundary before persisted or public projections consume them.
selectedStateSchemas
Resolves public state validators for existing synchronous callers.
Throws
TypeError for a selected key without a validator.
Example
selectedStateSchemas([state], ["answer"]);
Signature
declare const selectedStateSchemas: (
sources: readonly unknown[],
selected: readonly string[],
) => ReadonlyMap<string, StandardSchemaV1>;
selectedStateSchemasEffect
Resolves validators for selected public state keys.
Example
Effect.runSync(selectedStateSchemasEffect([state], ["answer"]));
Signature
declare const selectedStateSchemasEffect: (
sources: ReadonlyArray<unknown>,
selected: ReadonlyArray<string>,
) => Effect.Effect<
ReadonlyMap<string, StandardSchemaV1<unknown, unknown>>,
AgentInvocationFailure,
never
>;
runtime-strict-response-schema.ts
Selects the structural JSON-schema subset that can use provider enforcement without making optional fields required.
strictResponseSchema
Closes declared objects for native generation; runtime validation still uses the authored schema.
Signature
declare const strictResponseSchema: (schema: JsonSchema, depth?: number) => JsonSchema | undefined;
runtime-tool-adapter.ts
Adapts RELKIT callable tools to native SDK tools while preserving validated input, execution context and typed invocation failures.
createAgentInvocationDispatcher
Signature
declare const createAgentInvocationDispatcher: (
engine: ToolEngine,
options: RuntimeToolOptions,
invocationId: string,
traceId: string | undefined,
parentSpanId: string | undefined,
signal: AbortSignal,
) => InvocationDispatcher;
createAgentInvocationDispatcherEffect
Signature
declare const createAgentInvocationDispatcherEffect: (
engine: ToolEngine,
options: RuntimeToolOptions,
invocationId: string,
traceId: string | undefined,
parentSpanId: string | undefined,
signal: AbortSignal,
) => Effect.Effect<
Readonly<{
dispatch: <Input, Output, Context extends { readonly signal: AbortSignal }>(
request: InvocationDispatchRequest<Input, Output, Context>,
) => Promise<Output>;
}>,
never,
never
>;
invokeAgentTool
Invokes an allowed tool for existing Promise callers.
Throws
The original validation, sink, approval, or tool error.
Example
await invokeAgentTool(engine, tool, turn, options, signal, id);
Signature
declare const invokeAgentTool: (
engine: ToolEngine,
tool: ToolDescriptor<string>,
turn: AgentToolCall,
options: RuntimeToolOptions,
signal: AbortSignal,
invocationId: string,
traceId?: string,
parentSpanId?: string,
) => Promise<unknown>;
invokeAgentToolEffect
Invokes an allowed tool with validated input and public lifecycle events.
Example
await Effect.runPromise(invokeAgentToolEffect(engine, tool, turn, options, signal, id));
Signature
declare const invokeAgentToolEffect: (
engine: ToolEngine,
tool: ToolDescriptor<string>,
turn: AgentToolCall,
options: RuntimeToolOptions,
signal: AbortSignal,
invocationId: string,
traceId?: string | undefined,
parentSpanId?: string | undefined,
) => Effect.Effect<unknown, AgentInvocationFailure, never>;
runtime-tool-dispatcher.ts
Dispatches native tool calls to the selected RELKIT tool target and carries approval and execution failures back to the native loop.
createAgentInvocationDispatcher
Creates a nested function dispatcher for existing synchronous callers.
Example
createAgentInvocationDispatcher(engine, options, id, trace, span, signal);
Signature
declare const createAgentInvocationDispatcher: (
engine: ToolEngine,
options: RuntimeToolOptions,
invocationId: string,
traceId: string | undefined,
parentSpanId: string | undefined,
signal: AbortSignal,
) => InvocationDispatcher;
createAgentInvocationDispatcherEffect
Creates a nested function dispatcher with stable agent parent context.
Example
Effect.runSync(createAgentInvocationDispatcherEffect(engine, options, id, trace, span, signal));
Signature
declare const createAgentInvocationDispatcherEffect: (
engine: ToolEngine,
options: RuntimeToolOptions,
invocationId: string,
traceId: string | undefined,
parentSpanId: string | undefined,
signal: AbortSignal,
) => Effect.Effect<
Readonly<{
dispatch: <Input, Output, Context extends { readonly signal: AbortSignal }>(
request: InvocationDispatchRequest<Input, Output, Context>,
) => Promise<Output>;
}>,
never,
never
>;
runtime-tool-events.ts
Publishes tool lifecycle observations for native calls with stable call identity, preserving failure and completion ordering.
emitTool
Emits a tool transition for existing Promise callers.
Throws
The original sink or cancellation error.
Example
await emitTool(options, turn, "running", undefined, signal);
Signature
declare const emitTool: (
options: RuntimeToolOptions,
turn: Pick<AgentToolCall, "callId" | "toolId">,
state: ToolPartState,
value: unknown,
signal: AbortSignal,
) => Promise<void>;
emitToolEffect
Emits a public tool transition with linked Effect cancellation.
Example
await Effect.runPromise(emitToolEffect(options, turn, "running", undefined, signal));
Signature
declare const emitToolEffect: (
options: RuntimeToolOptions,
turn: Pick<AgentToolCall, "callId" | "toolId">,
state: ToolPartState,
value: unknown,
signal: AbortSignal,
) => Effect.Effect<undefined, AgentInvocationFailure, never>;
resolveAgentApproval
Resolves approval for existing Promise callers.
Throws
The original approval, sink, or cancellation error.
Example
await resolveAgentApproval(options, request, callId, id, signal);
Signature
declare const resolveAgentApproval: (
options: RuntimeToolOptions,
request: ToolApprovalRequest,
toolCallId: string,
invocationId: string,
signal: AbortSignal,
) => Promise<true>;
resolveAgentApprovalEffect
Resolves tool approval and emits its lifecycle transitions.
Example
await Effect.runPromise(resolveAgentApprovalEffect(options, request, callId, id, signal));
Signature
declare const resolveAgentApprovalEffect: (
options: RuntimeToolOptions,
request: FunctionToolApprovalRequest,
toolCallId: string,
invocationId: string,
signal: AbortSignal,
) => Effect.Effect<true, AgentInvocationFailure, never>;
runtime-tool-events.types.ts
Publishes tool lifecycle observations for native calls with stable call identity, preserving failure and completion ordering. This companion preserves the native input and output types without starting runtime work.
RuntimeToolOptions (type alias)
Runtime integrations needed to emit tool events and resolve approval. The invocation options supply the approval callback and content sink.
Example
const options: RuntimeToolOptions = { ...runtime, input };
Signature
type RuntimeToolOptions = AgentRuntimeOptions & AgentInvocationOptions;
runtime-tool-invocation.ts
Executes a validated tool in the original invocation scope and emits terminal lifecycle records without changing approval or progress routing.
invokeRegisteredAgentToolEffect
Dispatches a checked tool inside its existing call scope.
Signature
declare const invokeRegisteredAgentToolEffect: (
engine: ToolEngine,
tool: ToolDescriptor<string>,
turn: AgentToolCall,
options: RuntimeToolOptions,
signal: AbortSignal,
invocationId: string,
traceId: string | undefined,
parentSpanId: string | undefined,
progressSink: ProgressSink | undefined,
) => Effect.Effect<unknown, AgentInvocationFailure, never>;
runtime-tool-lookup.ts
Resolves authored RELKIT tool references against the invocation tool registry before native tool construction.
findModelTool
Finds a native tool for existing synchronous callers.
Example
findModelTool(tools, refs, "math_add_0");
Signature
declare const findModelTool: (
source: ToolSource,
refs: readonly { readonly ref: { readonly id: string } }[],
name: string,
) => ToolDescriptor<string> | undefined;
findModelToolEffect
Finds a native tool by direct or model-facing name.
Example
Effect.runSync(findModelToolEffect(tools, refs, "math_add_0"));
Signature
declare const findModelToolEffect: (
source: ToolSource,
refs: ReadonlyArray<{ readonly ref: { readonly id: string } }>,
name: string,
) => Effect.Effect<ToolDescriptor<string> | undefined, never, never>;
findTool
Finds a tool for existing synchronous callers.
Example
findTool(tools, "math.add");
Signature
declare const findTool: (source: ToolSource, id: string) => ToolDescriptor<string> | undefined;
findToolEffect
Finds a registered tool by map key or descriptor ID.
Example
Effect.runSync(findToolEffect(tools, "math.add"));
Signature
declare const findToolEffect: (
source: ToolSource,
id: string,
) => Effect.Effect<ToolDescriptor<string> | undefined, never, never>;
modelToolName
Produces a native tool name for existing synchronous callers.
Example
modelToolName("math.add", 0);
Signature
declare const modelToolName: (id: string, index: number) => string;
modelToolNameEffect
Produces a bounded model-facing name for one tool ID.
Example
Effect.runSync(modelToolNameEffect("math.add", 0));
Signature
declare const modelToolNameEffect: (
id: string,
index: number,
) => Effect.Effect<string, never, never>;
runtime-tools.ts
Builds invocation tool bindings from the selected RELKIT registry and native tool descriptors, keeping execution ownership with the caller.
AgentToolCall
Signature
declare const AgentToolCall: AgentToolCall;
findModelTool
Signature
declare const findModelTool: (
source: ToolSource,
refs: readonly { readonly ref: { readonly id: string } }[],
name: string,
) => ToolDescriptor<string> | undefined;
findModelToolEffect
Signature
declare const findModelToolEffect: (
source: ToolSource,
refs: ReadonlyArray<{ readonly ref: { readonly id: string } }>,
name: string,
) => Effect.Effect<ToolDescriptor<string> | undefined, never, never>;
findTool
Signature
declare const findTool: (source: ToolSource, id: string) => ToolDescriptor<string> | undefined;
findToolEffect
Signature
declare const findToolEffect: (
source: ToolSource,
id: string,
) => Effect.Effect<ToolDescriptor<string> | undefined, never, never>;
modelToolName
Signature
declare const modelToolName: (id: string, index: number) => string;
modelToolNameEffect
Signature
declare const modelToolNameEffect: (
id: string,
index: number,
) => Effect.Effect<string, never, never>;
runTool
Executes a tool for existing Promise callers.
Throws
ApprovalRequiredError or AgentRuntimeError for cancellation.
Example
await runTool(options, turn, signal, 1024, id);
Signature
declare const runTool: (
options: AgentRuntimeOptions & AgentInvocationOptions,
turn: AgentToolCall,
signal: AbortSignal,
maxOutputBytes: number,
invocationId: string,
traceId?: string,
parentSpanId?: string,
) => Promise<JsonValue>;
runToolEffect
Executes an allowed RELKIT tool with safe public error projection.
Example
await Effect.runPromise(runToolEffect(options, turn, signal, 1024, id));
Signature
declare const runToolEffect: (
options: AgentRuntimeBaseOptions & { readonly modelRegistry?: unknown } & AgentInvocationOptions,
turn: AgentToolCall,
signal: AbortSignal,
maxOutputBytes: number,
invocationId: string,
traceId?: string | undefined,
parentSpanId?: string | undefined,
) => Effect.Effect<JsonValue, AgentInvocationFailure, never>;
runtime-tools.types.ts
One model requested RELKIT tool call.
AgentToolCall (interface)
One model requested RELKIT tool call.
Signature
export interface AgentToolCall {
readonly callId: string;
readonly toolId: string;
readonly input: unknown;
}
runtime-utils.ts
Normalizes native invocation utility values shared by runtime adapters without changing the owning request’s execution context.
createExecutionSignal
Signature
declare const createExecutionSignal: (options: ExecutionSignalOptions) => ExecutionSignalHandle;
jsonValue
Produces bounded JSON for existing synchronous callers.
Throws
AgentRuntimeError for invalid JSON or byte limits.
Example
jsonValue({ ok: true }, 1024, "output");
Signature
declare const jsonValue: (value: unknown, maxBytes: number, label: string) => JsonValue;
jsonValueEffect
Produces bounded, canonical JSON from a runtime value.
Example
Effect.runSync(jsonValueEffect({ ok: true }, 1024, "output"));
Signature
declare const jsonValueEffect: (
value: unknown,
maxBytes: number,
label: string,
) => Effect.Effect<JsonValue, AgentInvocationFailure, never>;
modelFailure
Classifies a model failure for existing synchronous callers.
Example
modelFailure(error, signal);
Signature
declare const modelFailure: (cause: unknown, signal: AbortSignal) => AgentRuntimeError;
modelFailureEffect
Classifies a model failure without exposing provider details.
Example
Effect.runSync(modelFailureEffect(error, signal));
Signature
declare const modelFailureEffect: (
cause: unknown,
signal: AbortSignal,
) => Effect.Effect<AgentRuntimeError, never, never>;
signalFailure
Signature
declare const signalFailure: (signal: AbortSignal) => AgentRuntimeError;
validateValue
Validates an invocation value for existing Promise callers.
Throws
AgentRuntimeError for invalid values.
Example
await validateValue(schema, input, "input");
Signature
declare const validateValue: (
schema: StandardSchemaV1,
value: unknown,
phase: "input" | "output",
) => Promise<unknown>;
validateValueEffect
Validates an invocation value through a Standard Schema.
Example
await Effect.runPromise(validateValueEffect(schema, input, "input"));
Signature
declare const validateValueEffect: (
schema: StandardSchemaV1<unknown, unknown>,
value: unknown,
phase: "input" | "output",
) => Effect.Effect<unknown, AgentInvocationFailure, never>;
withSignal
Signature
declare const withSignal: <T>(work: MaybePromise<T>, signal: AbortSignal) => Promise<T>;
runtime.ts
Exposes generated and direct native invocation entrypoints plus dependency and persistence lifecycle operations for the selected integration.
“./runtime.types.js” (namespace export)
Re-exports all named exports from the “./runtime.types.js” module.
Signature
export * from "./runtime.types.js";
AgentInvocationFailure
Signature
declare const AgentInvocationFailure: typeof AgentInvocationFailure;
AgentRuntimeError
Signature
declare const AgentRuntimeError: typeof AgentRuntimeError;
assertAgentRuntimeDependencies
Signature
declare const assertAgentRuntimeDependencies: (
agents: readonly AgentDescriptor<string, unknown, unknown>[],
) => Promise<void>;
createAgentRuntime
Binds one agent catalog for existing synchronous callers.
Example
const runtime = createAgentRuntime(options);
Signature
declare const createAgentRuntime: (options: AgentRuntimeOptions) => AgentRuntime;
createAgentRuntimeEffect
Creates a reusable runtime through an observable Effect.
Example
Effect.runSync(createAgentRuntimeEffect(options));
Signature
declare const createAgentRuntimeEffect: (
options: AgentRuntimeOptions,
) => Effect.Effect<AgentRuntime, never, never>;
createGeneratedAgentFunction
Signature
declare const createGeneratedAgentFunction: (
agentId: unknown,
executor?: GeneratedAgentExecutor,
) => GeneratedAgentFunction;
invokeAgent
Runs an agent through the live Effect Layer for existing Promise callers.
Throws
The original validation, provider, cancellation, or runtime error.
Example
await invokeAgent({ ...options, input: { message: "hi" } });
Signature
declare const invokeAgent: (
options: AgentRuntimeOptions & AgentInvocationOptions,
) => Promise<unknown>;
invokeAgentEffect
Invokes an agent with typed failures and interruption linked to its work.
Example
Effect.runPromise(Effect.provide(invokeAgentEffect(options), AgentExecutionLive));
Signature
declare const invokeAgentEffect: (
options: AgentRuntimeBaseOptions & { readonly modelRegistry?: unknown } & AgentInvocationOptions,
) => Effect.Effect<unknown, AgentInvocationFailure, AgentExecution>;
invokeAgentFunction
Runs an agent once for generated function actions, retaining output failure identity.
Example
await invokeAgentFunction(options);
Signature
declare const invokeAgentFunction: (
options: AgentRuntimeOptions & AgentInvocationOptions,
) => Promise<unknown>;
releaseAgentPersistence
Signature
declare const releaseAgentPersistence: (descriptors: readonly unknown[]) => Promise<void>;
runAgent
Signature
declare const runAgent: (options: AgentRuntimeOptions & AgentInvocationOptions) => Promise<unknown>;
runtimeIntegration
Signature
declare const runtimeIntegration: Readonly<{
kind: "runtime-integration";
integrationId: "langchain";
registrations: ReadonlyArray<{ capability: string; adapterId: string; protocolVersion: number }>;
}>;
runtime.types.ts
Exposes generated and direct native invocation entrypoints plus dependency and persistence lifecycle operations for the selected integration. This companion preserves the native input and output types without starting runtime work.
AgentApprovalHandler (type alias)
Resolves a pending tool approval for an invocation.
Signature
type AgentApprovalHandler = (
approval: import("@relkit/agents/internal/approval").PendingApproval,
) => MaybePromise<ApprovalDecision>;
AgentContentSink (interface)
Sends agent output and events to the surrounding runtime.
Signature
export interface AgentContentSink {
readonly emitOutput: (value: unknown, signal: AbortSignal) => MaybePromise<void>;
readonly finishOutput?: (signal: AbortSignal) => MaybePromise<void>;
readonly progressSinkForTool?: (tool: {
readonly toolCallId: string;
readonly toolId: string;
}) => import("@relkit/invocation").ProgressSink;
readonly emitTool?: (
value: {
readonly toolCallId: string;
readonly toolId: string;
readonly state: import("@relkit/agents/internal/state.types").ToolPartState;
readonly value?: unknown;
},
signal: AbortSignal,
) => MaybePromise<void>;
readonly emitEvent?: (
value: import("@relkit/agents/internal/runtime-events").AgentExecutionEvent,
signal: AbortSignal,
) => MaybePromise<void>;
readonly emitMessage?: (
value: import("@relkit/contracts").BrowserMessage,
signal: AbortSignal,
) => MaybePromise<void>;
readonly emitWaiting?: (
value: Omit<
import("@relkit/agents/internal/state.types").AgentWaitingState,
"revision" | "runId"
>,
signal: AbortSignal,
) => MaybePromise<void>;
}
AgentConversationMessage (interface)
One user or assistant message in a native agent conversation.
Signature
export interface AgentConversationMessage {
readonly role: "user" | "assistant";
readonly content: string;
}
AgentInvocationOptions (interface)
Per-call identity, input, cancellation, and control options.
Signature
export interface AgentInvocationOptions {
readonly input: unknown;
readonly invocationId?: string;
readonly signal?: AbortSignal;
readonly deadlineMs?: number;
readonly timeoutMs?: number;
readonly approval?: AgentApprovalHandler;
readonly traceId?: string;
readonly parentSpanId?: string;
readonly hooks?: AgentRuntimeHooks;
readonly capture?: AgentCapturePolicy;
readonly threadId?: string;
readonly resume?: boolean;
}
AgentRuntime (interface)
Reusable invocation API bound to one agent catalog.
Signature
export interface AgentRuntime {
readonly invoke: (
input: unknown,
options?: Omit<AgentInvocationOptions, "input">,
) => Promise<unknown>;
}
AgentRuntimeBaseOptions (interface)
Common authoring and execution dependencies for an agent runtime.
Signature
export interface AgentRuntimeBaseOptions {
readonly agent: AgentAny;
readonly tools: import("@relkit/tools").ToolSource;
readonly bucketBackend?: import("./deepagent-bucket-client.types.js").DeepAgentBucketClient;
readonly engine: import("@relkit/tools").ToolEngine;
readonly maxInputBytes?: number;
readonly maxOutputBytes?: number;
readonly approval?: AgentApprovalHandler;
readonly messages?: readonly AgentConversationMessage[];
readonly steering?: AgentSteeringSource;
readonly contentSink?: AgentContentSink;
readonly hooks?: AgentRuntimeHooks;
readonly capture?: AgentCapturePolicy;
readonly environment?: Readonly<Record<string, unknown>>;
}
AgentRuntimeOptions (type alias)
Long-lived dependencies shared by agent invocations.
Signature
type AgentRuntimeOptions = AgentRuntimeBaseOptions & {
readonly modelRegistry?: unknown;
};
AgentSteeringSource (interface)
Supplies queued steering messages to a running agent.
Signature
export interface AgentSteeringSource {
readonly drain: () => MaybePromise<readonly string[]>;
}
signal-deadline.ts
Resolves the earliest authored deadline before the signal owner installs its timer. Invalid timeout/deadline values preserve the existing public diagnostic.
executionDeadline
Selects the earliest finite invocation deadline.
Signature
declare const executionDeadline: (options: ExecutionSignalOptions, now: number) => number;
signal.ts
Builds and validates RELKIT signal descriptors used by native agent execution while retaining their payload schema and stable identity.
“./signal.types.js” (namespace export)
Re-exports all named exports from the “./signal.types.js” module.
Signature
export * from "./signal.types.js";
ExecutionSignalClock (class)
Replaceable clock and timer boundary for execution deadlines.
Example
Effect.provide(createExecutionSignalEffect(options), ExecutionSignalClockLive);
Signature
declare class ExecutionSignalClock
ExecutionSignalClockLive
Live wall clock and timer implementation.
Example
Effect.runSync(Effect.provide(createExecutionSignalEffect(options), ExecutionSignalClockLive));
Signature
declare const ExecutionSignalClockLive: Layer.Layer<ExecutionSignalClock, never, never>;
acquireExecutionSignalEffect
Acquires an execution signal whose owner closes it with its Effect scope.
Example
Effect.scoped(
Effect.gen(function* () {
const active = yield* acquireExecutionSignalEffect(options);
}),
);
Signature
declare const acquireExecutionSignalEffect: (
options: ExecutionSignalOptions,
) => Effect.Effect<ExecutionSignalHandle, AgentInvocationFailure, ExecutionSignalClock | Scope>;
createExecutionSignal
Creates a live signal for existing callers that own and close the handle.
Throws
The original invalid deadline error.
Example
const active = createExecutionSignal(options);
try {
await work(active.signal);
} finally {
active.close();
}
Signature
declare const createExecutionSignal: (options: ExecutionSignalOptions) => ExecutionSignalHandle;
createExecutionSignalEffect
Creates a live execution signal with an owned timer and caller listener.
Example
Effect.runSync(Effect.provide(createExecutionSignalEffect(options), testClock));
Signature
declare const createExecutionSignalEffect: (
options: ExecutionSignalOptions,
) => Effect.Effect<ExecutionSignalHandle, AgentInvocationFailure, ExecutionSignalClock>;
signalFailure
Converts an abort reason for existing synchronous callers.
Example
signalFailure(signal);
Signature
declare const signalFailure: (signal: AbortSignal) => AgentRuntimeError;
signalFailureEffect
Converts an abort reason to a safe invocation error.
Example
Effect.runSync(signalFailureEffect(signal));
Signature
declare const signalFailureEffect: (
signal: AbortSignal,
) => Effect.Effect<AgentRuntimeError, never, never>;
withSignal
Races work with a caller signal for existing Promise callers.
Throws
The original work error or AgentRuntimeError on cancellation.
Example
await withSignal(fetchData(), signal);
Signature
declare const withSignal: <T>(work: MaybePromise<T>, signal: AbortSignal) => Promise<T>;
withSignalEffect
Races Promise work with caller and Effect cancellation.
Example
await Effect.runPromise(withSignalEffect(work, signal));
Signature
declare const withSignalEffect: <T>(
work: MaybePromise<T>,
signal: AbortSignal,
linkEffectSignal?: boolean | undefined,
) => Effect.Effect<T, AgentInvocationFailure, never>;
signal.types.ts
Builds and validates RELKIT signal descriptors used by native agent execution while retaining their payload schema and stable identity. This companion preserves the native input and output types without starting runtime work.
ExecutionSignalClockService (interface)
Replaceable deadline timer and current time boundary.
Signature
export interface ExecutionSignalClockService {
/** Reads the current wall time in milliseconds.
* @returns Epoch milliseconds.
* @example clock.now();
*/
readonly now: () => number;
/** Schedules a deadline callback.
* @param callback - Deadline action.
* @param delayMs - Nonnegative delay.
* @returns Opaque timer handle.
* @example clock.setTimeout(onDeadline, 1000);
*/
readonly setTimeout: (callback: () => void, delayMs: number) => unknown;
/** Cancels a scheduled callback.
* @param handle - Opaque timer handle.
* @returns Nothing.
* @example clock.clearTimeout(handle);
*/
readonly clearTimeout: (handle: unknown) => void;
}
ExecutionSignalHandle (interface)
Live execution signal whose owner must call close once finished.
Signature
export interface ExecutionSignalHandle {
readonly signal: AbortSignal;
/** Clears the deadline timer and caller signal listener.
* @returns Nothing; repeated calls are safe.
* @example handle.close();
*/
readonly close: () => void;
}
ExecutionSignalOptions (type alias)
Options whose limits and caller signal determine an execution deadline.
Signature
type ExecutionSignalOptions = AgentRuntimeOptions & AgentInvocationOptions;
agent-approvals.ts
Owns native pending decisions and cancellation listeners for one test agent. Settlement removes its listener before completing the same deferred decision.
createAgentApprovalState
Creates isolated native approval controls.
Signature
declare const createAgentApprovalState: (
choice: TestAgentApproval | undefined,
) => AgentApprovalState;
agent-approvals.types.ts
Exercises native agent approval continuations through the harness’s scoped model and execution owner, retaining resume identity and cleanup. This companion preserves the native input and output types without starting runtime work.
AgentApprovalOwnedState (interface)
Native callback state retained by one test approval owner.
Signature
export interface AgentApprovalOwnedState {
readonly pending: Map<string, import("../index.js").PendingApproval>;
readonly decisions: Map<string, PendingAgentDecision>;
readonly signals: Map<string, AbortSignal>;
}
AgentApprovalState (interface)
Synchronous controls over owned native approval decisions and cancellation.
Signature
export interface AgentApprovalState extends TestAgentApprovals {
readonly handler?: AgentApprovalHandler;
readonly reset: () => void;
readonly registerSignal: (id: string, signal: AbortSignal) => void;
readonly releaseSignal: (id: string) => void;
}
PendingAgentDecision (interface)
Deferred decision authority and its native cancellation listener.
Signature
export interface PendingAgentDecision {
readonly done: Deferred.Deferred<"approved" | "denied">;
readonly signal?: AbortSignal;
readonly abort: () => void;
}
agent-harness.types.ts
Defines the native test harness execution and lifecycle contract shared by model, tool and approval helpers. This companion preserves the native input and output types without starting runtime work.
AgentHarnessDependencies (type alias)
Acquired native model, state and observer dependencies for one harness owner.
Signature
type AgentHarnessDependencies = Effect.Success<ReturnType<typeof acquireAgentHarness>>;
AgentHarnessService (interface)
Native state facade and Effect-owned invocation/shutdown workflows.
Signature
export interface AgentHarnessService {
readonly close: Effect.Effect<void, unknown>;
readonly value: Omit<TestAgent, "invoke">;
readonly invoke: (
input: unknown,
invocation?: TestAgentInvocationOptions,
) => Effect.Effect<unknown, unknown>;
}
AgentOwnedState (interface)
Trace ledgers and native work belong to the same agent owner.
Signature
export interface AgentOwnedState {
closed: boolean;
invocationSequence: number;
readonly spans: ReturnType<typeof spanSnapshot>[];
readonly edges: AgentObservedEdge[];
readonly active: Set<AbortController>;
readonly pending: Set<Promise<unknown>>;
closing?: Promise<void>;
}
agent-state-invocation.ts
Runs native invocations under the harness-owned span and cancellation lifetime.
invokeAgentHarness
Signature
declare const invokeAgentHarness: <Agent extends TestAgentDescriptor>(
options: TestAgentOptions<Agent>,
harness: AgentHarnessDependencies,
input: import("@relkit/schema").InferInput<Agent["input"]>,
invocation?: TestAgentInvocationOptions,
) => Promise<import("@relkit/schema").InferOutput<Agent["output"]>>;
agent-state-lifecycle.ts
Stops admission before aborting and joining every native invocation and model owner.
agentHarnessClose
Signature
declare const agentHarnessClose: (
context: Context.Context<never>,
harness: AgentHarnessDependencies,
) => Effect.Effect<void, unknown, never>;
resetAgentHarness
Signature
declare const resetAgentHarness: (harness: AgentHarnessDependencies) => void;
agent-state-setup.ts
Acquires one native test model and its trace, approval and cancellation state.
acquireAgentHarness
Signature
declare const acquireAgentHarness: (
options: TestAgentOptions<TestAgentDescriptor>,
) => Effect.Effect<
{
failures: TestFailureControls;
model: RuntimeTestAgentModel;
state: Ref.Ref<AgentOwnedState>;
approvals: AgentApprovalState;
trace: TestAgentTrace;
hooks: AgentRuntimeHooks;
spanRuntime: SpanRuntime;
engine: {
invoke: (
request: Parameters<(options: ToolEngineInvocation) => Promise<unknown>>[0],
) => Promise<unknown>;
};
},
never,
Scope
>;
agent-state.ts
Builds an isolated native test facade whose work is joined before release.
createAgentState
Creates a network-free test owner retaining descriptor schema inference.
Signature
declare const createAgentState: <Agent extends TestAgentDescriptor>(
options: TestAgentOptions<Agent>,
) => Effect.Effect<
{ value: TestAgent<Agent>; close: Effect.Effect<void, unknown, never> },
never,
Scope
>;
agents-model-native.ts
Implements the scripted native chat-model adapter used by agent tests, preserving tool-call correlation and queued response ordering.
ScriptedChatModel (class)
Native LangChain model transport; script and cancellation remain owned by TestModelScript.
Signature
declare class ScriptedChatModel { constructor(
private readonly turn: (
request: TestAgentModelCall["request"],
signal?: AbortSignal,
) => Promise<TestModelTurn>,
private readonly provider: string,
private readonly modelId: string,
) }
_llmType (method)
Signature
declare const _llmType: () => string;
bindTools (method)
Records native presented tools for script-to-tool name matching.
Signature
declare const bindTools: (tools: BindToolsInput[]) => this;
_generate (method)
Consumes one owned scripted turn using the native invocation signal.
Signature
declare const _generate: (
messages: BaseMessage[],
_options?: this["ParsedCallOptions"],
_runManager?: CallbackManagerForLLMRun,
) => Promise<ChatResult>;
agents-model-operations.ts
Applies scripted native turns under the test model owner’s cancellation state. Reset, replacement and detached evidence retain their existing ordering.
modelScriptReplaceEffect
Replaces scripted decisions after resetting active work.
Signature
declare const modelScriptReplaceEffect: (
state: Ref.Ref<ModelScriptOwnedState>,
reset: Effect.Effect<void>,
turns: readonly TestModelTurn[],
) => Effect.Effect<undefined, TypeError, never>;
modelScriptResetEffect
Cancels active requests and clears this model’s script position/evidence.
Signature
declare const modelScriptResetEffect: (
state: Ref.Ref<ModelScriptOwnedState>,
) => Effect.Effect<void, never, never>;
modelScriptTurnEffect
Executes a turn through the original observed native cancellation boundary.
Signature
declare const modelScriptTurnEffect: (
state: Ref.Ref<ModelScriptOwnedState>,
options: TestAgentModelOptions,
request: TestAgentModelCall["request"],
signal?: AbortSignal,
) => Effect.Effect<TestModelTurn, unknown, never>;
agents-model.ts
Constructs deterministic native test models from scripted steps and exposes their observed calls for invocation assertions.
TestModelScript (class)
Stateful scripted turns and cancellation belong to one model owner.
Signature
declare class TestModelScript
createTestModel
Creates an isolated scripted native language model without network access.
See
- tests/fixtures/checked-examples.ts ownedHelpersExample for checked script ownership.
Signature
declare const createTestModel: (
options?: TestAgentModelOptions & { readonly script?: readonly TestModelTurn[] },
) => RuntimeTestAgentModel;
modelScriptLayer
Builds a network-free script service with cooperative native cancellation.
Signature
declare const modelScriptLayer: (
options?: TestAgentModelOptions,
) => Layer.Layer<TestModelScript, never, never>;
agents-model.types.ts
Constructs deterministic native test models from scripted steps and exposes their observed calls for invocation assertions. This companion preserves the native input and output types without starting runtime work.
ModelScriptOwnedState (interface)
Script index, detached evidence and cancellation owners for one model.
Signature
export interface ModelScriptOwnedState {
turns: readonly TestModelTurn[];
next: number;
readonly calls: TestAgentModelCall[];
readonly active: Set<AbortController>;
}
ModelScriptService (interface)
Effect script state, detached call capture and cancellable native turn decisions.
Signature
export interface ModelScriptService {
readonly turn: (
request: TestAgentModelCall["request"],
signal?: AbortSignal,
) => Effect.Effect<TestModelTurn, unknown>;
readonly script: (turns: readonly TestModelTurn[]) => Effect.Effect<void, unknown>;
readonly reset: Effect.Effect<void>;
readonly calls: Effect.Effect<readonly TestAgentModelCall[]>;
}
RuntimeTestAgentModel (interface)
Native LangChain-compatible scripted model with owned release.
Signature
export interface RuntimeTestAgentModel extends TestAgentModel {
readonly languageModel: BaseChatModel;
}
agents-types.ts
Preserved compatibility entrypoint for the canonical domain type companion.
“./agents.types.js” (namespace export)
Re-exports all named exports from the “./agents.types.js” module.
Signature
export * from "./agents.types.js";
agents-utils.ts
Normalizes scripted native test values and observations for the agent harness without starting a separate execution owner.
assertAgentTrace
Asserts selected native agent trace fields in their observed order.
Signature
declare const assertAgentTrace: (
trace: TestAgentTraceSnapshot,
expected: TestAgentTraceExpectation,
) => void;
captureHooks
Records observed agent edges while forwarding the caller’s native hooks.
Signature
declare const captureHooks: (
hooks: AgentRuntimeHooks | undefined,
edges: AgentObservedEdge[],
) => AgentRuntimeHooks;
createTrace
Creates isolated trace capture and the existing assertion facade.
Signature
declare const createTrace: (
spans: ReturnType<typeof spanSnapshot>[],
edges: AgentObservedEdge[],
) => TestAgentTrace;
agents.ts
Publishes the native agent test harness helpers from the explicit integration while sharing RELKIT testing ownership and clock boundaries.
TestAgent
Signature
declare const TestAgent: TestAgent<Agent>;
TestAgentApproval
Signature
declare const TestAgentApproval: TestAgentApproval;
TestAgentApprovalMode
Signature
declare const TestAgentApprovalMode: TestAgentApprovalMode;
TestAgentApprovals
Signature
declare const TestAgentApprovals: TestAgentApprovals;
TestAgentDescriptor
Signature
declare const TestAgentDescriptor: TestAgentDescriptor;
TestAgentHarness (class)
Agent decisions, approval ownership and scripted invocation share one service.
Signature
declare class TestAgentHarness
TestAgentInvocationOptions
Signature
declare const TestAgentInvocationOptions: TestAgentInvocationOptions;
TestAgentModel
Signature
declare const TestAgentModel: TestAgentModel;
TestAgentModelCall
Signature
declare const TestAgentModelCall: TestAgentModelCall;
TestAgentModelOptions
Signature
declare const TestAgentModelOptions: TestAgentModelOptions;
TestAgentOptions
Signature
declare const TestAgentOptions: TestAgentOptions<Agent>;
TestAgentTrace
Signature
declare const TestAgentTrace: TestAgentTrace;
TestAgentTraceExpectation
Signature
declare const TestAgentTraceExpectation: TestAgentTraceExpectation;
TestAgentTraceSnapshot
Signature
declare const TestAgentTraceSnapshot: TestAgentTraceSnapshot;
TestModelTurn
Signature
declare const TestModelTurn: TestModelTurn;
assertAgentTrace
Signature
declare const assertAgentTrace: (
trace: TestAgentTraceSnapshot,
expected: TestAgentTraceExpectation,
) => void;
createTestAgent
Creates isolated agent state with native model cancellation and owned approvals.
Signature
declare const createTestAgent: <Agent extends TestAgentDescriptor>(
options: TestAgentOptions<Agent>,
) => TestAgent<Agent>;
createTestModel
Signature
declare const createTestModel: (
options?: TestAgentModelOptions & { readonly script?: readonly TestModelTurn[] },
) => RuntimeTestAgentModel;
testAgentLayer
Acquires the network-free harness behind the public synchronous factory.
Signature
declare const testAgentLayer: <Agent extends TestAgentDescriptor>(
options: TestAgentOptions<Agent>,
) => Layer.Layer<TestAgentHarness, never, never>;
agents.types.ts
Publishes the native agent test harness helpers from the explicit integration while sharing RELKIT testing ownership and clock boundaries. This companion preserves the native input and output types without starting runtime work.
TestAgent (interface)
Owned native agent facade preserving schema inference, approvals and trace evidence.
Signature
export interface TestAgent<Agent extends TestAgentDescriptor = TestAgentDescriptor> {
readonly model: TestAgentModel;
readonly failures: TestFailureControls;
readonly approvals: TestAgentApprovals;
readonly pending: () => readonly PendingApproval[];
readonly trace: TestAgentTrace;
readonly script: (turns: readonly TestModelTurn[]) => void;
readonly invoke: (
input: InferInput<Agent["input"]>,
options?: TestAgentInvocationOptions,
) => Promise<InferOutput<Agent["output"]>>;
readonly reset: () => void;
readonly close: () => Promise<void>;
}
TestAgentApproval (type alias)
Fixed, pending or caller-native approval decision authority.
Signature
type TestAgentApproval = TestAgentApprovalMode | AgentApprovalHandler;
TestAgentApprovalMode (type alias)
Fixed or pending native approval policy vocabulary.
Signature
type TestAgentApprovalMode = "approved" | "denied" | "pending";
TestAgentApprovals (interface)
Synchronous selection controls over owned pending native decisions.
Signature
export interface TestAgentApprovals {
readonly pending: () => readonly PendingApproval[];
readonly approve: (toolCallId?: string) => void;
readonly deny: (toolCallId?: string) => void;
}
TestAgentDescriptor (type alias)
Native agent descriptor vocabulary retained by public test inference.
Signature
type TestAgentDescriptor = AgentDescriptor<string, unknown, unknown>;
TestAgentInvocationOptions (type alias)
Invocation-only native overrides excluding owned model and engine dependencies.
Signature
type TestAgentInvocationOptions = Omit<AgentInvocationOptions, "input" | "approval" | "hooks">;
TestAgentModel (interface)
Public model facade owning script mutation, capture and release.
Signature
export interface TestAgentModel {
readonly provider: string;
readonly modelId: string;
readonly calls: readonly TestAgentModelCall[];
readonly script: (turns: readonly TestModelTurn[]) => void;
readonly reset: () => void;
readonly close: () => Promise<void>;
}
TestAgentModelCall (interface)
Detached native request and scripted turn evidence captured in order.
Signature
export interface TestAgentModelCall {
readonly index: number;
readonly request: {
readonly messages: readonly unknown[];
readonly tools: readonly unknown[];
};
readonly turn: TestModelTurn;
}
TestAgentModelOptions (interface)
Network-free model identity, hanging behavior and explicit logging policy.
Signature
export interface TestAgentModelOptions {
readonly logger?: NonNullable<
Parameters<typeof import("@relkit/testing/internal/testing-owner").testingLoggerLayer>[0]
>;
readonly provider?: string;
readonly modelId?: string;
readonly hang?: boolean;
}
TestAgentOptions (interface)
Native agent, tool engine, model script and capture dependencies.
Signature
export interface TestAgentOptions<Agent extends TestAgentDescriptor = TestAgentDescriptor> {
readonly logger?: NonNullable<
Parameters<typeof import("@relkit/testing/internal/testing-owner").testingLoggerLayer>[0]
>;
readonly agent: Agent;
readonly tools: AgentRuntimeOptions["tools"];
readonly engine: AgentRuntimeOptions["engine"];
readonly script?: readonly TestModelTurn[];
readonly model?: TestAgentModelOptions;
readonly maxInputBytes?: number;
readonly maxOutputBytes?: number;
readonly approval?: TestAgentApproval;
readonly failures?: TestFailureControls;
readonly hooks?: AgentRuntimeHooks;
readonly capture?: AgentCapturePolicy;
}
TestAgentTrace (interface)
Owned trace evidence with explicit read, clear and assertion operations.
Signature
export interface TestAgentTrace extends TestAgentTraceSnapshot {
readonly read: () => TestAgentTraceSnapshot;
readonly clear: () => void;
readonly assert: (expected: TestAgentTraceExpectation) => void;
}
TestAgentTraceExpectation (interface)
Selected span, outcome and tool-edge evidence checked by trace assertions.
Signature
export interface TestAgentTraceExpectation {
readonly spanKinds?: readonly ReturnType<typeof spanSnapshot>["kind"][];
readonly names?: readonly string[];
readonly edges?: readonly AgentObservedEdge[];
}
TestAgentTraceSnapshot (interface)
Detached observed span and edge evidence for a test invocation.
Signature
export interface TestAgentTraceSnapshot {
readonly spans: readonly ReturnType<typeof spanSnapshot>[];
readonly edges: readonly AgentObservedEdge[];
}
TestModelTurn (type alias)
Scripted native model outcome supporting final values, tool calls and failures.
Signature
type TestModelTurn =
| {
readonly type: "tool-call";
readonly callId: string;
readonly toolId: string;
readonly input: JsonValue;
}
| { readonly type: "final"; readonly output: JsonValue }
| { readonly type: "error"; readonly code: string; readonly message: string }
| { readonly type: "cancelled"; readonly reason?: string };