Skip to content

Understand Yielded Agent

Getting started

Start with one agent that classifies a bug report. Your application supplies a model and history Layer; the definition owns the input, output, and execution limits. This example runs in memory. Choose a durable host when accepted work must survive restart.

In a TypeScript project with Bun:

bun add @yielded/agent@beta effect @effect/ai-openai @effect/platform-bun

The package manifests declare peer compatibility. Other providers use native Effect AI model Layers too.

Save as agent.ts. Supply OPENAI_API_KEY through your environment or secret manager.

agent.ts
import {
import OpenAiClient
OpenAiClient
,
import OpenAiLanguageModel
OpenAiLanguageModel
} from "@effect/ai-openai";
import {
import BunRuntime
BunRuntime
} from "@effect/platform-bun";
import {
import Agent
Agent
,
import AgentRuntime
AgentRuntime
,
import InMemory
InMemory
} from "@yielded/agent";
import {
import Config
Config
,
import Console
Console
,
import Effect
Effect
,
import Schema
Schema
} from "effect";
import {
import Toolkit
Toolkit
} from "effect/ai";
import {
import FetchHttpClient
FetchHttpClient
} from "effect/http";
const
const triage: Agent.Definition<Schema.String, Schema.Struct<{
readonly severity: Schema.Literals<readonly ["low", "medium", "high", "critical"]>;
readonly explanation: Schema.String;
}>, "Classify the bug report and explain the severity in one sentence.", Toolkit.Toolkit<{}>, undefined, undefined, undefined> & {
readonly id: Brand<"@effect-agent/core/AgentId"> & "triage";
}
triage
=
import Agent
Agent
.
function make<"triage", Schema.String, Schema.Struct<{
readonly severity: Schema.Literals<readonly ["low", "medium", "high", "critical"]>;
readonly explanation: Schema.String;
}>, "Classify the bug report and explain the severity in one sentence.", Toolkit.Toolkit<{}>, undefined>(id: "triage", options: Agent.DefinitionOptions<Schema.String, Schema.Struct<{
readonly severity: Schema.Literals<readonly ["low", "medium", "high", "critical"]>;
readonly explanation: Schema.String;
}>, "Classify the bug report and explain the severity in one sentence.", Toolkit.Toolkit<...>, undefined, undefined, undefined> & {
...;
}): Agent.Definition<...> & {
...;
} (+3 overloads)

Validate an agent ID and return a shallowly frozen, model-agnostic definition.

