Skip to content
Docs

Operations

An operation is the unit of compute in DXOS. It is a typed action that you define once. Whoever needs it runs it: a person through the UI, an agent as a tool, or a trigger. A trigger is an object that starts an operation on a schedule or an event.

An HTTP endpoint has a path, a request body and a response body. An operation has the same three parts: a key, an input schema and an output schema.

A definition is the value that Operation.make builds from metadata and two schemas:

  • The metadata, meta, holds the key, a name, a description and an icon. The key is a DXN, such as com.example.operation.stashedLink.markRead, and it names the operation everywhere it runs. The description is what an agent reads when it decides whether to call the operation.
  • The input and output schemas are Effect schemas. Their field descriptions tell people and agents what to pass.
  • A definition can also list the ECHO types it uses, so the types are known where it runs remotely, and the services its handler needs.

Example (Defining an operation)

src/types/StashedLinkOperation.ts
import * as
import Schema
Schema
from 'effect/Schema';
import * as
import Operation
Operation
from '@dxos/compute/Operation';
import {
import Database
Database
,
import DXN
DXN
,
import Ref
Ref
} from '@dxos/echo';
import {
class StashedLink
StashedLink
} from './StashedLink.ts';
export const
const MarkRead: Operation.Definition<{
readonly link: Ref<StashedLink & OfKind<EntityKind.Object> & Unknown>;
}, void, Database.Service>
MarkRead
=
import Operation
Operation
.
const make: <{
readonly meta: {
readonly key: DXN.DXN;
readonly name: "Mark as read";
readonly description: "Mark a link as read.";
readonly icon: "ph--check-circle--regular";
};
readonly services: readonly [typeof Database.Service];
readonly input: Schema.Struct<{
readonly link: Schema.Codec<Ref<StashedLink & OfKind<EntityKind.Object> & Unknown>, EncodedReference, never, never>;
}>;
readonly output: Schema.Void;
}>(props: {
readonly meta: {
readonly key: DXN.DXN;
readonly name: "Mark as read";
readonly description: "Mark a link as read.";
readonly icon: "ph--check-circle--regular";
};
readonly services: readonly [typeof Database.Service];
readonly input: Schema.Struct<{
readonly link: Schema.Codec<Ref<StashedLink & OfKind<EntityKind.Object> & Unknown>, EncodedReference, never, never>;
}>;
readonly output: Schema.Void;
}) => Operation.Definition<...>

Creates a new Operation definition. Applies default executionMode of 'async' if not specified. The returned type preserves the literal types of props (including services).

