agents 0.32.0 → 0.34.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 +1 -1
- package/dist/{agent-routing-vVMA7m8Y.d.ts → agent-routing-BSoZzNiP.d.ts} +537 -373
- package/dist/agent-routing.d.ts +1 -1
- package/dist/agent-tool-types.d.ts +1 -1
- package/dist/{agent-tools-gGXXkf1z.d.ts → agent-tools-Be-hpRpH.d.ts} +2 -2
- package/dist/agent-tools.d.ts +1 -1
- package/dist/{ai-sdk-Kon40i0q.js → ai-sdk-CRMlEBX7.js} +75 -44
- package/dist/ai-sdk-CRMlEBX7.js.map +1 -0
- package/dist/browser/ai.js +2 -3
- package/dist/browser/ai.js.map +1 -1
- package/dist/browser/index.d.ts +33 -21
- package/dist/browser/index.js +937 -4
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/tools/ai-sdk.d.ts +4 -4
- package/dist/browser/tools/ai-sdk.js +9 -3
- package/dist/browser/tools/ai-sdk.js.map +1 -1
- package/dist/browser/tools/pi.d.ts +11 -8
- package/dist/browser/tools/pi.js +58 -11
- package/dist/browser/tools/pi.js.map +1 -1
- package/dist/browser/tools/tanstack-ai.d.ts +4 -4
- package/dist/browser/tools/tanstack-ai.js +3 -3
- package/dist/browser/tools/tanstack-ai.js.map +1 -1
- package/dist/{browser-D9RNpJuT.d.ts → browser-C9T74n4c.d.ts} +302 -95
- package/dist/browser-tool-DOqT1oSD.js +360 -0
- package/dist/browser-tool-DOqT1oSD.js.map +1 -0
- package/dist/{browser-tool-BhjCcNVE.d.ts → browser-tool-DxAYQY9T.d.ts} +2 -2
- package/dist/capability-DBAKc6UZ.js.map +1 -1
- package/dist/{capability-runner-BiVUtjqC.d.ts → capability-runner-uFOdSANC.d.ts} +3 -2
- package/dist/chat/index.d.ts +37 -6
- package/dist/chat/index.js +39 -3
- package/dist/chat/index.js.map +1 -1
- package/dist/chat/react.js +1 -0
- package/dist/chat/react.js.map +1 -1
- package/dist/chat-sdk/index.d.ts +3 -3
- package/dist/chat-sdk/index.js +1 -1
- package/dist/cli.js +62 -60
- package/dist/client-CkT8voRY.js +3740 -0
- package/dist/client-CkT8voRY.js.map +1 -0
- package/dist/{client-eSfgYvd3.d.ts → client-DqS6oequ.d.ts} +2 -2
- package/dist/client.d.ts +1 -1
- package/dist/{connector-CM-uuxKM.js → connector-Bphz6wIw.js} +414 -3
- package/dist/connector-Bphz6wIw.js.map +1 -0
- package/dist/{conversations-FjHDRZyD.d.ts → conversations-CoAYNW_q.d.ts} +4 -4
- package/dist/{current-agent-CKgT5d1O.d.ts → current-agent-DShbQHDO.d.ts} +24 -3
- package/dist/current-agent-DhoDkSnH.js.map +1 -1
- package/dist/{do-oauth-client-provider-DtNqv7oj.d.ts → do-oauth-client-provider-BsT8-vtd.d.ts} +22 -2
- package/dist/{durable-object-lifecycle-DOI_bzCH.d.ts → durable-object-lifecycle-CRCA6O0W.d.ts} +2 -2
- package/dist/experimental/channels/index.d.ts +2 -2
- package/dist/experimental/channels/web/index.d.ts +2 -2
- package/dist/experimental/channels/web/index.js +1 -1
- package/dist/{gateway-BFO6vRDn.d.ts → gateway-Dz8zyZBJ.d.ts} +2 -2
- package/dist/harness/ai-sdk/index.d.ts +2 -2
- package/dist/harness/container/index.d.ts +2 -2
- package/dist/harness/container/index.js +1 -1
- package/dist/harness/container/index.js.map +1 -1
- package/dist/harness/opencode/index.d.ts +1 -1
- package/dist/harness/pi/index.d.ts +200 -37
- package/dist/harness/pi/index.js +202 -100
- package/dist/harness/pi/index.js.map +1 -1
- package/dist/harness/think/index.d.ts +2 -2
- package/dist/{images-CfuRCjwq.js → images-D4gtE06D.js} +119 -27
- package/dist/images-D4gtE06D.js.map +1 -0
- package/dist/{index-8k4qsX1T.d.ts → index-BXVgv6tp.d.ts} +4 -4
- package/dist/{index-BEL3ZV-s.d.ts → index-Cs7Ed9la.d.ts} +2 -2
- package/dist/{index-CBt8oRJt.d.ts → index-XiZxauMU.d.ts} +3 -3
- package/dist/index.d.ts +21 -21
- package/dist/index.js +2 -2
- package/dist/{input-schema-BQykTEp_.js → input-schema-D6GilRXI.js} +3 -3
- package/dist/input-schema-D6GilRXI.js.map +1 -0
- package/dist/{input-schema-B0Etuo-o.js → input-schema-y8W5bOdM.js} +3 -3
- package/dist/input-schema-y8W5bOdM.js.map +1 -0
- package/dist/internal_context.d.ts +1 -1
- package/dist/lifecycle/index.d.ts +3 -3
- package/dist/lifecycle/index.js +1 -1
- package/dist/{lifecycle-v1rKHV2C.js → lifecycle-CB5Dmtrt.js} +126 -38
- package/dist/lifecycle-CB5Dmtrt.js.map +1 -0
- package/dist/mcp/client/do-oauth-client-provider.d.ts +1 -1
- package/dist/mcp/client/do-oauth-client-provider.js +45 -2
- package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/client/index.d.ts +42 -36
- package/dist/mcp/client/index.js +2 -2
- package/dist/mcp/index.d.ts +16 -16
- package/dist/mcp/index.js +2 -2
- package/dist/models/ai-sdk/index.d.ts +9 -5
- package/dist/models/ai-sdk/index.js +1 -1
- package/dist/models/opencode/index.d.ts +3 -3
- package/dist/models/opencode/index.js +2 -2
- package/dist/models/opencode/index.js.map +1 -1
- package/dist/models/pi-ai/index.d.ts +4 -4
- package/dist/models/pi-ai/index.js +64 -170
- package/dist/models/pi-ai/index.js.map +1 -1
- package/dist/{options-CiIsJHXR.d.ts → options-CiXaymmZ.d.ts} +2 -2
- package/dist/queue/index.d.ts +1 -1
- package/dist/queue/index.js +1 -1
- package/dist/{queue-CcIjVYTE.js → queue-B_wl6K0Z.js} +24 -5
- package/dist/queue-B_wl6K0Z.js.map +1 -0
- package/dist/react.d.ts +2 -2
- package/dist/routing/index.d.ts +2 -2
- package/dist/{scheduler-BCLESHSC.d.ts → scheduler-CTpR0Ct0.d.ts} +2 -2
- package/dist/{scheduler-FIHv2-kJ.js → scheduler-DGNEmxQR.js} +2 -1
- package/dist/scheduler-DGNEmxQR.js.map +1 -0
- package/dist/schedules/index.d.ts +1 -1
- package/dist/schedules/index.js +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/{session-7CDgVE0z.js → session-CRY0bGiI.js} +423 -411
- package/dist/session-CRY0bGiI.js.map +1 -0
- package/dist/sessions/index.d.ts +1 -1
- package/dist/{settings-Dk2il2Hf.js → settings-D2F_qONv.js} +11 -2
- package/dist/settings-D2F_qONv.js.map +1 -0
- package/dist/{src-DoGNJ4Ud.js → src-BO1FdLK1.js} +145 -86
- package/dist/src-BO1FdLK1.js.map +1 -0
- package/dist/state/index.d.ts +1 -1
- package/dist/streams/index.d.ts +1 -1
- package/dist/{streams-vrCtbUIn.d.ts → streams-CAZxZBDg.d.ts} +2 -2
- package/dist/sub-routing.d.ts +12 -12
- package/dist/tasks/index.d.ts +1 -1
- package/dist/tasks/index.js +1 -1
- package/dist/{tasks-BN_5AWqI.js → tasks-Cf_UfEO4.js} +2 -1
- package/dist/{tasks-BN_5AWqI.js.map → tasks-Cf_UfEO4.js.map} +1 -1
- package/dist/{tasks-E89KdwkS.d.ts → tasks-Cs8ilctE.d.ts} +2 -2
- package/dist/{tool-DkT_DJBm.js → tool-CmAGY6Fo.js} +24 -3
- package/dist/tool-CmAGY6Fo.js.map +1 -0
- package/dist/{tool-CxKsvxjm.js → tool-Kxcj8_22.js} +24 -4
- package/dist/tool-Kxcj8_22.js.map +1 -0
- package/dist/{tool-helpers-BI7ifO2S.js → tool-helpers-F3_Wy2YX.js} +2 -2
- package/dist/{tool-helpers-BI7ifO2S.js.map → tool-helpers-F3_Wy2YX.js.map} +1 -1
- package/dist/{transport-5moD2pW5.d.ts → transport-hV8AW4Bv.d.ts} +45 -12
- package/dist/voice/index.d.ts +2 -2
- package/dist/web/fetch/index.js +1 -1
- package/dist/web/fetch/tools/ai-sdk.js +2 -2
- package/dist/web/fetch/tools/pi.d.ts +9 -7
- package/dist/web/fetch/tools/pi.js +31 -7
- package/dist/web/fetch/tools/pi.js.map +1 -1
- package/dist/web/fetch/tools/tanstack-ai.js +2 -2
- package/dist/web/search/index.js +1 -1
- package/dist/web/search/tools/ai-sdk.js +2 -2
- package/dist/web/search/tools/pi.d.ts +9 -4
- package/dist/web/search/tools/pi.js +27 -11
- package/dist/web/search/tools/pi.js.map +1 -1
- package/dist/web/search/tools/tanstack-ai.js +2 -2
- package/dist/websockets/index.d.ts +2 -2
- package/dist/websockets/index.js +1 -1
- package/dist/{websockets-C6SJtWCJ.js → websockets-W4uhRg4-.js} +68 -5
- package/dist/websockets-W4uhRg4-.js.map +1 -0
- package/dist/workflow-types.d.ts +1 -1
- package/dist/workflows.d.ts +1 -1
- package/docs/agent-class.md +30 -4
- package/docs/browse-the-web.md +50 -3
- package/docs/chat-agents.md +13 -10
- package/docs/client-tools-continuation.md +1 -1
- package/docs/codemode.md +1 -1
- package/docs/configuration.md +6 -3
- package/docs/cross-domain-authentication.md +1 -1
- package/docs/fetch-the-web.md +20 -0
- package/docs/harnesses/pi.md +242 -33
- package/docs/harnesses/think.md +1 -1
- package/docs/http-websockets.md +40 -32
- package/docs/human-in-the-loop.md +2 -2
- package/docs/lifecycle.md +56 -0
- package/docs/mcp-client.md +104 -7
- package/docs/models-pi-ai.md +24 -10
- package/docs/models.md +42 -17
- package/docs/resumable-streaming.md +1 -1
- package/docs/retries.md +3 -6
- package/docs/search-the-web.md +10 -0
- package/docs/voice.md +1 -1
- package/package.json +16 -9
- package/dist/ai-sdk-Kon40i0q.js.map +0 -1
- package/dist/browser-1eUbPvC2.js +0 -931
- package/dist/browser-1eUbPvC2.js.map +0 -1
- package/dist/browser-tool-DRan7Lk6.js +0 -497
- package/dist/browser-tool-DRan7Lk6.js.map +0 -1
- package/dist/client-DMWujQJ1.js +0 -2325
- package/dist/client-DMWujQJ1.js.map +0 -1
- package/dist/connector-CM-uuxKM.js.map +0 -1
- package/dist/images-CfuRCjwq.js.map +0 -1
- package/dist/input-schema-B0Etuo-o.js.map +0 -1
- package/dist/input-schema-BQykTEp_.js.map +0 -1
- package/dist/lifecycle-v1rKHV2C.js.map +0 -1
- package/dist/queue-CcIjVYTE.js.map +0 -1
- package/dist/scheduler-FIHv2-kJ.js.map +0 -1
- package/dist/session-7CDgVE0z.js.map +0 -1
- package/dist/settings-Dk2il2Hf.js.map +0 -1
- package/dist/src-DoGNJ4Ud.js.map +0 -1
- package/dist/tool-CxKsvxjm.js.map +0 -1
- package/dist/tool-DkT_DJBm.js.map +0 -1
- package/dist/websockets-C6SJtWCJ.js.map +0 -1
package/docs/harnesses/pi.md
CHANGED
|
@@ -11,10 +11,10 @@ Pi owns everything about a run: the transcript, the inbox of steers and follow-u
|
|
|
11
11
|
## Install the Pi packages
|
|
12
12
|
|
|
13
13
|
```sh
|
|
14
|
-
npm install agents @earendil-works/pi-durable @earendil-works/pi-ai @earendil-works/chord
|
|
14
|
+
npm install agents @earendil-works/pi-durable @earendil-works/pi-ai @earendil-works/pi-schema @earendil-works/chord
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
The
|
|
17
|
+
The four Pi packages are optional peer dependencies of `agents`, at `~1.6.0`. pi-durable is experimental, and its API can change in minor releases, so `agents` supports one Pi minor at a time. A new Pi minor can also store conversations in formats the previous one cannot read: after a conversation runs on Pi 1.6, rolling your Worker back to an `agents` version on Pi 1.5 blocks its tool calls and model requests, as Pi 1.6 stores them in versions Pi 1.5 does not run. Roll forward to fix a bad deploy instead. The examples use Workers AI through the `AI` binding. To configure the binding and choose other models, refer to [Models for pi-ai](../models-pi-ai.md).
|
|
18
18
|
|
|
19
19
|
## Create the harness
|
|
20
20
|
|
|
@@ -43,7 +43,7 @@ export class Assistant extends DurableObject<Env> {
|
|
|
43
43
|
);
|
|
44
44
|
},
|
|
45
45
|
defaults: {
|
|
46
|
-
model: this.ai("@cf/
|
|
46
|
+
model: this.ai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
47
47
|
thinkingLevel: "low"
|
|
48
48
|
}
|
|
49
49
|
});
|
|
@@ -61,7 +61,7 @@ export class Assistant extends DurableObject<Env> {
|
|
|
61
61
|
| Option | What it is |
|
|
62
62
|
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
63
63
|
| `harness` | Required. Receives `{ storage, context, onWake }` and returns Pi's `Harness`, usually from `Harness.open`. Pass `onWake` to `Harness.open`, so the object can hibernate while Pi's tasks sleep (see [How recovery works](#how-recovery-works)). Models, the registry, `settings`, `env` and `onReport` are all yours to build here. |
|
|
64
|
-
| `defaults` | What a new session starts with: `model`, a pi-ai `Model` such as `ai("@cf/…")`, and `
|
|
64
|
+
| `defaults` | What a new session starts with: `model`, a pi-ai `Model` such as `ai("@cf/…")`, `thinkingLevel`, and `maxTurns`, the most tool rounds one run takes before it ends unanswered (`turn_limit`). Without a model, a session's prompts end unanswered (`no_model`) until one is set. |
|
|
65
65
|
|
|
66
66
|
Create the registry per object, as the `registry` field above does, not at module scope: Pi keeps every `Harness` subscribed to its registry until the `Harness` closes, and an evicted object never closes it.
|
|
67
67
|
|
|
@@ -74,13 +74,13 @@ A model in `defaults` or `session.setModel()` is stored by its provider and id o
|
|
|
74
74
|
Tools and system prompt sections are Pi extensions. An extension is a plain object with a `name`, `tools` and `sections`:
|
|
75
75
|
|
|
76
76
|
```ts
|
|
77
|
-
import { Type } from "@earendil-works/pi-ai";
|
|
78
77
|
import {
|
|
79
78
|
createRegistry,
|
|
80
79
|
type ToolRegistration
|
|
81
80
|
} from "@earendil-works/pi-durable";
|
|
81
|
+
import { obj, str } from "@earendil-works/pi-schema";
|
|
82
82
|
|
|
83
|
-
const WordCount =
|
|
83
|
+
const WordCount = obj({ text: str() });
|
|
84
84
|
|
|
85
85
|
const wordCount: ToolRegistration<typeof WordCount> = {
|
|
86
86
|
name: "word_count",
|
|
@@ -180,7 +180,7 @@ const { text } = await this.harness.prompt("What is 47 × 19?");
|
|
|
180
180
|
|
|
181
181
|
// Another session, on a cheaper model.
|
|
182
182
|
const session = await this.harness.sessions.create();
|
|
183
|
-
await session.setModel(this.ai("@cf/
|
|
183
|
+
await session.setModel(this.ai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"));
|
|
184
184
|
|
|
185
185
|
// Durable once it returns; the same operation id twice is one submission.
|
|
186
186
|
const receipt = await session.submit("Summarize the latest report", {
|
|
@@ -189,24 +189,151 @@ const receipt = await session.submit("Summarize the latest report", {
|
|
|
189
189
|
const result = await session.wait(receipt.operationId);
|
|
190
190
|
```
|
|
191
191
|
|
|
192
|
-
| Call
|
|
193
|
-
|
|
|
194
|
-
| `prompt(input)`
|
|
195
|
-
| `submit(input, { operationId, whenBusy, entry })` | Hands the input to Pi and returns as soon as Pi has saved it, without waiting for the model. If the session is already working, the input waits until that work finishes. With `whenBusy: "steer"`, it joins the running work instead, after the current round of tool calls. With `whenBusy: "reject"`, it is not admitted: `submit` rejects with Pi's `ConversationBusy` and nothing is saved, so the same `operationId` can be submitted again later. `entry` records where the input came from (see below). |
|
|
196
|
-
| `wait(operationId, signal?)`
|
|
197
|
-
| `steer(input)`
|
|
198
|
-
| `
|
|
199
|
-
| `
|
|
200
|
-
| `
|
|
201
|
-
| `messages()`
|
|
202
|
-
| `
|
|
203
|
-
| `
|
|
204
|
-
| `
|
|
205
|
-
| `
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
192
|
+
| Call | What it does |
|
|
193
|
+
| ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
194
|
+
| `prompt(input)` | Submits and waits: the answer, and the transcript after it. |
|
|
195
|
+
| `submit(input, { operationId, whenBusy, whenIdle, onAbort, entry, notify })` | Hands the input to Pi and returns as soon as Pi has saved it, without waiting for the model. If the session is already working, the input waits until that work finishes. With `whenBusy: "steer"`, it joins the running work instead, after the current round of tool calls. With `whenBusy: "reject"`, it is not admitted: `submit` rejects with Pi's `ConversationBusy` and nothing is saved, so the same `operationId` can be submitted again later. With `whenIdle: "reject"`, an idle session refuses the input the same way, with Pi's `ConversationIdle`, so it never starts a run of its own; with `whenBusy: "steer"`, the input joins the running work or is refused, without racing the run's end. With `onAbort: "keep"`, aborting the session leaves the input queued instead of withdrawing it, and the next input, `continue()` or `reset()` runs it first (a kept steer waits for the next input or `continue()`); use it for input its sender cannot send again, such as another agent's message. `entry` records where the input came from (see below). `notify` names a Pi task to signal when the input settles (see [Wait for a subagent](#wait-for-a-subagent)). |
|
|
196
|
+
| `wait(operationId, signal?)` | The operation's result once Pi settles it. Aborting `signal` stops only the wait, not the work. |
|
|
197
|
+
| `steer(input)` | `submit` with `whenBusy: "steer"`. |
|
|
198
|
+
| `continue({ operationId, notify })` | Starts a run on the transcript as it is, without a new message, for example after a run ended unanswered. Only an idle session takes one: a busy one rejects with Pi's `ConversationBusy`. Inputs kept behind a failed run or an abort join it. A transcript that ends in an answer has nothing to continue: the operation settles `unanswered` with reason `nothing_to_answer`. `notify` works as it does on `submit`. |
|
|
199
|
+
| `abort(operationId?)` | Withdraws a queued operation, or with no id, stops everything running in the session and withdraws its queued inputs, apart from those submitted with `onAbort: "keep"`. |
|
|
200
|
+
| `pending()` | Operations Pi has not settled yet: queued, or part of the running work. |
|
|
201
|
+
| `messages()` | Pi's transcript entries since the newest reset. |
|
|
202
|
+
| `watch(window?)` | Pi's view of the session: the newest transcript entries, and the session's live state, such as the answer being streamed, running tools, and why the last run ended without an answer. Each change carries Pi's operations, for a client that forwards them. |
|
|
203
|
+
| `entries(query, limit)` | A page of the session's transcript, including entries before its resets. Pages a transcript longer than the view's window. |
|
|
204
|
+
| `reset(handoff?)` | Starts a new context, optionally from a handoff note. Inputs kept behind a failed run or an abort start a run in it. |
|
|
205
|
+
| `setModel(model)` | Changes this session's model. |
|
|
206
|
+
| `busy()` | Whether a run is going. |
|
|
207
|
+
|
|
208
|
+
`harness.prompt()`, `submit()`, `wait()`, `abort()`, `messages()` and `pending()` act on the root session, or on `{ session }`. `harness.sessions` has `create()`, `fork(from)`, `get(id)` and `list()`, which includes sessions subagents created. `ROOT_SESSION` is the root's id. `harness.signal()` delivers a signal to a parked tool call (see [Tools that wait](#tools-that-wait)).
|
|
209
|
+
|
|
210
|
+
The root session is created on its first use, with `defaults`: the first call that works with it, such as `prompt()`, `submit()`, `messages()` or `watch()`, creates it. Until then `sessions.list()` does not include it, and Pi's own `pi.conversation(ROOT_CONVERSATION_ID)` through `harness.pi()` returns `undefined`. Pi's own `pi.root()` would create it without `defaults`, so use `harness.root()` instead. Calls that only read around it, such as `pending()`, `busy()` and `list()`, do not create it. To create it yourself, with your own configuration or history, call `harness.root()` (see [Seed a session with an existing history](#seed-a-session-with-an-existing-history)).
|
|
211
|
+
|
|
212
|
+
`messages()` and `watch()` are Pi's own records, not a UI-ready chat transcript. The example below projects them into one.
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
const watch = await session.watch();
|
|
216
|
+
render(watch.value);
|
|
217
|
+
watch.start(async (call) => {
|
|
218
|
+
if (call.kind === "value") render(call.value);
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
function render(view: ConversationView): void {
|
|
222
|
+
const live = view.docs["pi.live"] as LiveState;
|
|
223
|
+
drawEntries(view.entries);
|
|
224
|
+
if (live.generation?.message) drawStreaming(live.generation.message);
|
|
225
|
+
if (live.runFailure) drawFailure(live.runFailure);
|
|
226
|
+
}
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
The window holds the newest 50 entries and grows to 100 before its oldest leave. To render a longer transcript, merge each value into Pi's `ConversationTranscript`, which pages older entries with `session.entries()`.
|
|
230
|
+
|
|
231
|
+
### Seed a session with an existing history
|
|
232
|
+
|
|
233
|
+
To start a session from a chat history your application already has, such as one imported from another system, write it into the session's transcript in the commit that creates the session. `harness.root()`, `sessions.create()` and `sessions.fork()` take Pi's `init` for that, and `agent` for the session's configuration:
|
|
234
|
+
|
|
235
|
+
| Option | What it is |
|
|
236
|
+
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
237
|
+
| `agent` | Pi's `AgentChange`, such as `instructions` or `thinkingLevel`. For the root and `create()`, it is applied over `defaults`. A fork starts with the configuration of the session it forks, and `agent` is applied over that. As in Pi, a field that is `undefined` leaves the value underneath in place, and `null` clears it. |
|
|
238
|
+
| `init` | Pi's `ConversationInit`, `(tx, conversationId) => …`. It runs inside the commit that creates the session, after `agent`. Append one entry per message with `tx.appendEntry()`. If it throws, the commit fails and the session is not created. |
|
|
239
|
+
|
|
240
|
+
Use Pi's own entry kinds, so Pi treats the messages as if they had happened in the session: `UserEntry` for a user message, `AssistantEntry` for a model message, and `ToolResultEntry` for a tool result, with an empty `diagnostics` list. An assistant message needs `usage`, which Pi sums; an imported message has none, so give it zeros. Its `api`, `provider` and `model` name the model that wrote it, as on a message Pi stores itself; the example takes them from a model of `createAI`.
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
import type {
|
|
244
|
+
Api,
|
|
245
|
+
AssistantMessage,
|
|
246
|
+
Model,
|
|
247
|
+
Usage
|
|
248
|
+
} from "@earendil-works/pi-ai";
|
|
249
|
+
import {
|
|
250
|
+
AssistantEntry,
|
|
251
|
+
ToolResultEntry,
|
|
252
|
+
UserEntry,
|
|
253
|
+
type ConversationInit
|
|
254
|
+
} from "@earendil-works/pi-durable";
|
|
255
|
+
|
|
256
|
+
const NO_USAGE: Usage = {
|
|
257
|
+
input: 0,
|
|
258
|
+
output: 0,
|
|
259
|
+
cacheRead: 0,
|
|
260
|
+
cacheWrite: 0,
|
|
261
|
+
totalTokens: 0,
|
|
262
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
/** The history, one entry per message, as `model` wrote it. */
|
|
266
|
+
function history(model: Model<Api>): ConversationInit {
|
|
267
|
+
const answer = (
|
|
268
|
+
content: AssistantMessage["content"],
|
|
269
|
+
stopReason: AssistantMessage["stopReason"]
|
|
270
|
+
): AssistantMessage => ({
|
|
271
|
+
role: "assistant",
|
|
272
|
+
content,
|
|
273
|
+
api: model.api,
|
|
274
|
+
provider: model.provider,
|
|
275
|
+
model: model.id,
|
|
276
|
+
usage: NO_USAGE,
|
|
277
|
+
stopReason,
|
|
278
|
+
timestamp: Date.now()
|
|
279
|
+
});
|
|
280
|
+
return async (tx, conversationId) => {
|
|
281
|
+
const timestamp = Date.now();
|
|
282
|
+
await tx.appendEntry(UserEntry, conversationId, {
|
|
283
|
+
model: [
|
|
284
|
+
{ role: "user", content: "How many words is the draft?", timestamp }
|
|
285
|
+
]
|
|
286
|
+
});
|
|
287
|
+
await tx.appendEntry(AssistantEntry, conversationId, {
|
|
288
|
+
model: [
|
|
289
|
+
answer(
|
|
290
|
+
[
|
|
291
|
+
{
|
|
292
|
+
type: "toolCall",
|
|
293
|
+
id: "call-1",
|
|
294
|
+
name: "word_count",
|
|
295
|
+
arguments: { text: "The quick brown fox" }
|
|
296
|
+
}
|
|
297
|
+
],
|
|
298
|
+
"toolUse"
|
|
299
|
+
)
|
|
300
|
+
]
|
|
301
|
+
});
|
|
302
|
+
await tx.appendEntry(ToolResultEntry, conversationId, {
|
|
303
|
+
model: [
|
|
304
|
+
{
|
|
305
|
+
role: "toolResult",
|
|
306
|
+
toolCallId: "call-1",
|
|
307
|
+
toolName: "word_count",
|
|
308
|
+
content: [{ type: "text", text: "4" }],
|
|
309
|
+
isError: false,
|
|
310
|
+
timestamp
|
|
311
|
+
}
|
|
312
|
+
],
|
|
313
|
+
data: { diagnostics: [] }
|
|
314
|
+
});
|
|
315
|
+
await tx.appendEntry(AssistantEntry, conversationId, {
|
|
316
|
+
model: [
|
|
317
|
+
answer([{ type: "text", text: "The draft is 4 words long." }], "stop")
|
|
318
|
+
]
|
|
319
|
+
});
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// In the Durable Object:
|
|
324
|
+
const { session, created } = await this.harness.root({
|
|
325
|
+
agent: { instructions: "You are an editor." },
|
|
326
|
+
init: history(this.ai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"))
|
|
327
|
+
});
|
|
328
|
+
if (!created) {
|
|
329
|
+
// The root already existed, so the history was not written.
|
|
330
|
+
}
|
|
331
|
+
await session.prompt("Make it longer.");
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
`harness.root()` returns the root session and `created`. When the root does not exist yet, it creates it with `agent` and `init` in one commit, and `created` is `true`. When it already exists, because a call used it first or an earlier `root()` created it, nothing is written, `init` does not run, and `created` is `false`. So call `root()` before anything else uses the root, and check `created` rather than assuming the history was written. A `root()` whose `init` throws creates nothing, so a later `root()` can try again.
|
|
335
|
+
|
|
336
|
+
`sessions.create({ agent, init })` and `sessions.fork(from, { agent, init })` seed the session they create the same way. A fork's `init` appends after the history it copies from `from`.
|
|
210
337
|
|
|
211
338
|
### Label input the user did not type
|
|
212
339
|
|
|
@@ -218,15 +345,95 @@ await session.submit("The deploy was approved. Run the migration.", {
|
|
|
218
345
|
});
|
|
219
346
|
```
|
|
220
347
|
|
|
221
|
-
The model sees no difference: it still gets the text as a user message. Only the transcript changes. The input is stored with your `kind` and `data` instead of `pi.user`, and `messages()` and `
|
|
348
|
+
The model sees no difference: it still gets the text as a user message. Only the transcript changes. The input is stored with your `kind` and `data` instead of `pi.user`, and `messages()`, `watch()` and `entries()` return both, so your UI can show it differently, for example as "Approved by ben" rather than as something the user said. Pi reserves kinds that start with `pi.`, so use a prefix of your own, such as `app.`.
|
|
222
349
|
|
|
223
350
|
The kind is a label, not a permission. It records what your code said the input was, and nothing checks it. The model reads the input as if the user wrote it, so do not put anything in it that you would not let the user send.
|
|
224
351
|
|
|
225
352
|
The example app folds the transcript into chat messages, ignores `kind` and `data`, and shows every input as a user message. To show labelled input differently, read them from the entry.
|
|
226
353
|
|
|
354
|
+
### Tools that wait
|
|
355
|
+
|
|
356
|
+
A Pi tool can park instead of returning: it returns `{ sleep: { signals, until } }`, and Pi runs it again when one of the signals arrives or the deadline passes. While it waits, the call holds no invocation, so the object can hibernate or be evicted. Deliver a signal with `harness.signal()`, for example from the request that carries a person's answer:
|
|
357
|
+
|
|
358
|
+
```ts
|
|
359
|
+
import { defineSignal } from "@earendil-works/pi-durable";
|
|
360
|
+
import { obj, str } from "@earendil-works/pi-schema";
|
|
361
|
+
|
|
362
|
+
const Answer = defineSignal({
|
|
363
|
+
name: "app.answer",
|
|
364
|
+
version: 1,
|
|
365
|
+
schema: obj({ text: str() })
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
// In the tool's execute(args, api, context): park until the answer comes.
|
|
369
|
+
const answer = await api.readSignal(Answer, "answer", context);
|
|
370
|
+
if (answer !== undefined && "value" in answer) {
|
|
371
|
+
return { output: [{ type: "text", text: answer.value.text }] };
|
|
372
|
+
}
|
|
373
|
+
await showQuestion(api.taskId, args.question);
|
|
374
|
+
return { sleep: { signals: [Answer.key("answer")] } };
|
|
375
|
+
|
|
376
|
+
// Later, in your agent, with the task id the question was shown with:
|
|
377
|
+
await this.harness.signal(taskId, Answer, "answer", { text: "Yes" });
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
`harness.signal()` returns Pi's result: `delivered`, or `duplicate`, `invalid`, `closed` or `not_found` when the call did not take the value. It schedules the harness's wake before it hands Pi the value, so if the object dies while the woken call runs, the wake's alarm restarts it. Deliver signals through it rather than through `harness.pi()`.
|
|
381
|
+
|
|
382
|
+
A tool can also give a `cancel()`, which Pi runs when a parked call is aborted, for example to cancel the work it was waiting on. A `beforeTool` hook can park a call the same way before it runs, to hold it for an approval, a rate limit or a budget. Pi runs that hook again each time it reopens, so the hook must be idempotent.
|
|
383
|
+
|
|
384
|
+
While a call is parked, its run is still going: `pending()` lists its operation as `running`, `busy()` is `true`, and Pi's `pi.live` shows the call's slot as `sleeping` or `waiting`. Refer to [Tools that park](https://github.com/earendil-works/pi/tree/main/packages/durable#tools-that-park) in the pi-durable README for the rules a parking tool follows.
|
|
385
|
+
|
|
386
|
+
#### Wait for a subagent
|
|
387
|
+
|
|
388
|
+
To have a tool wait for another session's answer, create the session owned by the call, submit to it with `notify`, and park on Pi's `SubmissionSettled` signal under the same key. This is Pi's own subagent pattern:
|
|
389
|
+
|
|
390
|
+
```ts
|
|
391
|
+
import { SubmissionSettled } from "@earendil-works/pi-durable";
|
|
392
|
+
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
393
|
+
|
|
394
|
+
// Inside a tool's execute({ task }, api, context):
|
|
395
|
+
const state = await api.readSignal(SubmissionSettled, "answered", context);
|
|
396
|
+
if (state !== undefined && "value" in state) {
|
|
397
|
+
const settled = state.value;
|
|
398
|
+
if (settled.status !== "done" || settled.type === "write") {
|
|
399
|
+
return {
|
|
400
|
+
output: [{ type: "text", text: `Subagent ended: ${settled.status}` }],
|
|
401
|
+
isError: true
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
const answer = await api.commit((tx) => tx.entry(settled.answer), context);
|
|
405
|
+
const message = answer?.model?.[0] as AssistantMessage;
|
|
406
|
+
return { output: message.content.filter((part) => part.type === "text") };
|
|
407
|
+
}
|
|
408
|
+
// The call's own child: found again on a rerun, stopped with the call.
|
|
409
|
+
const child = await api.commit(async (tx) => {
|
|
410
|
+
const existing = (await tx.scanConversations({ ownerTaskId: api.taskId }, 1))
|
|
411
|
+
.items[0];
|
|
412
|
+
if (existing !== undefined) return existing.id;
|
|
413
|
+
const created = await tx.createConversation({
|
|
414
|
+
ownership: { kind: "task", taskId: api.taskId }
|
|
415
|
+
});
|
|
416
|
+
return created.id;
|
|
417
|
+
}, context);
|
|
418
|
+
await (
|
|
419
|
+
await api.conversation(child, context)
|
|
420
|
+
)?.submit(
|
|
421
|
+
{
|
|
422
|
+
type: "input",
|
|
423
|
+
content: task,
|
|
424
|
+
requestId: `subagent:${api.taskId}`,
|
|
425
|
+
notify: { taskId: api.taskId, key: "answered" }
|
|
426
|
+
},
|
|
427
|
+
context
|
|
428
|
+
);
|
|
429
|
+
return { sleep: { signals: [SubmissionSettled.key("answered")] } };
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
When the child's input settles, Pi delivers the settled record to the call in the same commit, and the tool runs again with it. Because the child is owned by the call, aborting the parent session stops the child too, and a rerun before the park was stored finds the same child instead of creating another. The `requestId` makes a rerun find the same submission. If the task to notify has ended or does not exist, the input still settles as usual. `session.submit()` and `session.continue()` take the same `notify` option, for a child your own code created.
|
|
433
|
+
|
|
227
434
|
### Inputs queued behind a failed run
|
|
228
435
|
|
|
229
|
-
A run fails with `model_error` when the model errors and Pi does not retry or the error outlasts its retries,
|
|
436
|
+
A run fails with `model_error` when the model errors and Pi does not retry or the error outlasts its retries, with `no_model` when the session has no usable model, and with `turn_limit` when it reaches `defaults.maxTurns` (after that round's tools ran). Its own operation settles `unanswered` with that reason; to answer it once the cause is fixed, call `session.continue()`. Pi's `settings.afterFailedRun` decides what happens to the inputs queued behind it. Refer to [Failures and Recovery](https://github.com/earendil-works/pi/tree/main/packages/durable#failures-and-recovery) in the pi-durable README for what each value does. Set it in the factory:
|
|
230
437
|
|
|
231
438
|
```ts
|
|
232
439
|
harness: ({ storage, context, onWake }) =>
|
|
@@ -248,20 +455,22 @@ harness: ({ storage, context, onWake }) =>
|
|
|
248
455
|
| `continue` | `wait()` returns their results as usual. If the cause persists, such as a missing model, each queued input fails in its own run. |
|
|
249
456
|
| `withdraw` | `wait()` returns `{ status: "unanswered", reason: "run_failed" }`, and `pending()` no longer lists them. |
|
|
250
457
|
|
|
251
|
-
With `keep`, the kept inputs are not work to Pi: its `wake()` counts tasks, not queued inputs. The wake job completes, and the object can hibernate until the next `submit()` or `reset()`. Pass a `signal` to `wait()` if a caller should not wait that long. To withdraw a kept input, call `abort(operationId)`, which settles it `unanswered` with reason `aborted`. `session.abort()` with no id stops the whole session, which withdraws every kept input too
|
|
458
|
+
With `keep`, the kept inputs are not work to Pi: its `wake()` counts tasks, not queued inputs. The wake job completes, and the object can hibernate until the next `submit()` or `reset()`. Pass a `signal` to `wait()` if a caller should not wait that long. To withdraw a kept input, call `abort(operationId)`, which settles it `unanswered` with reason `aborted`. `session.abort()` with no id stops the whole session, which withdraws every kept input too, apart from those submitted with `onAbort: "keep"`.
|
|
252
459
|
|
|
253
460
|
## How recovery works
|
|
254
461
|
|
|
255
|
-
The harness schedules one lifecycle job, driven by Pi's `wake()`. While Pi has work running, the job waits on it and refreshes itself as a heartbeat. While Pi's tasks sleep, such as a retry backoff, the job is due when the first one wakes. Pi says when through the `onWake` the factory passes to `Harness.open`, and sets no in-memory timer of its own, so the object can hibernate until then. A task that sleeps while other work runs, such as a compaction retry during a generation, is resumed from the job's wait when it is due. Without `onWake` the harness still works, but Pi's timer keeps the object in memory, and billed, while a task sleeps, and the harness logs a warning. When Pi has nothing to do, the job completes. If the object is evicted or crashes, the job is still due, so its alarm restarts the object. Pi reopens its stored state and resumes the session's work: a replay-safe tool call runs again, and an unsafe one is reported to the model as interrupted.
|
|
462
|
+
The harness schedules one lifecycle job, driven by Pi's `wake()`. While Pi has work running, the job waits on it and refreshes itself as a heartbeat. While Pi's tasks sleep, such as a retry backoff, the job is due when the first one wakes. Pi says when through the `onWake` the factory passes to `Harness.open`, and sets no in-memory timer of its own, so the object can hibernate until then. A task that sleeps while other work runs, such as a compaction retry during a generation, is resumed from the job's wait when it is due. Without `onWake` the harness still works, but Pi's timer keeps the object in memory, and billed, while a task sleeps, and the harness logs a warning. When Pi has nothing to do, the job completes. That includes a tool parked on a signal with no deadline: nothing is due, so no alarm is set, and the object sleeps until your code delivers the signal with `harness.signal()`, which opens Pi again, schedules the wake and resumes the call. If the object is evicted or crashes, the job is still due, so its alarm restarts the object. Pi reopens its stored state and resumes the session's work: a replay-safe tool call runs again, and an unsafe one is reported to the model as interrupted. A model request cut off mid-answer is not sent again at once: it counts as a failed attempt under `settings.retry`, and the next attempt waits out the backoff. With no retry left, the operation ends unanswered with reason `interrupted`.
|
|
463
|
+
|
|
464
|
+
Pi shows a streaming answer and running tool output at once, but stores them in batches: with the next change that depends on them, such as the end of the answer, and at the latest after `settings.progress.persistWithinMs` (default 1,000 ms). A crash mid-stream loses up to that much of the stream, and a generation cut off before its first store leaves no partial answer in the transcript. To store every update instead, at the cost of a storage write each, set `settings: { progress: { persistWithinMs: 0 } }` in the factory's `Harness.open`.
|
|
256
465
|
|
|
257
|
-
A task that keeps crashing the object would restart it forever, so Pi
|
|
466
|
+
A task that keeps crashing the object would restart it forever, so Pi ends a task cut off by a crash or eviction `settings.restartLimit` times in a row (default 5). A tool call ends with an error result the model sees, and the run goes on. A model request ends its run, and the run's operations end unanswered with reason `restart_limit`. Either way the job completes and the object can hibernate. If your factory passes `onReport` to `Harness.open`, Pi reports it there as `task_interrupted`. To run the work again, call `session.continue()`, which answers the transcript as it is, or submit it again.
|
|
258
467
|
|
|
259
|
-
A storage error closes Pi for good: the call that hit it rejects with the error, and calls and `
|
|
468
|
+
A storage error closes Pi for good: the call that hit it rejects with the error, and calls underway reject with Pi's `SessionFailed` and `watch()` handles already open end with `{ kind: "failed" }`, so retry them. If your factory passes `onReport` to `Harness.open`, Pi reports the failure there as `storage_failed`. Once the failed Pi has closed, the harness opens Pi again, which runs the factory again, on the next call or the job's next step. Closing waits for running task code, such as a tool call, to return, so code that ignores its abort signal delays the reopen. Pi recovers from what it committed and resumes its work the same way.
|
|
260
469
|
|
|
261
|
-
If a step of the job fails, such as when the factory throws, the job is not dropped. It tries again after 30 seconds, doubling the delay with each failure in a row up to 10 minutes, and goes back to its usual schedule once a step succeeds. A Durable Object memory-limit reset that fails Pi while the job waits on it counts against the alarm's memory-limit circuit breaker. Lifecycle backs the job off and drops it after repeated resets. The next call opens Pi again and pushes the job again, so Pi's restart limit is what eventually
|
|
470
|
+
If a step of the job fails, such as when the factory throws, the job is not dropped. It tries again after 30 seconds, doubling the delay with each failure in a row up to 10 minutes, and goes back to its usual schedule once a step succeeds. A Durable Object memory-limit reset that fails Pi while the job waits on it counts against the alarm's memory-limit circuit breaker. Lifecycle backs the job off and drops it after repeated resets. The next call opens Pi again and pushes the job again, so Pi's restart limit is what eventually ends a task that keeps causing resets.
|
|
262
471
|
|
|
263
472
|
Every operation waits for the object's startup, which runs the factory. A call over RPC that arrives first waits for it rather than opening Pi on its own.
|
|
264
473
|
|
|
265
474
|
## Run the example
|
|
266
475
|
|
|
267
|
-
The [Pi harness example](https://github.com/cloudflare/agents/tree/main/examples/next/harnesses/pi)
|
|
476
|
+
The [Pi harness example](https://github.com/cloudflare/agents/tree/main/examples/next/harnesses/pi) sends `session.watch()` over WebSockets and projects Pi's view into a browser transcript. Its tools come from a `Workspace` from `@cloudflare/computer`: files, `exec` for JavaScript in a Dynamic Worker, and git. It uses a Workers AI model.
|
package/docs/harnesses/think.md
CHANGED
|
@@ -28,7 +28,7 @@ export class Assistant extends DurableObject<Env> {
|
|
|
28
28
|
ai = createAI({ binding: this.env.AI });
|
|
29
29
|
|
|
30
30
|
harness = new ThinkHarness({
|
|
31
|
-
model: this.ai("@cf/
|
|
31
|
+
model: this.ai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
32
32
|
system: "You are a helpful assistant.",
|
|
33
33
|
tools: {
|
|
34
34
|
weather: {
|
package/docs/http-websockets.md
CHANGED
|
@@ -43,6 +43,7 @@ Agents have several lifecycle hooks that are called at different points:
|
|
|
43
43
|
| `onClose(connection, code, reason, wasClean)` | When a WebSocket connection closes |
|
|
44
44
|
| `onError(connection, error)` | When a WebSocket error occurs |
|
|
45
45
|
| `onError(error)` | When a server error occurs (overloaded) |
|
|
46
|
+
| `onFetchError(request, error)` | When an HTTP request or WebSocket upgrade fails |
|
|
46
47
|
|
|
47
48
|
### Lifecycle Flow
|
|
48
49
|
|
|
@@ -406,6 +407,8 @@ export class MyAgent extends Agent {
|
|
|
406
407
|
}
|
|
407
408
|
```
|
|
408
409
|
|
|
410
|
+
`onError` observes errors. To choose what the client receives when a request or upgrade fails, override `onFetchError`. By default the client gets `500 Internal Server Error`, or for an upgrade a socket that closes with code `1011`, without the error's details. See [`this.onFetchError`](./agent-class.md#thisonfetcherror).
|
|
411
|
+
|
|
409
412
|
## Hibernation
|
|
410
413
|
|
|
411
414
|
Agent WebSockets always use Cloudflare's Hibernation API. An idle Agent can leave memory while its WebSocket clients remain connected; there is no non-hibernating mode.
|
|
@@ -448,34 +451,38 @@ export class MyAgent extends Agent<Env, { counter: number }> {
|
|
|
448
451
|
|
|
449
452
|
## Common Patterns
|
|
450
453
|
|
|
451
|
-
### Authentication
|
|
454
|
+
### Authentication
|
|
452
455
|
|
|
453
|
-
|
|
456
|
+
Check the caller in your Worker, before `routeAgentRequest()` forwards the upgrade. A client you reject there never reaches the agent, and the agent does not wake up for it.
|
|
454
457
|
|
|
455
458
|
```typescript
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
459
|
+
import { routeAgentRequest } from "agents";
|
|
460
|
+
|
|
461
|
+
export default {
|
|
462
|
+
async fetch(request: Request, env: Env) {
|
|
463
|
+
return (
|
|
464
|
+
(await routeAgentRequest(request, env, {
|
|
465
|
+
onBeforeConnect: async (req) => {
|
|
466
|
+
const token = new URL(req.url).searchParams.get("token");
|
|
467
|
+
const user = token ? await verifyToken(token, env) : null;
|
|
468
|
+
if (!user) {
|
|
469
|
+
return new Response("Unauthorized", { status: 401 });
|
|
470
|
+
}
|
|
471
|
+
// `set` replaces any value the client sent.
|
|
472
|
+
const forwarded = new Request(req);
|
|
473
|
+
forwarded.headers.set("x-user-id", user.id);
|
|
474
|
+
return forwarded;
|
|
475
|
+
}
|
|
476
|
+
})) ?? new Response("Not found", { status: 404 })
|
|
477
|
+
);
|
|
475
478
|
}
|
|
476
|
-
}
|
|
479
|
+
};
|
|
477
480
|
```
|
|
478
481
|
|
|
482
|
+
In `onConnect`, read the checked identity from `ctx.request.headers.get("x-user-id")` and keep it with `connection.setState()`.
|
|
483
|
+
|
|
484
|
+
You can also reject a connection from `onConnect` by calling `connection.close()`. The agent runs no message, callable, or state update the client sends after that close. That includes frames the client sends as soon as it connects, before it has received the Close frame. Prefer the Worker check anyway: `onConnect` runs inside the agent, so every rejected client still wakes it.
|
|
485
|
+
|
|
479
486
|
### Chat Room with Broadcast
|
|
480
487
|
|
|
481
488
|
```typescript
|
|
@@ -616,16 +623,17 @@ export class PresenceAgent extends Agent {
|
|
|
616
623
|
|
|
617
624
|
### Agent Lifecycle Methods
|
|
618
625
|
|
|
619
|
-
| Method | Signature
|
|
620
|
-
| ---------------------------- |
|
|
621
|
-
| `onStart` | `(props?) => void \| Promise<void>`
|
|
622
|
-
| `onRequest` | `(request: Request) => Response \| Promise<Response>`
|
|
623
|
-
| `onConnect` | `(connection, ctx) => void \| Promise<void>`
|
|
624
|
-
| `onMessage` | `(connection, message) => void \| Promise<void>`
|
|
625
|
-
| `onClose` | `(connection, code, reason, wasClean) => void \| Promise<void>`
|
|
626
|
-
| `onError` | `(connection, error) => void \| Promise<void>`
|
|
627
|
-
| `onError` | `(error) => void \| Promise<void>`
|
|
628
|
-
| `
|
|
626
|
+
| Method | Signature | Description |
|
|
627
|
+
| ---------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------ |
|
|
628
|
+
| `onStart` | `(props?) => void \| Promise<void>` | Called once when agent starts |
|
|
629
|
+
| `onRequest` | `(request: Request) => Response \| Promise<Response>` | Handle HTTP requests |
|
|
630
|
+
| `onConnect` | `(connection, ctx) => void \| Promise<void>` | WebSocket connected |
|
|
631
|
+
| `onMessage` | `(connection, message) => void \| Promise<void>` | Message received |
|
|
632
|
+
| `onClose` | `(connection, code, reason, wasClean) => void \| Promise<void>` | Connection closed |
|
|
633
|
+
| `onError` | `(connection, error) => void \| Promise<void>` | WebSocket error |
|
|
634
|
+
| `onError` | `(error) => void \| Promise<void>` | Server error (overload) |
|
|
635
|
+
| `onFetchError` | `(request, error) => Response \| void \| Promise<Response \| void>` | Choose the response for a failed request or upgrade |
|
|
636
|
+
| `shouldSendProtocolMessages` | `(connection, ctx) => boolean` | Control per-connection protocol frames (default: true) |
|
|
629
637
|
|
|
630
638
|
### Connection Management Methods
|
|
631
639
|
|
|
@@ -203,7 +203,7 @@ export class MyAgent extends AIChatAgent {
|
|
|
203
203
|
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
204
204
|
|
|
205
205
|
const result = streamText({
|
|
206
|
-
model: workersai("@cf/
|
|
206
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
207
207
|
messages: await convertToModelMessages(this.messages),
|
|
208
208
|
tools: {
|
|
209
209
|
// Tool with conditional approval
|
|
@@ -376,7 +376,7 @@ export class MyAgent extends AIChatAgent {
|
|
|
376
376
|
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
377
377
|
|
|
378
378
|
const result = streamText({
|
|
379
|
-
model: workersai("@cf/
|
|
379
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
380
380
|
messages: await convertToModelMessages(this.messages),
|
|
381
381
|
tools: {
|
|
382
382
|
// No execute function - client handles via onToolCall
|
package/docs/lifecycle.md
CHANGED
|
@@ -93,6 +93,57 @@ A warm object skips startup but still offers every request to its middleware.
|
|
|
93
93
|
There is no `next()` today: a capability either handles a request or declines
|
|
94
94
|
it, and cannot wrap or observe a downstream response.
|
|
95
95
|
|
|
96
|
+
## Failed requests
|
|
97
|
+
|
|
98
|
+
When startup, a capability's request or upgrade hook, or `onRequest` throws,
|
|
99
|
+
the lifecycle logs the error with `console.error` and sends a response that
|
|
100
|
+
does not include it:
|
|
101
|
+
|
|
102
|
+
- an HTTP request gets `500 Internal Server Error`;
|
|
103
|
+
- a WebSocket upgrade gets a socket that closes at once with code `1011`.
|
|
104
|
+
|
|
105
|
+
An error's message and stack can reveal internals, such as secret names or
|
|
106
|
+
file paths, to callers who are not authenticated. To send something else,
|
|
107
|
+
implement `onFetchError`. It runs after the error is logged, with the request
|
|
108
|
+
and the thrown value:
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
export class MyObject extends DurableObject<Env> {
|
|
112
|
+
readonly lifecycle = Lifecycle.install(this);
|
|
113
|
+
|
|
114
|
+
onFetchError(request: Request, error: unknown): Response | undefined {
|
|
115
|
+
// Show details only in local development.
|
|
116
|
+
if (this.env.ENVIRONMENT !== "development") return;
|
|
117
|
+
const detail = error instanceof Error ? error.stack : String(error);
|
|
118
|
+
return new Response(detail, { status: 500 });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Return nothing to send the default response. If `onFetchError` throws, the
|
|
124
|
+
lifecycle logs that error and also sends the default. In both cases, if the
|
|
125
|
+
original thrown value is not an `Error`, the lifecycle rethrows it to the
|
|
126
|
+
runtime instead. `error` is whatever was thrown, so narrow it before you read
|
|
127
|
+
it. `request` may already have had its body read.
|
|
128
|
+
|
|
129
|
+
For a WebSocket upgrade, return either an HTTP error response or a `101`
|
|
130
|
+
response with your own socket:
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
onFetchError(request: Request, error: unknown): Response | undefined {
|
|
134
|
+
if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return;
|
|
135
|
+
const pair = new WebSocketPair();
|
|
136
|
+
pair[1].accept();
|
|
137
|
+
pair[1].send(JSON.stringify({ error: "unavailable" }));
|
|
138
|
+
pair[1].close(1011, "Startup failed");
|
|
139
|
+
return new Response(null, { status: 101, webSocket: pair[0] });
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
`onFetchError` runs in the object's context, so `getCurrentAgent()` returns
|
|
144
|
+
the object and the request. After a failed startup, `onStart` has not
|
|
145
|
+
finished, so do not rely on state it sets up.
|
|
146
|
+
|
|
96
147
|
## Reusable capabilities
|
|
97
148
|
|
|
98
149
|
A capability implements only the phases it needs:
|
|
@@ -466,6 +517,11 @@ Handlers are wire-agnostic. Both kinds of connection dispatch the same
|
|
|
466
517
|
`onConnect`/`onMessage`/`onClose`/`onError`, appear in `getConnections()`,
|
|
467
518
|
and honour `connection.close(code, reason)`.
|
|
468
519
|
|
|
520
|
+
Once the host closes a connection, neither wire runs another message or
|
|
521
|
+
callable from it. This holds for frames the client sent before it received
|
|
522
|
+
the Close frame, so a client that `onConnect` rejects cannot run anything.
|
|
523
|
+
Messages the client sent before closing the connection itself still run.
|
|
524
|
+
|
|
469
525
|
## Native RPC
|
|
470
526
|
|
|
471
527
|
Native Durable Object RPC does not pass through `fetch`. An RPC method that
|