Derive selected background Tools directly from a child Agent, using its ID as the delegation
name and its input/output Schemas as the default contract. Pass an explicit Subagent.make
declaration to customize the name, projections, grants, or policy bounds.
A start returns { worker, delivery }. The delivery’s message reference identifies the retained
input; its receipt appears after destination acceptance. A pending delivery is queued for
delivery and says nothing about child execution. The parent keeps responding, and a
WorkerCompletion message arrives when the child run ends. It contains the projected result
or a bounded failure, the worker and run identities, and a budget-exhaustion flag. Finishing
or aborting the parent run leaves the worker and pending report running.
Reports join an active parent run at an input boundary or start a later run in the same thread.
The framework delivers them separately from the parent’s application input: no report tags,
mapper, input union, or extra host registration is required. Existing callers must opt in.
}>,"Use waiting when you need an answer; completed only when the assignment is done.",Toolkit.Toolkit<{}>,Schema.Literals<readonly["completed","waiting"]>,undefined>(id:"task",options:Agent.DefinitionOptions<Schema.String,Schema.Struct<{
}>,"Use waiting when you need an answer; completed only when the assignment is done.",Toolkit.Toolkit<...>,Agent.RunDispositionDeclaration<...>,undefined,undefined>&{
...;
}):Agent.Definition<...>&{
...;
}(+3overloads)
Validate an agent ID and return a shallowly frozen, model-agnostic definition.
make("task",{
DefinitionOptions<String,Struct<{ readonlystatus:Literals<readonly ["completed","waiting"]>;readonlyanswer:String; }>,"Use waiting when you need an answer; completed only when the assignment is done.",Toolkit<...>,RunDispositionDeclaration<...>,undefined,undefined>.input: Schema.String
input:
importSchema
Schema.
constString:Schema.String
Type-level representation of
String
.
Schema for string values. Validates that the input is typeof"string".
@category ― models
@since ― 4.0.0
@category ― schemas
@since ― 4.0.0
String,
DefinitionOptions<String,Struct<{ readonlystatus:Literals<readonly ["completed","waiting"]>;readonlyanswer:String; }>,"Use waiting when you need an answer; completed only when the assignment is done.",Toolkit<...>,RunDispositionDeclaration<...>,undefined,undefined>.output: Schema.Struct<{
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.
Assignment output selected through the Definition's runDisposition declaration.
AssignmentDisposition,
answer:Schema.String
answer:
importSchema
Schema.
constString:Schema.String
Type-level representation of
String
.
Schema for string values. Validates that the input is typeof"string".
@category ― models
@since ― 4.0.0
@category ― schemas
@since ― 4.0.0
String}),
DefinitionOptions<String,Struct<{ readonlystatus:Literals<readonly ["completed","waiting"]>;readonlyanswer:String; }>,"Use waiting when you need an answer; completed only when the assignment is done.",Toolkit<...>,RunDispositionDeclaration<...>,undefined,undefined>.instructions: "Use waiting when you need an answer; completed only when the assignment is done."
instructions:"Use waiting when you need an answer; completed only when the assignment is done.",
DefinitionOptions<String,Struct<{ readonlystatus:Literals<readonly ["completed","waiting"]>;readonlyanswer:String; }>,"Use waiting when you need an answer; completed only when the assignment is done.",Toolkit<...>,RunDispositionDeclaration<...>,undefined,undefined>.toolkit: Toolkit.Toolkit<{}>
toolkit:
importToolkit
Toolkit.
constempty: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.
Opt background workers into one retained assignment. The encoded disposition must be
Worker.AssignmentDisposition: completed seals the worker, waiting leaves it steerable.
Failures and exhausted Runs seal as failed; aborting an active Run seals as cancelled.
The worker origin retains this choice. Omission preserves reusable workers.
Pure selection from decoded output. undefined declares none, except for assignments.
fromOutput:(
output:{
readonlystatus:"completed"|"waiting";
readonlyanswer:string;
}
output)=>
output:{
readonlystatus:"completed"|"waiting";
readonlyanswer:string;
}
output.
status:"completed"|"waiting"
status,
},
});
Start and steer Task through the same background APIs. A waiting result ends that run and
keeps the assignment steerable. A completed result permanently seals the assignment only after
its latest accepted instructions have been applied. Failed or exhausted runs also seal it.
Inspect the worker’s state to distinguish assignment completion from a completed run.
The choice is retained at worker creation; existing workers and definitions without this opt-in
remain reusable. See the terminal contract.
Declare the update Schema on the Agent once, then enable parent reporting:
background-updates.ts
import{
importAgent
Agent,
importSubagent
Subagent }from"@yielded/agent";
import{
importSchema
Schema }from"effect";
import{
importToolkit
Toolkit }from"effect/ai";
exportconst
constHotelRequest:Schema.Struct<{
readonlycity:Schema.String;
readonlyarea:Schema.String;
readonlysources:Schema.$Array<Schema.Struct<{
readonlyurl:Schema.String;
readonlynotes:Schema.String;
}>>;
}>
HotelRequest=
importSchema
Schema.
functionStruct<{
readonlycity:Schema.String;
readonlyarea:Schema.String;
readonlysources:Schema.$Array<Schema.Struct<{
readonlyurl:Schema.String;
readonlynotes:Schema.String;
}>>;
}>(fields:{
readonlycity:Schema.String;
readonlyarea:Schema.String;
readonlysources:Schema.$Array<Schema.Struct<{
readonlyurl:Schema.String;
readonlynotes:Schema.String;
}>>;
}):Schema.Struct<{
readonlycity:Schema.String;
readonlyarea:Schema.String;
readonlysources:Schema.$Array<Schema.Struct<{
readonlyurl:Schema.String;
readonlynotes: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.
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.
Creates a struct schema with an automatically populated _tag field.
When to use
Use to define a tagged union case from a literal tag and a set of fields.
Details
When using the make method, the _tag field is optional and will be
added automatically. However, when decoding or encoding, the _tag field
must be present in the input.
Example (Defining a tagged struct shorthand)
import{ Schema }from"effect"
// Defines a struct with a fixed `_tag` field
consttagged=Schema.TaggedStruct("A",{
a:Schema.String
})
// This is the same as writing:
constequivalent=Schema.Struct({
_tag:Schema.tag("A"),
a:Schema.String
})
voidtagged
voidequivalent
Example (Accessing the literal value of the tag)
import{ Schema }from"effect"
consttagged=Schema.TaggedStruct("A",{
a:Schema.String
})
tagged.fields._tag.schema.literal// => "A"
@category ― constructors
@since ― 3.10.0
TaggedStruct("AreaConcern",{
area:Schema.String
area:
importSchema
Schema.
constString:Schema.String
Type-level representation of
String
.
Schema for string values. Validates that the input is typeof"string".
@category ― models
@since ― 4.0.0
@category ― schemas
@since ― 4.0.0
String,
finding:Schema.String
finding:
importSchema
Schema.
constString:Schema.String
Type-level representation of
String
.
Schema for string values. Validates that the input is typeof"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.
Derive selected background Tools directly from a child Agent, using its ID as the delegation
name and its input/output Schemas as the default contract. Pass an explicit Subagent.make
declaration to customize the name, projections, grants, or policy bounds.
Save as background-updates.ts. This example reviews source notes supplied in its input; add your
research tools to its toolkit for live retrieval. The native emit_update tool accepts
{ value: AreaConcern }. Its acknowledgement retains the finding and lets the child continue.
An update is provisional information, independent of the final hotel result.
Give a coordinator hotels.toolkit and provide hotels.layer. Register the exact
HotelResearcher definition alongside that coordinator, using the host setup below.
With reportToParent: true, the parent receives both WorkerUpdate and WorkerCompletion
without an application input union, mapper, or reporting entry. Agents without updates
continue to send only completion.
The parent consumes the finding at a safe input boundary or in a later run. It can explain the
concern, ask the user how to proceed, and use follow-up tools to redirect the hotel worker and
other workers to Rosebank. Emission does not wait for a user decision or stop the child.
See update delivery guarantees for ordering,
backpressure, and recovery.
Derive selected background Tools directly from a child Agent, using its ID as the delegation
name and its input/output Schemas as the default contract. Pass an explicit Subagent.make
declaration to customize the name, projections, grants, or policy bounds.
Finite, positive wall-clock duration accepted in any Effect Duration input form.
maxDuration:"2 minutes",
toolConcurrency?:number|undefined
toolConcurrency:2},
});
Save as background-coordinator.ts. This uses the
activity researcher directly.
The default result is { output, budgetExhausted }. Use an explicit Subagent.make declaration
when the parent should receive a custom result projection.
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.
Schema for string values. Validates that the input is typeof"string".
@category ― models
@since ― 4.0.0
@category ― schemas
@since ― 4.0.0
String});
Save as background-input.ts. Instructions and host policy keep the original admitted
application input as their context. For a completion, the framework renders the typed message
instead of calling the application’s inputPrompt again.
Acquire a complete Node host and start one bounded, scoped worker pool after recovery.
Own the SQLite file exclusively until the host and its storage close. A second connection
fails construction; after process death the replacement retires abandoned claims before
recovery, without waiting for their leases. Use this host's services for live inspection.
Provide model, tool, instruction, and schema dependencies to this Layer. Reusing the Layer
shares the same pool. A worker failure closes admission; observe it with run at the process
boundary so the application exits and releases the host instead of remaining idle.
Feeds the output services of the dependency layer into the requirements of
this layer, returning a layer that only provides the services from this layer.
When to use
Use when you need to hide an implementation dependency layer from callers.
Details
In serviceLayer.pipe(Layer.provide(dependencyLayer)), the dependency layer is
built first and is used to satisfy the requirements of serviceLayer.
Feeds the output services of the dependency layer into the requirements of
this layer, returning a layer that only provides the services from this layer.
When to use
Use when you need to hide an implementation dependency layer from callers.
Details
In serviceLayer.pipe(Layer.provide(dependencyLayer)), the dependency layer is
built first and is used to satisfy the requirements of serviceLayer.
Feeds the output services of the dependency layer into the requirements of
this layer, returning a layer that only provides the services from this layer.
When to use
Use when you need to hide an implementation dependency layer from callers.
Details
In serviceLayer.pipe(Layer.provide(dependencyLayer)), the dependency layer is
built first and is used to satisfy the requirements of serviceLayer.
Feeds the output services of the dependency layer into the requirements of
this layer, returning a layer that only provides the services from this layer.
When to use
Use when you need to hide an implementation dependency layer from callers.
Details
In serviceLayer.pipe(Layer.provide(dependencyLayer)), the dependency layer is
built first and is used to satisfy the requirements of serviceLayer.
Save as background-host.ts. Each entry registers an agent and its code versions with the host.
The host discovers reporting from the coordinator’s background tools.
The Layers supply tool handlers, provider credentials, and worker access.
The host recovers accepted work and pending reports after restarts. Keep report preparation
free of external side effects: recovery may repeat it before its decision is recorded.
Conclusive refusal before destination admission closes the retained source input and releases
its capacity without a destination receipt or acknowledgement. Ambiguous delivery remains owed.
Stable host-authenticated admission principal; the established durable brand is preserved.
Principal }from"@yielded/agent/submission-ledger";
import{
classWorkerError
Closed host-boundary failures. Original causes stay private and survive diagnostic transport.
Retained delivery states are successful MessageStatus values, including pending and refused.
After a storage failure, keep the same idempotency key and parameters when reconciling.
Decodes a typed input (the schema's Encoded type) against a schema
synchronously, returning the decoded value or throwing a
SchemaError
for schema mismatches.
When to use
Use when you already have input typed as the schema's Encoded type and
want schema mismatches to throw SchemaError synchronously.
Details
For unknown input use decodeUnknownSync.
Only service-free schemas can be decoded synchronously. Options may be
provided either when creating the decoder or when applying it; application
options override creation options.
Gotchas
Non-schema failures may throw a runtime failure instead of SchemaError.
@see ― SchemaParser.decodeSync for the adapter that throws an Error whose cause is SchemaIssue.Issue
Decodes a typed input (the schema's Encoded type) against a schema
synchronously, returning the decoded value or throwing a
SchemaError
for schema mismatches.
When to use
Use when you already have input typed as the schema's Encoded type and
want schema mismatches to throw SchemaError synchronously.
Details
For unknown input use decodeUnknownSync.
Only service-free schemas can be decoded synchronously. Options may be
provided either when creating the decoder or when applying it; application
options override creation options.
Gotchas
Non-schema failures may throw a runtime failure instead of SchemaError.
@see ― SchemaParser.decodeSync for the adapter that throws an Error whose cause is SchemaIssue.Issue
Closed host-boundary failures. Original causes stay private and survive diagnostic transport.
Retained delivery states are successful MessageStatus values, including pending and refused.
After a storage failure, keep the same idempotency key and parameters when reconciling.
Constructs a value from the make input representation synchronously.
When to use
Use when constructor input is trusted or when validation failure
should abort with a thrown Error.
Details
Applies constructor defaults and type-side validation according to
MakeOptions.
Gotchas
Throws an Error with the schema issue in its cause when validation
fails. Schema validation failures use the generic message
"Schema validation failed"; format the cause explicitly with
SchemaIssue.makeFormatterDefault() when human-readable details are needed.
Causes that contain defects, interruptions, or other non-schema reasons
throw with the underlying Cause attached instead.
@see ― BottomWithoutNew.makeOption — construct synchronously and discard validation details
@see ― BottomWithoutNew.makeEffect — construct through Effect when validation failure should stay in the error channel
Save as background-access.ts. Worker access denies by default; this local example permits
one user and conversation. In an application, check authenticated identity and thread ownership.
Helps you run a main effect with built-in error handling, logging, and signal management.
When to use
Use to run a Node.js 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.
The optional configuration object can include:
disableErrorReporting: Turn off automatic error logging.
Supervise the host's existing workers without starting another pool. Use with
Effect.provide(HostLive) and NodeRuntime.runMain; race it with a server Effect when
the same process also serves requests. Unlike Layer.launch, this observes worker failures.
Provides dependencies to an effect using layers or a context. Use options.local
to build the layer every time; by default, layers are shared between provide
calls.
Save as background-main.ts and run with node --experimental-transform-types background-main.ts.
Use the Node.js setup to submit
BackgroundCoordinator with the exported principal, threadId, and this input:
{"text":"Find food and walking activities in Lisbon."}
Keep the host running so research and report delivery can progress. The
Cloudflare runtime supports the same contracts.
A follow-up returns its retained delivery state and joins an active worker run at a safe input
boundary or starts a later run. Keep the returned message reference: inspect that delivery or wait
for a report instead of sending the command again. Opt in to inspect, list, or cancel tools
when needed. Inspection accepts a message reference for delivery state or a receipt for a saved
result. Cancellation targets one input’s receipt; it does not close the worker. Application code can
permanently seal the worker with Subagent.stop and a stable command key. See the
control contract for stop and input
application facts.
Several inputs joining one run produce one logical report.
An input cancelled before it starts a run produces no completion message.
Workers share a bounded allocation from their source by default. Host lifetime and concurrency
limits still apply. See independent budgets
for separately funded work.