make
({
meta: {
readonly key: DXN.DXN;
readonly name: "Mark as read";
readonly description: "Mark a link as read.";
readonly icon: "ph--check-circle--regular";
}
meta
: {
key: DXN.DXN
key
:
import DXN
DXN
.
const make: <"com.example.operation.stashedLink.markRead">(nsid: "com.example.operation.stashedLink.markRead", version?: string) => DXN.DXN

Constructs a DXN from an NSID (and optional version). Throws if the result is not a valid DXN. Use tryMake for non-throwing string parsing.

Static NSID strings are validated at compile time via

Name

: the final segment must be camelCase (no hyphens). Template-literal strings with a runtime prefix are accepted here but still validated at runtime.

@example make('org.dxos.type.calendar') → 'dxn:org.dxos.type.calendar'

@example make('org.dxos.type.calendar', '1.0.0') → 'dxn:org.dxos.type.calendar:1.0.0'

make
('com.example.operation.stashedLink.markRead'),
name: "Mark as read"
name
: 'Mark as read',
description: "Mark a link as read."
description
: 'Mark a link as read.',
icon: "ph--check-circle--regular"
icon
: 'ph--check-circle--regular',
},
// The handler resolves the reference in the link's space.
services: readonly [typeof Database.Service]
services
: [
import Database
Database
.
class Service

Effect service tag for Database dependency injection.

Service
],
input: Schema.Struct<{
readonly link: Schema.Codec<Ref<StashedLink & OfKind<EntityKind.Object> & Unknown>, EncodedReference, never, never>;
}>
input
:
import Schema
Schema
.
function Struct<{
readonly link: Schema.Codec<Ref<StashedLink & OfKind<EntityKind.Object> & Unknown>, EncodedReference, never, never>;
}>(fields: {
readonly link: Schema.Codec<Ref<StashedLink & OfKind<EntityKind.Object> & Unknown>, EncodedReference, never, never>;
}): Schema.Struct<{
readonly link: Schema.Codec<Ref<StashedLink & OfKind<EntityKind.Object> & Unknown>, EncodedReference, never, never>;
}>

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. Field definitions are discovered from own enumerable string and symbol properties of fields. Non-enumerable and inherited definitions are ignored.

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 on the input may be non-enumerable or 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
({
link: Schema.Codec<Ref<StashedLink & OfKind<EntityKind.Object> & Unknown>, EncodedReference, never, never>
link
:
import Ref
Ref
.
const Ref: <typeof StashedLink>(type: typeof StashedLink) => Ref.RefSchema<StashedLink & OfKind<EntityKind.Object> & Unknown> (+3 overloads)
Ref
(
class StashedLink
StashedLink
).
BottomWithoutNew<unknown, unknown, unknown, unknown, AST, Top, unknown, unknown, any, unknown, Mutability, Optionality, ConstructorDefault, Mutability, Optionality>.annotate(annotations: Schema.Annotations.Bottom<Ref<StashedLink & OfKind<EntityKind.Object> & Unknown>, any>): Schema.Codec<Ref<StashedLink & OfKind<EntityKind.Object> & Unknown>, EncodedReference, never, never>
annotate
({
Annotations.Augment.description?: string | undefined
description
: 'The link that was read.',
}),
}),
output: Schema.Void
output
:
import Schema
Schema
.
const Void: Schema.Void

Type-level representation of

Void

.

Schema for a TypeScript void return value.

When to use

Use when you need to model the return value of a function, RPC, or endpoint whose result is intentionally ignored.

Details

Runtime parsing accepts any present value and discards it, producing undefined. The public decoded and encoded TypeScript representation remains void, so typed construction, decoding, and encoding APIs are still modeled as void.

@stability ― stable

@category ― models

@since ― 3.10.0

@see ― Undefined for a schema that matches only the exact undefined value.

@stability ― stable

@category ― schemas

@since ― 3.10.0

Void
,
});

MarkRead has no handler yet. Its one input field, link, is a reference to the link, not the link itself, and its output is Schema.Void, so a caller gets nothing back.

A handler takes the input and returns an Effect that produces the output. Operation.withHandler attaches one to a definition.

Example (Attaching a handler)

