Skip to content
RELKIT
Esc
↑↓navigate↵open⌘Jpreview
On this page

Functions API

Generated public TypeScript reference for @relkit/functions.

Common APIs

For configuration and examples, read Functions, Declared errors, migration.

For a complete workflow, follow upload product images, connect react, cache product prices, react to order events, register users in a transaction.

Frontend usage

Call a public service operation shows the client side of this capability.

Public imports

  • @relkit/functions — 119 exports

All exported APIs

Names link to their complete contracts. Re-exports share their original contract; legacy exports keep their separate identity. Examples link to the API’s inline sample, a maintained repository usage, or the shared module walkthrough.

API Kind Import from Example
AgentClientFor Type @relkit/functions API example
AgentClients Type @relkit/functions API example
AgentRef Type @relkit/functions API example
AgentRefAny Type @relkit/functions API example
AuthContext Type @relkit/functions API example
BucketClient Type @relkit/functions API example
BucketClientFor Type @relkit/functions API example
BucketClients Type @relkit/functions API example
BucketObjectMetadata Type @relkit/functions API example
BucketRef Type @relkit/functions API example
BucketRefAny Type @relkit/functions API example
CacheClient Type @relkit/functions API example
CacheClientFor Type @relkit/functions API example
CacheClients Type @relkit/functions API example
CacheOperationOptions Type @relkit/functions API example
CacheRef Type @relkit/functions API example
CacheRefAny Type @relkit/functions API example
copyFunctionToolHooks Value @relkit/functions API example
copyFunctionToolHooksEffect Value @relkit/functions API example
createFunctionGraphNode Value @relkit/functions API example
createFunctionGraphNodeEffect Value @relkit/functions API example
createFunctionToolInvoker Value @relkit/functions API example
createFunctionToolInvokerEffect Value @relkit/functions API example
DeclaredError Value @relkit/functions API example
DeclaredErrorOf Type @relkit/functions API example
DeclaredErrorsOf Type @relkit/functions API example
defineError Value @relkit/functions API example
defineErrorEffect Value @relkit/functions API example
DefineErrorOptions Type @relkit/functions API example
defineFunction Value @relkit/functions API example
defineFunctionEffect Value @relkit/functions API example
DefineFunctionOptions Type @relkit/functions API example
DescriptorRef Type @relkit/functions API example
ErrorDescriptor Type @relkit/functions API example
ErrorDescriptorAny Type @relkit/functions Module example
ErrorHttpMapping Type @relkit/functions API example
ErrorRef Type @relkit/functions API example
ErrorRetry Type @relkit/functions API example
ErrorRetryInput Type @relkit/functions API example
EventAttributeValue Type @relkit/functions API example
EventClientFor Type @relkit/functions API example
EventClients Type @relkit/functions API example
EventPublishOptions Type @relkit/functions API example
EventPublishResult Type @relkit/functions API example
EventRef Type @relkit/functions API example
EventRefAny Type @relkit/functions API example
fail Value @relkit/functions API example
failEffect Value @relkit/functions API example
FunctionAsGraphNode Type @relkit/functions API example
functionAttempt Value @relkit/functions API example
FunctionContext Type @relkit/functions API example
FunctionDependencies Type @relkit/functions API example
FunctionDescriptor Type @relkit/functions API example
FunctionEffectValue Type @relkit/functions API example
FunctionFailure Type @relkit/functions API example
FunctionGraphNodeDescriptor Type @relkit/functions API example
FunctionGraphNodeOptions Type @relkit/functions API example
FunctionHandlerResult Type @relkit/functions API example
FunctionHandlerValidation Type @relkit/functions API example
FunctionOperation Type @relkit/functions API example
FunctionOperationError Value @relkit/functions API example
FunctionRef Type @relkit/functions API example
FunctionRefAny Type @relkit/functions API example
FunctionTelemetry Value @relkit/functions API example
FunctionTelemetryLive Value @relkit/functions API example
FunctionTelemetryService Type @relkit/functions API example
FunctionToolApproval Type @relkit/functions API example
FunctionToolApprovalDecision Type @relkit/functions API example
FunctionToolApprovalDeniedError Value @relkit/functions API example
FunctionToolApprovalDeniedFailure Value @relkit/functions API example
FunctionToolApprovalRequest Type @relkit/functions API example
FunctionToolApprovalRequiredError Value @relkit/functions API example
FunctionToolApprovalRequiredFailure Value @relkit/functions API example
FunctionToolApprovalResolver Type @relkit/functions API example
FunctionToolArgumentFailure Value @relkit/functions API example
FunctionToolArgumentValidationError Value @relkit/functions API example
FunctionToolCancelledFailure Value @relkit/functions API example
FunctionToolContext Type @relkit/functions API example
FunctionToolDescriptor Type @relkit/functions API example
FunctionToolHook Type @relkit/functions API example
FunctionToolInvokeOptions Type @relkit/functions API example
FunctionToolMetadata Type @relkit/functions API example
FunctionToolOperationCancelledError Value @relkit/functions API example
FunctionToolOptions Type @relkit/functions API example
FunctionToolSideEffect Type @relkit/functions API example
FunctionToolTarget Type @relkit/functions API example
functionTry Value @relkit/functions API example
InvocationMetadata Type @relkit/functions API example
InvocationSource Type @relkit/functions API example
invokeFunctionGraphNodeEffect Value @relkit/functions API example
invokeFunctionToolEffect Value @relkit/functions API example
isErrorDescriptor Value @relkit/functions API example
isErrorDescriptorEffect Value @relkit/functions API example
isFunctionGraphNode Value @relkit/functions API example
isFunctionGraphNodeEffect Value @relkit/functions API example
isStreamOutputSchema Value @relkit/functions API example
isStreamOutputSchemaEffect Value @relkit/functions API example
JobClientFor Type @relkit/functions API example
JobClients Type @relkit/functions API example
JobEnqueueOptions Type @relkit/functions API example
JobEnqueueResult Type @relkit/functions API example
JobRef Type @relkit/functions Module example
JobRefAny Type @relkit/functions Module example
JobState Type @relkit/functions API example
JobStatus Type @relkit/functions API example
NormalizedErrorRetry Type @relkit/functions API example
observeFunction Value @relkit/functions API example
PublicClock Type @relkit/functions API example
PublicLogger Type @relkit/functions API example
RELKIT_FUNCTION_GRAPH_NODE Value @relkit/functions API example
ResolvedApplicationEnv Type @relkit/functions API example
runFunctionPromise Value @relkit/functions API example
runFunctionSync Value @relkit/functions API example
streamOf Value @relkit/functions API example
streamOfEffect Value @relkit/functions API example
StreamOutputSchema Type @relkit/functions API example
TaskClientFor Type @relkit/functions API example
TaskClients Type @relkit/functions API example
TaskTriggerOptions Type @relkit/functions API example

client-maps.types.ts

AgentClientFor (type alias)

Typed callable client for an agent descriptor.

Example

const invoke: AgentClientFor<typeof agent> = async (input) => output;

Signature

type AgentClientFor<T> = (input: InputOf<T>) => Promise<OutputOf<T>>;

Source

AgentClients (type alias)

Named agent clients projected from dependencies.

Example

const agents: AgentClients<typeof dependencies.agents> = context.agents;

Signature

type AgentClients<M> = {
  readonly [Name in keyof NonNullable<M> & string]: AgentClientFor<NonNullable<M>[Name]>;
};

Source

BucketClientFor (type alias)

Bucket client exposed for a declared bucket.

Example

const client: BucketClientFor<typeof bucket> = buckets.uploads;

Signature

type BucketClientFor<T> = BucketClient;

Source

BucketClients (type alias)

Named bucket clients projected from dependencies.

Example

const buckets: BucketClients<typeof dependencies.buckets> = context.buckets;

Signature

type BucketClients<M> = {
  readonly [Name in keyof NonNullable<M> & string]: BucketClientFor<NonNullable<M>[Name]>;
};

Source

CacheClientFor (type alias)

Key and value typed cache client.

Example

const client: CacheClientFor<typeof cache> = caches.sessions;

Signature

type CacheClientFor<T> = CacheClient<KeyOf<T>, ValueOf<T>>;

Source

CacheClients (type alias)

Named cache clients projected from dependencies.

Example

const cache: CacheClients<typeof dependencies.cache> = context.cache;

Signature

type CacheClients<M> = {
  readonly [Name in keyof NonNullable<M> & string]: CacheClientFor<NonNullable<M>[Name]>;
};

Source

EventClientFor (type alias)

Typed publish client for an event descriptor.

Example

const client: EventClientFor<typeof event> = events.created;

Signature

type EventClientFor<T> = {
  /** Publishes an event.
   * @param payload - Event payload.
   * @param options - Optional key and attributes.
   * @returns Accepted event envelope.
   * @example await events.created.publish(payload);
   */
  publish(
    payload: EventInputOf<T>,
    options?: EventPublishOptions,
  ): Promise<EventPublishResult<EventIdOf<T>, EventVersionOf<T>, EventOutputOf<T>>>;
};

Source

EventClients (type alias)

Named event clients projected from published events.

Example

const events: EventClients<typeof published> = context.events;

Signature

type EventClients<M> = {
  readonly [Name in keyof NonNullable<M> & string]: EventClientFor<NonNullable<M>[Name]>;
};

Source

JobClientFor (type alias)

Typed enqueue client for a job descriptor.

Example

const client: JobClientFor<typeof job> = jobs.myJob;

Signature

type JobClientFor<T> = {
  /** Enqueues a job invocation.
   * @param input - Job input.
   * @param options - Optional correlation metadata.
   * @returns Acceptance receipt.
   * @example await jobs.send.enqueue(input);
   */
  enqueue(input: InputOf<T>, options?: JobEnqueueOptions): Promise<JobEnqueueResult>;
};

Source

JobClients (type alias)

Named job clients projected from dependencies.

Example

const jobs: JobClients<typeof dependencies.jobs> = context.jobs;

Signature

type JobClients<M> = {
  readonly [Name in keyof NonNullable<M> & string]: JobClientFor<NonNullable<M>[Name]>;
};

Source

TaskClientFor (type alias)

Typed trigger client for a task descriptor.

Example

const client: TaskClientFor<typeof task> = tasks.send;

Signature

type TaskClientFor<T> = {
  /** Triggers a task run.
   * @param input - Task input.
   * @param options - Optional scheduling and idempotency controls.
   * @returns Handle for the new run.
   * @example await tasks.send.trigger(input);
   */
  trigger(input: InputOf<T>, options?: TaskTriggerOptions): Promise<RunHandle>;
};

Source

TaskClients (type alias)

Named task clients projected from dependencies.

Example

const tasks: TaskClients<typeof dependencies.tasks> = context.tasks;

Signature

type TaskClients<M> = {
  readonly [Name in keyof NonNullable<M> & string]: TaskClientFor<NonNullable<M>[Name]>;
};

Source

TaskTriggerOptions (interface)

Scheduling and idempotency options for a task.

Example

await tasks.send.trigger(input, { operationId: "send-1" });

Signature

export interface TaskTriggerOptions {
  readonly operationId?: string;
  readonly idempotencyKey?: string;
  readonly delay?: string;
  readonly at?: string;
  readonly tags?: readonly string[];
  readonly correlationId?: string;
}

Source

clients.types.ts

“./client-maps.types.js” (namespace export)

Re-exports all named exports from the “./client-maps.types.js” module.

Signature

export * from "./client-maps.types.js";

Source

BucketClient

Signature

declare const BucketClient: BucketClient;

Source

BucketObjectMetadata

Signature

declare const BucketObjectMetadata: BucketObjectMetadata;

Source

BucketPutOptions

Signature

declare const BucketPutOptions: BucketPutOptions;

Source

CacheClient

Signature

declare const CacheClient: CacheClient<Key, Value>;

Source

CacheOperationOptions

Signature

declare const CacheOperationOptions: CacheOperationOptions;

Source

EventAttributeValue (type alias)

Scalar value accepted in event attributes.

Example

const value: EventAttributeValue = true;

Signature

type EventAttributeValue = string | number | boolean;

Source

EventPublishOptions (interface)

Metadata supplied with an event publication.

Example

await events.publish(payload, { key: "order-1" });

Signature

export interface EventPublishOptions {
  readonly key?: string;
  readonly attributes?: Readonly<Record<string, EventAttributeValue>>;
}

Source

EventPublishResult (interface)

Accepted event envelope returned by publication.

Example

const published: EventPublishResult = await events.publish(payload);

Signature

export interface EventPublishResult<
  Id extends string = string,
  Version extends number = number,
  Payload = unknown,
> extends EventEnvelope<Id, Version, Payload> {
  readonly accepted: true;
}

Source

JobEnqueueOptions (interface)

Options for enqueuing a job.

Example

await jobs.enqueue(input, { correlationId: "trace-1" });

Signature

export interface JobEnqueueOptions {
  readonly correlationId?: string;
}

Source

JobEnqueueResult (interface)

Receipt returned when a job is accepted.

Example

const receipt: JobEnqueueResult = await jobs.enqueue(input);

Signature

export interface JobEnqueueResult {
  readonly instanceId: string;
  readonly accepted: true;
  readonly duplicate?: boolean;
  readonly idempotencyKey?: string;
  readonly idempotencyExpiresAt?: number;
  readonly status: Extract<JobState, "accepted">;
  readonly profile: string;
  readonly correlationId?: string;
}

Source

JobState (type alias)

Lifecycle state of a queued job.

Example

const state: JobState = "accepted";

Signature

type JobState = "accepted" | "available" | "leased" | "delayed" | "completed" | "dead-lettered";

Source

JobStatus (interface)

Snapshot of one queued job.

Example

const status: JobStatus = await jobs.status(id);

Signature

export interface JobStatus {
  readonly instanceId: string;
  readonly state: JobState;
  readonly profile: string;
  readonly attempt: number;
  readonly correlationId?: string;
}

Source

define-error-validation.ts

assertErrorSchema

Asserts a declared error data schema.

Throws

TypeError for a nonstandard schema.

Example