make
("triage", {
DefinitionOptions<String, Struct<{ readonly severity: Literals<readonly ["low", "medium", "high", "critical"]>; readonly explanation: String; }>, "Classify the bug report and explain the severity in one sentence.", Toolkit<...>, undefined, undefined, undefined>.input: Schema.String
input
:
import Schema
Schema
.
const String: Schema.String

Type-level representation of

String

.

Schema for string values. Validates that the input is typeof "string".

@stability ― stable

@category ― models

@since ― 4.0.0

@stability ― stable

@category ― schemas

@since ― 4.0.0

String
,
DefinitionOptions<String, Struct<{ readonly severity: Literals<readonly ["low", "medium", "high", "critical"]>; readonly explanation: String; }>, "Classify the bug report and explain the severity in one sentence.", Toolkit<...>, undefined, undefined, undefined>.output: Schema.Struct<{
readonly severity: Schema.Literals<readonly ["low", "medium", "high", "critical"]>;
readonly explanation: Schema.String;
}>
output
:
import Schema
Schema
.
function Struct<{
readonly severity: Schema.Literals<readonly ["low", "medium", "high", "critical"]>;
readonly explanation: Schema.String;
}>(fields: {
readonly severity: Schema.Literals<readonly ["low", "medium", "high", "critical"]>;
readonly explanation: Schema.String;
}): Schema.Struct<{
readonly severity: Schema.Literals<readonly ["low", "medium", "high", "critical"]>;
readonly explanation: Schema.String;
}>

Defines a struct schema from a map of field schemas.

Details

Each field value is a schema. Use

optionalKey

or

optional

to mark fields as optional, and

mutableKey

to mark them as mutable.

The resulting schema's Type is a readonly object type with the fields' decoded types. The Encoded form mirrors the field schemas' encoded types. Declared fields may be inherited and are copied to own properties in the output. The __proto__ field is accepted only when it is an own property. Parsing does not guarantee that output keys retain their input order.

Example (Defining a basic struct)

import { Schema } from "effect"
const Person = Schema.Struct({
name: Schema.String,
age: Schema.Number,
email: Schema.optionalKey(Schema.String)
})
// { readonly name: string; readonly age: number; readonly email?: string }
type Person = typeof Person.Type
Schema.decodeUnknownSync(Person)({ name: "Alice", age: 30 }) // => { name: "Alice", age: 30 }

@stability ― stable

@category ― constructors

@since ― 3.10.0

Struct
({
severity: Schema.Literals<readonly ["low", "medium", "high", "critical"]>
severity
:
import Schema
Schema
.
function Literals<readonly ["low", "medium", "high", "critical"]>(literals: readonly ["low", "medium", "high", "critical"]): Schema.Literals<readonly ["low", "medium", "high", "critical"]>

Creates a union schema from an array of literal values.

Example (Defining status codes)

import { Schema } from "effect"
const schema = Schema.Literals(["active", "inactive", "pending"])
Schema.decodeSync(schema)("active") // => "active"

@see ― Literal for a schema that represents a single literal.

@stability ― stable

@category ― constructors

@since ― 4.0.0

Literals
(["low", "medium", "high", "critical"]),
explanation: Schema.String
explanation
:
import Schema
Schema
.
const String: Schema.String

Type-level representation of

String

.

Schema for string values. Validates that the input is typeof "string".

@stability ― stable

@category ― models

@since ― 4.0.0

@stability ― stable

@category ― schemas

@since ― 4.0.0

String
,
}),
DefinitionOptions<String, Struct<{ readonly severity: Literals<readonly ["low", "medium", "high", "critical"]>; readonly explanation: String; }>, "Classify the bug report and explain the severity in one sentence.", Toolkit<...>, undefined, undefined, undefined>.instructions: "Classify the bug report and explain the severity in one sentence."
instructions
: "Classify the bug report and explain the severity in one sentence.",
DefinitionOptions<String, Struct<{ readonly severity: Literals<readonly ["low", "medium", "high", "critical"]>; readonly explanation: String; }>, "Classify the bug report and explain the severity in one sentence.", Toolkit<...>, undefined, undefined, undefined>.toolkit: Toolkit.Toolkit<{}>
toolkit
:
import Toolkit
Toolkit
.
const empty: Toolkit.Toolkit<{}>

An empty toolkit with no tools.

When to use

Use when you need an empty starting point for building toolkits or a default toolkit value that can be extended with merge.

@stability ― unstable

@category ― constructors

@since ― 4.0.0

empty
,
DefinitionOptions<String, Struct<{ readonly severity: Literals<readonly ["low", "medium", "high", "critical"]>; readonly explanation: String; }>, "Classify the bug report and explain the severity in one sentence.", Toolkit<...>, undefined, undefined, undefined>.policy?: Partial<Readonly<Omit<{
readonly runStatus: "appended" | "off";
readonly maxTurns: number;
readonly maxToolCalls: number;
readonly maxDuration: Duration;
readonly toolConcurrency: number;
readonly repeatedFailureLimit: number;
readonly onExhaustion: "final-answer" | "fail";
readonly completionReserveTokens: number;
readonly toolResultBounds: ToolResultBounds;
readonly compaction: CompactionPolicy;
readonly tokenBudget?: number | undefined;
readonly costBudgetMicrousd?: number | undefined;
readonly contextTokenLimit?: number | undefined;
readonly restartOnJoinedInput?: boolean | undefined;
readonly modelRetries?: number | undefined;
}, "runStatus" | ... 7 more ... | "compaction"> & {
...;
}>> | undefined
policy
: {
maxTurns?: number | null | undefined

Maximum model turns, or null to leave turn count unbounded.

maxTurns
: 2,
maxToolCalls?: number | null | undefined

Maximum declared and programmatic Tool Calls, or null to leave count unbounded.

maxToolCalls
: 1,
maxDuration?: Input | undefined

Finite, positive wall-clock duration accepted in any Effect Duration input form.

maxDuration
: "30 seconds" },
});
const
const program: Effect.Effect<{
readonly finishReason: "completed" | "model-stop" | "budget-exhausted";
readonly turns: number;
readonly output: {
readonly severity: "low" | "medium" | "high" | "critical";
readonly explanation: string;
};
readonly threadId: string & Brand<"@effect-agent/core/ThreadId">;
readonly runId: string & Brand<"@effect-agent/core/RunId">;
readonly exhausted?: "tokens" | "tool-calls" | "turns" | undefined;
readonly runDisposition?: Schema.Json | undefined;
readonly usage?: RunTotals | undefined;
readonly delegatedUsage?: RunTotals | undefined;
}, AgentRuntime.AgentRuntimeFailure<...> | Config.ConfigError, never>
program
=
import AgentRuntime
AgentRuntime
.
const run: <Agent.Definition<Schema.String, Schema.Struct<{
readonly severity: Schema.Literals<readonly ["low", "medium", "high", "critical"]>;
readonly explanation: Schema.String;
}>, "Classify the bug report and explain the severity in one sentence.", Toolkit.Toolkit<{}>, undefined, undefined, undefined> & {
readonly id: Brand<"@effect-agent/core/AgentId"> & "triage";
}, never, never>(agent: Agent.Definition<Schema.String, Schema.Struct<{
readonly severity: Schema.Literals<readonly ["low", "medium", "high", "critical"]>;
readonly explanation: Schema.String;
}>, ... 4 more ..., undefined> & {
readonly id: Brand<"@effect-agent/core/AgentId"> & "triage";
}, input: string, options?: RunOptions<...> | undefined) => Effect.Effect<...>