src/operations/mark-read.ts
import * as
import Effect
Effect
from 'effect/Effect';
import * as
import Operation
Operation
from '@dxos/compute/Operation';
import {
import Database
Database
,
import Obj
Obj
} from '@dxos/echo';
import {
class StashedLink
StashedLink
} from '../types/StashedLink.ts';
import {
const MarkRead: Operation.Definition<{
readonly link: Ref<StashedLink & OfKind<EntityKind.Object> & Obj.Unknown>;
}, void, Database.Service>
MarkRead
} from '../types/StashedLinkOperation.ts';
const
const handler: Operation.WithHandler<Operation.Definition<{
readonly link: Ref<StashedLink & OfKind<EntityKind.Object> & Obj.Unknown>;
}, void, Database.Service>>
handler
:
import Operation
Operation
.
type WithHandler<T extends Operation.Definition.Any> = T & {
handler: Operation.Definition.HandlerType<T>;
}
WithHandler
<typeof
const MarkRead: Operation.Definition<{
readonly link: Ref<StashedLink & OfKind<EntityKind.Object> & Obj.Unknown>;
}, void, Database.Service>
MarkRead
> =
const MarkRead: Operation.Definition<{
readonly link: Ref<StashedLink & OfKind<EntityKind.Object> & Obj.Unknown>;
}, void, Database.Service>
MarkRead
.
Pipeable.pipe<Operation.Definition<{
readonly link: Ref<StashedLink & OfKind<EntityKind.Object> & Obj.Unknown>;
}, void, Database.Service>, Operation.WithHandler<Operation.Definition<{
readonly link: Ref<StashedLink & OfKind<EntityKind.Object> & Obj.Unknown>;
}, void, Database.Service>>>(this: Operation.Definition<...>, ab: (_: Operation.Definition<{
readonly link: Ref<StashedLink & OfKind<EntityKind.Object> & Obj.Unknown>;
}, void, Database.Service>) => Operation.WithHandler<...>): Operation.WithHandler<...> (+21 overloads)
pipe
(
import Operation
Operation
.
const withHandler: <Operation.Definition<{
readonly link: Ref<StashedLink & OfKind<EntityKind.Object> & Obj.Unknown>;
}, void, Database.Service>, EntityNotFoundError>(handler: Operation.Handler<{
readonly link: Ref<StashedLink & OfKind<EntityKind.Object> & Obj.Unknown>;
}, void, EntityNotFoundError, Database.Service | Operation.Service>) => (op: Operation.Definition<{
readonly link: Ref<StashedLink & OfKind<EntityKind.Object> & Obj.Unknown>;
}, void, Database.Service>) => Operation.WithHandler<...> (+1 overload)
withHandler
(({
link: Ref<StashedLink & OfKind<EntityKind.Object> & Obj.Unknown>
link
:
ref: Ref<StashedLink & OfKind<EntityKind.Object> & Obj.Unknown>
ref
}) =>
import Effect
Effect
.
const gen: <Effect.Effect<StashedLink & OfKind<EntityKind.Object>, EntityNotFoundError, Database.Service>, void>(f: () => Generator<Effect.Effect<StashedLink & OfKind<EntityKind.Object>, EntityNotFoundError, Database.Service>, void, never>) => Effect.Effect<void, EntityNotFoundError, Database.Service> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to use

Use when you want to write effectful code that looks and behaves like synchronous code, while still handling asynchronous tasks, errors, and complex control flow such as loops and conditions.

Generator functions work similarly to async/await but keep errors, requirements, and interruption in the Effect type. You can yield* values from effects and return the final result at the end.

Example (Sequencing effects with generators)

import { Data, Effect } from "effect"
class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {}
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, DiscountRateError> =>
discountRate === 0
? Effect.fail(new DiscountRateError())
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function*() {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})
await Effect.runPromise(program) // => "Final amount to charge: 96"

@stability ― stable

@category ― constructors

@since ― 2.0.0

gen
(function* () {
// The assistant passes a reference by id, so look it up in the space.
const
const link: StashedLink & OfKind<EntityKind.Object>
link
= yield*
import Database
Database
.
const resolve: <typeof StashedLink>(ref: URI | Ref<any>, schema: typeof StashedLink) => Effect.Effect<StashedLink & OfKind<EntityKind.Object>, EntityNotFoundError, Database.Service> (+1 overload)
resolve
(
ref: Ref<StashedLink & OfKind<EntityKind.Object> & Obj.Unknown>
ref
,
class StashedLink
StashedLink
);
import Obj
Obj
.
const update: <StashedLink & OfKind<EntityKind.Object>>(obj: StashedLink & OfKind<EntityKind.Object>, callback: ChangeCallback<StashedLink & OfKind<EntityKind.Object>>) => StashedLink & OfKind<EntityKind.Object>

Perform mutations on an echo object within a controlled context.

All mutations within the callback are batched and trigger a single notification when the callback completes. Direct mutations outside of Obj.update will throw an error for echo objects.

This function also works with nested objects within echo objects (e.g., Template structs) that are reactive at runtime.

@param ― obj - The echo object to mutate. Use Relation.update for relations.

@param ― callback - The callback that performs mutations on the object.

@example

const person = Obj.make(Person, { name: 'John', age: 25 });
// Mutate within Obj.update
Obj.update(person, (obj) => {
obj.name = 'Jane';
obj.age = 30;
});
// ONE notification fires here
// Direct mutation throws
person.name = 'Bob'; // Error: Cannot modify outside Obj.update()

Note: Only accepts objects. Use Relation.update for relations.

@performance ― Synchronous; costs the mutations made in the callback plus one batched notification and an O(owning fields) parent pass.

update
(
const link: StashedLink & OfKind<EntityKind.Object>
link
, (
link: {
title?: string | undefined;
url?: string | undefined;
note?: string | undefined;
read?: boolean | undefined;
id: EntityId;
"~@dxos/echo/Kind": EntityKind.Object;
}
link
) => {
link: {
title?: string | undefined;
url?: string | undefined;
note?: string | undefined;
read?: boolean | undefined;
id: EntityId;
"~@dxos/echo/Kind": EntityKind.Object;
}
link
.
read?: boolean | undefined
read
= true;
});
}),
),
);
export default
const handler: Operation.WithHandler<Operation.Definition<{
readonly link: Ref<StashedLink & OfKind<EntityKind.Object> & Obj.Unknown>;
}, void, Database.Service>>
handler
;