assertErrorSchema(z.string());

Signature

declare const assertErrorSchema: (value: unknown) => asserts value is StandardSchemaV1;

Source

assertErrorSchemaEffect

Validates a Standard Schema through Effect.

Example

Effect.runSync(assertErrorSchemaEffect(z.string()));

Signature

declare const assertErrorSchemaEffect: (
  value: unknown,
) => Effect.Effect<StandardSchemaV1<unknown, unknown>, FunctionOperationError, never>;

Source

isErrorDescriptor

Recognizes a declared error descriptor.

Example

if (isErrorDescriptor(value)) console.log(value.id);

Signature

declare const isErrorDescriptor: (value: unknown) => value is ErrorDescriptorAny;

Source

isErrorDescriptorEffect

Checks a declared error descriptor through Effect.

Example

Effect.runSync(isErrorDescriptorEffect(value));

Signature

declare const isErrorDescriptorEffect: (
  value: unknown,
) => Effect.Effect<boolean, FunctionOperationError, never>;

Source

isRecord

Recognizes a nonarray record-like value.

Example

isRecord({ id: "one" });

Signature

declare const isRecord: (value: unknown) => value is Record<PropertyKey, unknown>;

Source

isRecordEffect

Checks a record-like value through Effect.

Example

Effect.runSync(isRecordEffect({}));

Signature

declare const isRecordEffect: (
  value: unknown,
) => Effect.Effect<boolean, FunctionOperationError, never>;

Source

validateErrorHttp

Validates a declared error HTTP mapping.

Throws

TypeError for an invalid status.

Example

validateErrorHttp({ status: 404 });

Signature

declare const validateErrorHttp: (http: ErrorHttpMapping | undefined) => void;

Source

validateErrorHttpEffect

Validates an HTTP status mapping through Effect.

Example

Effect.runSync(validateErrorHttpEffect({ status: 404 }));

Signature

declare const validateErrorHttpEffect: (
  http: ErrorHttpMapping | undefined,
) => Effect.Effect<void, FunctionOperationError, never>;

Source

define-error.ts

defineError

Defines a typed application error.

Throws

TypeError for invalid schema, retry, HTTP status, or message.

Example

import { defineError } from "@relkit/functions";
import { z } from "@relkit/schema";
const NotFound = defineError({
  id: "orders.not-found",
  data: z.object({ id: z.string() }),
  message: "Missing",
});
const error = new NotFound({ id: "order-1" });

Signature

declare const defineError: <const Id extends string, const DataSchema extends StandardSchemaV1>(
  options: DefineErrorOptions<Id, DataSchema>,
) => ErrorDescriptor<Id, InferOutput<DataSchema>, DataSchema>;

Source

Since v0.1.0

defineErrorEffect

Defines a typed application error with safe data, transport metadata, and an optional retry hint. The compiler derives omitted IDs. Omitted retry means never; later only hints to durable work.

Example

const NotFound = Effect.runSync(
  defineErrorEffect({
    id: "orders.not-found",
    data: z.object({ orderId: z.string() }),
    message: ({ orderId }) => `Order ${orderId} was not found`,
  }),
);
new NotFound({ orderId: "order-1" });

Signature

declare const defineErrorEffect: <
  const Id extends string,
  const DataSchema extends StandardSchemaV1,
>(
  options: DefineErrorOptions<Id, DataSchema>,
) => Effect.Effect<
  ErrorDescriptor<Id, InferOutput<DataSchema>, DataSchema>,
  FunctionOperationError,
  never
>;

Source

Since v0.1.0

DeclaredError (class)

Validated application error instance.

Example

const error = new NotFound({ id: "one" });

Signature

declare class DeclaredError<Id, Data> {
  constructor(
    id: Id,
    ref: ErrorRef<Id>,
    data: Data,
    message: string,
    retry: ErrorRetry,
    afterMs: number | undefined,
    http: ErrorHttpMapping | undefined,
  );
}

Source

id (property)

Signature

readonly id: Id

Source

ref (property)

Signature

readonly ref: ErrorRef<Id>

Source

data (property)

Signature

readonly data: Data

Source

retry (property)

Signature

readonly retry: ErrorRetry

Source

afterMs (property)

Signature

readonly afterMs: number | undefined

Source

http (property)

Signature

readonly http: ErrorHttpMapping | undefined

Source

DefineErrorOptions

Signature

declare const DefineErrorOptions: DefineErrorOptions<Id, DataSchema>;

Source

ErrorDescriptor

Signature

declare const ErrorDescriptor: ErrorDescriptor<Id, Data, DataSchema>;

Source

ErrorDescriptorAny

Signature

declare const ErrorDescriptorAny: ErrorDescriptorAny;

Source

ErrorHttpMapping

Signature

declare const ErrorHttpMapping: ErrorHttpMapping;

Source

ErrorRef

Signature

declare const ErrorRef: ErrorRef<Id>;

Source

ErrorRetry

Signature

declare const ErrorRetry: ErrorRetry;

Source

ErrorRetryInput

Signature

declare const ErrorRetryInput: ErrorRetryInput;

Source

NormalizedErrorRetry

Signature

declare const NormalizedErrorRetry: NormalizedErrorRetry;

Source

isErrorDescriptor

Signature

declare const isErrorDescriptor: (value: unknown) => value is ErrorDescriptorAny;

Source

isErrorDescriptorEffect

Signature

declare const isErrorDescriptorEffect: (
  value: unknown,
) => Effect.Effect<boolean, FunctionOperationError, never>;

Source

define-error.types.ts

DefineErrorOptions (interface)

Options for constructing a declared error descriptor.

Example

defineError({ id: "orders.not-found", data: z.object({ id: z.string() }), message: "Missing" });

Signature

export interface DefineErrorOptions<
  Id extends string,
  DataSchema extends StandardSchemaV1,
> extends DescriptorMetadata {
  readonly id?: Id;
  readonly data: DataSchema;
  readonly message: string | ((data: InferOutput<DataSchema>) => string);
  readonly http?: ErrorHttpMapping;
  readonly retry?: ErrorRetryInput;
}

Source

ErrorDescriptor (interface)

Callable descriptor for creating a declared error.

Example

const error = new NotFound({ id: "one" });

Signature

export interface ErrorDescriptor<
  Id extends string,
  Data,
  DataSchema extends StandardSchemaV1 = StandardSchemaV1,
> extends DescriptorMetadata {
  readonly kind: "error";
  readonly id: Id;
  readonly ref: ErrorRef<Id>;
  readonly data: DataSchema;
  readonly message: string | ((data: Data) => string);
  readonly http?: ErrorHttpMapping;
  readonly retry: ErrorRetry;
  readonly afterMs?: number;
  readonly create: (input: InferInput<DataSchema>) => DeclaredError<Id, Data>;
  new (input: InferInput<DataSchema>): DeclaredError<Id, Data>;
}

Source

ErrorDescriptorAny (type alias)

Any declared error descriptor for heterogeneous collections.

Signature

type ErrorDescriptorAny = ErrorDescriptor<string, any, StandardSchemaV1<any, any>>;

Source

ErrorHttpMapping (interface)

HTTP mapping for a declared error.

Example

const http: ErrorHttpMapping = { status: 404 };

Signature

export interface ErrorHttpMapping {
  readonly status: number;
}

Source

ErrorRef (interface)

Stable reference to an application error.

Example

const ref: ErrorRef = { kind: "error", id: "orders.not-found" };

Signature

export interface ErrorRef<Id extends string = string> {
  readonly kind: "error";
  readonly id: Id;
}

Source

define-function-inference.types.ts

define-function-validation.ts

assertHook

Checks an optional function lifecycle hook.

Throws

TypeError when the hook is not callable.

Example

assertHook(() => {}, "onBefore");

Signature

declare const assertHook: (value: unknown, name: string) => void;

Source

assertHookEffect

Checks an optional hook through Effect.

Example

Effect.runSync(assertHookEffect(() => {}, "onBefore"));

Signature

declare const assertHookEffect: (
  value: unknown,
  name: string,
) => Effect.Effect<void, FunctionOperationError, never>;

Source

assertSchema

Asserts a Standard Schema validator.

Throws

TypeError for malformed schemas.

Example

assertSchema(z.string(), "input");

Signature

declare const assertSchema: (value: unknown, name: string) => asserts value is StandardSchemaV1;

Source

assertSchemaEffect

Checks a function schema through Effect.

Example

Effect.runSync(assertSchemaEffect(z.string(), "input"));

Signature

declare const assertSchemaEffect: (
  value: unknown,
  name: string,
) => Effect.Effect<StandardSchemaV1<unknown, unknown>, FunctionOperationError, never>;

Source

copyDependencies

Signature

declare const copyDependencies: <D extends FunctionDependencies>(
  dependencies: D | undefined,
) => D | undefined;

Source

copyDependenciesEffect

Signature

declare const copyDependenciesEffect: <D extends FunctionDependencies>(
  dependencies: D | undefined,
) => Effect.Effect<D | undefined, FunctionOperationError, never>;

Source

copyPublishes

Signature

declare const copyPublishes: <Names extends readonly string[]>(
  publishes: Names | undefined,
) => Names | undefined;

Source

copyPublishesEffect

Signature

declare const copyPublishesEffect: <Names extends readonly string[]>(
  publishes: Names | undefined,
) => Effect.Effect<Names | undefined, FunctionOperationError, never>;

Source

functionTargetForReceiver

Resolves a method receiver to a callable function descriptor.

Throws

TypeError when receiver is event-only.

Example

functionTargetForReceiver(fn, fn);

Signature

declare const functionTargetForReceiver: (
  receiver: unknown,
  fallback: FunctionRefAny,
) => FunctionRefAny;

Source

functionTargetForReceiverEffect

Resolves a callable receiver through Effect.

Example

Effect.runSync(functionTargetForReceiverEffect(fn, fn));

Signature

declare const functionTargetForReceiverEffect: (
  receiver: unknown,
  fallback: FunctionRefAny,
) => Effect.Effect<FunctionRefAny, FunctionOperationError, never>;

Source

validateLimit

Checks a positive integer function limit.

Throws

TypeError for an invalid limit.

Example

validateLimit(5, "timeoutMs");

Signature

declare const validateLimit: (value: number | undefined, name: string) => void;

Source

validateLimitEffect

Checks a function limit through Effect.

Example

Effect.runSync(validateLimitEffect(5, "timeoutMs"));

Signature

declare const validateLimitEffect: (
  value: number | undefined,
  name: string,
) => Effect.Effect<void, FunctionOperationError, never>;

Source

define-function.ts

defineFunction

Defines the graph-visible executable unit shared by HTTP, background, tool, and agent calls.

The id is optional for source-scoped functions; the compiler derives it from the source/export hierarchy. Durable resources keep explicit IDs. The handler receives validated reusable input and an invocation-scoped context. Use descriptor.invoke(input) for nested calls so the common engine preserves validation, service policy, limits, and telemetry.

Throws

TypeError for invalid definition inputs.

Example

import { defineFunction } from "@relkit/app/functions";
import { z } from "@relkit/app/schema";

const greet = defineFunction({
  input: z.object({ name: z.string() }),
  output: z.object({ message: z.string() }),
  handler: async ({ name }, context) => {
    context.log.info("greeting requested");
    return { message: `Hello, ${name}!` };
  },
});
const result = await greet.invoke({ name: "Ada" });
void result;
void greet;

Signature

declare const defineFunction: DefineFunction;

Source

Since v0.1.0

Backend and frontend example

Backend — these maintained files define the operation used by the frontend below.

/** Validates order input, invokes the service-local pricing function, and returns the calculated order. */
import { defineFunction } from "@relkit/app/functions";
import { z } from "@relkit/app/schema";
import priceOrder from "@app/services/orders/functions/price-order.function.js";

const orderInput = z.object({
  orderId: z.string().min(1),
  sku: z.string().min(1),
  quantity: z.number().int().positive(),
});

const orderOutput = z.object({
  orderId: z.string(),
  sku: z.string(),
  totalCents: z.number().int().nonnegative(),
});

const createOrder = defineFunction({
  input: orderInput,
  output: orderOutput,

  handler: async (input) => {
    const { totalCents } = await priceOrder.invoke({ quantity: input.quantity });
    const order = {
      orderId: input.orderId,
      sku: input.sku,
      totalCents,
    };

    return order;
  },
});

export default createOrder;
/** Maps the HTTP endpoint to its owning service's public member. */
import { defineServiceRoutes } from "@relkit/app/routes";
import orders from "@app/services/orders/service.js";

export const { POST } = defineServiceRoutes(orders, {
  POST: { member: "createOrder", successStatus: 201 },
});

Frontend

After frontend setup and pulling this API example’s contract, render this component under RelkitClientProvider:

"use client";

/** Calls the API example's Orders function through its public route, retaining the generated input and price result. */
import { useRelkitClient, useRouteMutation } from "@relkit/client/react";

/** Creates one order in the API example without importing the backend service.
 * @returns A guarded submission action and its typed price or failure. */
export function CreateOrder() {
  const { status } = useRelkitClient();
  const create = useRouteMutation("POST /orders");

  return (
    <section>
      <button
        disabled={status !== "ready" || !create.isIdle}
        onClick={() => create.mutate({ orderId: crypto.randomUUID(), sku: "book", quantity: 2 })}
      >
        Create an order
      </button>
      {create.isPending && <p role="status">Creating…</p>}
      {create.isSuccess && <p>Total: {create.data.totalCents} cents</p>}
      {create.isError && (
        <p role="alert">{create.error.message}. Check the outcome before retrying.</p>
      )}
    </section>
  );
}

This calls the same createOrder function through POST /orders: orderId, sku, and quantity come from its input schema, and totalCents comes from its output schema. The browser calls RPC; it never imports the descriptor or calls .invoke(). Service membership needs a client-exposed route to become a browser operation.

Reference: useRouteMutation. Continue with mutation state and recovery.

AgentClientFor

Signature

declare const AgentClientFor: AgentClientFor<T>;

Source

AgentClients

Signature

declare const AgentClients: AgentClients<M>;