Accept schema-encoded input, retaining runtime validation.

run
(
const triage: Agent.Definition<Schema.String, Schema.Struct<{
readonly severity: Schema.Literals<readonly ["low", "medium", "high", "critical"]>;
readonly explanation: Schema.String;
}>, "Classify the bug report and explain the severity in one sentence.", Toolkit.Toolkit<{}>, undefined, undefined, undefined> & {
readonly id: Brand<"@effect-agent/core/AgentId"> & "triage";
}
triage
, "Users cannot sign in.").
Pipeable.pipe<Effect.Effect<{
readonly finishReason: "completed" | "model-stop" | "budget-exhausted";
readonly turns: number;
readonly output: {
readonly severity: "low" | "medium" | "high" | "critical";
readonly explanation: string;
};
readonly threadId: string & Brand<"@effect-agent/core/ThreadId">;
readonly runId: string & Brand<"@effect-agent/core/RunId">;
readonly exhausted?: "tokens" | "tool-calls" | "turns" | undefined;
readonly runDisposition?: Schema.Json | undefined;
readonly usage?: RunTotals | undefined;
readonly delegatedUsage?: RunTotals | undefined;
}, AgentRuntime.AgentRuntimeFailure<...>, AgentRuntime.AgentRuntimeRequirements<...>>, Effect.Effect<...>, Effect.Effect<...>, Effect.Effect<...>, Effect.Effect<...>, Effect.Effect<...>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Effect.Effect<...>, bc: (_: Effect.Effect<...>) => Effect.Effect<...>, cd: (_: Effect.Effect<...>) => Effect.Effect<...>, de: (_: Effect.Effect<...>) => Effect.Effect<...>, ef: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect
Effect
.
const tap: <{
readonly finishReason: "completed" | "model-stop" | "budget-exhausted";
readonly turns: number;
readonly output: {
readonly severity: "low" | "medium" | "high" | "critical";
readonly explanation: string;
};
readonly threadId: string & Brand<"@effect-agent/core/ThreadId">;
readonly runId: string & Brand<"@effect-agent/core/RunId">;
readonly exhausted?: "tokens" | "tool-calls" | "turns" | undefined;
readonly runDisposition?: Schema.Json | undefined;
readonly usage?: RunTotals | undefined;
readonly delegatedUsage?: RunTotals | undefined;
}, void, never, never>(f: (a: {
readonly finishReason: "completed" | "model-stop" | "budget-exhausted";
readonly turns: number;
readonly output: {
readonly severity: "low" | "medium" | "high" | "critical";
readonly explanation: string;
};
readonly threadId: string & Brand<"@effect-agent/core/ThreadId">;
readonly runId: string & Brand<"@effect-agent/core/RunId">;
readonly exhausted?: "tokens" | "tool-calls" | "turns" | undefined;
readonly runDisposition?: Schema.Json | undefined;
readonly usage?: RunTotals | undefined;
readonly delegatedUsage?: RunTotals | undefined;
}) => Effect.Effect<...>) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+3 overloads)