handler is the MarkRead definition with its handler attached. The handler can call Database.resolve because the definition lists Database.Service. It then sets read to true inside Obj.update.

The definition and the handler are separate values, so a package can publish the definition for others to call without shipping how it runs.

Operation.lazyHandler names the module that holds the handler. Use it when the code should load only on the first call.

A handler set is a group of handlers that a runtime loads together. A PLEX plugin contributes one through a capability. See PLEX’s Operations.

The invoker runs an operation for a caller. It does four things in order:

  1. It finds the handler by the definition’s key.
  2. It checks the input against the input schema.
  3. It runs the handler with the services it declared.
  4. It checks the output.

The operation registry holds each definition as an ECHO object, so agents and the MCP server can search the operations a space offers. A definition whose metadata sets skipRegistry is left out of it.

A definition carries hints for its callers:

Annotation Says
Mutation Whether the operation changes nothing, writes, or destroys data
Idempotent Whether running it twice with the same input has the same effect as once
Visible Whether people can pick it, as in a trigger’s operation picker. Unmarked operations are hidden
  • One definition serves every caller. A button, the command palette, an agent and a trigger invoke the same key with the same input.
  • Errors are typed. A handler fails with tagged errors that the caller catches by tag. If you invoke a key that no handler set serves, the call fails with NoHandlerError.
  • A handler can stop early when its run is cancelled. It reads the run’s AbortSignal from Cancellation.signal in @dxos/compute, and hands the signal to work that can stop, such as a fetch.
  • The runtime that runs the operation fires the signal. In the app, it fires when the process is terminated, and the runtime then interrupts the handler. On EDGE, it fires when the client asks to cancel the run, and the handler is not interrupted.
  • If the runtime provides no cancellation, the signal never fires.
  • An operation can invoke other operations. The call is linked to the caller’s process, so the trace shows which call started it.
  • When you deploy an operation to EDGE, EDGE assigns it a deployment id. A client can invoke it there by that id or by its key.
  • Every call writes its start and end to the trace.
  • Input and output must be serializable, because a call may cross to a browser worker or to EDGE. Pass ECHO objects by reference.
  • A handler gets only the services its definition declares and the ones every process has. It does not get the UI.
  • An operation that sets skipRegistry is not in the operation registry, so agents and the MCP server cannot find it. Use it for an operation that only makes sense in the UI.