Source

AgentRef

Signature

declare const AgentRef: AgentRef<Id, InputSchema, OutputSchema>;

Source

AgentRefAny

Signature

declare const AgentRefAny: AgentRefAny;

Source

AuthContext

Signature

declare const AuthContext: AuthContext<Session>;

Source

BucketClient

Signature

declare const BucketClient: BucketClient;

Source

BucketClientFor

Signature

declare const BucketClientFor: BucketClient;

Source

BucketClients

Signature

declare const BucketClients: BucketClients<M>;

Source

BucketObjectMetadata

Signature

declare const BucketObjectMetadata: BucketObjectMetadata;

Source

BucketRef

Signature

declare const BucketRef: BucketRef<Id>;

Source

BucketRefAny

Signature

declare const BucketRefAny: BucketRefAny;

Source

CacheClient

Signature

declare const CacheClient: CacheClient<Key, Value>;

Source

CacheClientFor

Signature

declare const CacheClientFor: CacheClientFor<T>;

Source

CacheClients

Signature

declare const CacheClients: CacheClients<M>;

Source

CacheOperationOptions

Signature

declare const CacheOperationOptions: CacheOperationOptions;

Source

CacheRef

Signature

declare const CacheRef: CacheRef<Id, KeySchema, ValueSchema>;

Source

CacheRefAny

Signature

declare const CacheRefAny: CacheRefAny;

Source

DefineFunctionOptions

Signature

declare const DefineFunctionOptions: DefineFunctionOptions<
  Id,
  InputSchema,
  OutputSchema,
  Dependencies,
  Errors,
  Publishes,
  ProgressSchema
>;

Source

DescriptorRef

Signature

declare const DescriptorRef: DescriptorRef<Kind, Id>;

Source

EventAttributeValue

Signature

declare const EventAttributeValue: EventAttributeValue;

Source

EventClientFor

Signature

declare const EventClientFor: EventClientFor<T>;

Source

EventClients

Signature

declare const EventClients: EventClients<M>;

Source

EventPublishOptions

Signature

declare const EventPublishOptions: EventPublishOptions;

Source

EventPublishResult

Signature

declare const EventPublishResult: EventPublishResult<Id, Version, Payload>;

Source

EventRef

Signature

declare const EventRef: EventRef<Id, InputSchema>;

Source

EventRefAny

Signature

declare const EventRefAny: EventRefAny;

Source

FunctionContext

Signature

declare const FunctionContext: FunctionContext<D, Publishes, Progress>;

Source

FunctionDependencies

Signature

declare const FunctionDependencies: FunctionDependencies;

Source

FunctionDescriptor

Signature

declare const FunctionDescriptor: FunctionDescriptor<
  Id,
  Input,
  Output,
  Dependencies,
  Errors,
  InputSchema,
  OutputSchema,
  ToolMetadata,
  Publishes,
  ProgressSchema
>;

Source

FunctionRef

Signature

declare const FunctionRef: FunctionRef<Id, Input, Output, Errors, InputSchema, OutputSchema>;

Source

FunctionRefAny

Signature

declare const FunctionRefAny: FunctionRefAny;

Source

InvocationMetadata

Signature

declare const InvocationMetadata: InvocationMetadata;

Source

InvocationSource

Signature

declare const InvocationSource: InvocationSource;

Source

JobClientFor

Signature

declare const JobClientFor: JobClientFor<T>;

Source

JobClients

Signature

declare const JobClients: JobClients<M>;

Source

JobEnqueueOptions

Signature

declare const JobEnqueueOptions: JobEnqueueOptions;

Source

JobEnqueueResult

Signature

declare const JobEnqueueResult: JobEnqueueResult;

Source

JobRef

Signature

declare const JobRef: JobRef<Id, InputSchema, OutputSchema, Task>;

Source

JobRefAny

Signature

declare const JobRefAny: JobRefAny;

Source

JobState

Signature

declare const JobState: JobState;

Source

JobStatus

Signature

declare const JobStatus: JobStatus;

Source

PublicClock

Signature

declare const PublicClock: PublicClock;

Source

PublicLogger

Signature

declare const PublicLogger: PublicLogger;

Source

ResolvedApplicationEnv

Signature

declare const ResolvedApplicationEnv: Readonly<Record<string, unknown>>;

Source

TaskClientFor

Signature

declare const TaskClientFor: TaskClientFor<T>;

Source

TaskClients

Signature

declare const TaskClients: TaskClients<M>;

Source

TaskTriggerOptions

Signature

declare const TaskTriggerOptions: TaskTriggerOptions;

Source

defineFunctionEffect

Defines a callable function through Effect.

Example

Effect.runSync(defineFunctionEffect({ input, output, handler }));

Signature

declare const defineFunctionEffect: DefineFunctionEffect;

Source

define-function.types.ts

DefineFunction (interface)

Overloaded public function constructor preserving schema inference.

Example

const greet = defineFunction({ input, output, handler });

Signature

export interface DefineFunction {
  /** Defines a function without declared dependencies.
   * @param options - Schemas, handler, and function metadata.
   * @returns A callable descriptor with inferred input and output types.
   * @example const greet = defineFunction({ input, output, handler });
   */
  <
    const Id extends string,
    const InputSchema extends StandardSchemaV1,
    const OutputSchema extends StandardSchemaV1,
    const ProgressSchema extends StandardSchemaV1 | undefined = undefined,
    const Publishes extends readonly Extract<keyof Relkit.EventRegistry, string>[] = readonly [],
    const Options extends FunctionCallOptions<
      Id,
      InputSchema,
      OutputSchema,
      {},
      Publishes,
      ProgressSchema
    > = FunctionCallOptions<Id, InputSchema, OutputSchema, {}, Publishes, ProgressSchema>,
  >(
    options: FunctionCallOptions<Id, InputSchema, OutputSchema, {}, Publishes, ProgressSchema> &
      Options &
      FunctionCallValidation<NoInfer<Options>, InferOutput<OutputSchema>> & {
        readonly dependencies?: never;
      },
  ): FunctionDescriptor<
    Id,
    InferOutput<InputSchema>,
    InferOutput<OutputSchema>,
    {},
    ErrorListOf<Options>,
    InputSchema,
    OutputSchema,
    ToolMetadataOf<Options>,
    Publishes,
    ProgressSchema
  >;

  /** Defines a function with declared dependencies.
   * @param options - Schemas, handler, dependency map, and function metadata.
   * @returns A callable descriptor whose context includes the declared dependencies.
   * @example const lookup = defineFunction({ input, output, dependencies, handler });
   */
  <
    const Id extends string,
    const InputSchema extends StandardSchemaV1,
    const OutputSchema extends StandardSchemaV1,
    const Dependencies extends FunctionDependencies,
    const ProgressSchema extends StandardSchemaV1 | undefined = undefined,
    const Publishes extends readonly Extract<keyof Relkit.EventRegistry, string>[] = readonly [],
    const Options extends FunctionCallOptions<
      Id,
      InputSchema,
      OutputSchema,
      Dependencies,
      Publishes,
      ProgressSchema
    > = FunctionCallOptions<Id, InputSchema, OutputSchema, Dependencies, Publishes, ProgressSchema>,
  >(
    options: FunctionCallOptions<
      Id,
      InputSchema,
      OutputSchema,
      Dependencies,
      Publishes,
      ProgressSchema
    > &
      Options &
      FunctionCallValidation<NoInfer<Options>, InferOutput<OutputSchema>>,
  ): FunctionDescriptor<
    Id,
    InferOutput<InputSchema>,
    InferOutput<OutputSchema>,
    Dependencies,
    ErrorListOf<Options>,
    InputSchema,
    OutputSchema,
    ToolMetadataOf<Options>,
    Publishes,
    ProgressSchema
  >;
}

Source

DefineFunctionEffect (interface)

Effect constructor with the same schema and handler inference as defineFunction.

Signature

export interface DefineFunctionEffect {
  <
    const Id extends string,
    const InputSchema extends StandardSchemaV1,
    const OutputSchema extends StandardSchemaV1,
    const ProgressSchema extends StandardSchemaV1 | undefined = undefined,
    const Publishes extends readonly Extract<keyof Relkit.EventRegistry, string>[] = readonly [],
    const Options extends FunctionCallOptions<
      Id,
      InputSchema,
      OutputSchema,
      {},
      Publishes,
      ProgressSchema
    > = FunctionCallOptions<Id, InputSchema, OutputSchema, {}, Publishes, ProgressSchema>,
  >(
    options: FunctionCallOptions<Id, InputSchema, OutputSchema, {}, Publishes, ProgressSchema> &
      Options &
      FunctionCallValidation<NoInfer<Options>, InferOutput<OutputSchema>> & {
        readonly dependencies?: never;
      },
  ): Effect.Effect<
    FunctionDescriptor<
      Id,
      InferOutput<InputSchema>,
      InferOutput<OutputSchema>,
      {},
      ErrorListOf<Options>,
      InputSchema,
      OutputSchema,
      ToolMetadataOf<Options>,
      Publishes,
      ProgressSchema
    >,
    FunctionOperationError
  >;

  <
    const Id extends string,
    const InputSchema extends StandardSchemaV1,
    const OutputSchema extends StandardSchemaV1,
    const Dependencies extends FunctionDependencies,
    const ProgressSchema extends StandardSchemaV1 | undefined = undefined,
    const Publishes extends readonly Extract<keyof Relkit.EventRegistry, string>[] = readonly [],
    const Options extends FunctionCallOptions<
      Id,
      InputSchema,
      OutputSchema,
      Dependencies,
      Publishes,
      ProgressSchema
    > = FunctionCallOptions<Id, InputSchema, OutputSchema, Dependencies, Publishes, ProgressSchema>,
  >(
    options: FunctionCallOptions<
      Id,
      InputSchema,
      OutputSchema,
      Dependencies,
      Publishes,
      ProgressSchema
    > &
      Options &
      FunctionCallValidation<NoInfer<Options>, InferOutput<OutputSchema>>,
  ): Effect.Effect<
    FunctionDescriptor<
      Id,
      InferOutput<InputSchema>,
      InferOutput<OutputSchema>,
      Dependencies,
      ErrorListOf<Options>,
      InputSchema,
      OutputSchema,
      ToolMetadataOf<Options>,
      Publishes,
      ProgressSchema
    >,
    FunctionOperationError
  >;
}

Source

FunctionImplementationOptions (type alias)

Internal callable definition before the invocation mode is fixed.

Example

const options: FunctionImplementationOptions = { input, output, handler };

Signature

type FunctionImplementationOptions = Omit<
  FunctionDescriptorFactoryOptions,
  "id" | "invocationMode"
> & {
  readonly id?: string;
};

Source

function-as-tool.types.ts

FunctionAsTool (type alias)

Overloads for deriving a tool from a callable function.

Example

const tool = fn.asTool({ description: "Lookup", sideEffect: "read", approval: "never" });

Signature

type FunctionAsTool<
  FunctionId extends string,
  Input,
  Output,
  Errors extends readonly ErrorDescriptorAny[],
  InputSchema extends StandardSchemaV1,
  OutputSchema extends StandardSchemaV1,
  ToolMetadata extends FunctionToolMetadata | undefined,
> = {
  /** Creates a tool with an explicit ID and metadata.
   * @param options - Tool identity and behavior metadata.
   * @returns Frozen tool descriptor.
   * @example fn.asTool({ id: "lookup", description: "Lookup", sideEffect: "read", approval: "never" });
   */
  <const ToolId extends string>(
    options: FunctionToolOptions<ToolId, Input, Output> & { readonly id: ToolId },
  ): FunctionToolView<ToolId, FunctionId, Input, Output, Errors, InputSchema, OutputSchema>;
  /** Creates a tool with a derived ID.
   * @param options - Tool behavior metadata.
   * @returns Frozen tool descriptor.
   * @example fn.asTool({ description: "Lookup", sideEffect: "read", approval: "never" });
   */
  (
    options: FunctionToolOptions<string, Input, Output>,
  ): FunctionToolView<
    `${FunctionId}.tool`,
    FunctionId,
    Input,
    Output,
    Errors,
    InputSchema,
    OutputSchema
  >;
} & ([ToolMetadata] extends [FunctionToolMetadata]
  ? {
      /** Uses metadata declared on the function.
       * @returns Frozen tool descriptor.
       * @example fn.asTool();
       */
      (): FunctionToolView<
        `${FunctionId}.tool`,
        FunctionId,
        Input,
        Output,
        Errors,
        InputSchema,
        OutputSchema
      >;
    }
  : {});

Source

function-context.types.ts

ApplicationContextRegistry (type alias)

Application-owned additions to the handler context.

Example

type Registry = ApplicationContextRegistry;

Signature

type ApplicationContextRegistry = Relkit.ApplicationContextRegistry;

Source

AuthContext (interface)

Session lookup available to a handler.

Example

const session = await context.auth.getSession();

Signature

export interface AuthContext<Session = unknown> {
  /** Looks up the current session.
   * @returns The session or null when unauthenticated.
   * @example const session = await context.auth.getSession();
   */
  readonly getSession: () => Promise<Session | null>;
}

Source

FunctionContext (type alias)

Handler context with declared resources and optional progress.

Example

const run = async (_input: unknown, context: FunctionContext) => context.time.now();

Signature

type FunctionContext<
  D extends FunctionDependencies = {},
  Publishes extends readonly KnownEventName[] = readonly [],
  Progress = never,
> = FunctionContextBase<D, Publishes> &
  ([Progress] extends [never]
    ? {}
    : { readonly progress: import("@relkit/invocation").ProgressEmitter<Progress> });

Source

FunctionContextBase (interface)

Invocation context before optional progress is added.

Example

const env = context.env;

Signature

export interface FunctionContextBase<
  D extends FunctionDependencies = {},
  Publishes extends readonly KnownEventName[] = readonly [],
