@cloudflare/think 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,614 @@
1
+ # Multi-chat Applications
2
+
3
+ > **Experimental.** The API surface may evolve before Think graduates out of
4
+ > experimental.
5
+
6
+ A ChatGPT-style app gives each user a sidebar of conversations. With Think, you
7
+ build this as a composition of Durable Objects rather than a mode inside one
8
+ agent:
9
+
10
+ - one **directory** Durable Object per user, which owns the chat list and every
11
+ resource that should be shared across that user's chats;
12
+ - one **Think** agent per conversation, which owns that conversation's
13
+ messages, memory, extensions, and branch history. In the reference app each
14
+ chat is a facet of the directory: its own isolate and SQLite database, but
15
+ placed with the directory rather than independently.
16
+
17
+ A Think instance holds exactly one conversation. Putting every conversation in
18
+ one Durable Object would serialize all of a user's turns on one single-threaded
19
+ object, so each chat gets its own.
20
+
21
+ This guide walks through the pattern as implemented in
22
+ [`examples/assistant`](https://github.com/cloudflare/agents/tree/main/examples/assistant),
23
+ the reference Think app. The code below is taken from that example.
24
+
25
+ > **Topology note.** `examples/assistant` hosts each chat as a facet (a
26
+ > [dynamic agent](https://github.com/cloudflare/agents/blob/main/docs/agents/sub-agents.md))
27
+ > of the directory, using `subAgent()`, `hasSubAgent()`, `listSubAgents()`,
28
+ > and `deleteSubAgent()`. Those methods are aliases for `this.dynamicAgents`.
29
+ > The same ownership split also works with one top-level Durable Object per
30
+ > chat behind a per-user hub (see
31
+ > [Routing to independent Agents](https://github.com/cloudflare/agents/blob/main/docs/agents/routing.md#routing-to-independent-agents)),
32
+ > but that topology needs its own chat catalog on the hub instead of the facet
33
+ > registry. See [Known limits](#known-limits).
34
+
35
+ ## Architecture
36
+
37
+ ```text
38
+ Browser tab
39
+ ├── WebSocket → AssistantDirectory ("alice") one per signed-in user
40
+ │ - chat list (sidebar state)
41
+ │ - shared Workspace
42
+ │ - shared MCP servers, OAuth tokens, connections
43
+ │ - cross-chat scheduled work
44
+ │
45
+ └── WebSocket → MyAssistant [chat-abc] one Think DO per conversation
46
+ - messages and branches
47
+ - memory and other context blocks
48
+ - extensions, config, skills
49
+ - SharedWorkspace / SharedMCPClient proxies → directory
50
+ ```
51
+
52
+ The browser keeps two connections open: one to the directory for the sidebar,
53
+ the shared file browser, and MCP state, and one to the active chat for the
54
+ conversation itself.
55
+
56
+ | Resource | Owner | How chats reach it |
57
+ | ----------------------------------------------- | --------- | ----------------------------------------------- |
58
+ | Chat list, titles, previews | Directory | Chats push updates over Durable Object RPC |
59
+ | Workspace files | Directory | `SharedWorkspace` proxy, one RPC per file call |
60
+ | MCP registry, OAuth tokens, live connections | Directory | `SharedMCPClient` proxy, merged in `beforeTurn` |
61
+ | Cross-chat scheduled work | Directory | Directory RPCs into the selected chat |
62
+ | Messages, branches, compaction | Chat | Local Session |
63
+ | Memory and other context blocks | Chat | Local `configureContext()` |
64
+ | Extensions, `configure()` config, loaded skills | Chat | Local Durable Object storage |
65
+ | Client-side tools and approvals | Chat | The chat WebSocket |
66
+
67
+ ## Define the directory
68
+
69
+ The directory in the example extends `Think` so it can declare a scheduled
70
+ task with `getScheduledTasks()`. Its own chat machinery stays dormant: clients
71
+ talk to the per-chat agents, not to the directory. The other APIs it uses —
72
+ sub-agent management, `onBeforeSubAgent`, `addMcpServer()`, `setState()`, and
73
+ `@callable()` — come from `Agent`.
74
+
75
+ ```typescript
76
+ import { callable } from "agents";
77
+ import { Think, Workspace } from "@cloudflare/think";
78
+ import { nanoid } from "nanoid";
79
+ import { MyAssistant } from "./agents/my-assistant/agent";
80
+
81
+ export class AssistantDirectory extends Think<Env, DirectoryState> {
82
+ initialState: DirectoryState = { chats: [] };
83
+
84
+ // Required by Think; nothing in the directory role calls it.
85
+ override getModel() {
86
+ return "@cf/moonshotai/kimi-k2.7-code";
87
+ }
88
+
89
+ onStart() {
90
+ this.sql`CREATE TABLE IF NOT EXISTS chat_meta (
91
+ id TEXT PRIMARY KEY,
92
+ title TEXT NOT NULL,
93
+ updated_at INTEGER NOT NULL,
94
+ last_message_preview TEXT
95
+ )`;
96
+ this._refreshState();
97
+ }
98
+ }
99
+ ```
100
+
101
+ `DirectoryState` is the sidebar state broadcast to every connected tab:
102
+
103
+ ```typescript
104
+ export interface ChatSummary {
105
+ id: string;
106
+ title: string;
107
+ createdAt: number;
108
+ updatedAt: number;
109
+ lastMessagePreview?: string;
110
+ }
111
+
112
+ export interface DirectoryState {
113
+ chats: ChatSummary[];
114
+ }
115
+ ```
116
+
117
+ ## Create, list, rename, and delete chats
118
+
119
+ The set of chats that exist is owned by the sub-agent registry, which
120
+ `subAgent()` and `deleteSubAgent()` keep in lockstep with the actual children.
121
+ The `chat_meta` table only decorates registry entries with a title and preview.
122
+ If the two disagree, the registry wins.
123
+
124
+ ```typescript
125
+ export class AssistantDirectory extends Think<Env, DirectoryState> {
126
+ @callable()
127
+ async createChat(opts?: { title?: string }): Promise<ChatSummary> {
128
+ const id = nanoid(10);
129
+ const now = Date.now();
130
+ const title = opts?.title?.trim() || defaultChatTitle(now);
131
+
132
+ // Spawn the child first so the registry is populated.
133
+ await this.subAgent(MyAssistant, id);
134
+ this.sql`
135
+ INSERT INTO chat_meta (id, title, updated_at, last_message_preview)
136
+ VALUES (${id}, ${title}, ${now}, NULL)
137
+ `;
138
+ this._refreshState();
139
+ return { id, title, createdAt: now, updatedAt: now };
140
+ }
141
+
142
+ @callable()
143
+ async deleteChat(id: string): Promise<void> {
144
+ // Idempotent: safe for an id that is already gone.
145
+ await this.deleteSubAgent(MyAssistant, id);
146
+ this.sql`DELETE FROM chat_meta WHERE id = ${id}`;
147
+ this._refreshState();
148
+ }
149
+
150
+ private _refreshState() {
151
+ const registry = this.listSubAgents(MyAssistant);
152
+ const metaRows = this.sql<{
153
+ id: string;
154
+ title: string;
155
+ updated_at: number;
156
+ last_message_preview: string | null;
157
+ }>`SELECT id, title, updated_at, last_message_preview FROM chat_meta`;
158
+ const metaById = new Map(metaRows.map((row) => [row.id, row]));
159
+
160
+ const chats: ChatSummary[] = registry
161
+ .map((entry) => {
162
+ const meta = metaById.get(entry.name);
163
+ return {
164
+ id: entry.name,
165
+ title: meta?.title ?? defaultChatTitle(entry.createdAt),
166
+ createdAt: entry.createdAt,
167
+ updatedAt: meta?.updated_at ?? entry.createdAt,
168
+ lastMessagePreview: meta?.last_message_preview ?? undefined
169
+ };
170
+ })
171
+ .sort((a, b) => b.updatedAt - a.updatedAt);
172
+
173
+ this.setState({ ...this.state, chats });
174
+ }
175
+ }
176
+ ```
177
+
178
+ `renameChat(id, title)` is another `@callable()` method that upserts the
179
+ `chat_meta` row and calls `_refreshState()`. Because the sidebar is agent state,
180
+ every tab connected to the directory sees creates, renames, and deletes
181
+ immediately.
182
+
183
+ ### Keep the sidebar preview current
184
+
185
+ Each chat reports back to its directory after every turn from
186
+ `onChatResponse`, using the typed `parentAgent()` stub:
187
+
188
+ ```typescript
189
+ export class MyAssistant extends Think<Env> {
190
+ async onChatResponse(result: ChatResponseResult): Promise<void> {
191
+ const preview = result.message.parts
192
+ .filter((p): p is { type: "text"; text: string } => p.type === "text")
193
+ .map((p) => p.text)
194
+ .join("")
195
+ .slice(0, 120);
196
+ if (!preview) return;
197
+
198
+ try {
199
+ const directory = await this.parentAgent(AssistantDirectory);
200
+ await directory.recordChatTurn(this.name, preview);
201
+ } catch (err) {
202
+ console.warn("[MyAssistant] Failed to update directory preview:", err);
203
+ }
204
+ }
205
+ }
206
+ ```
207
+
208
+ `recordChatTurn()` on the directory updates `chat_meta` and refreshes state. It
209
+ is deliberately **not** `@callable()`: Durable Object RPC between agents does not
210
+ need the decorator, and exposing it would let a browser forge sidebar entries.
211
+ The update is best-effort; a failed call leaves the preview stale until the next
212
+ turn.
213
+
214
+ ## Route the client to a chat
215
+
216
+ The Worker, not the browser, decides which directory a request belongs to. The
217
+ example authenticates the user, resolves their directory by login, and forwards
218
+ chat URLs to the matching child with `routeSubAgentRequest()`:
219
+
220
+ ```typescript
221
+ import {
222
+ camelCaseToKebabCase,
223
+ getAgentByName,
224
+ routeSubAgentRequest
225
+ } from "agents";
226
+
227
+ const SUB_AGENT_SEGMENT = camelCaseToKebabCase(MyAssistant.name);
228
+ const SUB_AGENT_PREFIX = `/chat/sub/${SUB_AGENT_SEGMENT}/`;
229
+
230
+ export default {
231
+ async fetch(request: Request, env: Env) {
232
+ const url = new URL(request.url);
233
+
234
+ if (url.pathname === "/chat" || url.pathname.startsWith("/chat/")) {
235
+ const user = await getGitHubUserFromRequest(request);
236
+ if (!user) return createUnauthorizedResponse(request);
237
+
238
+ const directory = await getAgentByName(
239
+ env.AssistantDirectory as DurableObjectNamespace<AssistantDirectory>,
240
+ user.login
241
+ );
242
+
243
+ if (url.pathname.startsWith(SUB_AGENT_PREFIX)) {
244
+ const childPath = url.pathname.slice(SUB_AGENT_PREFIX.length);
245
+ return routeSubAgentRequest(request, directory, {
246
+ fromPath: `/sub/${SUB_AGENT_SEGMENT}/${childPath}`
247
+ });
248
+ }
249
+
250
+ // `/chat` and `/chat/mcp-callback` belong to the directory itself.
251
+ return directory.fetch(request);
252
+ }
253
+
254
+ return new Response("Not found", { status: 404 });
255
+ }
256
+ } satisfies ExportedHandler<Env>;
257
+ ```
258
+
259
+ The example intentionally does not fall back to `routeAgentRequest()`. That
260
+ would let a client address `/agents/assistant-directory/<login>` or a chat by id
261
+ without passing the authenticated `/chat*` gate. `wrangler.jsonc` routes only
262
+ `/auth/*`, `/chat`, and `/chat/*` to the Worker with `run_worker_first`.
263
+
264
+ The directory then gates which chats can be reached. `onBeforeSubAgent` runs
265
+ before a child is woken, so an unknown or deleted chat id gets a 404:
266
+
267
+ ```typescript
268
+ export class AssistantDirectory extends Think<Env, DirectoryState> {
269
+ override async onBeforeSubAgent(
270
+ _req: Request,
271
+ { className, name }: { className: string; name: string }
272
+ ): Promise<Request | Response | void> {
273
+ if (!this.hasSubAgent(className, name)) {
274
+ return new Response(`${className} "${name}" not found`, { status: 404 });
275
+ }
276
+ }
277
+ }
278
+ ```
279
+
280
+ ### Connect from React
281
+
282
+ The client opens one connection to the directory for the sidebar and one to the
283
+ active chat. `examples/assistant` wraps the directory connection in a local
284
+ `useChats()` hook (`src/use-chats.ts`):
285
+
286
+ ```typescript
287
+ import { useAgent } from "agents/react";
288
+
289
+ export function useChats(): UseChats {
290
+ const directory = useAgent<DirectoryState>({
291
+ agent: "AssistantDirectory",
292
+ basePath: "chat"
293
+ // onMcpUpdate and onMessage handlers: see the sections below
294
+ });
295
+
296
+ const chats = directory.state?.chats ?? [];
297
+
298
+ const createChat = useCallback(
299
+ async (opts?: { title?: string }) =>
300
+ (await directory.call("createChat", opts ? [opts] : [])) as ChatSummary,
301
+ [directory]
302
+ );
303
+
304
+ // renameChat, deleteChat, addMcpServer, removeMcpServer follow the same shape
305
+ return { directory, chats, createChat /* ... */ };
306
+ }
307
+ ```
308
+
309
+ `useChats()` is example code, not a package export. Copy and adapt it; the chat
310
+ list shape, permissions, and shared state are application policy.
311
+
312
+ Each chat pane connects to its chat through the directory using the `sub`
313
+ option, then hands that connection to Think's `useAgentChat`:
314
+
315
+ ```tsx
316
+ import { useAgent } from "agents/react";
317
+ import { useAgentChat } from "@cloudflare/think/react";
318
+
319
+ function Chat({ chatId }: { chatId: string }) {
320
+ const agent = useAgent({
321
+ agent: "AssistantDirectory",
322
+ basePath: "chat",
323
+ sub: [{ agent: "MyAssistant", name: chatId }]
324
+ });
325
+ const { messages, sendMessage, status } = useAgentChat({ agent });
326
+ // ...
327
+ }
328
+ ```
329
+
330
+ The app renders the active chat with `key={activeChat.id}`, so switching chats
331
+ remounts the pane and resets its local state (input draft, branch map, open
332
+ panels). The directory's state is the source of truth for which ids exist; the
333
+ client never invents one. When the sidebar loads, or when the active chat is
334
+ deleted from another tab, the app selects the most recently active chat.
335
+
336
+ ## Share the workspace
337
+
338
+ The directory owns one `Workspace` backed by its own SQLite, so a file written in
339
+ one chat is visible in every other chat for that user:
340
+
341
+ ```typescript
342
+ export class AssistantDirectory extends Think<Env, DirectoryState> {
343
+ workspace = new Workspace({
344
+ sql: this.ctx.storage.sql,
345
+ name: () => this.name,
346
+ onChange: (event) =>
347
+ this.broadcast(JSON.stringify({ type: "workspace-change", event }))
348
+ });
349
+
350
+ // One-line delegates, called by child chats over Durable Object RPC.
351
+ // Not @callable(): browsers must not write files through the sidebar socket.
352
+ async readFile(path: string): Promise<string | null> {
353
+ return this.workspace.readFile(path);
354
+ }
355
+
356
+ async writeFile(
357
+ path: string,
358
+ content: string,
359
+ mimeType?: Parameters<Workspace["writeFile"]>[2]
360
+ ): Promise<void> {
361
+ return this.workspace.writeFile(path, content, mimeType);
362
+ }
363
+
364
+ // ...readFileBytes, writeFileBytes, appendFile, exists, readDir, rm, glob,
365
+ // mkdir, stat, lstat, cp, mv, symlink, readlink
366
+ }
367
+ ```
368
+
369
+ Each chat replaces Think's default workspace with a `SharedWorkspace` proxy that
370
+ forwards every call to the directory. Assigning it as a class field means Think
371
+ never creates a per-chat `Workspace`:
372
+
373
+ ```typescript
374
+ import type { WorkspaceFsLike } from "@cloudflare/shell";
375
+
376
+ export class MyAssistant extends Think<Env> {
377
+ override workspace: WorkspaceFsLike = new SharedWorkspace(() =>
378
+ this.parentAgent(AssistantDirectory)
379
+ );
380
+ }
381
+
382
+ export class SharedWorkspace implements WorkspaceFsLike {
383
+ #stubPromise?: Promise<DurableObjectStub<AssistantDirectory>>;
384
+
385
+ constructor(
386
+ private getParent: () => Promise<DurableObjectStub<AssistantDirectory>>
387
+ ) {}
388
+
389
+ private parent() {
390
+ this.#stubPromise ??= this.getParent();
391
+ return this.#stubPromise;
392
+ }
393
+
394
+ async readFile(path: string) {
395
+ return (await this.parent()).readFile(path);
396
+ }
397
+
398
+ // ...every other WorkspaceFsLike method forwards the same way
399
+ }
400
+ ```
401
+
402
+ The proxy implements `WorkspaceFsLike` from `@cloudflare/shell`, which is wider
403
+ than the `WorkspaceLike` type Think requires. That lets the same object drive
404
+ Think's built-in workspace tools, `createWorkspaceTools(this.workspace)`, the
405
+ `state.*` API inside `createExecuteTool(this, ...)`, `fetchTools` workspace
406
+ spill, and skill script runners.
407
+
408
+ To keep file browsers live across chats and tabs, `useChats()` listens for the
409
+ directory's `workspace-change` broadcasts and exposes a `workspaceRevision`
410
+ counter that chat panes use as a `useEffect` dependency:
411
+
412
+ ```typescript
413
+ const directory = useAgent<DirectoryState>({
414
+ agent: "AssistantDirectory",
415
+ basePath: "chat",
416
+ onMessage: (message) => {
417
+ if (typeof message.data !== "string") return;
418
+ let parsed: unknown;
419
+ try {
420
+ parsed = JSON.parse(message.data);
421
+ } catch {
422
+ return;
423
+ }
424
+ if (isWorkspaceChangeMessage(parsed)) {
425
+ setWorkspaceRevision((n) => n + 1);
426
+ }
427
+ }
428
+ });
429
+ ```
430
+
431
+ ## Share MCP servers
432
+
433
+ MCP follows the same shape. The directory owns the server registry, OAuth
434
+ credentials, live connections, and tool caches. Browsers manage servers through
435
+ two `@callable()` methods on the directory; chats read tools through two
436
+ methods that are only reachable over Durable Object RPC:
437
+
438
+ ```typescript
439
+ export class AssistantDirectory extends Think<Env, DirectoryState> {
440
+ @callable()
441
+ async addServer(name: string, url: string) {
442
+ return await this.addMcpServer(name, url, {
443
+ callbackPath: "chat/mcp-callback"
444
+ });
445
+ }
446
+
447
+ @callable()
448
+ async removeServer(id: string): Promise<void> {
449
+ await this.removeMcpServer(id);
450
+ }
451
+
452
+ // Child-only. Waits for in-progress connections, then snapshots tools.
453
+ async listMcpToolDescriptors(
454
+ timeoutMs = 5_000
455
+ ): Promise<McpToolDescriptor[]> {
456
+ await this.mcp.waitForConnections({ timeout: timeoutMs });
457
+ return this.mcp.listTools() as McpToolDescriptor[];
458
+ }
459
+
460
+ // Child-only. Not @callable(), so a browser cannot bypass the chat's
461
+ // beforeToolCall / afterToolCall hooks.
462
+ async callMcpTool(
463
+ serverId: string,
464
+ name: string,
465
+ args: Record<string, unknown>
466
+ ): Promise<CallToolResult> {
467
+ return (await this.mcp.callTool({
468
+ arguments: args,
469
+ name,
470
+ serverId
471
+ })) as CallToolResult;
472
+ }
473
+ }
474
+ ```
475
+
476
+ The directory also configures the OAuth popup response in `onStart()` with
477
+ `this.mcp.configureOAuthCallback({ customHandler })`. The callback URL
478
+ `/chat/mcp-callback` reaches the directory through the same authenticated
479
+ `/chat*` gate, so one URL serves every server and every chat.
480
+
481
+ Each chat builds an AI SDK `ToolSet` from the directory's descriptors on every
482
+ turn and merges it through `beforeTurn`. Think merges `TurnConfig.tools` on top
483
+ of the base tool set:
484
+
485
+ ```typescript
486
+ export class MyAssistant extends Think<Env> {
487
+ sharedMcp = new SharedMCPClient(() => this.parentAgent(AssistantDirectory));
488
+
489
+ async beforeTurn(ctx: TurnContext): Promise<TurnConfig | void> {
490
+ const mcpTools = await this.sharedMcp.getAITools();
491
+ return { tools: mcpTools };
492
+ }
493
+ }
494
+ ```
495
+
496
+ `SharedMCPClient.getAITools()` (in `agents/assistant/shared-mcp-client.ts`)
497
+ converts each descriptor's JSON Schema with `z.fromJSONSchema`, uses the same
498
+ `tool_<serverId>_<name>` key format as `MCPClientManager`, and routes each
499
+ tool's `execute` to `parent.callMcpTool(...)`, turning an MCP `isError` result
500
+ into a thrown error. The chat's own `this.mcp` stays empty.
501
+
502
+ On the client, `useChats()` passes an `onMcpUpdate` handler to the directory
503
+ connection and exposes the resulting `mcpState`, plus `addMcpServer` and
504
+ `removeMcpServer`, so every chat pane and tab shows the same server list.
505
+
506
+ ## What stays per chat
507
+
508
+ Everything not proxied to the directory lives in the chat's own storage:
509
+
510
+ - **Messages and branches.** Each chat has its own Session. The example exposes
511
+ regenerated response versions with a `@callable()` wrapper around
512
+ `this.session.getBranches(userMessageId)`.
513
+ - **Memory.** `configureContext()` in `MyAssistant` declares `soul`, `memory`,
514
+ and a searchable `knowledge` block. They are stored per chat, so a fact the
515
+ model saves in one chat is not visible in another. Think does not ship a
516
+ cross-Durable-Object context provider; to share memory, store it on the
517
+ directory and expose it through your own RPC.
518
+ - **Extensions.** `ExtensionManager` persists extensions in the chat's Durable
519
+ Object storage, not in the workspace, so a tool the model authors in chat A is
520
+ not available in chat B.
521
+ - **Configuration.** `configure()` / `getConfig()` (model tier and persona in
522
+ the example) are per chat.
523
+ - **Client tools and approvals** run over the chat's own WebSocket.
524
+
525
+ ## Run cross-chat scheduled work
526
+
527
+ Work that spans chats belongs to the directory. The example declares a daily
528
+ summary as a Think scheduled task on the directory; its handler picks the most
529
+ recently active chat and RPCs into it:
530
+
531
+ ```typescript
532
+ export class AssistantDirectory extends Think<Env, DirectoryState> {
533
+ override getDefaultTimezone(): string {
534
+ return "UTC";
535
+ }
536
+
537
+ override getScheduledTasks(): ThinkScheduledTasks {
538
+ return {
539
+ dailySummary: {
540
+ schedule: "every day at 09:00",
541
+ handler: async () => {
542
+ const [row] = this.sql<{ id: string }>`
543
+ SELECT id FROM chat_meta ORDER BY updated_at DESC LIMIT 1
544
+ `;
545
+ if (!row) return;
546
+ const target = await this.subAgent(MyAssistant, row.id);
547
+ await target.postDailySummaryPrompt();
548
+ }
549
+ }
550
+ };
551
+ }
552
+ }
553
+ ```
554
+
555
+ `postDailySummaryPrompt()` on the chat calls `saveMessages()` with a user
556
+ message, which runs a normal durable turn in that chat. Like `recordChatTurn()`,
557
+ it is not `@callable()`.
558
+
559
+ Declared scheduled tasks run on the root agent only, so a `getScheduledTasks()`
560
+ on the chat class does nothing unless it also overrides
561
+ `getScheduledTasksScope()` to return `"all"`. Keep cross-chat schedules on the
562
+ directory.
563
+
564
+ See [Scheduled Tasks](./index.md#scheduled-tasks) for the schedule syntax.
565
+
566
+ ## Known limits
567
+
568
+ - **Facet topology.** Because the example's chats are facets of the directory,
569
+ they are colocated with it on one machine, share its physical alarm, and
570
+ depend on the root for their native WebSockets, so every chat frame wakes the
571
+ directory. The
572
+ [dynamic agents guide](https://github.com/cloudflare/agents/blob/main/docs/agents/sub-agents.md#when-to-use-dynamic-agents)
573
+ covers these tradeoffs and does not recommend facets for many independent,
574
+ busy chats per user. For that case, host each chat as a top-level Durable
575
+ Object: the hub keeps its own catalog of chats (the facet registry behind
576
+ `listSubAgents()` no longer applies), and chats look up the hub with
577
+ `getAgentByName()` instead of `parentAgent()`. The workspace and MCP
578
+ boundaries do not change. Moving existing facet chats to top-level objects
579
+ means exporting and re-importing each chat's state; there is no in-place
580
+ storage move (see
581
+ [`rfc-user-chat-durable-objects.md`](https://github.com/cloudflare/agents/blob/main/design/rfc-user-chat-durable-objects.md#migration-of-existing-facet-backed-apps)).
582
+ - **The directory is the fan-in point.** Every shared workspace call and every
583
+ MCP tool call from every chat is one RPC into the directory's single-threaded
584
+ isolate. Writes to the same path serialize there, and concurrent MCP calls
585
+ interleave on its event loop. The directory keeps one live connection per
586
+ registered MCP server. The SDK does not yet publish measured limits for this
587
+ fan-out.
588
+ - **Shared means shared.** Every chat can read and write every file the user
589
+ owns and call every connected MCP tool. Extensions declared with
590
+ `workspace: "read-write"` inherit the same reach. For less-trusted surfaces,
591
+ gate access in the directory's RPC methods, filter tools in the MCP proxy, or
592
+ remove the `workspace` override so each chat keeps a private workspace.
593
+ - **No server-side cross-chat events.** Workspace changes are broadcast to
594
+ browser tabs connected to the directory, not delivered to other chat agents.
595
+ Add a directory-to-chat RPC if a tool must react to another chat's writes.
596
+ - **Sidebar metadata is best-effort.** `recordChatTurn()` is an unconditional
597
+ upsert and can run after the chat was deleted. The resulting `chat_meta` row
598
+ is ignored because the registry decides which chats exist, but it is not
599
+ cleaned up. The example does not coordinate `deleteChat()` with a turn that is
600
+ still running.
601
+ - **No cross-chat search.** Each chat's Session search covers only that chat.
602
+ The example has no directory-level search index.
603
+ - **No packaged helpers.** There is no `Chats` base class and `useChats()` is not
604
+ exported from any package. The pattern is documented through
605
+ `examples/assistant` until the shape settles.
606
+
607
+ ## Related
608
+
609
+ - [Sub-agents and Programmatic Turns](./sub-agents.md) — `chat()`, `saveMessages()`, and parent-to-child turns
610
+ - [Tools](./tools.md) — workspace tools, code execution, and MCP tools
611
+ - [Lifecycle Hooks](./lifecycle-hooks.md) — `beforeTurn` and `onChatResponse`
612
+ - [Dynamic agents](https://github.com/cloudflare/agents/blob/main/docs/agents/sub-agents.md) — `onBeforeSubAgent`, `parentAgent()`, `useAgent({ sub })`, and routing
613
+ - [Routing to independent Agents](https://github.com/cloudflare/agents/blob/main/docs/agents/routing.md#routing-to-independent-agents) — `RoutedAgents` for top-level chat Durable Objects
614
+ - [`examples/assistant`](https://github.com/cloudflare/agents/tree/main/examples/assistant) — the full reference app
@@ -100,9 +100,54 @@ const active = await this.listSubmissions({
100
100
  await this.cancelSubmission(submission.submissionId, "No longer needed");
101
101
  ```
102
102
 
103
+ Once the turn persists its assistant message, the inspection carries that
104
+ message's id as `messageId`, so a caller that admitted the turn by submission
105
+ id can find the exact message it wrote, even if later turns have added messages
106
+ since.
107
+
103
108
  Use `cancelSubmission(submissionId)` for durable cancellation. This works across
104
109
  Worker and Durable Object RPC boundaries, unlike `AbortSignal`.
105
110
 
111
+ `cancelSubmission()` reports what it did, so a caller does not need a separate,
112
+ race-prone inspection to find out:
113
+
114
+ | `outcome` | Meaning |
115
+ | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
116
+ | `cancelled` | The submission is now `aborted`. `previousStatus` is `pending` when it was removed before its turn started, or `running` when its turn had been claimed and was signalled to abort. `messagesApplied` says whether any of its messages reached the conversation. `submission` holds the new state. |
117
+ | `already_terminal` | The submission had already finished. `submission` holds its final state, which is unchanged. |
118
+ | `not_found` | No submission has this id. |
119
+
120
+ A `running` cancellation stops the turn, but work a tool had already started,
121
+ such as an external request, may still finish.
122
+
123
+ ## Wait for a submission
124
+
125
+ `waitForSubmission(submissionId)` resolves once the submission reaches
126
+ `completed`, `aborted`, `skipped`, or `error`, after `onSubmissionStatus` has run
127
+ for it. It returns immediately for a submission that has already finished and
128
+ returns `null` for an unknown id. An `error` status resolves rather than
129
+ rejects, so read `status` and `error` from the result.
130
+
131
+ ```typescript
132
+ const { submissionId } = await agent.submitMessages([message], {
133
+ idempotencyKey: `${workflowName}:${instanceId}:${stepName}`
134
+ });
135
+ const settled = await agent.waitForSubmission(submissionId, {
136
+ timeoutMs: 60_000
137
+ });
138
+ if (!settled) {
139
+ throw new Error("Submission not found");
140
+ }
141
+ if (settled.status === "pending" || settled.status === "running") {
142
+ throw new Error("Still running; retry this step");
143
+ }
144
+ ```
145
+
146
+ With `timeoutMs`, the call returns the submission as it is when the time runs
147
+ out, still `pending` or `running`, or `null` if it was deleted. The wait is held in the agent's memory, so it
148
+ rejects if the agent restarts. The submission itself is durable, so call
149
+ `waitForSubmission()` again to keep waiting.
150
+
106
151
  Completed submission records are retained until you delete them:
107
152
 
108
153
  ```typescript