Connect a front end
A front end needs two things from a session: a live view of what it does, and a way to act on it. The way that needs nothing new is to make the session part of your Domain model. The front end then talks to one Api: it sends commands, and watches the agent’s status and transcript like any other view and stream.
The code is from the cloudflare-ai-issues example, which has a web page for an issue.
Record what the session does
Section titled “Record what the session does”One command carries a batch of what a session reported: its status, what is queued, and the items it stored. @alchemy.run/ai/Session has the Schemas.
import { QueuedMessage, SessionEntry } from "@alchemy.run/ai/Session";import * as Domain from "@alchemy.run/domain";import * as Schema from "effect/Schema";import { IssueId } from "./Issue.id.ts";
export const Status = Schema.Literals(["idle", "working"]);
/** What an issue's session did since the last record: where it stands, and the items it stored. */export class ActivityRecorded extends Domain.Event("ActivityRecorded", { status: Status, queued: Schema.Array(QueuedMessage), items: Schema.Array(SessionEntry),}) {}
/** Sent by the object that runs the session, with a batch of what the session reported. */export class RecordActivity extends Domain.Command("RecordActivity", { input: { issueId: IssueId, status: Status, queued: Schema.Array(QueuedMessage), items: Schema.Array(SessionEntry), }, events: [ActivityRecorded], rejects: [],}) {}An aggregate decides it. It drops the items it already has, so a batch sent twice changes nothing:
import { QueuedMessage } from "@alchemy.run/ai/Session";import * as Domain from "@alchemy.run/domain";import * as Schema from "effect/Schema";import { IssueId } from "./Issue.id.ts";import { ActivityRecorded, RecordActivity, Status } from "./RecordActivity.command.ts";
const sameQueue = (a: ReadonlyArray<QueuedMessage>, b: ReadonlyArray<QueuedMessage>) => a.length === b.length && a.every((message, index) => message.id === b[index]!.id);
/** * The session that looks after one issue, as the board knows it: what the * session's object has recorded of it so far. */export class IssueSession extends Domain.Aggregate("IssueSession", { id: IssueId, state: Schema.Struct({ /** The last item recorded. */ seq: Schema.Number, status: Status, queued: Schema.Array(QueuedMessage), }), initial: { seq: 0, status: "idle", queued: [] }, commands: [RecordActivity], keyOf: (command) => command.issueId, decide: { // Items already recorded are dropped, so a batch sent again changes nothing. RecordActivity: (session, command) => { const items = command.items.filter((entry) => entry.seq > session.seq); const changed = command.status !== session.status || !sameQueue(command.queued, session.queued); return items.length === 0 && !changed ? [] : [new ActivityRecorded({ status: command.status, queued: command.queued, items })]; }, }, evolve: { ActivityRecorded: (session, event) => ({ seq: event.items.at(-1)?.seq ?? session.seq, status: event.status, queued: event.queued, }), },}) {}Show the status as a view
Section titled “Show the status as a view”Whether the agent is working, and what is queued for it, is the latest recorded status:
import { QueuedMessage } from "@alchemy.run/ai/Session";import * as Domain from "@alchemy.run/domain";import * as Schema from "effect/Schema";import { IssueSession } from "./IssueSession.aggregate.ts";import { Status } from "./RecordActivity.command.ts";
/** Whether the issue's session is working, and what is queued for it. */export class SessionStatus extends Domain.View("SessionStatus", { from: [IssueSession], key: IssueSession, state: Schema.Struct({ status: Status, queued: Schema.Array(QueuedMessage) }), initial: { status: "idle", queued: [] }, evolve: { ActivityRecorded: (_, event) => ({ status: event.status, queued: event.queued }), },}) {}Keep the transcript as a stream
Section titled “Keep the transcript as a stream”Each item is one entry of a stream, so a page reads what it missed and then follows:
import { SessionEntry } from "@alchemy.run/ai/Session";import * as Domain from "@alchemy.run/domain";import { IssueSession } from "./IssueSession.aggregate.ts";
/** One item of the transcript: a message, a tool call or a tool result. */export class ItemStored extends Domain.Event("ItemStored", SessionEntry.fields) {}
/** The session's transcript, one entry per item. */export class Transcript extends Domain.Stream("Transcript", { key: IssueSession, entries: [ItemStored],}) {}A projection appends them:
import * as Domain from "@alchemy.run/domain";import * as Effect from "effect/Effect";import { IssueSession } from "./IssueSession.aggregate.ts";import { ActivityRecorded } from "./RecordActivity.command.ts";import { ItemStored, Transcript } from "./Transcript.stream.ts";
/** Appends each recorded item to the transcript. */export class Transcripts extends Domain.Projection("Transcripts", { from: [IssueSession], key: IssueSession, on: [ActivityRecorded], writes: [Transcript],}) {}
export const TranscriptsLive = Transcripts.toLayer( Effect.gen(function* () { const transcript = yield* Transcript; return Effect.fn(function* (batch) { for (const input of batch) { yield* transcript.append(input, ...input.event.items.map((entry) => new ItemStored(entry))); } }); }),);Serve what the front end may use
Section titled “Serve what the front end may use”The Api lists the commands a page may send. RecordActivity is not one of them: only the session’s object sends it.
import * as Domain from "@alchemy.run/domain";import { Board } from "./Board.model.ts";
/** * What the web app may do and read: report an issue, reply on one, and read * every view and stream. Labeling and recording are left out: only the * session's object sends those. */export class WebApi extends Domain.Api("WebApi", { model: Board, commands: ["ReportIssue", "CommentOnIssue"],}) {}Record from the session’s object
Section titled “Record from the session’s object”The object that runs the session reads its events and sends them to the model. live follows the session from the last item the model has. catchUp records everything stored that the model lacks, and says whether the session is done:
/** Send the board a batch of what the session reported. */const report = ( issue: IssueId, status: AI.SessionEvent & { type: "status" }, items: ReadonlyArray<AI.SessionEntry>,) => sessions.send( new RecordActivity({ issueId: issue, status: status.status, queued: status.queued, items }), );
/** * Record the session as it happens: every event after the last item the * board has, a batch at a time. It runs for as long as this instance does. */const live = Effect.fn(function* (issue: IssueId) { const recorded = yield* sessions.get(IssueSession.ref(issue)); let status: AI.SessionEvent & { type: "status" } = { type: "status", status: recorded.status, queued: recorded.queued, }; yield* triage .get(issue) .events({ after: recorded.seq }) .pipe( Stream.groupedWithin(50, "100 millis"), Stream.runForEach((batch) => { const events = Array.from(batch); status = events.findLast((event) => event.type === "status") ?? status; return report( issue, status, events.flatMap((event) => event.type === "item" ? [{ seq: event.seq, item: event.item }] : [], ), ); }), );});
/** * Record everything the session has stored that the board lacks, and say * whether the session is done: idle, with nothing queued. */const catchUp = Effect.fn(function* (issue: IssueId) { const session = triage.get(issue); const status = Option.getOrUndefined(yield* Stream.runHead(session.events())); if (status?.type !== "status") return true; let after = (yield* sessions.get(IssueSession.ref(issue))).seq; while (true) { const page = yield* session.history({ after, take: 100 }); yield* report(issue, status, page.items); if (page.next === undefined) break; after = page.next; } return status.status === "idle" && status.queued.length === 0;});Keep recording through an eviction
Section titled “Keep recording through an eviction”live runs in memory, so it ends when the object is evicted. A job on the object’s alarm makes recording durable. It is stored with the object, wakes it, records what the model lacks, and comes back every five seconds until the session is idle:
let recording = false;/** Start recording live, once for as long as this instance lives. */const follow = (issue: IssueId) => Effect.suspend(() => { if (recording) return Effect.void; recording = true; return state.waitUntil( live(issue).pipe(Effect.ensuring(Effect.sync(() => void (recording = false)))), ); });
/** * What makes recording durable: a job on the object's alarm, kept in * its storage. It wakes the object, records what the board lacks, and * comes back until the session is done, however often the object is * evicted in between. */const again = (issue: IssueId): Effect.Effect<void, never, RuntimeContext> => onRecord.schedule(issue, { after: "5 seconds", payload: issue }).pipe(Effect.orDie);const onRecord: Alchemy.Callback<IssueId> = yield* Alchemy.makeCallback( "record", Effect.fn(function* (issue: IssueId) { yield* follow(issue); if (!(yield* catchUp(issue))) yield* again(issue); }, Effect.orDie),);/** Record from now until the session is done. */const record = (issue: IssueId) => Effect.andThen(follow(issue), again(issue));
return { // The same id however often the event is delivered, so the issue is taken up once. start: (issue) => triage .get(issue) .send(`The issue is ${issue}.`, { requestId: "start" }) .pipe(Effect.andThen(record(issue)), Effect.orDie), tell: (issue, text, id) => triage .get(issue) .send(text, { requestId: id }) .pipe(Effect.andThen(record(issue)), Effect.orDie),} satisfies Agent;The harness already resumes the session itself after an eviction. This job is what makes the model catch up with it.
Act on the session with commands
Section titled “Act on the session with commands”A page does not call the session. It sends a command, and the model’s policy passes it on through a port, as in Processes and Domain models. Here a reply on an issue is CommentOnIssue, and the policy tells the issue’s session. A session that is working queues it.
List every issue
Section titled “List every issue”The page’s sidebar needs every issue at once, with whether its agent is working. That is one more view, over both aggregates and kept under a single key:
import * as Domain from "@alchemy.run/domain";import { pipe } from "effect/Function";import * as Optic from "effect/Optic";import * as Schema from "effect/Schema";import { Issue } from "./Issue.aggregate.ts";import { IssueId } from "./Issue.id.ts";import { IssueSession } from "./IssueSession.aggregate.ts";import { Label } from "./LabelIssue.command.ts";
/** The one key the list is kept under. */export const ALL = "all";
const Listed = Schema.Struct({ title: Schema.String, label: Schema.NullOr(Label), replies: Schema.Int,});
const State = Schema.Struct({ /** Newest first. */ order: Schema.Array(IssueId), issues: Schema.Record(IssueId, Listed), /** The issues whose agent is working now. */ working: Schema.Array(IssueId),});
// Optics into the list. One that focuses on an issue leaves the list as it// is when the issue is not in it, which keeps evolve total.const list = Optic.id<typeof State.Type>();const order = list.key("order");const working = list.key("working");const listed = (id: IssueId) => list.key("issues").optionalKey(id);const issue = (id: IssueId) => list.key("issues").at(id);
const without = (id: IssueId) => (ids: ReadonlyArray<IssueId>) => ids.filter((each) => each !== id);
/** * Every issue of the board, newest first, with whether its agent is working: * what the page's sidebar shows. It is one entry, which suits a board of a * few hundred issues. */export class IssueList extends Domain.View("IssueList", { from: [Issue, IssueSession], key: Schema.String, keyOf: { IssueReported: () => ALL, IssueLabeled: () => ALL, IssueCommented: () => ALL, ActivityRecorded: () => ALL, }, state: State, initial: { order: [], issues: {}, working: [] }, evolve: { IssueReported: (state, event, { source }) => pipe( state, order.modify((ids) => [source.id, ...without(source.id)(ids)]), listed(source.id).modify(() => ({ title: event.title, label: null, replies: 0 })), ), IssueLabeled: (state, event, { source }) => issue(source.id) .key("label") .modify(() => event.label)(state), IssueCommented: (state, _, { source }) => issue(source.id) .key("replies") .modify((replies) => replies + 1)(state), ActivityRecorded: (state, event, { source }) => working.modify((ids) => event.status === "working" ? [...without(source.id)(ids), source.id] : without(source.id)(ids), )(state), },}) {}Views are stored, so the list and every transcript are still there after a refresh or a deploy.
Read it in a Foldkit app
Section titled “Read it in a Foldkit app”DomainFoldkit.make gives a Command for each command of the Api, and watch and events for each view and stream. Opening another issue changes the key the reads follow.
The page never waits for the board before it shows something. It keeps what it has read of every issue it opened, so going back to one is instant. A new issue or a reply is put in pending and shown at once, then dropped when the board’s own copy arrives, or taken back when the board refuses it:
import { QueuedMessage, SessionEntry } from "@alchemy.run/ai/Session";import type * as Domain from "@alchemy.run/domain";import * as DomainFoldkit from "@alchemy.run/domain/Foldkit";import * as Effect from "effect/Effect";import * as Option from "effect/Option";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";import { Command, Subscription, type Update } from "foldkit";import { defineMessageUnion } from "foldkit/message";import { modifyFields } from "foldkit/struct";import { IssueId } from "../../src/Board/Issue.id.ts";import { ALL } from "../../src/Board/IssueList.view.ts";import { Label } from "../../src/Board/LabelIssue.command.ts";import { Status } from "../../src/Board/RecordActivity.command.ts";import { replied } from "../../src/Board/Said.ts";import { WebApi } from "../../src/Board/WebApi.api.ts";import { issueIn, urlOf } from "./Location.ts";
export type Board = Domain.Api.ClientKey<"WebApi">;/** One Command per command of the Api, and a read namespace per view and stream. */export const BoardClient = DomainFoldkit.make(WebApi);
// MODEL
/** One issue as the sidebar lists it. */export const Listed = Schema.Struct({ issueId: IssueId, title: Schema.String, label: Schema.NullOr(Label), replies: Schema.Number, working: Schema.Boolean,});export type Listed = typeof Listed.Type;
export const Flags = Schema.Struct({ /** The issue the address names, if it names one. */ issueId: Schema.Option(IssueId), page: Schema.String, /** The list as the last visit left it, shown until the board answers. */ issues: Schema.Array(Listed),});export type Flags = typeof Flags.Type;
/** What the page knows of one issue. It is kept when another is opened, so coming back is instant. */export const Thread = Schema.Struct({ /** The issue itself. Known at once for one this page reported or lists. */ detail: Schema.Option( Schema.Struct({ title: Schema.String, body: Schema.String, label: Schema.NullOr(Label) }), ), /** Whether its agent is working, and what is queued for it. */ status: Status, queued: Schema.Array(QueuedMessage), /** The agent's transcript so far, and where to resume reading it. */ items: Schema.Array(SessionEntry), cursor: Schema.Option(Schema.Number), /** The transcript has been read up to now: what arrives next is live. */ caughtUp: Schema.Boolean,});export type Thread = typeof Thread.Type;
const unread: Thread = { detail: Option.none(), status: "idle", queued: [], items: [], cursor: Option.none(), caughtUp: false,};
/** * Something the person did that the board has not shown back yet. The page * shows it at once, and drops it when the board's own copy arrives, or says * so when the board refuses it. */export const Pending = Schema.Struct({ commandId: Schema.String, issueId: IssueId, kind: Schema.Literals(["issue", "reply"]), /** A reply's text. */ text: Schema.String,});export type Pending = typeof Pending.Type;
export const Model = Schema.Struct({ commandIds: DomainFoldkit.CommandIds, /** Every issue of the board, newest first. */ issues: Schema.Array(Listed), listed: Schema.Boolean, /** The issue that is open. None shows the form for a new one. */ selected: Schema.Option(IssueId), /** The new issue being written. */ title: Schema.String, body: Schema.String, /** The reply being written. */ reply: Schema.String, /** Every issue this page has opened. */ threads: Schema.Record(IssueId, Thread), pending: Schema.Array(Pending), error: Schema.Option(Schema.String),});export type Model = typeof Model.Type;
/** * The open issue's thread. While something this page sent is on its way, its * agent is about to work, whatever the board last said. */export const threadOf = (model: Model): Thread => Option.match(model.selected, { onNone: () => unread, onSome: (issueId) => { const known = model.threads[issueId] ?? unread; return model.pending.some((pending) => pending.issueId === issueId) ? { ...known, status: "working" } : known; }, });
/** The sidebar: the board's list, with what this page reported ahead of it. */export const listOf = (model: Model): ReadonlyArray<Listed & { readonly sending: boolean }> => { const known = new Set(model.issues.map((issue) => issue.issueId)); const ahead = model.pending.flatMap((pending) => pending.kind === "issue" && !known.has(pending.issueId) ? [ { issueId: pending.issueId, title: Option.match(model.threads[pending.issueId]?.detail ?? Option.none(), { onNone: () => "", onSome: (detail) => detail.title, }), label: null, replies: 0, working: true, sending: true, }, ] : [], ); return [ ...ahead, ...model.issues.map((issue) => ({ ...issue, // The page knows its own issue's agent is at work before the list says so. working: issue.working || model.threads[issue.issueId]?.status === "working" || model.pending.some((pending) => pending.issueId === issue.issueId), sending: false, })), ];};
/** The replies to the open issue that its transcript does not show yet. */export const sendingOf = (model: Model): ReadonlyArray<Pending> => { const thread = threadOf(model); const shown = [ ...thread.queued.map((message) => message.text), ...thread.items.flatMap(({ item }) => (item.type === "user" ? [item.text] : [])), ]; return model.pending.filter( (pending) => pending.kind === "reply" && Option.contains(model.selected, pending.issueId) && !shown.includes(replied(pending.text)), );};
// MESSAGE
export const Message = defineMessageUnion({ ClickedNewIssue: {}, ClickedIssue: { issueId: IssueId }, /** The browser's back or forward button moved to another address. */ ChangedAddress: { issueId: Schema.Option(IssueId) }, ChangedTitle: { text: Schema.String }, ChangedBody: { text: Schema.String }, ChangedReply: { text: Schema.String }, SubmittedIssue: {}, SubmittedReply: {}, CompletedShowAddress: {}, CompletedRemember: {}, ReceivedBoardResult: { result: BoardClient.Message }, ReceivedIssues: { issues: Schema.Array(Listed) }, ReceivedIssue: { issueId: IssueId, detail: Thread.fields.detail }, ReceivedStatus: { issueId: IssueId, status: Status, queued: Schema.Array(QueuedMessage) }, ReceivedItem: { issueId: IssueId, entry: SessionEntry, cursor: Schema.Number }, CaughtUpTranscript: { issueId: IssueId, cursor: Schema.Number }, FailedRead: { reason: Schema.String },});export type Message = typeof Message.Type;
// COMMAND
/** Put the open issue in the address bar, so a refresh or a shared link opens it. */export const ShowAddress = Command.define("ShowAddress", { args: { issueId: Schema.Option(IssueId) }, messages: [Message.CompletedShowAddress], execute: ({ issueId }) => Effect.sync(() => { if (typeof history !== "undefined") { history.pushState(null, "", urlOf(location.href, issueId)); } return Message.CompletedShowAddress(); }),});
/** Keep the list for the next visit, so it is on screen before the board answers. */export const Remember = Command.define("Remember", { args: { issues: Schema.Array(Listed) }, messages: [Message.CompletedRemember], execute: ({ issues }) => Effect.sync(() => { if (typeof localStorage !== "undefined") { localStorage.setItem(REMEMBERED, JSON.stringify(issues.slice(0, 100))); } return Message.CompletedRemember(); }),});export const REMEMBERED = "board:issues";
// UPDATE
type Return = Update.Return<Model, Message, Board>;
/** Change what the page knows of one issue. */const thread = (model: Model, issueId: IssueId, change: (thread: Thread) => Thread): Model => modifyFields(model, { threads: (threads) => ({ ...threads, [issueId]: change(threads[issueId] ?? unread) }), });
/** * Open an issue, or none. Nothing is waited for: an issue this page has open * already is shown as it was left, and one it only lists shows its title. */const show = (model: Model, selected: Option.Option<IssueId>): Model => Option.match(selected, { onNone: () => modifyFields(model, { selected: () => selected, error: () => Option.none() }), onSome: (issueId) => { const listed = model.issues.find((issue) => issue.issueId === issueId); const opened = thread(model, issueId, (known) => Option.isSome(known.detail) || listed === undefined ? known : { ...known, detail: Option.some({ title: listed.title, body: "", label: listed.label }), status: listed.working ? "working" : known.status, }, ); return modifyFields(opened, { selected: () => selected, reply: () => "", error: () => Option.none(), }); }, });
/** Send one command of the Api, named so that a retry is not run twice. */const send = ( model: Model, command: (commandId: string) => Command.Command<typeof BoardClient.Message.Type, never, Board>,): Return & { readonly commandId: string } => { const { commandId, commandIds } = DomainFoldkit.next(model.commandIds); return { commandId, model: modifyFields(model, { commandIds: () => commandIds, error: () => Option.none() }), commands: [ Command.mapMessage(command(commandId), (result) => Message.ReceivedBoardResult({ result })), ], };};
/** The board refused, or never answered: take back what the page showed ahead of it. */const undo = (model: Model, commandId: string, reason: string): Model => { const refused = model.pending.find((pending) => pending.commandId === commandId); const rest = modifyFields(model, { pending: (pending) => pending.filter((each) => each.commandId !== commandId), error: () => Option.some(reason), }); if (refused === undefined) return rest; if (refused.kind === "reply") { // The words go back in the box, unless the person has started another. return modifyFields(rest, { reply: (reply) => (reply === "" ? refused.text : reply) }); } const written = Option.getOrUndefined(rest.threads[refused.issueId]?.detail ?? Option.none()); const { [refused.issueId]: _dropped, ...threads } = rest.threads; return modifyFields(rest, { threads: () => threads, selected: (selected) => (Option.contains(selected, refused.issueId) ? Option.none() : selected), title: (title) => (title === "" ? (written?.title ?? "") : title), body: (body) => (body === "" ? (written?.body ?? "") : body), });};
export const update = (model: Model, message: Message) => Message.match<Return>(message, { ClickedNewIssue: () => ({ model: show(model, Option.none()), commands: [ShowAddress({ issueId: Option.none() })], }), ClickedIssue: ({ issueId }) => ({ model: show(model, Option.some(issueId)), commands: [ShowAddress({ issueId: Option.some(issueId) })], }), ChangedAddress: ({ issueId }) => ({ model: show(model, issueId) }), ChangedTitle: ({ text }) => ({ model: modifyFields(model, { title: () => text }) }), ChangedBody: ({ text }) => ({ model: modifyFields(model, { body: () => text }) }), ChangedReply: ({ text }) => ({ model: modifyFields(model, { reply: () => text }) }), // Reporting the issue is what starts its agent: the board's policy does that. SubmittedIssue: () => { const title = model.title.trim(); const body = model.body.trim(); if (title === "") return { model }; // The page names the issue, so it can show it before the board answers. const issueId = IssueId.make( `${model.commandIds.session}-${model.commandIds.sent}`.replace(/[^\w-]/g, "-"), ); const sent = send(model, (commandId) => BoardClient.ReportIssue({ input: { issueId, title, body }, commandId }), ); // Shown at once: the issue as written, its agent starting, and a place in the list. const written = thread(sent.model, issueId, () => ({ ...unread, detail: Option.some({ title, body, label: null }), caughtUp: true, })); return { model: modifyFields(written, { selected: () => Option.some(issueId), title: () => "", body: () => "", reply: () => "", pending: (pending) => [ ...pending, { commandId: sent.commandId, issueId, kind: "issue" as const, text: "" }, ], }), commands: [...(sent.commands ?? []), ShowAddress({ issueId: Option.some(issueId) })], }; }, // A reply is passed to the agent by the same policy. A working agent queues it. SubmittedReply: () => Option.match(model.selected, { onNone: (): Return => ({ model }), onSome: (issueId) => { const text = model.reply.trim(); if (text === "") return { model }; const sent = send(model, (commandId) => BoardClient.CommentOnIssue({ input: { issueId, commentId: commandId, body: text }, commandId, }), ); return { // Shown at once, with the agent taking it up. model: modifyFields(sent.model, { reply: () => "", pending: (pending) => [ ...pending, { commandId: sent.commandId, issueId, kind: "reply" as const, text }, ], }), commands: sent.commands, }; }, }), CompletedShowAddress: () => ({ model }), CompletedRemember: () => ({ model }), ReceivedBoardResult: ({ result }) => ({ model: result._tag === "FailedReportIssue" || result._tag === "FailedCommentOnIssue" ? undo( model, result.commandId, result.failure._tag === "Rejected" ? result.failure.rejection._tag : "The board did not answer. Your words are back in the box.", ) : model, }), ReceivedIssues: ({ issues }) => ({ model: modifyFields(model, { issues: () => issues, listed: () => true }), commands: [Remember({ issues })], }), ReceivedIssue: ({ issueId, detail }) => ({ // The board's copy replaces the page's, once it has one. model: Option.isNone(detail) ? model : thread(model, issueId, (known) => ({ ...known, detail })), }), ReceivedStatus: ({ issueId, status, queued }) => ({ model: thread(model, issueId, (known) => ({ ...known, queued, status, })), }), ReceivedItem: ({ issueId, entry, cursor }) => { const read = thread(model, issueId, (known) => known.items.some((item) => item.seq === entry.seq) ? known : { ...known, items: [...known.items, entry], cursor: Option.some(cursor) }, ); // The agent has it: the page's own copy of the reply, or of the issue, is done. const text = entry.item.type === "user" ? entry.item.text : undefined; const arrived = read.pending.find( (pending) => pending.issueId === issueId && (pending.kind === "issue" ? text !== undefined : text === replied(pending.text)), ); return { model: arrived === undefined ? read : modifyFields(read, { pending: (pending) => pending.filter((each) => each !== arrived), }), }; }, CaughtUpTranscript: ({ issueId, cursor }) => ({ model: thread(model, issueId, (known) => ({ ...known, cursor: Option.some(cursor), caughtUp: true, })), }), FailedRead: ({ reason }) => ({ model: modifyFields(model, { error: () => Option.some(reason) }), }), });
// INIT
export const init = (flags: Flags): Return => ({ model: show( Model.make({ commandIds: { session: flags.page, sent: 0 }, issues: flags.issues, listed: false, selected: Option.none(), title: "", body: "", reply: "", threads: {}, pending: [], error: Option.none(), }), flags.issueId, ),});
// SUBSCRIPTION
const open = (model: Model) => Option.getOrElse(model.selected, () => IssueId.make(""));const isOpen = (model: Model) => Option.isSome(model.selected);const failed = (error: { readonly _tag: string }): Message => Message.FailedRead({ reason: error._tag });const defect = (): Message => Message.FailedRead({ reason: "The board could not be read" });
export const subscriptions = Subscription.make<Model, Message, Board>()((entry) => ({ // Back and forward open the issue their address names. address: entry( {}, { modelToDependencies: () => ({}), dependenciesToStream: () => typeof window === "undefined" ? Stream.empty : Stream.fromEventListener(window, "popstate").pipe( Stream.map(() => Message.ChangedAddress({ issueId: issueIn(location.href) })), ), }, ), issues: BoardClient.IssueList.watch({ key: () => ALL, toMessage: ({ state }): Message => Message.ReceivedIssues({ issues: Option.match(state, { onNone: () => [], onSome: (list) => list.order.flatMap((issueId) => { const issue = list.issues[issueId]; return issue === undefined ? [] : [{ issueId, ...issue, working: list.working.includes(issueId) }]; }), }), }), onFailure: failed, onDefect: defect, }), issue: BoardClient.IssueDetail.watch({ key: open, isEnabled: isOpen, toMessage: ({ state }, issueId): Message => Message.ReceivedIssue({ issueId, detail: Option.map(state, ({ title, body, label }) => ({ title, body, label })), }), onFailure: failed, onDefect: defect, }), status: BoardClient.SessionStatus.watch({ key: open, isEnabled: isOpen, toMessage: ({ state }, issueId): Message => Message.ReceivedStatus({ issueId, ...Option.getOrElse(state, () => ({ status: "idle" as const, queued: [] })), }), onFailure: failed, onDefect: defect, }), transcript: BoardClient.Transcript.events({ key: open, isEnabled: isOpen, cursor: (model) => threadOf(model).cursor, onEntry: ({ event, envelope }): Message => Message.ReceivedItem({ issueId: IssueId.make(envelope.id), entry: { seq: event.seq, item: event.item }, cursor: envelope.seq, }), onCaughtUp: (cursor, issueId): Message => Message.CaughtUpTranscript({ issueId, cursor }), onFailure: failed, onDefect: defect, }),}));The open issue is kept in the address, so a refresh or a shared link opens it again:
import * as Option from "effect/Option";import { IssueId } from "../../src/Board/Issue.id.ts";
/** The issue an address names with `?issue=`, if it names one. */export const issueIn = (url: string): Option.Option<IssueId> => { const named = new URL(url).searchParams.get("issue"); return named === null || named === "" ? Option.none() : Option.some(IssueId.make(named));};
/** The address that opens an issue, or the board with none open. */export const urlOf = (url: string, issueId: Option.Option<IssueId>): string => { const parsed = new URL(url); Option.match(issueId, { onNone: () => parsed.searchParams.delete("issue"), onSome: (id) => parsed.searchParams.set("issue", id), }); return parsed.toString();};The client is provided once, on the app’s own origin:
import * as Domain from "@alchemy.run/domain";import * as Effect from "effect/Effect";import * as FetchHttpClient from "effect/http/FetchHttpClient";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Schema from "effect/Schema";import * as Socket from "effect/socket/Socket";import { Runtime } from "foldkit";import { WebApi } from "../../src/Board/WebApi.api.ts";import { Flags, init, Listed, Model, REMEMBERED, subscriptions, update } from "./Board.ts";import { issueIn } from "./Location.ts";import { view } from "./View.ts";
/** * The board's Api for the life of the app. Commands go over HTTP. Each live * read is a WebSocket to the Durable Object that owns what it reads. */const BoardConnection = WebApi.layerClient.pipe( Layer.provide(Domain.protocolWebSocket(`${location.origin}/api`)), Layer.provide(Layer.mergeAll(FetchHttpClient.layer, Socket.layerWebSocketConstructorGlobal)),);
Runtime.run( Runtime.makeApplication({ Model, Flags, init, update, view, subscriptions, resources: BoardConnection, container: document.getElementById("root"), }), { flags: Effect.sync(() => ({ // The issue the address names is opened: a refresh or a shared link resumes it. issueId: issueIn(location.href), // Short, and names this page's commands and issues: each is unique across reloads. page: crypto.randomUUID().slice(0, 8), // The list as the last visit left it, on screen before the board answers. issues: Option.getOrElse( Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Array(Listed)))( localStorage.getItem(REMEMBERED) ?? "[]", ), () => [], ), })), },);web/src/View.ts draws it: a list of issues, and the open one as a thread, with each tool call joined to its result.
Test the page with the board
Section titled “Test the page with the board”The page’s update is tested with Foldkit stories. To test the page and the board together, run the page’s own init, update, Commands and Subscriptions against the board in memory, with a stand-in for the agent:
import * as Effect from "effect/Effect";import * as Stream from "effect/Stream";import * as SubscriptionRef from "effect/SubscriptionRef";import type { WebApi } from "../src/Board/WebApi.api.ts";import { type Flags, init, type Message, type Model, subscriptions, update,} from "../web/src/Board.ts";
type Client = (typeof WebApi)["Client"]["Identifier"];
/** * Run the web page without a browser: its own `init`, `update`, Commands and * Subscriptions, against whatever board the `WebApi` client reaches. Only * the view is left out. It stops when the scope closes. */export const open = Effect.fn(function* (flags: Flags) { const started = init(flags); let current: Model = started.model; const models = yield* SubscriptionRef.make(current);
const dispatch = (message: Message): Effect.Effect<void, never, Client> => Effect.gen(function* () { const next = update(current, message); current = next.model; yield* SubscriptionRef.set(models, current); // Each Command runs in the background, and its Message is dispatched in turn. for (const command of next.commands ?? []) { yield* Effect.forkDetach(Effect.flatMap(command.effect, dispatch)); } });
// Each Subscription follows its dependencies: when they change (another // issue is opened), its Stream is restarted, as Foldkit's runtime does. for (const entry of Object.values(subscriptions)) { const read = () => entry.modelToDependencies(current) as unknown; const same = (entry as { keepAliveEquivalence?: (a: unknown, b: unknown) => boolean }) .keepAliveEquivalence; const key = (dependencies: unknown) => JSON.stringify(dependencies); const run = entry.dependenciesToStream as unknown as ( dependencies: unknown, read: () => unknown, ) => Stream.Stream<Message, never, Client>; const messages: Stream.Stream<Message, never, Client> = SubscriptionRef.changes(models).pipe( Stream.map(read), Stream.changesWith((a, b) => (same ? same(a, b) : key(a) === key(b))), Stream.switchMap((dependencies) => run(dependencies, read)), ); yield* Effect.forkScoped(Stream.runForEach(messages, dispatch)); }
return { /** What a click or a keystroke does. */ dispatch, /** The Model once it satisfies `predicate`. */ until: (predicate: (model: Model) => boolean) => SubscriptionRef.changes(models).pipe( Stream.filter(predicate), Stream.runHead, Effect.map(() => current), Effect.timeout("90 seconds"), Effect.orDie, ), };});The same runner drives a deployed stack in test/integ.test.ts, with the real agent.
Deploy the page with the board
Section titled “Deploy the page with the board”The page is built with Vite and served by its own Worker, which forwards /api to the board:
import * as Boat from "@alchemy.run/boat";import * as Cloudflare from "@alchemy.run/cloudflare";import * as DomainCloudflare from "@alchemy.run/domain/Cloudflare";import * as GitHub from "@alchemy.run/github";import * as Alchemy from "alchemy";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import { Repo } from "./src/Repo.ts";import Worker from "./src/Worker.ts";
export default Alchemy.Stack( "CloudflareAiIssues", { providers: Layer.mergeAll( Cloudflare.providers(), DomainCloudflare.providers(), Boat.providers(), GitHub.providers(), ), state: Alchemy.localState(), }, Effect.gen(function* () { const repo = yield* Repo; const worker = yield* Worker; // The foldkit app, built with Vite. Its Worker serves the build and // forwards /api to the board, so the app and the Api share one origin. const app = yield* Cloudflare.Website.Foldkit("BoardApp", { rootDir: "web", main: "src/worker.ts", env: { BOARD: worker }, assets: { runWorkerFirst: ["/api", "/api/*"] }, }); return { url: worker.url, app: app.url, repository: repo.htmlUrl }; }),);Without a Domain model
Section titled “Without a Domain model”An app with no model can serve a session over an Effect RPC group of its own. Alchemy AI gives the Schemas, and Alchemy serves the group over a WebSocket from the session’s Durable Object.
Define the interface
Section titled “Define the interface”@alchemy.run/ai/Session has a Schema for everything a session says about itself: SessionEvent, SessionEntry, SessionItem, QueuedMessage, HistoryOptions and SessionPage. Use them as the results of your own procedures:
import { HistoryOptions, SessionEvent, SessionPage } from "@alchemy.run/ai/Session";import * as Rpc from "effect/rpc/Rpc";import * as RpcGroup from "effect/rpc/RpcGroup";import * as Schema from "effect/Schema";
/** The session could not do what it was asked. */export class ChatError extends Schema.TaggedClass<ChatError>()("ChatError", { message: Schema.String,}) {}
const Text = { text: Schema.String, requestId: Schema.String };
/** What the front end may ask of one session. */export class ChatRpcs extends RpcGroup.make( Rpc.make("send", { payload: Text, error: ChatError }), Rpc.make("steer", { payload: Text, error: ChatError }), Rpc.make("withdraw", { payload: { id: Schema.String }, error: ChatError }), Rpc.make("interrupt", { error: ChatError }), Rpc.make("events", { payload: { after: Schema.optional(Schema.Number) }, success: SessionEvent, error: ChatError, stream: true, }), Rpc.make("history", { payload: HistoryOptions, success: SessionPage, error: ChatError }),) {}events is a stream. The interface is yours, so it holds only what this front end may do: leave out interrupt, add a field, or put a middleware on it.
Implement it with a session
Section titled “Implement it with a session”Each procedure calls one method of AI.Session:
import type * as AI from "@alchemy.run/ai";import * as Effect from "effect/Effect";import * as Stream from "effect/Stream";import { ChatError, ChatRpcs } from "./Rpcs.ts";
const failed = (error: AI.NotStarted | AI.HarnessError) => ChatError.make({ message: error._tag === "NotStarted" ? "Not started" : error.message });
/** Each procedure is one method of the session. */export const ChatHandlers = (session: AI.Session) => ChatRpcs.toLayer({ send: ({ text, requestId }) => session.send(text, { requestId }).pipe(Effect.mapError(failed)), steer: ({ text, requestId }) => session.steer(text, { requestId }).pipe(Effect.mapError(failed)), withdraw: ({ id }) => session.withdraw(id).pipe(Effect.mapError(failed)), interrupt: () => session.interrupt.pipe(Effect.mapError(failed)), events: ({ after }) => session.events({ after }).pipe(Stream.mapError(failed)), history: (options) => session.history(options).pipe(Effect.mapError(failed)), });Serve it from the session’s object
Section titled “Serve it from the session’s object”Cloudflare.RpcDurableObject serves a group over HTTP and over a WebSocket. Return the handlers for the session the object holds:
import * as Cloudflare from "@alchemy.run/cloudflare";import * as Effect from "effect/Effect";import { ChatHandlers } from "./chat/Handlers.ts";import { ChatRpcs } from "./chat/Rpcs.ts";import { Engineer } from "./Engineer.process.ts";import { Live } from "./Layers.ts";
export default class Engineers extends Cloudflare.RpcDurableObject<Engineers>()( "Engineers", { schema: ChatRpcs }, Effect.gen(function* () { const engineer = yield* Engineer; const state = yield* Cloudflare.DurableObjectState;
return Effect.sync(() => ChatHandlers(engineer.get(state.id.name ?? ""))); }).pipe(Effect.provide(Live)),) {}The object is named after the session’s key, so each session has an object of its own. Live is the same Layer as in Where sessions run.
Forward the browser to it
Section titled “Forward the browser to it”The Worker maps a URL to an object and forwards the request. The same route carries plain HTTP calls and the WebSocket upgrade:
import * as Cloudflare from "@alchemy.run/cloudflare";import * as Effect from "effect/Effect";import { HttpServerRequest } from "effect/http/HttpServerRequest";import * as HttpServerResponse from "effect/http/HttpServerResponse";import Engineers from "./Engineers.ts";
export default class Api extends Cloudflare.Worker<Api>()( "Api", { main: import.meta.url }, Effect.gen(function* () { const engineers = yield* Engineers;
return { fetch: Effect.gen(function* () { const request = yield* HttpServerRequest; const id = /^\/sessions\/([\w-]+)$/.exec(new URL(request.url, "http://api").pathname)?.[1]; if (id === undefined) return HttpServerResponse.empty({ status: 404 }); return yield* engineers.fetch(id, request); }).pipe(Effect.orDie), }; }),) {}Anyone who can open this route can read and steer that session. Check who is asking before you call fetch, or take the id from the signed-in user.
Connect and follow
Section titled “Connect and follow”In the browser, RpcWebSocketClient.layer gives a typed client over one WebSocket. follow reads the session’s events and resumes after a reconnect:
import type { SessionEvent } from "@alchemy.run/ai/Session";import * as RpcWebSocketClient from "@alchemy.run/cloudflare/Workers/RpcWebSocketClient";import * as Context from "effect/Context";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import type * as RpcClient from "effect/rpc/RpcClient";import type { RpcClientError } from "effect/rpc/RpcClientError";import * as Socket from "effect/socket/Socket";import * as Stream from "effect/Stream";import { ChatRpcs, type ChatError } from "./Rpcs.ts";
/** The typed client of one session. */export class Chat extends Context.Service< Chat, RpcClient.FromGroup<typeof ChatRpcs, RpcClientError>>()("Chat") {}
/** One WebSocket to the session's object, open for as long as the Layer is. */export const ChatLive = (url: string) => RpcWebSocketClient.layer(Chat, ChatRpcs, url).pipe( Layer.provide(Socket.layerWebSocketConstructorGlobal), );
/** * The session's events for as long as they are read. When the connection * drops it asks again from the last item it delivered. */export const follow = (options?: { readonly after?: number;}): Stream.Stream<SessionEvent, ChatError, Chat> => Stream.suspend(() => { let after = options?.after; const read = (): Stream.Stream<SessionEvent, ChatError, Chat> => Stream.unwrap(Effect.map(Chat, (chat) => chat.events({ after }))).pipe( Stream.tap((event) => Effect.sync(() => { if (event.type === "item") after = event.seq; }), ), Stream.catchTag("RpcClientError", () => Stream.flatMap(Stream.fromEffect(Effect.sleep("1 second")), read), ), ); return read(); });The first event is the status: idle or working, and the messages that are queued. Then come the stored items, then each new one as it happens. A change of status follows the items stored with it, so idle arrives after the answer.
The stream is the whole picture. A page that folds these events knows the transcript, whether the session is working and what is queued, with no other call.
An idle object is put to sleep with its sockets open, and wakes when the session is sent something. Each item has a seq, so follow asks again from the last one it delivered and nothing is missed or repeated.
Send, steer and stop
Section titled “Send, steer and stop”The client has the procedures you declared:
import * as Effect from "effect/Effect";import { Chat } from "./Client.ts";
export const act = Effect.gen(function* () { const chat = yield* Chat;
yield* chat.send({ text: "Rename the config flag.", requestId: "m-1" }); yield* chat.steer({ text: "Only in src.", requestId: "m-2" }); yield* chat.interrupt();});A requestId makes a message exactly-once, so a retry after a lost answer is safe.