> {
  readonly invocation: InvocationMetadata;
  readonly signal: AbortSignal;
  readonly env: ResolvedApplicationEnv;
  readonly log: PublicLogger;
  readonly time: PublicClock;
  readonly trace: PublicTrace;
  readonly tasks: TaskClients<D["tasks"]>;
  readonly jobs: JobClients<D["jobs"]>;
  readonly events: EventClients<PublishedEventMap<Publishes>>;
  readonly buckets: BucketClients<D["buckets"]>;
  readonly cache: CacheClients<D["cache"]>;
  readonly agents: AgentClients<D["agents"]>;
  readonly database: RegisteredContext<"database", Readonly<Record<string, never>>>;
  readonly auth: RegisteredContext<"auth", AuthContext>;
  readonly constants: RegisteredContext<"constants", Readonly<Record<string, never>>>;
  readonly prompts: RegisteredContext<"prompts", Readonly<Record<string, never>>>;
}

Source

FunctionDependencies (interface)

Allowed resources a function may declare.

Example

const dependencies: FunctionDependencies = { buckets: { uploads } };

Signature

export interface FunctionDependencies {
  readonly tasks?: Readonly<Record<string, TaskRefAny>>;
  readonly jobs?: Readonly<Record<string, JobRefAny>>;
  readonly buckets?: Readonly<Record<string, BucketRefAny>>;
  readonly cache?: Readonly<Record<string, CacheRefAny>>;
  readonly agents?: Readonly<Record<string, AgentRefAny>>;
}

Source

FunctionDependencyOptions (type alias)

Rejects unsupported function dependency declarations.

Example

type Allowed = FunctionDependencyOptions<FunctionDependencies>;

Signature

type FunctionDependencyOptions<D extends FunctionDependencies> = "functions" extends keyof D
  ? never
  : D;

Source

InvocationMetadata (type alias)

Trace and identity metadata for one invocation.

Example

const metadata: InvocationMetadata = context.invocation;

Signature

type InvocationMetadata = SharedInvocationMetadata;

Source

InvocationSource (type alias)

Source category of a function invocation.

Example

const source: InvocationSource = "tool";

Signature

type InvocationSource = SharedInvocationSource;

Source

KnownEventName (type alias)

Registered event names accepted by publishes.

Example

type EventName = KnownEventName;

Signature

type KnownEventName = Extract<keyof Relkit.EventRegistry, string>;

Source

PublicClock (type alias)

Clock exposed to application handlers.

Example

const clock: PublicClock = context.time;

Signature

type PublicClock = SharedPublicClock;

Source

PublicLogger (type alias)

Logger exposed to application handlers.

Example

const logger: PublicLogger = context.log;

Signature

type PublicLogger = SharedPublicLogger;

Source

PublicTrace (type alias)

Trace controls exposed to handlers.

Example

const trace: PublicTrace = context.trace;

Signature

type PublicTrace = SharedPublicTrace;

Source

ResolvedApplicationEnv (type alias)

Application environment supplied to handlers.

Example

const env: ResolvedApplicationEnv = context.env;

Signature

type ResolvedApplicationEnv = keyof Relkit.ApplicationEnv extends never
  ? Readonly<Record<string, unknown>>
  : Readonly<Relkit.ApplicationEnv>;

Source

function-dependency-copy.ts

copyDependencies

Copies and validates function dependencies.

Throws

TypeError for unsupported or malformed references.

Example

copyDependencies({ buckets: { uploads } });

Signature

declare const copyDependencies: <D extends FunctionDependencies>(
  dependencies: D | undefined,
) => D | undefined;

Source

copyDependenciesEffect

Validates and freezes a dependency map through Effect.

Example

Effect.runSync(copyDependenciesEffect({ buckets: { uploads } }));

Signature

declare const copyDependenciesEffect: <D extends FunctionDependencies>(
  dependencies: D | undefined,
) => Effect.Effect<D | undefined, FunctionOperationError, never>;

Source

copyPublishes

Copies and validates published event IDs.

Throws

TypeError for duplicate or empty IDs.

Example

copyPublishes(["orders.created"]);

Signature

declare const copyPublishes: <Names extends readonly string[]>(
  publishes: Names | undefined,
) => Names | undefined;

Source

copyPublishesEffect

Validates a published event list through Effect.

Example

Effect.runSync(copyPublishesEffect(["orders.created"]));

Signature

declare const copyPublishesEffect: <Names extends readonly string[]>(
  publishes: Names | undefined,
) => Effect.Effect<Names | undefined, FunctionOperationError, never>;

Source

function-descriptor-factory.ts

FunctionDescriptorFactoryOptions

Signature

declare const FunctionDescriptorFactoryOptions: FunctionDescriptorFactoryOptions;

Source

createFunctionDescriptor

Creates a frozen function descriptor for an authoring package.

Throws

TypeError for malformed schemas, hooks, limits, or dependencies.

Example

createFunctionDescriptor(options);

Signature

declare const createFunctionDescriptor: (options: FunctionDescriptorFactoryOptions) => unknown;

Source

createFunctionDescriptorEffect

Creates a function descriptor through Effect.

Example

Effect.runSync(createFunctionDescriptorEffect(options));

Signature

declare const createFunctionDescriptorEffect: (
  options: FunctionDescriptorFactoryOptions,
) => Effect.Effect<unknown, FunctionOperationError, never>;

Source

function-descriptor-factory.types.ts

FunctionDescriptorFactoryOptions (interface)

Inputs for a function descriptor shared by authoring packages.

Example

createFunctionDescriptor({ id: "orders.get", input, output, invocationMode: "callable", handler });

Signature

export interface FunctionDescriptorFactoryOptions extends DescriptorMetadata {
  readonly id: string;
  readonly input: StandardSchemaV1;
  readonly output: StandardSchemaV1;
  readonly progress?: StandardSchemaV1;
  readonly invocationMode: "callable" | "event-only";
  readonly handler: (...args: any[]) => unknown;
  readonly errors?: readonly ErrorDescriptorAny[];
  readonly dependencies?: FunctionDependencies;
  readonly publishes?: readonly string[];
  readonly timeoutMs?: number;
  readonly concurrency?: number;
  readonly tool?: FunctionToolMetadata;
  readonly onBefore?: (...args: any[]) => unknown;
  readonly onAfter?: (...args: any[]) => unknown;
  readonly descriptorFields?: Readonly<Record<string, unknown>>;
}

Source

function-descriptor-methods.ts

addCallableMethods

Installs compatibility methods while the descriptor creation Effect owns mutation.

Example

addCallableMethods(descriptor, metadata);

Signature

declare const addCallableMethods: (
  descriptor: Record<string, any>,
  tool: FunctionToolMetadata | undefined,
) => void;

Source

asGraphNodeEffect

Derives a graph node view through Effect.

Example

Effect.runSync(asGraphNodeEffect(fn, fn));

Signature

declare const asGraphNodeEffect: (
  receiver: unknown,
  descriptor: FunctionRefAny,
  options?: { readonly id?: string } | undefined,
) => Effect.Effect<
  FunctionGraphNodeDescriptor<
    string,
    string,
    unknown,
    unknown,
    ReadonlyArray<ErrorDescriptorAny>,
    StandardSchemaV1<unknown, unknown>,
    StandardSchemaV1<unknown, unknown>,
    FunctionDependencies
  >,
  FunctionOperationError,
  never
>;

Source

asToolEffect

Derives a tool view through Effect.

Example

Effect.runSync(asToolEffect(fn, fn, fn.tool));

Signature

declare const asToolEffect: (
  receiver: unknown,
  descriptor: FunctionRefAny & { readonly id: string },
  tool: FunctionToolMetadata | undefined,
  options?: FunctionToolOptions<string, unknown, unknown> | undefined,
) => Effect.Effect<FunctionToolDescriptor<string, FunctionRefAny>, FunctionOperationError, never>;

Source

invokeDescriptorEffect

Invokes a callable descriptor through the Effect dispatcher.

Example

Effect.runPromise(invokeDescriptorEffect(fn, fn, { id: "one" }));

Signature

declare const invokeDescriptorEffect: (
  receiver: unknown,
  descriptor: FunctionRefAny,
  input: unknown,
) => Effect.Effect<unknown, FunctionOperationError, never>;

Source

function-descriptor.types.ts

DefineFunctionOptions (interface)

Schemas, handler, and metadata used to define a function.

Example

const options: DefineFunctionOptions<"orders.get", typeof input, typeof output> = {
  input,
  output,
  handler,
};

Signature

export interface DefineFunctionOptions<
  Id extends string,
  InputSchema extends StandardSchemaV1,
  OutputSchema extends StandardSchemaV1,
  Dependencies extends FunctionDependencies = {},
  Errors extends readonly ErrorDescriptorAny[] = readonly [],
  Publishes extends readonly KnownEventName[] = readonly [],
  ProgressSchema extends StandardSchemaV1 | undefined = undefined,
> extends DescriptorMetadata {
  readonly id?: Id;
  readonly input: InputSchema;
  readonly output: OutputSchema;
  readonly errors?: Errors;
  readonly dependencies?: Dependencies;
  readonly publishes?: Publishes;
  readonly progress?: ProgressSchema;
  readonly timeoutMs?: number;
  readonly concurrency?: number;
  readonly tool?: FunctionToolMetadata;
  readonly onBefore?: FunctionLifecycleHook<
    InferOutput<InputSchema>,
    Dependencies,
    Publishes,
    ProgressSchema
  >;
  readonly onAfter?: FunctionLifecycleHook<
    InferOutput<OutputSchema>,
    Dependencies,
    Publishes,
    ProgressSchema
  >;
  readonly handler: FunctionHandler<
    InferOutput<InputSchema>,
    InferOutput<OutputSchema>,
    Dependencies,
    Errors,
    Publishes,
    ProgressSchema
  >;
}

Source

FunctionDescriptor (interface)

Frozen callable descriptor for a defined function.

Example

const descriptor: FunctionDescriptor<"orders.get", Input, Output, {}> = defineFunction(options);

Signature

export interface FunctionDescriptor<
  Id extends string,
  Input,
  Output,
  Dependencies extends FunctionDependencies,
  Errors extends readonly ErrorDescriptorAny[] = readonly ErrorDescriptorAny[],
  InputSchema extends StandardSchemaV1 = StandardSchemaV1,
  OutputSchema extends StandardSchemaV1 = StandardSchemaV1,
  ToolMetadata extends FunctionToolMetadata | undefined = undefined,
  Publishes extends readonly KnownEventName[] = readonly [],
  ProgressSchema extends StandardSchemaV1 | undefined = undefined,
>
  extends
    DescriptorBase<"function", Id>,
    FunctionRef<Id, Input, Output, Errors, InputSchema, OutputSchema> {
  readonly dependencies?: FunctionDependencyOptions<Dependencies>;
  readonly invocationMode: "callable";
  readonly publishes?: Publishes;
  readonly progress?: ProgressSchema;
  readonly timeoutMs?: number;
  readonly concurrency?: number;
  readonly tool?: ToolMetadata;
  readonly onBefore?: FunctionLifecycleHook<Input, Dependencies, Publishes, ProgressSchema>;
  readonly onAfter?: FunctionLifecycleHook<Output, Dependencies, Publishes, ProgressSchema>;
  readonly handler: FunctionHandler<Input, Output, Dependencies, Errors, Publishes, ProgressSchema>;
  /** Invokes this function through the common runtime.
   * @param input - Value accepted by the input schema.
   * @returns Validated output, rejecting with an invocation error on failure.
   * @example await descriptor.invoke({ id: "one" });
   */
  readonly invoke: (input: InferInput<InputSchema>) => Promise<Output>;
  /** Creates a tool view when the output is not a stream.
   * @param options - Optional tool metadata overriding the declared metadata.
   * @returns A tool descriptor derived from this function.
   * @example descriptor.asTool({ description: "Lookup", sideEffect: "read", approval: "never" });
   */
  readonly asTool: OutputSchema extends StreamOutputSchema
    ? never
    : FunctionAsTool<Id, Input, Output, Errors, InputSchema, OutputSchema, ToolMetadata>;
  /** Creates a graph node view when the output is not a stream.
   * @param options - Optional graph node identity.
   * @returns A graph node descriptor derived from this function.
   * @example descriptor.asGraphNode({ id: "lookup" });
   */
  readonly asGraphNode: OutputSchema extends StreamOutputSchema
    ? never
    : FunctionAsGraphNode<Id, Input, Output, Errors, InputSchema, OutputSchema, Dependencies>;
}

Source

FunctionHandler (type alias)

Handler contract for a declared function.

Example

const handler: FunctionHandler<Input, Output, {}> = async (input) => input;

Signature

type FunctionHandler<
  Input,
  Output,
  Dependencies extends FunctionDependencies,
  Errors extends readonly ErrorDescriptorAny[] = readonly ErrorDescriptorAny[],
  Publishes extends readonly KnownEventName[] = readonly [],
  ProgressSchema extends StandardSchemaV1 | undefined = undefined,
> = (
  input: Input,
  context: FunctionContext<Dependencies, Publishes, ProgressValue<ProgressSchema>>,
) => MaybePromise<FunctionHandlerResult<Output, Errors>>;

Source

FunctionLifecycleHook

Signature

declare const FunctionLifecycleHook: FunctionLifecycleHook<
  Value,
  Dependencies,
  Publishes,
  ProgressSchema
>;

Source

function-graph-node.ts

FunctionAsGraphNode

Signature

declare const FunctionAsGraphNode: FunctionAsGraphNode<
  FunctionId,
  Input,
  Output,
  Errors,
  InputSchema,
  OutputSchema,
  Dependencies
>;

Source

FunctionGraphNodeDescriptor

Signature

declare const FunctionGraphNodeDescriptor: FunctionGraphNodeDescriptor<
  Id,
  FunctionId,
  Input,
  Output,
  Errors,
  InputSchema,
  OutputSchema,
  Dependencies
>;

Source

FunctionGraphNodeOptions

Signature

declare const FunctionGraphNodeOptions: FunctionGraphNodeOptions<Id>;

Source

RELKIT_FUNCTION_GRAPH_NODE

Marker identifying a frozen function graph node.

Example

if (node[RELKIT_FUNCTION_GRAPH_NODE]) console.log(node.id);