Runs a side effect with the result of an effect without changing the original value.

When to use

Use when you need to run an effectful observation, such as logging or tracking, while passing the original success value to the next step.

Details

tap works similarly to flatMap, but it ignores the result of the function passed to it. The value from the previous effect remains available for the next part of the chain. Note that if the side effect fails, the entire chain will fail too.

Example (Logging a step in a pipeline)

import { Data, Effect, pipe } from "effect"
const output: Array<unknown> = []
class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {}
// Function to apply a discount safely to a transaction amount
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, DiscountRateError> =>
discountRate === 0
? Effect.fail(new DiscountRateError())
: Effect.succeed(total - (total * discountRate) / 100)
// Simulated asynchronous task to fetch a transaction amount from database
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const finalAmount = pipe(
fetchTransactionAmount,
// Log the fetched transaction amount
Effect.tap((amount) => Effect.sync(() => { output.push(`Apply a discount to: ${amount}`) })),
// `amount` is still available!
Effect.flatMap((amount) => applyDiscount(amount, 5))
)
void output.push(await Effect.runPromise(finalAmount))
output // => ["Apply a discount to: 100", 95]

@stability ― stable

@category ― sequencing

@since ― 2.0.0

tap
((
result: {
readonly finishReason: "completed" | "model-stop" | "budget-exhausted";
readonly turns: number;
readonly output: {
readonly severity: "low" | "medium" | "high" | "critical";
readonly explanation: string;
};
readonly threadId: string & Brand<"@effect-agent/core/ThreadId">;
readonly runId: string & Brand<"@effect-agent/core/RunId">;
readonly exhausted?: "tokens" | "tool-calls" | "turns" | undefined;
readonly runDisposition?: Schema.Json | undefined;
readonly usage?: RunTotals | undefined;
readonly delegatedUsage?: RunTotals | undefined;
}
result
) =>
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>

Logs a general-purpose message to the console.

Example (Writing log messages)

import { Console, Effect } from "effect"
const messages: Array<ReadonlyArray<unknown>> = []
const testConsole: Console.Console = Object.assign(Object.create(console), {
log: (...args: ReadonlyArray<unknown>) => messages.push(args)
})
const program = Effect.gen(function*() {
yield* Console.log("Hello, world!")
yield* Console.log("User data:", { name: "John", age: 30 })
yield* Console.log("Processing", 42, "items")
})
Effect.runSync(Effect.provideService(program, Console.Console, testConsole))
const expected = [
["Hello, world!"],
["User data:", { name: "John", age: 30 }],
["Processing", 42, "items"]
]
messages // => expected

@stability ― stable

@category ― accessors

@since ― 2.0.0

log
(
result: {
readonly finishReason: "completed" | "model-stop" | "budget-exhausted";
readonly turns: number;
readonly output: {
readonly severity: "low" | "medium" | "high" | "critical";
readonly explanation: string;
};
readonly threadId: string & Brand<"@effect-agent/core/ThreadId">;
readonly runId: string & Brand<"@effect-agent/core/RunId">;
readonly exhausted?: "tokens" | "tool-calls" | "turns" | undefined;
readonly runDisposition?: Schema.Json | undefined;
readonly usage?: RunTotals | undefined;
readonly delegatedUsage?: RunTotals | undefined;
}
result
.
output: {
readonly severity: "low" | "medium" | "high" | "critical";
readonly explanation: string;
}
output
)),
import Effect
Effect
.
const provide: <LanguageModel | ProviderName | ModelName, never, OpenAiClient.OpenAiClient>(layer: Layer<LanguageModel | ProviderName | ModelName, never, OpenAiClient.OpenAiClient>, options?: {
readonly local?: boolean | undefined;
} | undefined) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, OpenAiClient.OpenAiClient | Exclude<R, LanguageModel | ProviderName | ModelName>> (+5 overloads)

Provides dependencies to an effect using layers or a context. A layer already built by an enclosing provide or runtime is reused. Sibling provide calls build their own copies. Use options.local to build a fresh layer subtree.

