agents 0.33.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 +1 -1
- package/dist/browser/index.d.ts +7 -3
- package/dist/browser/index.js +2 -2
- package/dist/browser/tools/ai-sdk.d.ts +68 -3
- package/dist/browser/tools/pi.d.ts +2 -2
- package/dist/browser/tools/tanstack-ai.d.ts +2 -2
- package/dist/{browser-CI97khiJ.d.ts → browser-C9T74n4c.d.ts} +84 -5
- package/dist/{browser-tool-Cxtiwfua.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-sdk/index.d.ts +3 -3
- package/dist/chat-sdk/index.js +1 -1
- package/dist/cli.js +64 -63
- 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-Dl098To-.js → connector-Bphz6wIw.js} +16 -4
- 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/experimental/webmcp.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 +128 -12
- package/dist/harness/pi/index.js +128 -20
- 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-0uUu392-.js → input-schema-D6GilRXI.js} +2 -2
- package/dist/{input-schema-0uUu392-.js.map → input-schema-D6GilRXI.js.map} +1 -1
- package/dist/{input-schema-waggtYrH.js → input-schema-y8W5bOdM.js} +2 -2
- package/dist/{input-schema-waggtYrH.js.map → input-schema-y8W5bOdM.js.map} +1 -1
- 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/client/x402.d.ts +8 -8
- package/dist/mcp/index.d.ts +17 -17
- package/dist/mcp/index.js +5 -5
- package/dist/mcp/index.js.map +1 -1
- 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 +53 -29
- 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-CRY0bGiI.js.map +1 -1
- 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/{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 +5 -0
- package/dist/web/fetch/tools/pi.js +25 -2
- 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 +4 -0
- package/dist/web/search/tools/pi.js +23 -2
- 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 +14 -0
- 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 +211 -22
- 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 +13 -12
- package/dist/ai-sdk-CpuRsjP5.d.ts +0 -72
- package/dist/ai-sdk-Kon40i0q.js.map +0 -1
- package/dist/client-DMWujQJ1.js +0 -2325
- package/dist/client-DMWujQJ1.js.map +0 -1
- package/dist/connector-Dl098To-.js.map +0 -1
- package/dist/images-CfuRCjwq.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/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/agent-class.md
CHANGED
|
@@ -286,9 +286,12 @@ Schedules are stored as jobs in the `cf_agents_jobs` SQL table, the Lifecycle-ow
|
|
|
286
286
|
|
|
287
287
|
```ts
|
|
288
288
|
class MyAgent extends Agent {
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
289
|
+
@callable()
|
|
290
|
+
async addServer(url: string) {
|
|
291
|
+
// Calling this again for the same server reconnects it if it is not
|
|
292
|
+
// connected. A server stopped for a reason only a person can fix
|
|
293
|
+
// (authorization refused, for example) needs reconnectMcpServer(id).
|
|
294
|
+
return this.addMcpServer("GitHub", url, { id: "github" });
|
|
292
295
|
}
|
|
293
296
|
}
|
|
294
297
|
```
|
|
@@ -376,12 +379,35 @@ class MyAgent extends Agent {
|
|
|
376
379
|
console.error("Server error:", connectionOrError);
|
|
377
380
|
}
|
|
378
381
|
|
|
379
|
-
//
|
|
382
|
+
// Throw to replace the error. If onError returns, the original error
|
|
383
|
+
// continues, and for a request reaches onFetchError.
|
|
380
384
|
throw connectionOrError;
|
|
381
385
|
}
|
|
382
386
|
}
|
|
383
387
|
```
|
|
384
388
|
|
|
389
|
+
### `this.onFetchError`
|
|
390
|
+
|
|
391
|
+
When an HTTP request or WebSocket upgrade fails, including a failed `onStart`, the Agent logs the error and sends a response that does not include it: `500 Internal Server Error`, or for an upgrade a socket that closes with code `1011`. Override `onFetchError` to send something else, and return nothing to keep the default:
|
|
392
|
+
|
|
393
|
+
```ts
|
|
394
|
+
class MyAgent extends Agent<Env> {
|
|
395
|
+
onFetchError(request: Request, error: unknown) {
|
|
396
|
+
if (this.env.ENVIRONMENT !== "development") return;
|
|
397
|
+
const detail = error instanceof Error ? error.stack : String(error);
|
|
398
|
+
return new Response(detail, { status: 500 });
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
Errors from `onStart`, `onRequest`, and `onConnect` pass through `onError` first. If `onError` throws, `onFetchError` receives what it threw; if `onError` returns, `onFetchError` receives the original error.
|
|
404
|
+
|
|
405
|
+
For a [sub-agent](./sub-agents.md), the object that accepts the request or socket answers it. Today, a failed HTTP request reaches the child's `onFetchError`, and a failed WebSocket upgrade reaches the parent's, because the parent accepts the socket and passes the connection to the child, even when the child's `onConnect` threw. If `onBeforeSubAgent` throws, no `onFetchError` runs and the error reaches the caller of `fetch`.
|
|
406
|
+
|
|
407
|
+
When the parent's `onFetchError` answers a child's failed upgrade, `error` is a copy that crossed from the child to the parent. It is still an `Error` with the same `name` and `message`, but it is no longer an instance of the child's error class, so `error instanceof MyError` is `false`. Check `error.name` instead.
|
|
408
|
+
|
|
409
|
+
See [Failed requests](./lifecycle.md#failed-requests) for the full behavior.
|
|
410
|
+
|
|
385
411
|
### `this.destroy`
|
|
386
412
|
|
|
387
413
|
`this.destroy()` drops all tables, deletes alarms, clears storage, and aborts the context. To ensure that the DO is fully evicted, `this.ctx.abort()` is called, which throws an uncatchable error that will show up in your logs (read more about it [here](https://developers.cloudflare.com/durable-objects/api/state/#abort)).
|
package/docs/browse-the-web.md
CHANGED
|
@@ -329,6 +329,20 @@ const spec = await loadCdpSpec({ browser: this.env.BROWSER, sessionId });
|
|
|
329
329
|
|
|
330
330
|
`connectBrowserSession` does not delete the session when the connection closes, so you can reconnect. `loadCdpSpec` without a `sessionId` creates a temporary session to read the protocol, then deletes it.
|
|
331
331
|
|
|
332
|
+
A custom `BrowserSource` with no `/json/protocol` endpoint or Browser Run binding can build its spec with `normalizeCdpSpec`. Chrome publishes the protocol as `browser_protocol.json` and `js_protocol.json` ([ChromeDevTools/devtools-protocol](https://github.com/ChromeDevTools/devtools-protocol/tree/master/json)). Merge their `domains`, normalize once, and keep the result, since `normalizeCdpSpec` does not cache:
|
|
333
|
+
|
|
334
|
+
```ts
|
|
335
|
+
import { normalizeCdpSpec, type RawCdpProtocol } from "agents/browser";
|
|
336
|
+
|
|
337
|
+
// Protocol JSON you already have, such as the two published files
|
|
338
|
+
declare const browserProtocol: RawCdpProtocol;
|
|
339
|
+
declare const jsProtocol: RawCdpProtocol;
|
|
340
|
+
|
|
341
|
+
const spec = normalizeCdpSpec({
|
|
342
|
+
domains: [...(browserProtocol.domains ?? []), ...(jsProtocol.domains ?? [])]
|
|
343
|
+
});
|
|
344
|
+
```
|
|
345
|
+
|
|
332
346
|
## Local development
|
|
333
347
|
|
|
334
348
|
Recent Wrangler releases support Browser Run in local development. `npx wrangler dev` provisions the browser automatically, so the same `browser: env.BROWSER` setup works locally and when deployed.
|
package/docs/chat-agents.md
CHANGED
|
@@ -40,7 +40,7 @@ export class ChatAgent extends AIChatAgent {
|
|
|
40
40
|
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
41
41
|
|
|
42
42
|
const result = streamText({
|
|
43
|
-
model: workersai("@cf/
|
|
43
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
44
44
|
messages: await convertToModelMessages(this.messages)
|
|
45
45
|
});
|
|
46
46
|
|
|
@@ -166,7 +166,7 @@ async onChatMessage() {
|
|
|
166
166
|
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
167
167
|
|
|
168
168
|
const result = streamText({
|
|
169
|
-
model: workersai("@cf/
|
|
169
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
170
170
|
system: "You are a helpful assistant.",
|
|
171
171
|
messages: await convertToModelMessages(this.messages)
|
|
172
172
|
});
|
|
@@ -221,7 +221,7 @@ async onChatMessage() {
|
|
|
221
221
|
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
222
222
|
|
|
223
223
|
const result = streamText({
|
|
224
|
-
model: workersai("@cf/
|
|
224
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
225
225
|
messages: pruneMessages({
|
|
226
226
|
messages: await convertToModelMessages(this.messages),
|
|
227
227
|
reasoning: "before-last-message",
|
|
@@ -570,7 +570,7 @@ When a user clicks "stop" in the chat UI, the client sends a `CF_AGENT_CHAT_REQU
|
|
|
570
570
|
```typescript
|
|
571
571
|
async onChatMessage(_onFinish, options) {
|
|
572
572
|
const result = streamText({
|
|
573
|
-
model: workersai("@cf/
|
|
573
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
574
574
|
messages: await convertToModelMessages(this.messages),
|
|
575
575
|
abortSignal: options?.abortSignal // Pass through for cancellation
|
|
576
576
|
});
|
|
@@ -988,7 +988,7 @@ async onChatMessage() {
|
|
|
988
988
|
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
989
989
|
|
|
990
990
|
const result = streamText({
|
|
991
|
-
model: workersai("@cf/
|
|
991
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
992
992
|
messages: await convertToModelMessages(this.messages),
|
|
993
993
|
tools: {
|
|
994
994
|
getWeather: tool({
|
|
@@ -1059,7 +1059,7 @@ import { createToolsFromClientSchemas } from "@cloudflare/ai-chat";
|
|
|
1059
1059
|
|
|
1060
1060
|
async onChatMessage(_onFinish, options) {
|
|
1061
1061
|
const result = streamText({
|
|
1062
|
-
model: workersai("@cf/
|
|
1062
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
1063
1063
|
messages: await convertToModelMessages(this.messages),
|
|
1064
1064
|
tools: createToolsFromClientSchemas(options?.clientTools)
|
|
1065
1065
|
});
|
|
@@ -1230,7 +1230,7 @@ export class ChatAgent extends AIChatAgent {
|
|
|
1230
1230
|
const stream = createUIMessageStream({
|
|
1231
1231
|
execute: async ({ writer }) => {
|
|
1232
1232
|
const result = streamText({
|
|
1233
|
-
model: workersai("@cf/
|
|
1233
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
1234
1234
|
messages: await convertToModelMessages(this.messages)
|
|
1235
1235
|
});
|
|
1236
1236
|
|
|
@@ -1323,7 +1323,10 @@ On the server, write transient parts with `transient: true`:
|
|
|
1323
1323
|
writer.write({
|
|
1324
1324
|
transient: true,
|
|
1325
1325
|
type: "data-thinking",
|
|
1326
|
-
data: {
|
|
1326
|
+
data: {
|
|
1327
|
+
model: "deepseek-v4.1-flash-1017",
|
|
1328
|
+
startedAt: new Date().toISOString()
|
|
1329
|
+
}
|
|
1327
1330
|
});
|
|
1328
1331
|
```
|
|
1329
1332
|
|
|
@@ -1434,7 +1437,7 @@ export class ChatAgent extends AIChatAgent {
|
|
|
1434
1437
|
|
|
1435
1438
|
async onChatMessage() {
|
|
1436
1439
|
const result = streamText({
|
|
1437
|
-
model: workersai("@cf/
|
|
1440
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
1438
1441
|
messages: pruneMessages({
|
|
1439
1442
|
// LLM context limit
|
|
1440
1443
|
messages: await convertToModelMessages(this.messages),
|
|
@@ -1459,7 +1462,7 @@ import { createWorkersAI } from "workers-ai-provider";
|
|
|
1459
1462
|
|
|
1460
1463
|
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
1461
1464
|
const result = streamText({
|
|
1462
|
-
model: workersai("@cf/
|
|
1465
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
1463
1466
|
messages: await convertToModelMessages(this.messages)
|
|
1464
1467
|
});
|
|
1465
1468
|
```
|
|
@@ -24,7 +24,7 @@ export class MyAgent extends AIChatAgent {
|
|
|
24
24
|
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
25
25
|
|
|
26
26
|
const result = streamText({
|
|
27
|
-
model: workersai("@cf/
|
|
27
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
28
28
|
messages: await convertToModelMessages(this.messages),
|
|
29
29
|
tools: {
|
|
30
30
|
// Client-side tool: no execute function
|
package/docs/codemode.md
CHANGED
|
@@ -230,7 +230,7 @@ export class BrowserCodemodeAgent extends AIChatAgent<Env> {
|
|
|
230
230
|
const workersai = createWorkersAI({ binding: this.env.AI });
|
|
231
231
|
|
|
232
232
|
const result = streamText({
|
|
233
|
-
model: workersai("@cf/
|
|
233
|
+
model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
|
|
234
234
|
messages: await convertToModelMessages(this.messages),
|
|
235
235
|
tools: createToolsFromClientSchemas(options?.clientTools),
|
|
236
236
|
stopWhen: stepCountIs(10)
|
package/docs/configuration.md
CHANGED
|
@@ -154,9 +154,12 @@ For Workers AI integration:
|
|
|
154
154
|
Access in your agent:
|
|
155
155
|
|
|
156
156
|
```typescript
|
|
157
|
-
const response = await this.env.AI.run(
|
|
158
|
-
|
|
159
|
-
|
|
157
|
+
const response = await this.env.AI.run(
|
|
158
|
+
"@cf/deepseek-ai/deepseek-v4.1-flash-1017",
|
|
159
|
+
{
|
|
160
|
+
prompt: "Hello!"
|
|
161
|
+
}
|
|
162
|
+
);
|
|
160
163
|
```
|
|
161
164
|
|
|
162
165
|
## TypeScript Configuration
|
|
@@ -14,7 +14,7 @@ WebSockets are not HTTP, so the handshake is limited when making cross-domain co
|
|
|
14
14
|
**What works**
|
|
15
15
|
|
|
16
16
|
- Put a signed, short-lived token in the connection URL as query parameters
|
|
17
|
-
- Verify the token in your
|
|
17
|
+
- Verify the token in your Worker's `onBeforeConnect` hook, before `routeAgentRequest()` forwards the upgrade. For an example, refer to [Authentication](./http-websockets.md#authentication).
|
|
18
18
|
|
|
19
19
|
> Tip: never place raw secrets in URLs. Prefer a JWT or a signed token that expires quickly and is scoped to the user or room.
|
|
20
20
|
|
package/docs/fetch-the-web.md
CHANGED
|
@@ -221,6 +221,26 @@ const tools = {
|
|
|
221
221
|
};
|
|
222
222
|
```
|
|
223
223
|
|
|
224
|
+
## In pi's code mode
|
|
225
|
+
|
|
226
|
+
With pi-durable's code mode installed beside the tool (setup in [Browse the Web](./browse-the-web.md#in-pis-code-mode)), a script calls `tools.web_fetch({ url, offset, format })` and gets the window as an object, not the model's text:
|
|
227
|
+
|
|
228
|
+
```ts
|
|
229
|
+
{ url, status, contentType, title?, content, offset, nextOffset, totalChars }
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
`url` is the URL after redirects. `content` stays wrapped in the `<untrusted_web_content>` tags, so text a script hands back to the model is still marked as data. Pass `nextOffset` as `offset` to read on; it is `null` at the end. A failed fetch rejects with the model's text. The model's own result is the same text as before.
|
|
233
|
+
|
|
234
|
+
With `web_search` installed too, one script can search and read the results in parallel:
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
const found = await tools.web_search({ query: "Durable Objects alarms" });
|
|
238
|
+
const pages = await Promise.all(
|
|
239
|
+
found.items.slice(0, 3).map((item) => tools.web_fetch({ url: item.url }))
|
|
240
|
+
);
|
|
241
|
+
return pages.map((page) => ({ title: page.title, content: page.content }));
|
|
242
|
+
```
|
|
243
|
+
|
|
224
244
|
## What It Is Not
|
|
225
245
|
|
|
226
246
|
- **Not an HTTP client.** There is no POST, no request body, and no custom headers, cookies, or credentials. For calls to your own APIs, write a tool for them.
|
package/docs/harnesses/pi.md
CHANGED
|
@@ -14,7 +14,7 @@ Pi owns everything about a run: the transcript, the inbox of steers and follow-u
|
|
|
14
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 four Pi packages are optional peer dependencies of `agents`, at `~1.
|
|
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
|
});
|
|
@@ -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,23 +189,25 @@ 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, whenIdle, 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. 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. `entry` records where the input came from (see below). |
|
|
196
|
-
| `wait(operationId, signal?)`
|
|
197
|
-
| `steer(input)`
|
|
198
|
-
| `continue({ operationId })`
|
|
199
|
-
| `abort(operationId?)`
|
|
200
|
-
| `pending()`
|
|
201
|
-
| `messages()`
|
|
202
|
-
| `watch(window?)`
|
|
203
|
-
| `entries(query, limit)`
|
|
204
|
-
| `reset(handoff?)`
|
|
205
|
-
| `setModel(model)`
|
|
206
|
-
| `busy()`
|
|
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.
|
|
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)).
|
|
209
211
|
|
|
210
212
|
`messages()` and `watch()` are Pi's own records, not a UI-ready chat transcript. The example below projects them into one.
|
|
211
213
|
|
|
@@ -226,6 +228,113 @@ function render(view: ConversationView): void {
|
|
|
226
228
|
|
|
227
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()`.
|
|
228
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`.
|
|
337
|
+
|
|
229
338
|
### Label input the user did not type
|
|
230
339
|
|
|
231
340
|
Pi records every submitted input as a `pi.user` entry, as if the user typed it. Your code often submits input of its own, such as a prompt from a scheduled job, a webhook payload or the outcome of an approval. To record where that input came from, pass `entry` with a `kind` of your own and any `data` you want to keep with it:
|
|
@@ -242,6 +351,86 @@ The kind is a label, not a permission. It records what your code said the input
|
|
|
242
351
|
|
|
243
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.
|
|
244
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
|
+
|
|
245
434
|
### Inputs queued behind a failed run
|
|
246
435
|
|
|
247
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:
|
|
@@ -266,11 +455,11 @@ harness: ({ storage, context, onWake }) =>
|
|
|
266
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. |
|
|
267
456
|
| `withdraw` | `wait()` returns `{ status: "unanswered", reason: "run_failed" }`, and `pending()` no longer lists them. |
|
|
268
457
|
|
|
269
|
-
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"`.
|
|
270
459
|
|
|
271
460
|
## How recovery works
|
|
272
461
|
|
|
273
|
-
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. 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`.
|
|
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`.
|
|
274
463
|
|
|
275
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`.
|
|
276
465
|
|
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: {
|