Signature

declare const RELKIT_FUNCTION_GRAPH_NODE: unique symbol;

Source

createFunctionGraphNode

Creates a frozen graph node view of a function.

Throws

TypeError for invalid options or a non-callable function.

Example

createFunctionGraphNode(fn, fn, { id: "lookup" });

Signature

declare const createFunctionGraphNode: (
  receiver: unknown,
  fallback: FunctionRefAny,
  options?: FunctionGraphNodeOptions,
) => FunctionGraphNodeDescriptor;

Source

createFunctionGraphNodeEffect

Creates a graph node view in the Effect error channel.

Example

Effect.runSync(createFunctionGraphNodeEffect(fn, fn));

Signature

declare const createFunctionGraphNodeEffect: (
  receiver: unknown,
  fallback: FunctionRefAny,
  options?: FunctionGraphNodeOptions<string> | undefined,
) => Effect.Effect<
  FunctionGraphNodeDescriptor<
    string,
    string,
    unknown,
    unknown,
    ReadonlyArray<ErrorDescriptorAny>,
    StandardSchemaV1<unknown, unknown>,
    StandardSchemaV1<unknown, unknown>,
    FunctionDependencies
  >,
  FunctionOperationError,
  never
>;

Source

invokeFunctionGraphNodeEffect

Invokes the function retained by a graph node through Effect.

Example

Effect.runPromise(invokeFunctionGraphNodeEffect(fn, { orderId: "one" }));

Signature

declare const invokeFunctionGraphNodeEffect: (
  target: FunctionRefAny,
  input: unknown,
) => Effect.Effect<unknown, FunctionOperationError, never>;

Source

isFunctionGraphNode

Recognizes a function graph node.

Example

if (isFunctionGraphNode(value)) console.log(value.id);

Signature

declare const isFunctionGraphNode: (value: unknown) => value is FunctionGraphNodeDescriptor;

Source

isFunctionGraphNodeEffect

Checks the shape of a graph node through Effect.

Example

Effect.runSync(isFunctionGraphNodeEffect(value));

Signature

declare const isFunctionGraphNodeEffect: (
  value: unknown,
) => Effect.Effect<boolean, FunctionOperationError, never>;

Source

function-graph-node.types.ts

FunctionAsGraphNode (type alias)

Overloads for creating a graph view with a derived or explicit ID.

Example

const node = fn.asGraphNode({ id: "lookup" });

Signature

type FunctionAsGraphNode<
  FunctionId extends string,
  Input,
  Output,
  Errors extends readonly ErrorDescriptorAny[],
  InputSchema extends StandardSchemaV1,
  OutputSchema extends StandardSchemaV1,
  Dependencies extends FunctionDependencies,
> = {
  /** Creates a graph view with an explicit node ID.
   * @param options - Required stable node ID.
   * @returns Frozen graph node descriptor.
   * @example fn.asGraphNode({ id: "lookup" });
   */
  <const NodeId extends string>(
    options: FunctionGraphNodeOptions<NodeId> & { readonly id: NodeId },
  ): FunctionGraphNodeDescriptor<
    NodeId,
    FunctionId,
    Input,
    Output,
    Errors,
    InputSchema,
    OutputSchema,
    Dependencies
  >;
  /** Creates a graph view using the function ID.
   * @returns Frozen graph node descriptor.
   * @example fn.asGraphNode();
   */
  (): FunctionGraphNodeDescriptor<
    FunctionId,
    FunctionId,
    Input,
    Output,
    Errors,
    InputSchema,
    OutputSchema,
    Dependencies
  >;
};

Source

FunctionGraphNodeDescriptor (interface)

Frozen graph view of a callable function descriptor.

Example

const node: FunctionGraphNodeDescriptor = fn.asGraphNode();

Signature

export interface FunctionGraphNodeDescriptor<
  Id extends string = string,
  FunctionId extends string = string,
  Input = unknown,
  Output = unknown,
  Errors extends readonly ErrorDescriptorAny[] = readonly ErrorDescriptorAny[],
  InputSchema extends StandardSchemaV1 = StandardSchemaV1,
  OutputSchema extends StandardSchemaV1 = StandardSchemaV1,
  Dependencies extends FunctionDependencies = FunctionDependencies,
> extends DescriptorMetadata {
  readonly [RELKIT_FUNCTION_GRAPH_NODE]: true;
  readonly kind: "function-graph-node";
  readonly id: Id;
  readonly target: Ref<"function", FunctionId>;
  readonly input: InputSchema;
  readonly output: OutputSchema;
  readonly errors?: Errors;
  readonly dependencies?: Dependencies;
  /** Invokes the source function using services supplied when the Effect runs.
   * @param input - Value accepted by the source input schema.
   * @returns Validated output or a tagged dispatch failure.
   * @example yield* node.invokeEffect({ id: "one" });
   */
  readonly invokeEffect: (
    input: InferInput<InputSchema>,
  ) => Effect.Effect<Output, FunctionOperationError>;
  /** Invokes the source function through the common dispatcher.
   * @param input - Value accepted by the source input schema.
   * @returns Validated output or an invocation rejection.
   * @example await node.invoke({ id: "one" });
   */
  readonly invoke: (input: InferInput<InputSchema>) => Promise<Output>;
  readonly __input?: Input;
  readonly __output?: Output;
}

Source

FunctionGraphNodeOptions (interface)

Optional graph node identity override.

Example

const options: FunctionGraphNodeOptions = { id: "lookup" };

Signature

export interface FunctionGraphNodeOptions<Id extends string = string> {
  readonly id?: Id;
}

Source

function-input-error.ts

Internal marker for an expected synchronous input failure. It remains a TypeError for existing compatibility callers.

Example

throw new FunctionInputError("Invalid function input");

FunctionInputError (class)

Internal marker for an expected synchronous input failure. It remains a TypeError for existing compatibility callers.

Example

throw new FunctionInputError("Invalid function input");

Signature

declare class FunctionInputError {
  constructor(message: string);
}

Source

function-lifecycle.types.ts

FunctionLifecycleHook (type alias)

Hook called before or after a function invocation.

Example

const hook: FunctionLifecycleHook<Input, {}, []> = (value) => value;

Signature

type FunctionLifecycleHook<
  Value,
  Dependencies extends FunctionDependencies = {},
  Publishes extends readonly KnownEventName[] = readonly [],
  ProgressSchema extends StandardSchemaV1 | undefined = undefined,
> = (
  value: Value,
  context: FunctionContext<Dependencies, Publishes, ProgressValue<ProgressSchema>>,
) => MaybePromise<Value>;

Source

ProgressValue (type alias)

Validated progress value inferred from an optional schema.

Example

type Progress = ProgressValue<typeof progressSchema>;

Signature

type ProgressValue<Schema extends StandardSchemaV1 | undefined> = Schema extends StandardSchemaV1
  ? InferOutput<Schema>
  : never;

Source

function-observability.ts

FunctionOperation

Signature

declare const FunctionOperation: FunctionOperation;

Source

FunctionOperationError (class)

Tagged failure of a function authoring operation.

Example

const error = new FunctionOperationError({
  operation: "stream.create",
  cause: new TypeError("Invalid item"),
});

Signature

declare class FunctionOperationError

Source

FunctionTelemetry (class)

Replaceable telemetry service for operation spans and metrics.

Example

Effect.provide(streamOfEffect(schema), FunctionTelemetryLive);

Signature

declare class FunctionTelemetry

Source

FunctionTelemetryLive

Default telemetry layer for function operations.

Example

Effect.runSync(Effect.provide(Effect.void, FunctionTelemetryLive));

Signature

declare const FunctionTelemetryLive: Layer.Layer<FunctionTelemetry, never, never>;

Source

FunctionTelemetryService

Signature

declare const FunctionTelemetryService: FunctionTelemetryService;

Source

functionAttempt

Evaluates a synchronous step within an already observed operation.

Example

yield * functionAttempt("error.define", () => validateInput(input));

Signature

declare const functionAttempt: <A>(
  operation: FunctionOperation,
  evaluate: () => A,
) => Effect.Effect<A, FunctionOperationError>;

Source

functionTry

Maps an expected input error into the tagged channel and preserves defects.

Example

runFunctionSync(functionTry("stream.is-output", () => true));

Signature

declare const functionTry: <A>(
  operation: FunctionOperation,
  evaluate: () => A,
) => Effect.Effect<A, FunctionOperationError>;

Source

observeFunction

Measures an operation using the provided telemetry service or the live observer.

Example

observeFunction("stream.is-output", Effect.succeed(true));

Signature

declare const observeFunction: <A, E, R>(
  operation: FunctionOperation,
  effect: Effect.Effect<A, E, R>,
) => Effect.Effect<A, E, R>;

Source

runFunctionPromise

Executes an asynchronous compatibility adapter and restores its original error.

Throws

The original domain error or an unexpected defect.

Example

await runFunctionPromise(Effect.succeed(1));

Signature

declare const runFunctionPromise: <A, E>(effect: Effect.Effect<A, E>) => Promise<A>;

Source

runFunctionSync

Executes a synchronous compatibility adapter and restores its original error.

Throws

The original validation error or an unexpected defect.

Example

runFunctionSync(Effect.succeed(1));

Signature

declare const runFunctionSync: <A, E>(effect: Effect.Effect<A, E>) => A;

Source

function-observability.types.ts

FunctionOperation (type alias)

Fixed operation name used as a bounded telemetry label.

Example

const operation: FunctionOperation = "tool.invoke";

Signature

type FunctionOperation =
  | "error.define"
  | "error.create"
  | "error.is-descriptor"
  | "error.validate-http"
  | "error.assert-schema"
  | "error.is-record"
  | "function.define"
  | "function.invoke"
  | "function.invoke-target"
  | "function.as-tool"
  | "function.as-graph-node"
  | "function.create-descriptor"
  | "function.graph-node"
  | "function.graph-node-invoke"
  | "function.is-graph-node"
  | "function.fail"
  | "function.copy-dependencies"
  | "function.copy-publishes"
  | "function.validate-limit"
  | "function.assert-hook"
  | "function.assert-schema"
  | "function.target-for-receiver"
  | "stream.create"
  | "stream.validate"
  | "stream.is-output"
  | "tool.create"
  | "tool.copy-metadata"
  | "tool.invoke"
  | "tool.invoker-create"
  | "tool.is-target"
  | "tool.is-error-descriptor"
  | "tool.is-record"
  | "tool.has-own"
  | "tool.validate-side-effect"
  | "tool.validate-approval"
  | "tool.required-text"
  | "tool.positive-integer"
  | "tool.copy-hooks";

Source

FunctionTelemetryService (interface)

Substitutable observer for function authoring operations.

Example

const observer: FunctionTelemetryService = { observe: (_operation, effect) => effect };

Signature

export interface FunctionTelemetryService {
  /** Measures one operation while preserving the original Effect channels.
   * @param operation - Fixed operation name.
   * @param effect - Work to measure.
   * @returns Effect with the same success, error, and requirement channels.
   * @example observer.observe("tool.invoke", Effect.succeed(1));
   */
  readonly observe: <A, E, R>(
    operation: FunctionOperation,
    effect: Effect.Effect<A, E, R>,
  ) => Effect.Effect<A, E, R>;
}

Source

function-ref.types.ts

AgentRef (interface)

Input and output schemas for an agent reference.

Example

const ref: AgentRef = agent;

Signature

export interface AgentRef<
  Id extends string = string,
  InputSchema extends StandardSchemaV1 = StandardSchemaV1,
  OutputSchema extends StandardSchemaV1 = StandardSchemaV1,
> extends DescriptorRef<"agent", Id> {
  readonly input: InputSchema;
  readonly output: OutputSchema;
}

Source

AgentRefAny (type alias)

Broad agent reference for heterogeneous collections.

Example

const ref: AgentRefAny = agent;

Signature

type AgentRefAny = AgentRef;

Source

BucketRef (type alias)

Stable reference to a bucket.

Example

const ref: BucketRef = bucket;

Signature

type BucketRef<Id extends string = string> = DescriptorRef<"bucket", Id>;

Source

BucketRefAny (type alias)

Broad bucket reference for heterogeneous collections.

Example

const ref: BucketRefAny = bucket;

Signature

type BucketRefAny = BucketRef;

Source

CacheRef (interface)

Key and value schemas for a cache reference.

Example

const ref: CacheRef = cache;

Signature

export interface CacheRef<
  Id extends string = string,
  KeySchema extends StandardSchemaV1 = StandardSchemaV1,
  ValueSchema extends StandardSchemaV1 = StandardSchemaV1,
> extends DescriptorRef<"cache", Id> {
  readonly key: KeySchema;
  readonly value: ValueSchema;
}

Source

CacheRefAny (type alias)

Broad cache reference for heterogeneous collections.

Example

const ref: CacheRefAny = cache;

Signature

type CacheRefAny = CacheRef;

Source

DescriptorRef (interface)

Stable reference carried by a descriptor.

Example

const ref: DescriptorRef<"function"> = { ref: { kind: "function", id: "orders.get" } };

Signature

export interface DescriptorRef<Kind extends DescriptorKind, Id extends string = string> {
  readonly ref: Ref<Kind, Id>;
}

Source

EventRef (interface)

Schema and version view of a declared event.

Example

const ref: EventRef = event;

Signature

export interface EventRef<
  Id extends string = string,
  InputSchema extends StandardSchemaV1 = StandardSchemaV1,
> extends DescriptorRef<"event", Id> {
  readonly version: number;
  readonly input: InputSchema;
}

Source

EventRefAny (type alias)

Broad event reference for heterogeneous collections.

Example

const ref: EventRefAny = event;

Signature

type EventRefAny = EventRef;

Source

FunctionRef (interface)

Schema and identity view of a callable function.

Example

const ref: FunctionRef = descriptor;

Signature

export interface FunctionRef<
  Id extends string = string,
  Input = unknown,
  Output = unknown,
  Errors extends readonly ErrorDescriptorAny[] = readonly ErrorDescriptorAny[],
  InputSchema extends StandardSchemaV1 = StandardSchemaV1,
  OutputSchema extends StandardSchemaV1 = StandardSchemaV1,
