Skip to content

Processes and Domain models

A process has no output, so it needs somewhere to report. A Domain model is a good place: a session issues commands and reads views like any other client, and the model’s policies decide when there is work for one.

A model’s commands and views are members of its class. Mention one in a process’s prose, and a session may use it:

src/Assistant.process.ts
import * as AI from "@alchemy.run/ai";
import { Bank } from "./Bank.ts";
export class Assistant extends AI.Process<Assistant>()("Assistant", {
description: "Help one customer with their account.",
})`
Take a deposit with ${Bank.DepositMoney}. Pay money out with ${Bank.WithdrawMoney}.
Read the balance with ${Bank.AccountSummary}.
` {}

Each mention is a tool: Bank_DepositMoney_send, Bank_WithdrawMoney_send and Bank_AccountSummary_get, with the command’s or the view’s own schemas. Nothing else in the bank is within the session’s reach. A rejection comes back to the model as the tool’s failure, so it can read why and try again.

Assistant requires the hosted Bank: provide Bank.layer(...) where the process runs.

An aggregate is every command it takes:

`Do what the customer asks with ${Bank.Account}.`

Mention a single command where you can. An aggregate grows, and what a session may do grows with it.

A command says which middleware guards it. DepositMoney is behind Session, which says who is calling by providing CurrentActor:

export class DepositMoney extends Domain.Command("DepositMoney", {
middleware: [Session],
input: { accountId: AccountId, amount: Schema.Int },
events: [Deposited],
rejects: [NotOwner],
}) {}

A session has no cookie to show. It is started as someone, and that answers every middleware which only says who is calling:

yield* assistant.start(customer.customerId, { as: CurrentActor.context(customer) });

as is required: start does not compile without a CurrentActor, because Assistant mentions a command that needs one. It is kept with the session and never shown to the model. Every command the session sends runs as that customer, so the model’s own rules decide what happens: a session started as Ada cannot touch Bob’s account, because decide rejects it.

Authenticate the person where you already do, in your Worker, and start the session as them:

const customer = actorOf(request.headers);
if (customer === undefined) return HttpServerResponse.text("sign in", { status: 401 });
const answer = yield* assistants.getByName(customer.customerId).chat(customer, yield* request.text);

WithdrawMoney is also behind MfaChallenge, which provides nothing: it checks a second factor on each call. What a session is started as cannot answer that. Say what the check means for a session, as a Layer where the process runs:

/** A session can't pass a second factor, so it may not make a call that needs one. */
const MfaForSessions = Layer.succeed(MfaChallenge, () => Effect.fail(new MfaRequired()));

Assistant does not compile without a Layer for MfaChallenge, because it mentions WithdrawMoney. With this one, the model is told MfaRequired when it tries to withdraw.

A middleware that has a Layer where the process runs is run with it. So do not provide your HTTP Session Layer there: it would look for a cookie on a session’s call and refuse it.

A command sent by a session takes its id from the tool call that asked for it. A call that runs again after a crash sends its command once, and the model cannot make two commands look like one.

A session chooses which commands to send, so you can’t test every path it might take. State the rules on the aggregate, and verify them: a proved rule holds for every state and every command, whoever sends it.

transitions: {
OnlyLabelingChangesTheLabel: ({ before, after, command }) =>
before._tag !== "Open" ||
after._tag !== "Open" ||
before.label === after.label ||
command._tag === "LabelIssue",
},

Part 5 of the tutorial states and proves the issue board’s rules.

A model should not know that an AI process does part of its work. It declares what it asks for as an external system, and a policy calls that:

src/Triager.external.ts
import * as Domain from "@alchemy.run/domain";
import * as Schema from "effect/Schema";
import { IssueId } from "./Issue.id.ts";
export class Triager extends Domain.ExternalSystem("Triager", {
start: { args: { issue: IssueId } },
tell: { args: { issue: IssueId, text: Schema.String, id: Schema.String } },
}) {}
src/IssueWork.policy.ts
import * as Domain from "@alchemy.run/domain";
import * as Effect from "effect/Effect";
import * as Match from "effect/Match";
import { IssueCommented } from "./CommentOnIssue.command.ts";
import { Issue } from "./Issue.aggregate.ts";
import { IssueReported } from "./ReportIssue.command.ts";
import { Triager } from "./Triager.external.ts";
export class IssueWork extends Domain.Policy("IssueWork", {
from: Issue,
on: [IssueReported, IssueCommented],
}) {}
export const IssueWorkLive = IssueWork.toLayer(
Effect.gen(function* () {
const triager = yield* Triager;
return Effect.fn(function* ({ source, event }) {
yield* Match.valueTags(event, {
IssueReported: () => triager.start({ issue: source.id }),
IssueCommented: ({ body, commentId }) =>
triager.tell({ issue: source.id, text: body, id: commentId }),
});
});
}),
);

A policy never waits for a session. Triage reports by sending LabelIssue, which is an event another policy can react to.

Answer from the session’s Durable Object

Section titled “Answer from the session’s Durable Object”

The adapter for Triager calls the Durable Object that runs the session. A policy can run twice for one event, and requestId keeps a message from being sent twice.

return Effect.succeed({
start: (issue) =>
triage
.get(issue)
.send(`The issue is ${issue}.`, { requestId: "start" })
.pipe(Effect.orDie),
tell: (issue, text, id) => triage.get(issue).send(text, { requestId: id }).pipe(Effect.orDie),
} satisfies Agent);

Using a session requires the runtime context, so these methods do: Agent declares each as Effect.Effect<void, never, RuntimeContext>. A policy’s handler and an external system’s operations run inside the runtime and carry the same requirement, so the call type-checks from the policy to the session with nothing passed along by hand.

The session sends commands to the model, so its object hosts the model. The model’s policy calls the session’s object. Host the model with a function of a handle on the objects: inside an object that handle is its own namespace, and in the Worker it is the class.

const boardOver = <R>(agents: Effect.Effect<Agents, never, R>) =>
Board.layer(IssueWorkLive).pipe(
Layer.provide(
Layer.mergeAll(
DomainCloudflare.layerDurableObjects(),
Triager.toLayer(
Effect.map(agents, (agents) => ({
start: ({ issue }) => agents.getByName(issue).start(issue),
tell: ({ issue, text, id }) => agents.getByName(issue).tell(issue, text, id),
})),
),
),
),
);

The tutorial builds this one step at a time, and examples/cloudflare-ai-issues is the whole of it.