Example (Providing dependencies with a layer)

import { Context, Effect, Layer } from "effect"
interface Database {
readonly query: (sql: string) => Effect.Effect<string>
}
const Database = Context.Service<Database>("Database")
const DatabaseLayer = Layer.succeed(Database)({
query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`))
})
const program = Effect.gen(function*() {
const db = yield* Database
return yield* db.query("SELECT * FROM users")
})
const provided = Effect.provide(program, DatabaseLayer)
await Effect.runPromise(provided) // => "Result for: SELECT * FROM users"

@stability ― stable

@category ― providing services

@since ― 2.0.0

provide
(
import OpenAiLanguageModel
OpenAiLanguageModel
.
const model: (model: (string & {}) | OpenAiLanguageModel.Model, config?: Omit<{
readonly metadata?: {
readonly [x: string]: string;
} | undefined;
readonly top_logprobs?: number | undefined;
readonly temperature?: number | undefined;
readonly top_p?: number | undefined;
readonly user?: string | undefined;
readonly safety_identifier?: string | undefined;
readonly prompt_cache_key?: string | undefined;
readonly prompt_cache_retention?: "24h" | "in_memory" | undefined;
readonly prompt_cache_options?: {
readonly mode?: "explicit" | "implicit" | undefined;
readonly ttl?: "30m" | undefined;
readonly comparison_response_id?: string | null | undefined;
} | undefined;
... 18 more ...;
readonly reasoningModel?: boolean | undefined;
}, "model">) => Model<"openai", LanguageModel, OpenAiClient.OpenAiClient>

Creates an OpenAI model descriptor that can be provided with Effect.provide.

When to use

Use when you want an OpenAI language model value that carries provider and model metadata and can be supplied directly to an Effect program.

@see ― layer for creating a LanguageModel.LanguageModel layer directly

@see ― make for constructing the language model service effectfully

@stability ― unstable

@category ― constructors

@since ― 4.0.0

model
("gpt-6-luna")),
import Effect
Effect
.
const provide: <OpenAiClient.OpenAiClient, Config.ConfigError, HttpClient>(layer: Layer<OpenAiClient.OpenAiClient, Config.ConfigError, HttpClient>, options?: {
readonly local?: boolean | undefined;
} | undefined) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, Config.ConfigError | E, HttpClient | Exclude<R, OpenAiClient.OpenAiClient>> (+5 overloads)

Provides dependencies to an effect using layers or a context. A layer already built by an enclosing provide or runtime is reused. Sibling provide calls build their own copies. Use options.local to build a fresh layer subtree.

Example (Providing dependencies with a layer)

import { Context, Effect, Layer } from "effect"
interface Database {
readonly query: (sql: string) => Effect.Effect<string>
}
const Database = Context.Service<Database>("Database")
const DatabaseLayer = Layer.succeed(Database)({
query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`))
})
const program = Effect.gen(function*() {
const db = yield* Database
return yield* db.query("SELECT * FROM users")
})
const provided = Effect.provide(program, DatabaseLayer)
await Effect.runPromise(provided) // => "Result for: SELECT * FROM users"

@stability ― stable

@category ― providing services

@since ― 2.0.0