> extends DescriptorRef<"function", Id> {
  readonly invocationMode?: "callable";
  readonly input: InputSchema;
  readonly output: OutputSchema;
  readonly errors?: Errors;
  readonly __input?: Input;
  readonly __output?: Output;
}

Source

FunctionRefAny (type alias)

Broad function reference for heterogeneous collections.

Example

const ref: FunctionRefAny = descriptor;

Signature

type FunctionRefAny = FunctionRef;

Source

function-tool-approval.ts

resolveFunctionToolApprovalEffect

Resolves approval within the owning invocation’s span and resource scope.

Example

yield * resolveFunctionToolApprovalEffect(request, { approval: () => true });

Signature

declare const resolveFunctionToolApprovalEffect: (
  approval: FunctionToolApprovalRequest,
  options: FunctionToolInvokeOptions,
) => Effect.Effect<
  undefined,
  | FunctionOperationError
  | FunctionToolCancelledFailure
  | FunctionToolApprovalRequiredFailure
  | FunctionToolApprovalDeniedFailure,
  never
>;

Source

function-tool-errors.ts

FunctionToolApprovalDeniedError (class)

Compatibility error when a resolver denies execution.

Example

throw new FunctionToolApprovalDeniedError(request);

Signature

declare class FunctionToolApprovalDeniedError { constructor(readonly approval: FunctionToolApprovalRequest) }

Source

code (property)

Signature

readonly code: "RELKIT_APPROVAL_DENIED"

Source

FunctionToolApprovalRequiredError (class)

Compatibility error when approval is required but unavailable.

Example

throw new FunctionToolApprovalRequiredError(request);

Signature

declare class FunctionToolApprovalRequiredError { constructor(readonly approval: FunctionToolApprovalRequest) }

Source

code (property)

Signature

readonly code: "RELKIT_APPROVAL_REQUIRED"

Source

FunctionToolArgumentValidationError (class)

Compatibility error for malformed tool arguments.

Example

throw new FunctionToolArgumentValidationError([{ message: "Missing id" }]);

Signature

declare class FunctionToolArgumentValidationError {
  constructor(issues: readonly StandardIssue[]);
}

Source

code (property)

Signature

readonly code: "RELKIT_TOOL_ARGUMENT_VALIDATION"

Source

issues (property)

Signature

readonly issues: ReadonlyArray<StandardIssue>

Source

FunctionToolOperationCancelledError (class)

Compatibility cancellation error for a tool operation.

Example

throw new FunctionToolOperationCancelledError();

Signature

declare class FunctionToolOperationCancelledError {
  constructor();
}

Source

code (property)

Signature

readonly code: "ABORT_ERR"

Source

function-tool-failures.ts

FunctionToolApprovalDeniedFailure (class)

Tagged Effect failure when approval is denied.

Example

Effect.catchTag(
  invokeFunctionToolEffect(target, metadata, input),
  "FunctionToolApprovalDeniedFailure",
  () => Effect.void,
);

Signature

declare class FunctionToolApprovalDeniedFailure

Source

FunctionToolApprovalRequiredFailure (class)

Tagged Effect failure when a tool needs an approval resolver.

Example

Effect.catchTag(
  invokeFunctionToolEffect(target, metadata, input),
  "FunctionToolApprovalRequiredFailure",
  () => Effect.void,
);

Signature

declare class FunctionToolApprovalRequiredFailure

Source

FunctionToolArgumentFailure (class)

Tagged Effect failure for malformed tool arguments.

Example

Effect.catchTag(
  invokeFunctionToolEffect(target, metadata, input),
  "FunctionToolArgumentFailure",
  () => Effect.void,
);

Signature

declare class FunctionToolArgumentFailure

Source

FunctionToolCancelledFailure (class)

Tagged Effect failure when tool execution is cancelled.

Example

Effect.catchTag(
  invokeFunctionToolEffect(target, metadata, input),
  "FunctionToolCancelledFailure",
  () => Effect.void,
);

Signature

declare class FunctionToolCancelledFailure

Source

function-tool-runtime.ts

FunctionToolApprovalDeniedError

Signature

declare const FunctionToolApprovalDeniedError: typeof FunctionToolApprovalDeniedError;

Source

FunctionToolApprovalDeniedFailure

Signature

declare const FunctionToolApprovalDeniedFailure: typeof FunctionToolApprovalDeniedFailure;

Source

FunctionToolApprovalRequiredError

Signature

declare const FunctionToolApprovalRequiredError: typeof FunctionToolApprovalRequiredError;

Source

FunctionToolApprovalRequiredFailure

Signature

declare const FunctionToolApprovalRequiredFailure: typeof FunctionToolApprovalRequiredFailure;

Source

FunctionToolArgumentFailure

Signature

declare const FunctionToolArgumentFailure: typeof FunctionToolArgumentFailure;

Source

FunctionToolArgumentValidationError

Signature

declare const FunctionToolArgumentValidationError: typeof FunctionToolArgumentValidationError;

Source

FunctionToolCancelledFailure

Signature

declare const FunctionToolCancelledFailure: typeof FunctionToolCancelledFailure;

Source

FunctionToolOperationCancelledError

Signature

declare const FunctionToolOperationCancelledError: typeof FunctionToolOperationCancelledError;

Source

createFunctionToolInvoker

Creates a Promise compatibility invoker for a tool.

Throws

TypeError if construction metadata is invalid.

Example

const invoke = createFunctionToolInvoker(fn, metadata);

Signature

declare const createFunctionToolInvoker: <Target extends FunctionRefAny>(
  target: Target,
  metadata: FunctionToolRuntimeMetadata,
  identity?: object,
) => (
  input: InferInput<Target["input"]>,
  options?: FunctionToolInvokeOptions,
) => Promise<InferOutput<Target["output"]>>;

Source

createFunctionToolInvokerEffect

Creates an Effect invoker that resolves services when each call runs.

Example

Effect.runSync(createFunctionToolInvokerEffect(fn, metadata));

Signature

declare const createFunctionToolInvokerEffect: <Target extends FunctionRefAny>(
  target: Target,
  metadata: FunctionToolRuntimeMetadata,
  identity?: object | undefined,
) => Effect.Effect<
  (
    input: InferInput<Target["input"]>,
    options?: FunctionToolInvokeOptions,
  ) => Effect.Effect<
    InferOutput<Target["output"]>,
    | FunctionOperationError
    | FunctionToolArgumentFailure
    | FunctionToolCancelledFailure
    | FunctionToolApprovalRequiredFailure
    | FunctionToolApprovalDeniedFailure,
    SchemaValidator
  >,
  FunctionOperationError,
  never
>;

Source

invokeFunctionToolEffect

Invokes a tool through schema validation, approval, and the Effect dispatcher.

Example

Effect.runPromise(
  Effect.provide(invokeFunctionToolEffect(fn, metadata, input), SchemaValidatorLive),
);

Signature

declare const invokeFunctionToolEffect: <Target extends FunctionRefAny>(
  target: Target,
  metadata: FunctionToolRuntimeMetadata,
  input: InferInput<Target["input"]>,
  options?: FunctionToolInvokeOptions | undefined,
  identity?: object | undefined,
) => Effect.Effect<
  InferOutput<Target["output"]>,
  | FunctionOperationError
  | FunctionToolArgumentFailure
  | FunctionToolCancelledFailure
  | FunctionToolApprovalRequiredFailure
  | FunctionToolApprovalDeniedFailure,
  SchemaValidator
>;

Source

function-tool-runtime.types.ts

FunctionToolRuntimeMetadata (type alias)

Runtime policy and hooks attached to a tool invoker.

Example

const metadata: FunctionToolRuntimeMetadata = {
  id: "lookup",
  sideEffect: "read",
  approval: "never",
};

Signature

type FunctionToolRuntimeMetadata = Pick<
  FunctionToolMetadata,
  "sideEffect" | "approval" | "timeoutMs"
> & {
  readonly id: string;
  readonly onBefore?: FunctionToolHook;
  readonly onAfter?: FunctionToolHook;
};

Source

TargetSchema (type alias)

Input schema accepted by a callable function target.

Example

const schema: TargetSchema = target.input;

Signature

type TargetSchema = FunctionRefAny["input"];

Source

function-tool-shape.ts

hasOwn

Checks whether an object owns a property.

Example

hasOwn({ id: "one" }, "id");

Signature

declare const hasOwn: (value: object, key: PropertyKey) => boolean;

Source

hasOwnEffect

Checks an own property through Effect.

Example

Effect.runSync(hasOwnEffect({}, "id"));

Signature

declare const hasOwnEffect: (
  value: object,
  key: PropertyKey,
) => Effect.Effect<boolean, FunctionOperationError, never>;

Source

isErrorDescriptor

Recognizes an error descriptor accepted by tool metadata.

Example

isErrorDescriptor(value);

Signature

declare const isErrorDescriptor: (value: unknown) => value is ErrorDescriptorAny;

Source

isErrorDescriptorEffect

Checks a declared error shape through Effect.

Example

Effect.runSync(isErrorDescriptorEffect(value));

Signature

declare const isErrorDescriptorEffect: (
  value: unknown,
) => Effect.Effect<boolean, FunctionOperationError, never>;

Source

isFunctionTarget

Recognizes a function usable as a tool target.

Example

if (isFunctionTarget(value)) console.log(value.ref.id);

Signature

declare const isFunctionTarget: (value: unknown) => value is FunctionRefAny;

Source

isFunctionTargetEffect

Checks a callable function target through Effect.

Example

Effect.runSync(isFunctionTargetEffect(fn));

Signature

declare const isFunctionTargetEffect: (
  value: unknown,
) => Effect.Effect<boolean, FunctionOperationError, never>;

Source

isRecord

Recognizes a record-like tool value.

Example

isRecord({ id: "one" });

Signature

declare const isRecord: (value: unknown) => value is Record<PropertyKey, any>;

Source

isRecordEffect

Checks a record-like value through Effect.

Example

Effect.runSync(isRecordEffect({}));

Signature

declare const isRecordEffect: (
  value: unknown,
) => Effect.Effect<boolean, FunctionOperationError, never>;

Source

function-tool-validation.ts

copyFunctionToolHooks

Copies optional tool hooks.

Throws

TypeError for malformed hooks.

Example

copyFunctionToolHooks({ onBefore: (x) => x });

Signature

declare const copyFunctionToolHooks: (
  value: unknown,
) => Pick<FunctionToolOptions, "onBefore" | "onAfter">;

Source

copyFunctionToolHooksEffect

Copies validated tool hooks through Effect.

Example

Effect.runSync(copyFunctionToolHooksEffect({ onBefore: (x) => x }));

Signature

declare const copyFunctionToolHooksEffect: (
  value: unknown,
) => Effect.Effect<
  Pick<FunctionToolOptions<string, unknown, unknown>, "onBefore" | "onAfter">,
  FunctionOperationError,
  never
>;

Source

hasOwn

Signature

declare const hasOwn: (value: object, key: PropertyKey) => boolean;

Source

isErrorDescriptor

Signature

declare const isErrorDescriptor: (value: unknown) => value is ErrorDescriptorAny;

Source

isFunctionTarget

Signature

declare const isFunctionTarget: (value: unknown) => value is FunctionRefAny;

Source

isRecord

Signature

declare const isRecord: (value: unknown) => value is Record<PropertyKey, any>;

Source

positiveInteger

Asserts a positive integer tool field.

Throws

TypeError for invalid input.

Example

positiveInteger(5, "timeoutMs");

Signature

declare const positiveInteger: (value: unknown, name: string) => asserts value is number;

Source

positiveIntegerEffect

Checks a positive integer through Effect.

Example

Effect.runSync(positiveIntegerEffect(5, "timeoutMs"));

Signature

declare const positiveIntegerEffect: (
  value: unknown,
  name: string,
) => Effect.Effect<number, FunctionOperationError, never>;

Source

requiredText

Requires nonempty tool text.

Throws

TypeError for an empty value.

Example

requiredText(" Read order ", "description");

Signature

declare const requiredText: (value: unknown, name: string) => string;

Source

requiredTextEffect

Requires nonempty text through Effect.

Example

Effect.runSync(requiredTextEffect(" Hello ", "name"));

Signature

declare const requiredTextEffect: (
  value: unknown,
  name: string,
) => Effect.Effect<string, FunctionOperationError, never>;

Source

validateApproval

Validates a tool approval policy.

Throws

TypeError for unknown values.

Example

validateApproval("always");

Signature

declare const validateApproval: (value: unknown) => FunctionToolApproval;

Source

validateApprovalEffect

Validates an approval policy through Effect.

Example

Effect.runSync(validateApprovalEffect("always"));

Signature

declare const validateApprovalEffect: (
  value: unknown,
) => Effect.Effect<"never" | "on-write" | "always", FunctionOperationError, never>;

Source

validateSideEffect

Validates a tool side effect policy.

Throws

TypeError for unknown values.

Example

validateSideEffect("read");

Signature

declare const validateSideEffect: (value: unknown) => FunctionToolSideEffect;

Source

validateSideEffectEffect

Validates a side effect policy through Effect.

Example

Effect.runSync(validateSideEffectEffect("read"));

Signature

declare const validateSideEffectEffect: (
  value: unknown,
) => Effect.Effect<"none" | "read" | "write" | "external", FunctionOperationError, never>;

Source

function-tool.ts

“./function-tool.types.js” (namespace export)

Re-exports all named exports from the “./function-tool.types.js” module.

Signature

export * from "./function-tool.types.js";

Source

copyFunctionToolHooks

Signature

declare const copyFunctionToolHooks: (
  value: unknown,
) => Pick<FunctionToolOptions, "onBefore" | "onAfter">;

Source

copyFunctionToolHooksEffect

Signature

declare const copyFunctionToolHooksEffect: (
  value: unknown,
) => Effect.Effect<
  Pick<FunctionToolOptions<string, unknown, unknown>, "onBefore" | "onAfter">,
  FunctionOperationError,
  never
>;

Source

