@cloudflare/think 0.16.0 → 0.18.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.
- package/README.md +137 -35
- package/dist/{chat-sdk-C8BvREXn.js → chat-sdk-B77QwYuj.js} +49 -31
- package/dist/chat-sdk-B77QwYuj.js.map +1 -0
- package/dist/extensions/index.d.ts +1 -1
- package/dist/extensions/index.js +1 -1
- package/dist/extensions/index.js.map +1 -1
- package/dist/{index-BZKPlFcA.d.ts → index-CJ--4uax.d.ts} +626 -192
- package/dist/{manager-CSk5htym.js → manager-Cb3DNZgp.js} +10 -10
- package/dist/{manager-CSk5htym.js.map → manager-Cb3DNZgp.js.map} +1 -1
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/index.js +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/messengers/telegram.js +1 -1
- package/dist/think.d.ts +3 -3
- package/dist/think.js +1220 -440
- package/dist/think.js.map +1 -1
- package/dist/tools/execute.d.ts +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/workspace.d.ts +1 -1
- package/dist/tools/workspace.js.map +1 -1
- package/dist/workflows.d.ts +1 -1
- package/dist/{workspace-DxZQSbko.d.ts → workspace-CNeXc2vl.d.ts} +8 -2
- package/docs/client-tools.md +1 -1
- package/docs/getting-started.md +19 -14
- package/docs/index.md +126 -56
- package/docs/lifecycle-hooks.md +51 -15
- package/docs/sub-agents.md +7 -19
- package/docs/tools.md +2 -2
- package/package.json +6 -6
- package/dist/chat-sdk-C8BvREXn.js.map +0 -1
package/docs/index.md
CHANGED
|
@@ -204,18 +204,18 @@ Both Think and [`AIChatAgent`](https://github.com/cloudflare/agents/blob/main/do
|
|
|
204
204
|
|
|
205
205
|
**AIChatAgent** is a protocol adapter. You override `onChatMessage` and are responsible for calling `streamText`, wiring tools, converting messages, and returning a `Response`. AIChatAgent handles the plumbing — message persistence, streaming, abort, resume — but the LLM call is entirely your concern.
|
|
206
206
|
|
|
207
|
-
**Think** is an opinionated framework. It makes decisions for you: `getModel()` returns the model, `getSystemPrompt()` or `
|
|
208
|
-
|
|
209
|
-
| Concern | AIChatAgent | Think
|
|
210
|
-
| ---------------------- | ---------------------------------------------------------------- |
|
|
211
|
-
| **Minimal subclass** | ~15 lines (wire `streamText` + tools + system prompt + response) | 3 lines (`getModel()` only)
|
|
212
|
-
| **Storage** | Flat SQL table |
|
|
213
|
-
| **Regeneration** | Destructive (old response deleted) | Non-destructive branching (old responses preserved)
|
|
214
|
-
| **Context management** | Manual | Context blocks with LLM-writable persistent memory
|
|
215
|
-
| **Sub-agent RPC** | Not built in | `chat()` with `StreamCallback`
|
|
216
|
-
| **Programmatic turns** | `saveMessages()` | `saveMessages()`, `submitMessages()`, `continueLastTurn()`
|
|
217
|
-
| **Compaction** | `maxPersistedMessages` (deletes oldest) | Non-destructive summaries via overlays
|
|
218
|
-
| **Search** | Not available | FTS5 full-text search per-session and cross-session
|
|
207
|
+
**Think** is an opinionated framework. It makes decisions for you: `getModel()` returns the model, `getSystemPrompt()` or `configureContext()` sets the prompt, `getTools()` returns tools. The default `onChatMessage` runs the complete agentic loop. You override individual pieces, not the whole pipeline.
|
|
208
|
+
|
|
209
|
+
| Concern | AIChatAgent | Think |
|
|
210
|
+
| ---------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------- |
|
|
211
|
+
| **Minimal subclass** | ~15 lines (wire `streamText` + tools + system prompt + response) | 3 lines (`getModel()` only) |
|
|
212
|
+
| **Storage** | Flat SQL table | Sessions: tree-structured messages, compaction, FTS5 |
|
|
213
|
+
| **Regeneration** | Destructive (old response deleted) | Non-destructive branching (old responses preserved) |
|
|
214
|
+
| **Context management** | Manual | Context blocks with LLM-writable persistent memory |
|
|
215
|
+
| **Sub-agent RPC** | Not built in | `chat()` with `StreamCallback` |
|
|
216
|
+
| **Programmatic turns** | `saveMessages()` | `saveMessages()`, `submitMessages()`, `continueLastTurn()` |
|
|
217
|
+
| **Compaction** | `maxPersistedMessages` (deletes oldest) | Non-destructive summaries via overlays |
|
|
218
|
+
| **Search** | Not available | FTS5 full-text search per-session and cross-session |
|
|
219
219
|
|
|
220
220
|
### When to use AIChatAgent
|
|
221
221
|
|
|
@@ -305,9 +305,9 @@ Key behaviors:
|
|
|
305
305
|
re-submitting a known key returns the existing record with `accepted: false`
|
|
306
306
|
instead of starting a second turn. See [Programmatic
|
|
307
307
|
Submissions](./programmatic-submissions.md).
|
|
308
|
-
- **Recovery-safe.**
|
|
309
|
-
|
|
310
|
-
|
|
308
|
+
- **Recovery-safe.** The `wait`, `stream`, and drained `submit` paths all run
|
|
309
|
+
inference inside a recovery fiber, so an interrupted turn resumes after
|
|
310
|
+
eviction.
|
|
311
311
|
|
|
312
312
|
`runTurn` is exported alongside its option and result types: `RunTurnOptions`,
|
|
313
313
|
`RunTurnWait`, `RunTurnSubmit`, `RunTurnStream`, `TurnInputMessages`, and
|
|
@@ -390,30 +390,34 @@ path.
|
|
|
390
390
|
|
|
391
391
|
## Configuration Overrides
|
|
392
392
|
|
|
393
|
-
| Method / Property | Default | Description
|
|
394
|
-
| -------------------------- | -------------------------------- |
|
|
395
|
-
| `getModel()` | throws | Return a model id `string` (resolved via the bundled `workers-ai-provider` off `getAIBinding()` — a `@cf/...` id hits Workers AI, a `"provider/model"` slug routes through AI Gateway) or a `LanguageModel`
|
|
396
|
-
| `getAIBinding()` | `this.env.AI` | Workers AI binding used to resolve string models from `getModel()`
|
|
397
|
-
| `getSystemPrompt()` | `"You are a helpful assistant."` | System prompt (fallback when no context blocks)
|
|
398
|
-
| `getTools()` | `{}` | AI SDK `ToolSet` for the agentic loop
|
|
399
|
-
| `getScheduledTasks()` | `{}` | Code-declared recurring prompts or handlers
|
|
400
|
-
| `getDefaultTimezone()` | `undefined` | Default timezone for wall-clock scheduled tasks
|
|
401
|
-
| `getMessengers()` | `{}` | Messenger ingress and delivery declarations — see [Messengers](./messengers.md)
|
|
402
|
-
| `getActions()` | `{}` | Server actions (idempotency, approvals, authorization) compiled into tools — see [Actions](./actions.md)
|
|
403
|
-
| `configureChannels()` | `{}` | Per-channel policy and surfaces beyond the implicit `web` channel — see [Channels](./channels.md)
|
|
404
|
-
| `maxSteps` | `10` | Max tool-call rounds per turn
|
|
405
|
-
| `sendReasoning` | `true` | Send reasoning chunks to chat clients
|
|
406
|
-
| `configureSession()` | identity |
|
|
407
|
-
| `
|
|
408
|
-
| `
|
|
409
|
-
| `
|
|
410
|
-
| `
|
|
411
|
-
| `
|
|
412
|
-
| `
|
|
413
|
-
| `
|
|
414
|
-
| `
|
|
415
|
-
| `
|
|
416
|
-
| `
|
|
393
|
+
| Method / Property | Default | Description |
|
|
394
|
+
| -------------------------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
395
|
+
| `getModel()` | throws | Return a model id `string` (resolved via the bundled `workers-ai-provider` off `getAIBinding()` — a `@cf/...` id hits Workers AI, a `"provider/model"` slug routes through AI Gateway) or a `LanguageModel` |
|
|
396
|
+
| `getAIBinding()` | `this.env.AI` | Workers AI binding used to resolve string models from `getModel()` |
|
|
397
|
+
| `getSystemPrompt()` | `"You are a helpful assistant."` | System prompt (fallback when no context blocks) |
|
|
398
|
+
| `getTools()` | `{}` | AI SDK `ToolSet` for the agentic loop |
|
|
399
|
+
| `getScheduledTasks()` | `{}` | Code-declared recurring prompts or handlers |
|
|
400
|
+
| `getDefaultTimezone()` | `undefined` | Default timezone for wall-clock scheduled tasks |
|
|
401
|
+
| `getMessengers()` | `{}` | Messenger ingress and delivery declarations — see [Messengers](./messengers.md) |
|
|
402
|
+
| `getActions()` | `{}` | Server actions (idempotency, approvals, authorization) compiled into tools — see [Actions](./actions.md) |
|
|
403
|
+
| `configureChannels()` | `{}` | Per-channel policy and surfaces beyond the implicit `web` channel — see [Channels](./channels.md) |
|
|
404
|
+
| `maxSteps` | `10` | Max tool-call rounds per turn |
|
|
405
|
+
| `sendReasoning` | `true` | Send reasoning chunks to chat clients |
|
|
406
|
+
| `configureSession()` | identity | Configure the default session handle: compaction and search — see [Sessions](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) |
|
|
407
|
+
| `configureContext()` | `[]` | Declare prompt context blocks — see [Session and context](#session-and-context) |
|
|
408
|
+
| `hydrationByteBudget` | 32 MiB | Byte budget for startup transcript hydration. Charges each row its stored bytes plus the attachment bytes it re-inflates |
|
|
409
|
+
| `mediaEviction` | `true` | Media eviction policy: aged media leaves the conversation and is preserved as a Workspace file. `false` keeps aged media in the conversation |
|
|
410
|
+
| `getSkills()` | `[]` | Return Agent Skills sources for on-demand skill activation |
|
|
411
|
+
| `skillWorkspace` | `false` | Project skills into the Workspace as files; `{}` enables with defaults |
|
|
412
|
+
| `getSkillScriptRunner()` | `null` | Enable the optional `run_skill_script` tool |
|
|
413
|
+
| `workspaceBash` | `true` | Include or configure the default workspace `bash` tool |
|
|
414
|
+
| `fetchTools` | `false` | Opt-in allowlisted, read-only HTTP fetch tools (`fetch_url` + per-binding `fetch_<name>`). Set to a config object; see [Fetch tool](#fetch-tool) |
|
|
415
|
+
| `messageConcurrency` | `"queue"` | How overlapping submits behave — see [Client Tools](./client-tools.md) |
|
|
416
|
+
| `includeMcpTools` | `true` | Automatically convert connected MCP tools to AI SDK tools and merge them into model turns |
|
|
417
|
+
| `waitForMcpConnections` | `false` | Wait for MCP servers before inference |
|
|
418
|
+
| `chatRecovery` | Always on | Durable recovery configuration. See [`ChatRecoveryConfig`](https://github.com/cloudflare/agents/blob/main/docs/agents/chat-agents.md#stream-recovery) for all options and defaults. |
|
|
419
|
+
| `chatStreamStallTimeoutMs` | `0` (off) | Opt-in inactivity watchdog: abort a turn whose model stream produces no chunk for this long (measures the gap between chunks, including tool execution — set above your slowest model TTFT + tool, e.g. `120_000`). Emits a `chat:stream:stalled` event; the stall routes into bounded recovery (see below) instead of an infinite spinner, and only terminalizes once the budget is exhausted. Override per-turn via `TurnConfig.chatStreamStallTimeoutMs` (returned from `beforeTurn`) for a turn with a known-slow tool. |
|
|
420
|
+
| `contextOverflow` | `undefined` | Opt-in mid-turn context-overflow handling: `{ reactive?, maxRetries?, proactive? }`. Requires `classifyChatError` + a session compaction function. See [Context-window overflow recovery](#context-window-overflow-recovery). |
|
|
417
421
|
|
|
418
422
|
### MCP tools exposed outside the harness
|
|
419
423
|
|
|
@@ -486,6 +490,18 @@ agent (including a plain `@cloudflare/ai-chat` `onChatMessage`) can build a
|
|
|
486
490
|
`SkillRegistry`; `@cloudflare/think` re-exports it as `skills` and wires
|
|
487
491
|
`getSkills()` into the turn automatically.
|
|
488
492
|
|
|
493
|
+
Think can also project each resolved `SKILL.md` into the active workspace so
|
|
494
|
+
the agent can read and edit skills as files. This is off by default: skills
|
|
495
|
+
load from their sources and nothing is written to the Workspace. Set
|
|
496
|
+
`skillWorkspace = {}` to enable it. Computer uses `/workspace/.agents/skills`;
|
|
497
|
+
legacy Shell uses `/.agents/skills`. Existing workspace edits are preserved and
|
|
498
|
+
affect later activation. Resources copy into the workspace when first requested
|
|
499
|
+
rather than at startup. A durable source fingerprint lets unchanged cold wakes
|
|
500
|
+
attach to the existing projection without statting or rewriting every file.
|
|
501
|
+
|
|
502
|
+
Set `skillWorkspace = { root: "/workspace/.agents/skills" }` when a custom
|
|
503
|
+
Computer proxy presents Think's legacy direct-method shape.
|
|
504
|
+
|
|
489
505
|
Sources are applied in order; the first source to register a skill name wins,
|
|
490
506
|
and later duplicates (or a source that fails to load) are skipped with a logged
|
|
491
507
|
warning rather than failing the agent.
|
|
@@ -507,9 +523,9 @@ When skills are available, Think exposes:
|
|
|
507
523
|
| `run_skill_script` | Run a bundled script when `getSkillScriptRunner()` returns a runner |
|
|
508
524
|
|
|
509
525
|
Skills are not always-on system prompt text. Use `getSystemPrompt()` or a
|
|
510
|
-
|
|
511
|
-
for task-specific procedures, references, scripts, templates,
|
|
512
|
-
should be loaded only when relevant.
|
|
526
|
+
context block from `configureContext()` for behavior that should apply to every
|
|
527
|
+
turn. Use skills for task-specific procedures, references, scripts, templates,
|
|
528
|
+
and assets that should be loaded only when relevant.
|
|
513
529
|
|
|
514
530
|
Script execution is opt-in and requires a Worker Loader binding:
|
|
515
531
|
|
|
@@ -552,9 +568,9 @@ Network access, tools, and workspace writes are opt-in. The default timeout is
|
|
|
552
568
|
|
|
553
569
|
### Chat Recovery
|
|
554
570
|
|
|
555
|
-
Think wraps chat turns in recoverable fibers
|
|
571
|
+
Think always wraps chat turns in recoverable fibers. If the Durable Object is evicted mid-stream, Think reconstructs any buffered chunks, persists partial output, and schedules either a continuation of the assistant turn or a retry of the unanswered user turn. `chatRecovery = false` is no longer supported; assign an object only to tune recovery.
|
|
556
572
|
|
|
557
|
-
A stream-stall watchdog abort (`chatStreamStallTimeoutMs`, above) is treated as just another interruption
|
|
573
|
+
A stream-stall watchdog abort (`chatStreamStallTimeoutMs`, above) is treated as just another interruption and routes into this same bounded path. The settled partial is preserved and a continuation is scheduled, so a transient hang recovers automatically. A persistently hanging provider exhausts the budget and terminalizes through the **same** exhaustion handling as a deploy/eviction interruption: `onExhausted` fires, the `chat:recovery:exhausted` event is emitted, and the configured `terminalMessage` is shown (not a raw stall error).
|
|
558
574
|
|
|
559
575
|
Override `onChatRecovery` when you need provider-specific recovery, such as retrieving a stored OpenAI Responses result instead of issuing a new model call:
|
|
560
576
|
|
|
@@ -646,7 +662,7 @@ export class MyAgent extends Think<Env> {
|
|
|
646
662
|
|
|
647
663
|
Use either layer alone, or both together: the proactive guard avoids most overflows, and the reactive backstop catches any that still slip through (for example, a turn that starts already over budget, or a single tool result so large that compaction cannot help — in which case it terminalizes cleanly). Both apply to every turn entry path (WebSocket, sub-agent `chat()`, and programmatic `saveMessages()` / `submitMessages()`), and both emit a `chat:context:compacted` [observability event](https://github.com/cloudflare/agents/blob/main/docs/agents/observability.md#chat-context-events).
|
|
648
664
|
|
|
649
|
-
> A no-op compaction cannot rescue an over-budget turn, so recovery is only as effective as your compaction configuration. For tool-heavy histories,
|
|
665
|
+
> A no-op compaction cannot rescue an over-budget turn, so recovery is only as effective as your compaction configuration. For tool-heavy histories, lower the `compactAfter()` threshold and the `keepRecentTokens` budget of your compaction function (see [Sessions](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md#compaction)).
|
|
650
666
|
|
|
651
667
|
For a runnable demo against a real Workers AI model, see [`examples/context-overflow-recovery`](https://github.com/cloudflare/agents/tree/main/examples/context-overflow-recovery).
|
|
652
668
|
|
|
@@ -817,12 +833,15 @@ You do not need new machinery to gate egress per call: `beforeToolCall` can `blo
|
|
|
817
833
|
| Browser Run (`tools/browser`) | Rendered pages, auth flows, screenshots, CDP automation |
|
|
818
834
|
| Typed tools / `agentTool()` | Calling a `WorkerEntrypoint`/DO method with a typed schema, or delegating to a sub-agent |
|
|
819
835
|
|
|
820
|
-
## Session
|
|
836
|
+
## Session and context
|
|
837
|
+
|
|
838
|
+
Think splits conversation storage from prompt assembly. [`agents/sessions`](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) stores messages; [`agents/context`](https://github.com/cloudflare/agents/blob/main/docs/agents/context.md) builds the system prompt. Think wires both during `onStart`.
|
|
821
839
|
|
|
822
|
-
|
|
840
|
+
`configureSession()` configures the default session handle: compaction and search.
|
|
823
841
|
|
|
824
842
|
```typescript
|
|
825
843
|
import { Think, Session } from "@cloudflare/think";
|
|
844
|
+
import { createCompactFunction } from "agents/sessions";
|
|
826
845
|
|
|
827
846
|
export class MyAgent extends Think<Env> {
|
|
828
847
|
getModel() {
|
|
@@ -831,19 +850,70 @@ export class MyAgent extends Think<Env> {
|
|
|
831
850
|
|
|
832
851
|
configureSession(session: Session) {
|
|
833
852
|
return session
|
|
834
|
-
.
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
.withCachedPrompt();
|
|
853
|
+
.onCompaction(
|
|
854
|
+
createCompactFunction({
|
|
855
|
+
summarize: (prompt) => this.summarize(prompt),
|
|
856
|
+
keepRecentTokens: 20_000
|
|
857
|
+
})
|
|
858
|
+
)
|
|
859
|
+
.compactAfter(100_000);
|
|
842
860
|
}
|
|
843
861
|
}
|
|
844
862
|
```
|
|
845
863
|
|
|
846
|
-
|
|
864
|
+
`configureContext()` declares the prompt blocks:
|
|
865
|
+
|
|
866
|
+
```typescript
|
|
867
|
+
import type { ContextConfig } from "agents/context";
|
|
868
|
+
|
|
869
|
+
export class MyAgent extends Think<Env> {
|
|
870
|
+
configureContext(): ContextConfig[] {
|
|
871
|
+
return [
|
|
872
|
+
{ label: "soul", provider: { get: async () => "You are helpful." } },
|
|
873
|
+
{ label: "memory", description: "Learned facts", maxTokens: 2_000 }
|
|
874
|
+
];
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
```
|
|
878
|
+
|
|
879
|
+
A block declared without a `provider` is auto-wired to durable per-agent SQLite, so `memory` above is writable through the `set_context` tool with no extra wiring. The frozen system prompt is always persisted, so there is nothing to opt into: a cold wake reuses the exact prompt string the model already cached.
|
|
880
|
+
|
|
881
|
+
The assembled blocks are available as `this.context` once the Lifecycle has started.
|
|
882
|
+
|
|
883
|
+
### Upgrading from 0.17
|
|
884
|
+
|
|
885
|
+
A subclass written against 0.17 keeps compiling and running. `configureSession(session)` still accepts the `withContext()` / `withCachedPrompt()` chain, and `this.session` still carries the context methods (`addContext`, `getContextBlock`, `replaceContextBlock`, `refreshSystemPrompt`, `freezeSystemPrompt`, `tools()`), which now forward to `this.context`. They are deprecated; move blocks into `configureContext()` and read `this.context` at your own pace. Blocks from both hooks are merged, `configureContext()` first.
|
|
886
|
+
|
|
887
|
+
Two things do change on upgrade:
|
|
888
|
+
|
|
889
|
+
- **Storage migrates on first wake and cannot be rolled back.** Each Durable Object lifts its `assistant_*` tables into `cf_agents_session_*`, verifies every row, and drops the old tables. An object that has woken on this version has an empty conversation if you roll back; rolling forward again is safe. Canary the deploy if you need a rollback path.
|
|
890
|
+
- **Hydration has no message-count floor.** `hydrationByteBudget` (now 32 MiB) is a hard ceiling that charges each row its stored size plus attachments, so a run of very large messages can hydrate fewer than four. `getHistory()` still reads the full path.
|
|
891
|
+
|
|
892
|
+
Annotate a `configureSession` override with `Session` imported from `@cloudflare/think`. The `Session` class exported by `agents/sessions` is the raw storage handle and is not assignable to Think's.
|
|
893
|
+
|
|
894
|
+
`sessionAttachments` is gone (Sessions stores media out of the row on its own), `MediaEvictionConfig.externalizeToWorkspace` is ignored (bytes are always preserved), and `WorkspaceLike.writeFileBytes` is optional (a workspace without it disables media eviction and skills projection with a one-time warning).
|
|
895
|
+
|
|
896
|
+
Think's `this.messages` getter reads directly from the Session tree. Compaction overlays and search are handled by Sessions.
|
|
897
|
+
|
|
898
|
+
### Message storage
|
|
899
|
+
|
|
900
|
+
Sessions stores MESSAGES; it is not a file store. A message rides in one SQLite row until its serialized JSON exceeds the 1.5 MiB row budget; a message larger than that is split across continuation rows and reassembled on read, byte for byte. Nothing is truncated and no message is too large to store, so there is no size error to handle and nothing to configure. Splitting never reclaims database space — the continuation rows live in the same Durable Object as the message — and Sessions imposes no upper bound on a single message, so a Durable Object's 10 GB ceiling is the real bound on how much one conversation can hold and bounding untrusted input is the application's job. Files belong in the Workspace, which spills to R2; put a reference to one in the message. This is a storage detail: it is invisible to the model, and it is unrelated to media eviction.
|
|
901
|
+
|
|
902
|
+
### Media eviction
|
|
903
|
+
|
|
904
|
+
Media eviction is a different concern: a context-window technique, not a storage one. Sending a screenshot the model has already looked at back through the context on every subsequent turn is pure cost, so once a message has aged past `mediaEviction.keepRecentMessages` (8 by default) on the active path, Think takes the media out of the conversation and leaves a marker in its place:
|
|
905
|
+
|
|
906
|
+
```
|
|
907
|
+
[evicted image/png, 812004 bytes; preserved at /attachments/evicted/msg_01H8-0.png]
|
|
908
|
+
```
|
|
909
|
+
|
|
910
|
+
The bytes are written to the Workspace at that path, raw and with their real mime type — not as a `data:` URL string. The workspace `read` tool recognises `image/*`, so when the agent decides it needs to look at the picture again it reads the path out of the marker and the actual image goes back into context. Eviction is visible to the model and lossy on purpose; nothing reconstructs it behind the model's back.
|
|
911
|
+
|
|
912
|
+
Passes are bounded (`maxRowsPerPass`, 64 by default) and run in the background after a turn or a hydration read, rescheduling themselves while a backlog remains. Only payloads of at least `minPartBytes` are evicted, and `keepRecentMessages` is clamped to the four messages the model replays at full fidelity, so eviction can never rewrite content the model is still reading. Once a row is rewritten, the Sessions attachment reference is dropped and the blob is reaped: the bytes exist in exactly one place, the Workspace file.
|
|
913
|
+
|
|
914
|
+
`mediaEviction: false` keeps aged media in the conversation, so the model keeps seeing it. It does not change where Sessions keeps the bytes — a large payload may still be stored as a pointer, which is unobservable.
|
|
915
|
+
|
|
916
|
+
Startup hydration reads a recent window bounded by `hydrationByteBudget` (32 MiB by default). The budget charges each row its stored bytes plus the attachment bytes it re-inflates, so it bounds isolate memory rather than the on-disk footprint.
|
|
847
917
|
|
|
848
918
|
## Package Exports
|
|
849
919
|
|
package/docs/lifecycle-hooks.md
CHANGED
|
@@ -7,6 +7,7 @@ Think owns the `streamText` call and provides hooks at each stage of the chat tu
|
|
|
7
7
|
| Hook | When it fires | Return | Async |
|
|
8
8
|
| -------------------------------- | ----------------------------------------------------------- | --------------------------------- | ----- |
|
|
9
9
|
| `configureSession(session)` | Once during `onStart` | `Session` | yes |
|
|
10
|
+
| `configureContext()` | Once during `onStart` | `ContextConfig[]` | yes |
|
|
10
11
|
| `beforeTurn(ctx)` | Before `streamText` | `TurnConfig` or void | yes |
|
|
11
12
|
| `beforeStep(ctx)` | Before each model step | `StepConfig` or void | yes |
|
|
12
13
|
| `beforeToolCall(ctx)` | When model calls a tool | `ToolCallDecision` or void | yes |
|
|
@@ -23,6 +24,7 @@ For a turn with two tool calls:
|
|
|
23
24
|
|
|
24
25
|
```
|
|
25
26
|
configureSession() ← once at startup, not per-turn
|
|
27
|
+
configureContext() ← once at startup, not per-turn
|
|
26
28
|
│
|
|
27
29
|
beforeTurn() ← inspect assembled context, override model/tools/prompt
|
|
28
30
|
│
|
|
@@ -53,7 +55,7 @@ onChatResponse() ← message persisted, turn lock released
|
|
|
53
55
|
|
|
54
56
|
## configureSession
|
|
55
57
|
|
|
56
|
-
Called once during Durable Object initialization (`onStart`).
|
|
58
|
+
Called once during Durable Object initialization (`onStart`). Configures the default session handle: compaction and search. Prompt context is declared by [`configureContext`](#configurecontext) instead.
|
|
57
59
|
|
|
58
60
|
```typescript
|
|
59
61
|
configureSession(session: Session): Session | Promise<Session>
|
|
@@ -61,7 +63,7 @@ configureSession(session: Session): Session | Promise<Session>
|
|
|
61
63
|
|
|
62
64
|
```typescript
|
|
63
65
|
import { Think, Session } from "@cloudflare/think";
|
|
64
|
-
import { createCompactFunction } from "agents/
|
|
66
|
+
import { createCompactFunction } from "agents/sessions";
|
|
65
67
|
import { generateText } from "ai";
|
|
66
68
|
|
|
67
69
|
export class MyAgent extends Think<Env> {
|
|
@@ -71,28 +73,62 @@ export class MyAgent extends Think<Env> {
|
|
|
71
73
|
|
|
72
74
|
configureSession(session: Session) {
|
|
73
75
|
return session
|
|
74
|
-
.withContext("soul", {
|
|
75
|
-
provider: { get: async () => "You are a helpful coding assistant." }
|
|
76
|
-
})
|
|
77
|
-
.withContext("memory", {
|
|
78
|
-
description: "Learned facts about the user.",
|
|
79
|
-
maxTokens: 1100
|
|
80
|
-
})
|
|
81
76
|
.onCompaction(
|
|
82
77
|
createCompactFunction({
|
|
83
78
|
summarize: (prompt) =>
|
|
84
79
|
generateText({ model: this.resolveModel(), prompt }).then(
|
|
85
80
|
(r) => r.text
|
|
86
|
-
)
|
|
81
|
+
),
|
|
82
|
+
keepRecentTokens: 20_000
|
|
87
83
|
})
|
|
88
84
|
)
|
|
89
|
-
.compactAfter(100_000)
|
|
90
|
-
.withCachedPrompt();
|
|
85
|
+
.compactAfter(100_000);
|
|
91
86
|
}
|
|
92
87
|
}
|
|
93
88
|
```
|
|
94
89
|
|
|
95
|
-
|
|
90
|
+
The handle also accepts the 0.17 `withContext()` / `withCachedPrompt()` chain and the positional `appendMessage(message, parentId)` form, so an existing override keeps working; see [Upgrading from 0.17](./index.md#upgrading-from-017).
|
|
91
|
+
|
|
92
|
+
`createCompactFunction` takes exactly two options: `summarize`, which calls the model with a prompt and returns its text, and `keepRecentTokens`, the token budget for the recent tail kept verbatim (default `20_000`). `compactAfter(threshold)` gates on the O(1) token estimate Sessions stamps on each row. See the [Sessions documentation](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) for the full API.
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
## configureContext
|
|
97
|
+
|
|
98
|
+
Called once during Durable Object initialization (`onStart`). Declares the prompt context blocks for this agent.
|
|
99
|
+
|
|
100
|
+
```typescript
|
|
101
|
+
configureContext(): ContextConfig[] | Promise<ContextConfig[]>
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
```typescript
|
|
105
|
+
import { Think } from "@cloudflare/think";
|
|
106
|
+
import type { ContextConfig } from "agents/context";
|
|
107
|
+
|
|
108
|
+
export class MyAgent extends Think<Env> {
|
|
109
|
+
getModel() {
|
|
110
|
+
/* ... */
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
configureContext(): ContextConfig[] {
|
|
114
|
+
return [
|
|
115
|
+
{
|
|
116
|
+
label: "soul",
|
|
117
|
+
provider: { get: async () => "You are a helpful coding assistant." }
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
label: "memory",
|
|
121
|
+
description: "Learned facts about the user.",
|
|
122
|
+
maxTokens: 1100
|
|
123
|
+
}
|
|
124
|
+
];
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
A block declared without a `provider` is auto-wired to durable per-agent SQLite, so `memory` above is writable through the `set_context` tool with no extra wiring. When context blocks are configured, Think builds the system prompt from those blocks instead of using `getSystemPrompt()`. The frozen system prompt is always persisted, so a cold wake reuses the exact prompt string the model already cached.
|
|
130
|
+
|
|
131
|
+
The assembled blocks are available as `this.context` once the Lifecycle has started. See the [Context documentation](https://github.com/cloudflare/agents/blob/main/docs/agents/context.md) for providers, tools, and frozen-prompt behavior.
|
|
96
132
|
|
|
97
133
|
---
|
|
98
134
|
|
|
@@ -110,7 +146,7 @@ beforeTurn(ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>
|
|
|
110
146
|
| -------------- | ------------------------- | ------------------------------------------------------------------------ |
|
|
111
147
|
| `system` | `string` | Assembled system prompt (from context blocks or `getSystemPrompt()`) |
|
|
112
148
|
| `messages` | `ModelMessage[]` | Assembled model messages (truncated) |
|
|
113
|
-
| `tools` | `ToolSet` | Merged tool set (workspace + getTools +
|
|
149
|
+
| `tools` | `ToolSet` | Merged tool set (workspace + getTools + context + MCP + client + caller) |
|
|
114
150
|
| `model` | `LanguageModel` | The resolved model (a string from `getModel()` is already resolved here) |
|
|
115
151
|
| `continuation` | `boolean` | Whether this is a continuation turn (auto-continue after tool result) |
|
|
116
152
|
| `body` | `Record<string, unknown>` | Custom body fields from the client request |
|
|
@@ -783,7 +819,7 @@ onChatError(error: unknown, ctx?: ChatErrorContext) {
|
|
|
783
819
|
|
|
784
820
|
## classifyChatError
|
|
785
821
|
|
|
786
|
-
Called when an error occurs during a turn, **before** `onChatError`. Maps a raw provider error into a provider-agnostic category so Think can react without baking provider-specific strings into the framework
|
|
822
|
+
Called when an error occurs during a turn, **before** `onChatError`. Maps a raw provider error into a provider-agnostic category so Think can react without baking provider-specific strings into the framework. The app owns the mapping because it knows which provider and model it talks to.
|
|
787
823
|
|
|
788
824
|
```typescript
|
|
789
825
|
classifyChatError(error: unknown, ctx?: ChatErrorContext): ChatErrorClassification | void
|
package/docs/sub-agents.md
CHANGED
|
@@ -300,14 +300,14 @@ controller.
|
|
|
300
300
|
|
|
301
301
|
Think chat recovery works in sub-agents. The underlying fiber is stored in the sub-agent's own SQLite database, and the top-level parent keeps a small index of active child fibers. When the parent alarm fires, it routes recovery checks into the owning sub-agent, so recovery runs with the sub-agent as `this` even if the child is otherwise idle. Recovered continuations can call `schedule()` inside the sub-agent — the top-level parent owns the physical alarm and routes the continuation back into the child.
|
|
302
302
|
|
|
303
|
-
The external signal lives in memory only. If the Durable Object hibernates mid-turn
|
|
303
|
+
The external signal lives in memory only. If the Durable Object hibernates mid-turn, the recovered turn runs via `continueLastTurn()` **without** the original `options.signal` — the listener was lost on eviction, and the recovery path has no way to reach back to the original caller.
|
|
304
304
|
|
|
305
305
|
In practice this means:
|
|
306
306
|
|
|
307
307
|
- A signal that aborts **after** the DO restarts has no effect on the recovered turn.
|
|
308
308
|
- Subclasses that need the recovered turn to honor a fresh signal should override `onChatRecovery` and reject continuation (`return { continue: false }`) when the original caller is gone.
|
|
309
309
|
- Recovery is best for long-lived chat sub-agents that have their own client reconnect path. Agent tools define a parent-side replay and terminal-state policy for cases where the original parent forwarding loop is gone.
|
|
310
|
-
- If the parent restarts mid-agent-tool run,
|
|
310
|
+
- If the parent restarts mid-agent-tool run, Agent Tools reattaches to the child's durable run, replays stored chunks, and waits for its real terminal result within the configured reattach budget.
|
|
311
311
|
|
|
312
312
|
See [`cloudflare/agents#1406`](https://github.com/cloudflare/agents/issues/1406) for the original motivation, and [Agent Tools](https://github.com/cloudflare/agents/blob/main/docs/agents/agent-tools.md) for the shipped orchestration API.
|
|
313
313
|
|
|
@@ -352,21 +352,9 @@ Both methods produce the same end state as `chat-request-cancel`: inference loop
|
|
|
352
352
|
|
|
353
353
|
## Chat Recovery
|
|
354
354
|
|
|
355
|
-
Think
|
|
355
|
+
Think wraps chat turns in Durable Object fibers for durable execution. When a DO is evicted mid-turn, the turn can be recovered on restart. This works for top-level agents and sub-agents; for sub-agents, the top-level parent alarm drives recovery checks back into the child facet.
|
|
356
356
|
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
```typescript
|
|
360
|
-
export class MyAgent extends Think<Env> {
|
|
361
|
-
chatRecovery = true;
|
|
362
|
-
|
|
363
|
-
getModel() {
|
|
364
|
-
/* ... */
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
```
|
|
368
|
-
|
|
369
|
-
When `chatRecovery` is `true`, every turn entry path is wrapped in `runFiber`: WebSocket chat, sub-agent `chat()` RPC, auto-continuation, `saveMessages()`, `submitMessages()` execution, and `continueLastTurn()`.
|
|
357
|
+
Every turn entry path is wrapped in `runFiber`: WebSocket chat, sub-agent `chat()` RPC, auto-continuation, `saveMessages()`, `submitMessages()` execution, and `continueLastTurn()`. Durable recovery is always enabled; use `chatRecovery` only to tune recovery budgets and terminal behavior.
|
|
370
358
|
|
|
371
359
|
### onChatRecovery
|
|
372
360
|
|
|
@@ -405,8 +393,6 @@ onChatRecovery(ctx: ChatRecoveryContext): ChatRecoveryOptions | void
|
|
|
405
393
|
|
|
406
394
|
```typescript
|
|
407
395
|
export class MyAgent extends Think<Env> {
|
|
408
|
-
chatRecovery = true;
|
|
409
|
-
|
|
410
396
|
getModel() {
|
|
411
397
|
/* ... */
|
|
412
398
|
}
|
|
@@ -449,7 +435,9 @@ onChatRecovery(ctx: ChatRecoveryContext): ChatRecoveryOptions {
|
|
|
449
435
|
|
|
450
436
|
### Recovery budgets and limits
|
|
451
437
|
|
|
452
|
-
|
|
438
|
+
Assign a `chatRecovery` object to tune how long recovery is allowed to run and when it is given up on. A turn that keeps making forward progress survives unbounded interruption — duration is not a bound — as long as it stays under the `maxRecoveryWork` backstop. Recovery is only sealed by one of the limits below.
|
|
439
|
+
|
|
440
|
+
`chatRecovery = false` is no longer supported. If automatic continuation is unsafe, return `{ continue: false }` from `onChatRecovery()`. For cancellation that must survive hibernation, store cancellation intent durably and check it in that hook. See [Controlling automatic continuation](https://github.com/cloudflare/agents/blob/main/docs/agents/chat-agents.md#controlling-automatic-continuation) for side-effect and cost guidance.
|
|
453
441
|
|
|
454
442
|
```typescript
|
|
455
443
|
export class MyAgent extends Think<Env> {
|
package/docs/tools.md
CHANGED
|
@@ -9,7 +9,7 @@ On every turn, Think merges tools from multiple sources. Later sources override
|
|
|
9
9
|
1. **Workspace tools** — `read`, `write`, `edit`, `list`, `find`, `grep`, `delete`, `bash` (built-in)
|
|
10
10
|
2. **`getTools()`** — your custom server-side tools
|
|
11
11
|
3. **Extension tools** — tools from loaded extensions (prefixed by extension name)
|
|
12
|
-
4. **
|
|
12
|
+
4. **Context tools** — `set_context`, `search_context` (from `configureContext`)
|
|
13
13
|
5. **Skill tools** — `activate_skill`, `read_skill_resource`, `run_skill_script` (from `getSkills()`)
|
|
14
14
|
6. **MCP tools** — from connected MCP servers (when `includeMcpTools` is enabled)
|
|
15
15
|
7. **Client tools** — from the browser (see [Client Tools](./client-tools.md))
|
|
@@ -530,7 +530,7 @@ Loaded extensions persist across DO restarts via `extensionManager.restore()`.
|
|
|
530
530
|
|
|
531
531
|
### Extension Context Blocks
|
|
532
532
|
|
|
533
|
-
Extensions can declare context blocks in their manifest. These are automatically
|
|
533
|
+
Extensions can declare context blocks in their manifest. These are automatically added to the agent's context blocks:
|
|
534
534
|
|
|
535
535
|
```typescript
|
|
536
536
|
getExtensions() {
|
package/package.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"tools"
|
|
10
10
|
],
|
|
11
11
|
"type": "module",
|
|
12
|
-
"version": "0.
|
|
12
|
+
"version": "0.18.0",
|
|
13
13
|
"license": "MIT",
|
|
14
14
|
"repository": {
|
|
15
15
|
"directory": "packages/think",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@ai-sdk/anthropic": "^4.0.0",
|
|
25
25
|
"@ai-sdk/openai": "^4.0.0",
|
|
26
|
-
"@cloudflare/codemode": "^0.5.
|
|
26
|
+
"@cloudflare/codemode": "^0.5.2",
|
|
27
27
|
"@cloudflare/shell": "^0.4.3",
|
|
28
28
|
"chat": "^4.31.0",
|
|
29
29
|
"just-bash": "^3.0.2",
|
|
@@ -32,23 +32,23 @@
|
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@ai-sdk/react": "^4.0.0",
|
|
34
34
|
"@chat-adapter/telegram": "^4.31.0",
|
|
35
|
-
"@cloudflare/ai-chat": "^0.
|
|
35
|
+
"@cloudflare/ai-chat": "^0.12.0",
|
|
36
36
|
"@testing-library/react": "^16.3.2",
|
|
37
37
|
"@types/react": "^19.2.17",
|
|
38
38
|
"@types/react-dom": "^19.2.3",
|
|
39
39
|
"@vitejs/plugin-react": "^6.0.3",
|
|
40
|
-
"agents": "^0.
|
|
40
|
+
"agents": "^0.23.0",
|
|
41
41
|
"ai": "^7.0.0",
|
|
42
42
|
"jsdom": "^29.1.1",
|
|
43
43
|
"react": "^19.2.7",
|
|
44
44
|
"react-dom": "^19.2.7",
|
|
45
45
|
"vite": "^8.1.0",
|
|
46
|
-
"zod": "^4.4
|
|
46
|
+
"zod": "^4.5.4"
|
|
47
47
|
},
|
|
48
48
|
"peerDependencies": {
|
|
49
49
|
"@ai-sdk/react": "^3.0.0 || ^4.0.0",
|
|
50
50
|
"@chat-adapter/telegram": "^4.29.0",
|
|
51
|
-
"agents": ">=0.
|
|
51
|
+
"agents": ">=0.23.0 <1.0.0",
|
|
52
52
|
"ai": "^6.0.0 || ^7.0.0",
|
|
53
53
|
"react": "^19.0.0",
|
|
54
54
|
"zod": "^4.0.0"
|