provide
(
import OpenAiClient
OpenAiClient
.
const layerConfig: (options?: {
readonly apiKey?: Config.Config<Redacted<string> | undefined> | undefined;
readonly apiUrl?: Config.Config<string> | undefined;
readonly organizationId?: Config.Config<Redacted<string> | undefined> | undefined;
readonly projectId?: Config.Config<Redacted<string> | undefined> | undefined;
readonly transformClient?: ((client: HttpClient) => HttpClient) | undefined;
}) => Layer<OpenAiClient.OpenAiClient, Config.ConfigError, HttpClient>

Creates a layer for the OpenAI client from provided Config values.

When to use

Use when you need client settings for OpenAI-compatible APIs to be read from Effect Config values while providing OpenAiClient as a Layer.

Details

Only config values supplied in options are loaded. Omitted fields are passed to make as undefined, and transformClient is forwarded as a plain option.

@see ― make for constructing the client service effectfully

@see ― layer for providing the client from already-resolved options

@stability ― unstable

@category ― layers

@since ― 4.0.0

layerConfig
({
apiKey?: Config.Config<Redacted<string> | undefined> | undefined

The config value to load for the API key.

apiKey
:
import Config
Config
.
function Redacted(name?: string): Config.Config<import("effect/Redacted").Redacted<string>>

Creates a config for a redacted string value. The parsed result is wrapped in a Redacted container that hides the value from logs and toString.

When to use

Use to read secret string settings that should not be exposed in logs or string output.

Details

Shortcut for Config.schema(Schema.Redacted(Schema.String), name).

Example (Reading a secret)

import { Config, ConfigProvider, Effect } from "effect"
const program = Config.Redacted("API_KEY").pipe(Effect.map(String))
const provider = ConfigProvider.fromEnv({
env: {
API_KEY: "sk-1234567890abcdef"
}
})
Effect.runSync(
program.pipe(Effect.provideService(ConfigProvider.ConfigProvider, provider))
) // => "<redacted>"

@see ― String for non-secret string settings

@stability ― stable

@category ― constructors

@since ― 2.0.0

Redacted
("OPENAI_API_KEY") })),
import Effect
Effect
.
const provide: <HttpClient, never, never>(layer: Layer<HttpClient, never, never>, options?: {
readonly local?: boolean | undefined;
} | undefined) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, HttpClient>> (+5 overloads)

Provides dependencies to an effect using layers or a context. A layer already built by an enclosing provide or runtime is reused. Sibling provide calls build their own copies. Use options.local to build a fresh layer subtree.

Example (Providing dependencies with a layer)

import { Context, Effect, Layer } from "effect"
interface Database {
readonly query: (sql: string) => Effect.Effect<string>
}
const Database = Context.Service<Database>("Database")
const DatabaseLayer = Layer.succeed(Database)({
query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`))
})
const program = Effect.gen(function*() {
const db = yield* Database
return yield* db.query("SELECT * FROM users")
})
const provided = Effect.provide(program, DatabaseLayer)
await Effect.runPromise(provided) // => "Result for: SELECT * FROM users"

@stability ― stable

@category ― providing services

@since ― 2.0.0

provide
(
import FetchHttpClient
FetchHttpClient
.
const layer: Layer<HttpClient, never, never>

Layer that provides an HttpClient implementation backed by the configured Fetch function.

When to use

Use when an Effect program should execute HttpClient requests through the platform fetch implementation, especially in browser, edge, or Node.js runtimes with globalThis.fetch.

Details

The layer uses the current Fetch reference and optional RequestInit service for each request. Request-specific method, headers, body, and abort signal are supplied by the client and override matching RequestInit fields.

Gotchas

Fetch behavior comes from the runtime's implementation, so CORS, cookies, redirects, abort handling, and streaming support can vary by platform. fetch follows redirects itself by default, so HttpClient.followRedirects has no effect unless RequestInit sets redirect: "manual". Trace propagation is on by default, and a browser preflight fails unless the target allows b3 and traceparent. Stream request bodies are sent as Web streams with duplex: "half" when the runtime supports it; see StreamBodyFallback for the unsupported case. Any content-length header is removed before calling fetch. Chrome passes the support check but rejects streaming uploads over HTTP/1.1, which surfaces as a TransportError, and browsers only deliver the response after the entire request body has been sent.

@see ― Fetch for supplying the fetch implementation used by this layer

@see ― RequestInit for default RequestInit options applied before request-specific fields

@see ― StreamBodyFallback for opting into buffering on unsupported runtimes

@see ― HttpClient.TracerPropagationEnabled for leaving b3 and traceparent off a browser request

@stability ― unstable

@category ― layers

@since ― 4.0.0

layer
),
import Effect
Effect
.
const provide: <ThreadHistory | Store | SubagentReservations, never, never>(layer: Layer<ThreadHistory | Store | SubagentReservations, never, never>, options?: {
readonly local?: boolean | undefined;
} | undefined) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, ThreadHistory | Store | SubagentReservations>> (+5 overloads)

Provides dependencies to an effect using layers or a context. A layer already built by an enclosing provide or runtime is reused. Sibling provide calls build their own copies. Use options.local to build a fresh layer subtree.

Example (Providing dependencies with a layer)

import { Context, Effect, Layer } from "effect"
interface Database {
readonly query: (sql: string) => Effect.Effect<string>
}
const Database = Context.Service<Database>("Database")
const DatabaseLayer = Layer.succeed(Database)({
query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`))
})
const program = Effect.gen(function*() {
const db = yield* Database
return yield* db.query("SELECT * FROM users")
})
const provided = Effect.provide(program, DatabaseLayer)
await Effect.runPromise(provided) // => "Result for: SELECT * FROM users"