copyFunctionToolMetadata

Copies and validates tool metadata.

Throws

TypeError for invalid fields.

Example

copyFunctionToolMetadata({ description: "Get order", sideEffect: "read", approval: "never" });

Signature

declare const copyFunctionToolMetadata: (value: unknown) => FunctionToolMetadata;

Source

copyFunctionToolMetadataEffect

Copies and validates tool metadata through Effect.

Example

Effect.runSync(copyFunctionToolMetadataEffect(raw));

Signature

declare const copyFunctionToolMetadataEffect: (
  value: unknown,
) => Effect.Effect<FunctionToolMetadata, FunctionOperationError, never>;

Source

createFunctionTool

Creates a frozen tool descriptor.

Throws

TypeError for malformed target or metadata.

Example

const tool = createFunctionTool({
  target: fn,
  description: "Get order",
  sideEffect: "read",
  approval: "never",
});

Signature

declare const createFunctionTool: <const Id extends string, const Target extends FunctionRefAny>(
  options: FunctionToolCreateOptions<Id, Target>,
) => FunctionToolDescriptor<Id, Target>;

Source

createFunctionToolEffect

Creates a tool descriptor through Effect.

Example

Effect.runSync(
  createFunctionToolEffect({
    target: fn,
    description: "Get order",
    sideEffect: "read",
    approval: "never",
  }),
);

Signature

declare const createFunctionToolEffect: <
  const Id extends string,
  const Target extends FunctionRefAny,
>(
  options: FunctionToolCreateOptions<Id, Target>,
) => Effect.Effect<FunctionToolDescriptor<Id, Target>, FunctionOperationError, never>;

Source

function-tool.types.ts

FunctionToolApproval (type alias)

Approval policy applied before tool dispatch.

Example

const policy: FunctionToolApproval = "on-write";

Signature

type FunctionToolApproval = "never" | "on-write" | "always";

Source

FunctionToolApprovalDecision (type alias)

Decision returned by an approval resolver.

Example

const decision: FunctionToolApprovalDecision = "approved";

Signature

type FunctionToolApprovalDecision = "approved" | "denied" | boolean;

Source

FunctionToolApprovalRequest (interface)

Request shown to an approval resolver.

Example

const request: FunctionToolApprovalRequest = {
  toolId: "orders.lookup",
  sideEffect: "read",
  policy: "always",
};

Signature

export interface FunctionToolApprovalRequest {
  readonly toolId: string;
  readonly sideEffect: FunctionToolSideEffect;
  readonly policy: FunctionToolApproval;
}

Source

FunctionToolApprovalResolver (type alias)

Callback that decides whether a tool may execute.

Example

const approve: FunctionToolApprovalResolver = async () => "approved";

Signature

type FunctionToolApprovalResolver = (
  approval: FunctionToolApprovalRequest,
  signal?: AbortSignal,
) => MaybePromise<FunctionToolApprovalDecision>;

Source

FunctionToolContext (type alias)

Restricted invocation context passed to tool hooks.

Example

const time = context.time;

Signature

type FunctionToolContext = Pick<FunctionContext, "invocation" | "signal" | "env" | "log" | "time">;

Source

FunctionToolCreateOptions (type alias)

Target and metadata required to construct a tool.

Example

const options: FunctionToolCreateOptions<"lookup", typeof fn> = {
  id: "lookup",
  target: fn,
  description: "Lookup",
  sideEffect: "read",
  approval: "never",
};

Signature

type FunctionToolCreateOptions<
  Id extends string,
  Target extends FunctionRefAny,
> = FunctionToolOptions<Id, InferInput<Target["input"]>, InferOutput<Target["output"]>> & {
  readonly id?: Id;
  readonly target: Target;
};

Source

FunctionToolDescriptor (interface)

Frozen tool descriptor with a Promise invoke adapter.

Example

const tool: FunctionToolDescriptor<"lookup", typeof fn> = createFunctionTool(options);

Signature

export interface FunctionToolDescriptor<
  Id extends string,
  Target extends FunctionRefAny = FunctionRefAny,
> extends DescriptorBase<"tool", Id> {
  readonly ref: { readonly kind: "tool"; readonly id: Id };
  readonly target: FunctionToolTarget<Target>;
  readonly description: string;
  readonly sideEffect: FunctionToolSideEffect;
  readonly approval: FunctionToolApproval;
  readonly timeoutMs?: number;
  readonly mcp: boolean;
  readonly onBefore?: FunctionToolHook<InferInput<Target["input"]>>;
  readonly onAfter?: FunctionToolHook<InferOutput<Target["output"]>>;
  /** Invokes the target using services supplied when the Effect runs.
   * @param input - Tool argument value.
   * @param options - Optional cancellation and approval controls.
   * @returns Validated output or a tagged tool failure.
   * @example yield* tool.invokeEffect({ id: "one" });
   */
  readonly invokeEffect: (
    input: InferInput<Target["input"]>,
    options?: FunctionToolInvokeOptions,
  ) => Effect.Effect<
    InferOutput<Target["output"]>,
    | FunctionOperationError
    | FunctionToolArgumentFailure
    | FunctionToolCancelledFailure
    | FunctionToolApprovalRequiredFailure
    | FunctionToolApprovalDeniedFailure,
    SchemaValidator
  >;
  /** Invokes the target through the common tool and function runtime.
   * @param input - Tool argument value.
   * @param options - Optional cancellation and approval controls.
   * @returns Validated output, rejecting with a tool error on failure.
   * @example await tool.invoke({ id: "one" });
   */
  readonly invoke: (
    input: InferInput<Target["input"]>,
    options?: FunctionToolInvokeOptions,
  ) => Promise<InferOutput<Target["output"]>>;
}

Source

FunctionToolHook (type alias)

Optional input or output transform for a tool.

Example

const hook: FunctionToolHook<string> = (value) => value.trim();

Signature

type FunctionToolHook<Value = unknown> = (
  value: Value,
  context: FunctionToolContext,
) => MaybePromise<Value>;

Source

FunctionToolInvokeOptions (interface)

Per-call signal and approval resolver.

Example

await tool.invoke(input, { signal: controller.signal });

Signature

export interface FunctionToolInvokeOptions {
  readonly signal?: AbortSignal;
  readonly approval?: FunctionToolApprovalResolver;
}

Source

FunctionToolMetadata (interface)

Display and policy metadata for a tool.

Example

const metadata: FunctionToolMetadata = {
  description: "Lookup",
  sideEffect: "read",
  approval: "never",
};

Signature

export interface FunctionToolMetadata extends DescriptorMetadata {
  readonly description: string;
  readonly sideEffect: FunctionToolSideEffect;
  readonly approval: FunctionToolApproval;
  readonly timeoutMs?: number;
  readonly mcp?: boolean;
}

Source

FunctionToolOptions (interface)

Options used when creating a tool view.

Example

const options: FunctionToolOptions = {
  description: "Lookup",
  sideEffect: "read",
  approval: "never",
};

Signature

export interface FunctionToolOptions<
  Id extends string = string,
  Input = unknown,
  Output = unknown,
> extends FunctionToolMetadata {
  readonly id?: Id;
  readonly onBefore?: FunctionToolHook<Input>;
  readonly onAfter?: FunctionToolHook<Output>;
}

Source

FunctionToolSideEffect (type alias)

Bounded side effect category for a tool.

Example

const effect: FunctionToolSideEffect = "read";

Signature

type FunctionToolSideEffect = "none" | "read" | "write" | "external";

Source

FunctionToolTarget (type alias)

Function contract copied into a tool view.

Example

const target: FunctionToolTarget<typeof fn> = tool.target;

Signature

type FunctionToolTarget<Target extends FunctionRefAny> = FunctionRef<
  Target["ref"]["id"],
  Target extends { readonly __input?: infer Input } ? Input : unknown,
  Target extends { readonly __output?: infer Output } ? Output : unknown,
  TargetErrors<Target>,
  Target["input"],
  Target["output"]
>;

Source

handler-result.ts

“./handler-result.types.js” (namespace export)

Re-exports all named exports from the “./handler-result.types.js” module.

Signature

export * from "./handler-result.types.js";

Source

fail

Returns a typed application failure from a plain function handler.

Throws

The descriptor’s validation error.

Example

return fail(NotFound, { id: "one" });

Signature

declare const fail: <const Descriptor extends ErrorDescriptorAny>(
  descriptor: Descriptor,
  data: Parameters<Descriptor["create"]>[0],
) => FunctionFailure<DeclaredErrorOf<Descriptor>>;

Source

failEffect

Creates a typed application failure in the Effect error channel.

Example

Effect.runSync(failEffect(NotFound, { id: "one" }));

Signature

declare const failEffect: <const Descriptor extends ErrorDescriptorAny>(
  descriptor: Descriptor,
  data: Parameters<Descriptor["create"]>[0],
) => Effect.Effect<
  FunctionFailure<ReturnType<Descriptor["create"]>>,
  FunctionOperationError,
  never
>;

Source

handler-result.types.ts

DeclaredErrorOf (type alias)

Instance type produced by one error descriptor.

Example

type NotFoundError = DeclaredErrorOf<typeof NotFound>;

Signature

type DeclaredErrorOf<Descriptor extends ErrorDescriptorAny> = ReturnType<Descriptor["create"]>;

Source

DeclaredErrorsOf (type alias)

Union of instances from an error descriptor list.

Example

type Allowed = DeclaredErrorsOf<typeof errors>;

Signature

type DeclaredErrorsOf<Descriptors extends readonly ErrorDescriptorAny[]> =
  Descriptors[number] extends infer Descriptor
    ? Descriptor extends ErrorDescriptorAny
      ? DeclaredErrorOf<Descriptor>
      : never
    : never;

Source

FunctionEffectValue (interface)

Structural Effect type accepted from a handler.

Example

const result: FunctionEffectValue = Effect.succeed(output);

Signature

export interface FunctionEffectValue<Output = unknown, Error = unknown, Requirements = unknown> {
  readonly "~effect/Effect": {
    readonly _A: (_: never) => Output;
    readonly _E: (_: never) => Error;
    readonly _R: (_: never) => Requirements;
  };
  readonly pipe: (...args: never[]) => unknown;
  readonly [Symbol.iterator]: () => unknown;
}

Source

FunctionFailure (interface)

Tagged failure returned by a plain function handler.

Example

const failure: FunctionFailure = fail(NotFound, data);

Signature

export interface FunctionFailure<Error extends globalThis.Error = globalThis.Error> {
  readonly _tag: "FunctionFailure";
  readonly error: Error;
}

Source

FunctionHandlerResult (type alias)

Values and declared failures a handler may return.

Example

const result: FunctionHandlerResult<string> = "done";

Signature

type FunctionHandlerResult<
  Output,
  Errors extends readonly ErrorDescriptorAny[] = readonly ErrorDescriptorAny[],
> =
  | Output
  | DeclaredErrorsOf<Errors>
  | FunctionFailure<DeclaredErrorsOf<Errors>>
  | FunctionEffectValue<Output, DeclaredErrorsOf<Errors>, never>;

Source

FunctionHandlerValidation (type alias)

Compile-time check of handler output and declared errors.

Example

type Valid = FunctionHandlerValidation<ReturnType<typeof handler>, Output, Errors>;

Signature

type FunctionHandlerValidation<Result, Output, Errors extends readonly ErrorDescriptorAny[]> = [
  InvalidHandlerResult<Awaited<Result>, Output, DeclaredErrorsOf<Errors>>,
] extends [never]
  ? [MissingDeclaredErrors<Result, Errors>] extends [never]
    ? {}
    : {
        readonly __relkit_handler_error__: "Return every error declared in the function's errors list";
      }
  : {
      readonly __relkit_handler_error__: "Return values and errors must match the function contract";
    };

Source

index.ts

“./define-error.js” (namespace export)

Re-exports all named exports from the “./define-error.js” module.

Signature

export * from "./define-error.js";

Source

“./define-function.js” (namespace export)

Re-exports all named exports from the “./define-function.js” module.

Signature

export * from "./define-function.js";

Source

“./function-graph-node.js” (namespace export)

Re-exports all named exports from the “./function-graph-node.js” module.

Signature

export * from "./function-graph-node.js";

Source

“./function-observability.js” (namespace export)

Re-exports all named exports from the “./function-observability.js” module.

Signature

export * from "./function-observability.js";

Source

“./handler-result.js” (namespace export)

Re-exports all named exports from the “./handler-result.js” module.

Signature

export * from "./handler-result.js";

Source

“./stream.js” (namespace export)

Re-exports all named exports from the “./stream.js” module.

Signature

export * from "./stream.js";

Source

FunctionToolApproval

Signature

declare const FunctionToolApproval: FunctionToolApproval;

Source

FunctionToolApprovalDecision

Signature

declare const FunctionToolApprovalDecision: FunctionToolApprovalDecision;

Source

FunctionToolApprovalDeniedError

Signature

declare const FunctionToolApprovalDeniedError: typeof FunctionToolApprovalDeniedError;

Source

FunctionToolApprovalDeniedFailure

Signature

declare const FunctionToolApprovalDeniedFailure: typeof FunctionToolApprovalDeniedFailure;

Source

FunctionToolApprovalRequest

Signature

declare const FunctionToolApprovalRequest: FunctionToolApprovalRequest;

Source

FunctionToolApprovalRequiredError

Signature

declare const FunctionToolApprovalRequiredError: typeof FunctionToolApprovalRequiredError;

Source

FunctionToolApprovalRequiredFailure

Signature

declare const FunctionToolApprovalRequiredFailure: typeof FunctionToolApprovalRequiredFailure;

Source

FunctionToolApprovalResolver

Signature

declare const FunctionToolApprovalResolver: FunctionToolApprovalResolver;

Source

FunctionToolArgumentFailure

Signature

declare const FunctionToolArgumentFailure: typeof FunctionToolArgumentFailure;

Source

FunctionToolArgumentValidationError

Signature

declare const FunctionToolArgumentValidationError: typeof FunctionToolArgumentValidationError;

Source

FunctionToolCancelledFailure

Signature

declare const FunctionToolCancelledFailure: typeof FunctionToolCancelledFailure;

Source

FunctionToolContext

Signature

declare const FunctionToolContext: FunctionToolContext;

Source

FunctionToolDescriptor

Signature

declare const FunctionToolDescriptor: FunctionToolDescriptor<Id, Target>;

Source

FunctionToolHook

Signature

declare const FunctionToolHook: FunctionToolHook<Value>;

Source

FunctionToolInvokeOptions

Signature

declare const FunctionToolInvokeOptions: FunctionToolInvokeOptions;

Source

FunctionToolMetadata

Signature

declare const FunctionToolMetadata: FunctionToolMetadata;

Source

FunctionToolOperationCancelledError

Signature

declare const FunctionToolOperationCancelledError: typeof FunctionToolOperationCancelledError;

Source

FunctionToolOptions

Signature

declare const FunctionToolOptions: FunctionToolOptions<Id, Input, Output>;

Source

FunctionToolSideEffect

Signature

declare const FunctionToolSideEffect: FunctionToolSideEffect;

Source

FunctionToolTarget

Signature

declare const FunctionToolTarget: FunctionToolTarget<Target>;

Source

copyFunctionToolHooks

Signature

declare const copyFunctionToolHooks: (
  value: unknown,
) => Pick<FunctionToolOptions, "onBefore" | "onAfter">;

Source

copyFunctionToolHooksEffect

Signature

declare const copyFunctionToolHooksEffect: (
  value: unknown,
) => Effect<
  Pick<FunctionToolOptions<string, unknown, unknown>, "onBefore" | "onAfter">,
  FunctionOperationError,
  never
>;

Source

createFunctionToolInvoker

Signature

declare const createFunctionToolInvoker: <Target extends FunctionRefAny>(
  target: Target,
  metadata: FunctionToolRuntimeMetadata,
  identity?: object,
) => (
  input: InferInput<Target["input"]>,
  options?: FunctionToolInvokeOptions,
) => Promise<InferOutput<Target["output"]>>;

Source

createFunctionToolInvokerEffect

Signature

declare const createFunctionToolInvokerEffect: <Target extends FunctionRefAny>(
  target: Target,
  metadata: FunctionToolRuntimeMetadata,
  identity?: object | undefined,
) => Effect<
  (
    input: InferInput<Target["input"]>,
    options?: FunctionToolInvokeOptions,
  ) => Effect<
    InferOutput<Target["output"]>,
    | FunctionOperationError
    | FunctionToolArgumentFailure
    | FunctionToolCancelledFailure
    | FunctionToolApprovalRequiredFailure
    | FunctionToolApprovalDeniedFailure,
    SchemaValidator
  >,
  FunctionOperationError,
  never
>;

Source

invokeFunctionToolEffect

Signature

declare const invokeFunctionToolEffect: <Target extends FunctionRefAny>(
  target: Target,
  metadata: FunctionToolRuntimeMetadata,
  input: InferInput<Target["input"]>,
  options?: FunctionToolInvokeOptions | undefined,
  identity?: object | undefined,
) => Effect<
  InferOutput<Target["output"]>,
  | FunctionOperationError
  | FunctionToolArgumentFailure
  | FunctionToolCancelledFailure
  | FunctionToolApprovalRequiredFailure
  | FunctionToolApprovalDeniedFailure,
  SchemaValidator
>;

Source

internal.ts

“./function-descriptor-factory.js” (namespace export)

Re-exports all named exports from the “./function-descriptor-factory.js” module.

Signature

export * from "./function-descriptor-factory.js";

Source

stream.ts

StreamOutputSchema

Signature

declare const StreamOutputSchema: StreamOutputSchema<ItemSchema>;

Source

isStreamOutputSchema

Recognizes a stream output schema.

Example

if (isStreamOutputSchema(value)) console.log(value.item);

Signature

declare const isStreamOutputSchema: (value: unknown) => value is StreamOutputSchema;

Source

isStreamOutputSchemaEffect

Checks whether a value is a stream output schema through Effect.

Example

Effect.runSync(isStreamOutputSchemaEffect(value));

Signature

declare const isStreamOutputSchemaEffect: (
  value: unknown,
) => Effect.Effect<boolean, FunctionOperationError, never>;

Source

streamOf

Declares a validated asynchronous stream result.

Throws

TypeError when the item is not a Standard Schema validator.

Example

const output = streamOf(z.string());

Signature

declare const streamOf: <const ItemSchema extends StandardSchemaV1>(
  item: ItemSchema,
) => StreamOutputSchema<ItemSchema>;

Source

Backend and frontend example

Backend — these maintained files define the operation used by the frontend below.

/** Supplies the report route with ten validated stream items, stopping when its invocation signal aborts. */
import { defineFunction, streamOf } from "@relkit/app/functions";
import { z } from "@relkit/app/schema";

const streamOrderReport = defineFunction({
  input: z.object({ reportId: z.string().min(1) }),
  output: streamOf(z.object({ completed: z.number().int(), total: z.number().int() })),
  handler: async function* (_input, context) {
    for (let completed = 1; completed <= 10; completed += 1) {
      // if (completed > 1) {
      //   await Bun.sleep(1_000);
      // }
      if (context.signal.aborted) return;
      yield { completed, total: completed };
    }
  },
});

export default streamOrderReport;
/** Maps a report path identifier to the order stream and exposes its validated items as server-sent events. */
import { defineRoute, http } from "@relkit/app/routes";
import orders from "../../../services/orders/service.js";

export const GET = defineRoute({
  target: orders.streamOrderReport,
  request: http.input({ reportId: http.path("reportId") }),
  client: { operation: "query" },
  stream: { format: "sse" },
});

Frontend

After frontend setup and pulling the commerce contract, render this component under the provider. The GET /reports/:reportId route exposes the streaming function:

"use client";

/** Consumes the commerce report route as a cancellable typed stream inside the client provider. */
import { useRelkitClient, useStream } from "@relkit/client/react";

/** Starts one report explicitly and displays its validated progress items.
 * @returns Start/cancel controls and visible progress or stream failure. */
export function Report() {
  const { status } = useRelkitClient();
  const report = useStream("GET /reports/:reportId");

  return (
    <section>
      <button
        disabled={status !== "ready"}
        onClick={() => void report.start({ reportId: "daily" })}
      >
        Run report
      </button>
      <button onClick={() => report.cancel()}>Cancel report</button>
      <p role="status">Completed: {report.items.map((item) => item.completed).join(", ")}</p>
      {report.error && <p role="alert">{String(report.error)}</p>}
    </section>
  );
}

streamOf supplies the item type, so report.items exposes each item’s completed field. start({ reportId }) begins the request; cancel() releases it. Use the domain input even when REST places a field in the URL. Streaming operations are excluded from finite useRoute queries.

Reference: useStream. Continue with stream lifecycle and failures.

streamOfEffect

Creates a stream output schema in the Effect error channel.

Example

Effect.runSync(streamOfEffect(z.string()));

Signature

declare const streamOfEffect: <const ItemSchema extends StandardSchemaV1>(
  item: ItemSchema,
) => Effect.Effect<StreamOutputSchema<ItemSchema>, FunctionOperationError, never>;

Source

stream.types.ts

StreamOutputSchema (interface)

Standard Schema contract for an asynchronous sequence of validated items.

Example

const output: StreamOutputSchema = streamOf(z.string());

Signature

export interface StreamOutputSchema<
  ItemSchema extends StandardSchemaV1 = StandardSchemaV1,
> extends StandardSchemaV1<
  AsyncIterable<InferInput<ItemSchema>>,
  AsyncIterable<InferOutput<ItemSchema>>
> {
  readonly kind: "stream";
  readonly item: ItemSchema;
  readonly relkit: {
    readonly jsonSchema: () => { readonly kind: "stream"; readonly item: object };
  };
}

Source

types.ts

“./function-context.types.js” (namespace export)

Re-exports all named exports from the “./function-context.types.js” module.

Signature

export * from "./function-context.types.js";

Source

“./function-descriptor.types.js” (namespace export)

Re-exports all named exports from the “./function-descriptor.types.js” module.

Signature

export * from "./function-descriptor.types.js";

Source

“./function-ref.types.js” (namespace export)

Re-exports all named exports from the “./function-ref.types.js” module.

Signature

export * from "./function-ref.types.js";

Source

AgentClientFor

Signature

declare const AgentClientFor: AgentClientFor<T>;

Source

AgentClients

Signature

declare const AgentClients: AgentClients<M>;

Source

BucketClient

Signature

declare const BucketClient: BucketClient;

Source

BucketClientFor

Signature

declare const BucketClientFor: BucketClient;

Source

BucketClients

Signature

declare const BucketClients: BucketClients<M>;

Source

BucketObjectMetadata

Signature

declare const BucketObjectMetadata: BucketObjectMetadata;

Source

CacheClient

Signature

declare const CacheClient: CacheClient<Key, Value>;

Source

CacheClientFor

Signature

declare const CacheClientFor: CacheClientFor<T>;

Source

CacheClients

Signature

declare const CacheClients: CacheClients<M>;

Source

CacheOperationOptions

Signature

declare const CacheOperationOptions: CacheOperationOptions;

Source

EventAttributeValue

Signature

declare const EventAttributeValue: EventAttributeValue;

Source

EventClientFor

Signature

declare const EventClientFor: EventClientFor<T>;

Source

EventClients

Signature

declare const EventClients: EventClients<M>;

Source

EventPublishOptions

Signature

declare const EventPublishOptions: EventPublishOptions;

Source

EventPublishResult

Signature

declare const EventPublishResult: EventPublishResult<Id, Version, Payload>;

Source

JobClientFor

Signature

declare const JobClientFor: JobClientFor<T>;

Source

JobClients

Signature

declare const JobClients: JobClients<M>;

Source

JobEnqueueOptions

Signature

declare const JobEnqueueOptions: JobEnqueueOptions;

Source

JobEnqueueResult

Signature

declare const JobEnqueueResult: JobEnqueueResult;

Source

JobRef

Signature

declare const JobRef: JobRef<Id, InputSchema, OutputSchema, Task>;

Source

JobRefAny

Signature

declare const JobRefAny: JobRefAny;

Source

JobState

Signature

declare const JobState: JobState;

Source

JobStatus

Signature

declare const JobStatus: JobStatus;

Source

TaskClientFor

Signature

declare const TaskClientFor: TaskClientFor<T>;

Source

TaskClients

Signature

declare const TaskClients: TaskClients<M>;

Source

TaskRef

Signature

declare const TaskRef: TaskRef<Id, InputSchema, OutputSchema, Errors>;

Source

TaskRefAny

Signature

declare const TaskRefAny: TaskRefAny;

Source

TaskTriggerOptions

Signature

declare const TaskTriggerOptions: TaskTriggerOptions;

Source

error-retry.types.ts

Retry policy for a declared application error.

Example

const retry: ErrorRetry = "later";

ErrorRetry (type alias)

Retry policy for a declared application error.

Example

const retry: ErrorRetry = "later";

Signature

type ErrorRetry = "never" | "later";

Source

ErrorRetryInput (type alias)

Accepted retry policy input. Normalization validates the optional delay and freezes the result.

Example

const retry: ErrorRetryInput = { kind: "later", afterMs: 500 };

Signature

type ErrorRetryInput = ErrorRetry | ErrorRetryLater;

Source

ErrorRetryLater (interface)

Delayed retry policy with an optional minimum delay. afterMs must be a finite non-negative integer when supplied.

Example

const retry: ErrorRetryLater = { kind: "later", afterMs: 500 };

Signature

export interface ErrorRetryLater {
  readonly kind: "later";
  readonly afterMs?: number;
}

Source

NormalizedErrorRetry (interface)

Canonical immutable retry policy. Normalization removes a delay when retry is never.

Example

const policy = normalizeErrorRetry("later", 500);

Signature

export interface NormalizedErrorRetry {
  readonly retry: ErrorRetry;
  readonly afterMs?: number;
}

Source

identity-bind.ts

bindDescriptorIdentity

Synchronous canonical identity binding adapter.

Throws

DescriptorIdentityError or TypeError for invalid identity.

Example

bindDescriptorIdentity(descriptor, "tasks.run");

Signature

declare const bindDescriptorIdentity: <T extends object>(descriptor: T, id: string) => T;

Source

bindDescriptorIdentityEffect

Binds a canonical descriptor identity without mutating the descriptor.

Example

Effect.runSync(bindDescriptorIdentityEffect(descriptor, "tasks.run"));

Signature

declare const bindDescriptorIdentityEffect: <T extends object>(
  descriptor: T,
  id: string,
) => Effect.Effect<T, import("./identity-state.js").DescriptorIdentityFailure>;

Source

bindDescriptorServiceMembers

Synchronous service member binding adapter.

Throws

DescriptorIdentityError when a member belongs to another service.

Example

bindDescriptorServiceMembers([member], service);

Signature

declare const bindDescriptorServiceMembers: <T extends object>(
  descriptors: readonly T[],
  service: object & DescriptorIdentitySource,
) => readonly T[];

Source

bindDescriptorServiceMembersEffect

Associates descriptor members with one service without changing them.

Example

Effect.runSync(bindDescriptorServiceMembersEffect([member], service));

Signature

declare const bindDescriptorServiceMembersEffect: <T extends object>(
  descriptors: readonly T[],
  service: object & DescriptorIdentitySource,
) => Effect.Effect<ReadonlyArray<T>, DescriptorIdentityFailure, never>;

Source

isDescriptorIdentityBound

Synchronous bound check adapter.

Example

isDescriptorIdentityBound(descriptor);

Signature

declare const isDescriptorIdentityBound: (descriptor: object) => boolean;

Source

isDescriptorIdentityBoundEffect

Checks if a descriptor has an explicit canonical binding.

Example

Effect.runSync(isDescriptorIdentityBoundEffect(descriptor));

Signature

declare const isDescriptorIdentityBoundEffect: (
  descriptor: object,
) => Effect.Effect<boolean, DescriptorIdentityFailure, never>;

Source