@stability ― stable

@category ― providing services

@since ― 2.0.0

provide
(
import InMemory
InMemory
.
const layer: Layer<ThreadHistory | Store | SubagentReservations, never, never>

Run agents and attached subagents with in-memory conversation history. Provide once around the parent program and all child handler Layers so siblings share history and one reservation ledger. Reuse a Thread ID to continue a conversation. Each parent Run releases its reservation pool after its attached children finish cleanup. Conversations have no per-Thread history quota; individual messages and total host memory are bounded. Use scoped for disposable request workflows within this shared store. Each independent Layer build owns fresh state; state is released when its Scope closes. Process loss loses history and active execution; this Layer provides no crash recovery.

Models, tool handlers, and provider clients remain application-supplied. Default IDs need no Layer; enclosing ID and context-preparation overrides are preserved. For storage-backed history, provide PersistentHistory.layer and a shared SubagentReservationsMemoryLive instead. Durable hosts own their own assembly.

layer
),
);
import BunRuntime
BunRuntime
.
const runMain: <AgentRuntime.AgentRuntimeFailure<Agent.Definition<Schema.String, Schema.Struct<{
readonly severity: Schema.Literals<readonly ["low", "medium", "high", "critical"]>;
readonly explanation: Schema.String;
}>, "Classify the bug report and explain the severity in one sentence.", Toolkit.Toolkit<{}>, undefined, undefined, undefined> & {
readonly id: Brand<"@effect-agent/core/AgentId"> & "triage";
}, never, never> | Config.ConfigError, {
readonly finishReason: "completed" | ... 1 more ... | "budget-exhausted";
... 7 more ...;
readonly delegatedUsage?: RunTotals | undefined;
}>(effect: Effect.Effect<...>, options?: {
readonly disableErrorReporting?: boolean | undefined;
readonly teardown?: Teardown | undefined;
}) => void (+1 overload)

Helps you run a main effect with built-in error handling, logging, and signal management.

When to use

Use to run a Bun application's main Effect with structured error handling, log management, interrupt support, or advanced teardown capabilities.

Details

This function launches an Effect as the main entry point, setting exit codes based on success or failure, handling interrupts (e.g., Ctrl+C), and optionally logging errors. By default, it logs errors and uses a "pretty" format, but both behaviors can be turned off. You can also provide custom teardown logic to finalize resources or produce different exit codes.

An optional object that can include:

  • disableErrorReporting: Turn off automatic error logging.
  • disablePrettyLogger: Avoid adding the pretty logger.
  • teardown: Provide custom finalization logic.

@stability ― unstable

@category ― running

@since ― 4.0.0

runMain
(
const program: Effect.Effect<{
readonly finishReason: "completed" | "model-stop" | "budget-exhausted";
readonly turns: number;
readonly output: {
readonly severity: "low" | "medium" | "high" | "critical";
readonly explanation: string;
};
readonly threadId: string & Brand<"@effect-agent/core/ThreadId">;
readonly runId: string & Brand<"@effect-agent/core/RunId">;
readonly exhausted?: "tokens" | "tool-calls" | "turns" | undefined;
readonly runDisposition?: Schema.Json | undefined;
readonly usage?: RunTotals | undefined;
readonly delegatedUsage?: RunTotals | undefined;
}, AgentRuntime.AgentRuntimeFailure<...> | Config.ConfigError, never>
program
);
bun agent.ts

The result contains schema-validated output, a Thread ID, and execution metadata. A possible output is:

{ "severity": "high", "explanation": "Users are blocked from accessing the application." }

Share the same InMemory.layer across Runs and pass the returned threadId for follow-up input. Providing a fresh Layer around each call creates a separate store. History lasts until its owner Scope closes; active execution has no process-loss recovery.

The repository has complete runnable snippets and a Cloudflare travel planner. Next, add tools, stream progress, or choose what the Thread retains.