@cloudflare/think 0.11.0 → 0.11.1
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 +63 -0
- package/dist/fetch-By3eIQ-a.d.ts +147 -0
- package/dist/{index-D_S5mETO.d.ts → index-CR4-ffm_.d.ts} +147 -34
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/think.d.ts +3 -2
- package/dist/think.js +160 -46
- package/dist/think.js.map +1 -1
- package/dist/tools/fetch.d.ts +22 -0
- package/dist/tools/fetch.js +646 -0
- package/dist/tools/fetch.js.map +1 -0
- package/dist/workflows.d.ts +1 -1
- package/docs/index.md +52 -0
- package/docs/lifecycle-hooks.md +25 -14
- package/docs/sub-agents.md +17 -13
- package/package.json +8 -4
package/README.md
CHANGED
|
@@ -327,6 +327,7 @@ Script execution requires a Worker Loader binding:
|
|
|
327
327
|
| `@cloudflare/think/messengers` | Messenger contracts, Chat SDK bridge, state agent, delivery |
|
|
328
328
|
| `@cloudflare/think/messengers/telegram` | Telegram messenger provider and delivery helpers |
|
|
329
329
|
| `@cloudflare/think/tools/workspace` | `createWorkspaceTools()` — for custom storage backends |
|
|
330
|
+
| `@cloudflare/think/tools/fetch` | `createFetchTools()` — opt-in allowlisted HTTP reads |
|
|
330
331
|
| `@cloudflare/think/tools/execute` | `createExecuteTool()` — sandboxed code execution via codemode |
|
|
331
332
|
| `@cloudflare/think/tools/extensions` | `createExtensionTools()` — LLM-driven extension loading |
|
|
332
333
|
| `@cloudflare/think/extensions` | `ExtensionManager`, `HostBridgeLoopback` — extension runtime |
|
|
@@ -352,6 +353,7 @@ Script execution requires a Worker Loader binding:
|
|
|
352
353
|
| `getExtensions()` | `[]` | Sandboxed extension declarations (load order) |
|
|
353
354
|
| `extensionLoader` | `undefined` | `WorkerLoader` binding — enables extensions |
|
|
354
355
|
| `workspaceBash` | `true` | Include the default workspace `bash` tool |
|
|
356
|
+
| `fetchTools` | `false` | Opt-in allowlisted HTTP read tools (`fetch_url` + per-binding `fetch_<name>`). Set to a config object; see [Fetch tool](#fetch-tool) |
|
|
355
357
|
| `chatRecovery` | `true` | Wrap turns in `runFiber` for durable execution. Set `{ maxAttempts, terminalMessage, onExhausted }` to tune bounded recovery |
|
|
356
358
|
| `chatStreamStallTimeoutMs` | `0` (off) | Inactivity watchdog: abort a turn whose model stream produces no chunk for this long, surfacing a terminal stream error instead of an infinite spinner |
|
|
357
359
|
| `contextOverflow` | `undefined` | Opt-in mid-turn context-overflow handling: `{ reactive?, maxRetries?, proactive? }`. Requires `classifyChatError` + a session compaction function. See [Context-window overflow recovery](#context-window-overflow-recovery) |
|
|
@@ -903,6 +905,67 @@ getTools() {
|
|
|
903
905
|
|
|
904
906
|
Requires `@cloudflare/codemode` and a `worker_loaders` binding in `wrangler.jsonc`.
|
|
905
907
|
|
|
908
|
+
## Fetch tool
|
|
909
|
+
|
|
910
|
+
Give the model a conservative, read-only way to read HTTP resources. It is **off by default** — set the `fetchTools` property (static config) or call `createFetchTools()` inside `getTools()` (dynamic/per-tenant). It registers a generic `fetch_url` tool when a public `allowlist` is configured, plus one `fetch_<name>` tool per binding target.
|
|
911
|
+
|
|
912
|
+
```ts
|
|
913
|
+
export class DocsAgent extends Think<Env> {
|
|
914
|
+
getModel() { ... }
|
|
915
|
+
|
|
916
|
+
fetchTools = {
|
|
917
|
+
allowlist: ["https://developers.cloudflare.com/**"],
|
|
918
|
+
bindings: {
|
|
919
|
+
docsApi: {
|
|
920
|
+
binding: this.env.DOCS_API, // a service binding / Fetcher
|
|
921
|
+
allowlist: ["/v1/docs/**"],
|
|
922
|
+
headers: { "x-agent": "think" }
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
};
|
|
926
|
+
}
|
|
927
|
+
```
|
|
928
|
+
|
|
929
|
+
For per-tenant allowlists computed at request time, build the tools in `getTools()` (it runs every turn) instead of using the static property:
|
|
930
|
+
|
|
931
|
+
```ts
|
|
932
|
+
import { createFetchTools } from "@cloudflare/think/tools/fetch";
|
|
933
|
+
|
|
934
|
+
getTools() {
|
|
935
|
+
return {
|
|
936
|
+
...createFetchTools({ allowlist: this.allowedOriginsForTenant() })
|
|
937
|
+
};
|
|
938
|
+
}
|
|
939
|
+
```
|
|
940
|
+
|
|
941
|
+
Behavior and safety:
|
|
942
|
+
|
|
943
|
+
- **Read-only** — `GET` only. Mutations belong in explicit, approval-gated actions, not here.
|
|
944
|
+
- **Allowlisted** — every request must match the configured allowlist; private, loopback, link-local, and `*.internal` targets are blocked even if the allowlist is misconfigured.
|
|
945
|
+
- **Bounded** — `maxBytes` caps the download, `maxModelChars` truncates the model-facing text, and `response: "workspace"` (or `spillToWorkspace: true` with auto) writes large or binary bodies to a workspace file instead of bloating the transcript.
|
|
946
|
+
- **Header-safe** — only headers in `modelHeaderAllowlist` (default `accept`, `accept-language`, `range`) may be set by the model; fixed binding headers are server-side only and are stripped on cross-origin redirects.
|
|
947
|
+
- **Markdown-first** — a weighted default `Accept` header (`text/markdown` → `text/plain` → `application/json` → `text/html` → `*/*`) nudges content-negotiating endpoints to return clean markdown instead of HTML. Override per call (the model can set `accept`) or globally via `defaultAccept` (set to `""` to disable).
|
|
948
|
+
- **Redirects** — followed only when the final URL is still allowlisted (`followRedirects`); binding targets never follow cross-origin redirects.
|
|
949
|
+
|
|
950
|
+
Results are structured `{ ok, ... }` values: success carries `status`, `finalUrl`, `contentType`, `bytes`, `truncated`, and the `body`/`json`/`path`; failures carry a `code` (`disallowed_url`, `disallowed_redirect`, `timeout`, `non_2xx`, `unsupported_content_type`, `invalid_json`, `too_large`, `request_failed`). A `tool:fetch` observability event fires for each call, including blocked attempts.
|
|
951
|
+
|
|
952
|
+
Allowlist semantics:
|
|
953
|
+
|
|
954
|
+
- A bare origin (`https://example.com`) matches that origin and every subpath under it.
|
|
955
|
+
- Patterns are globs: `**` matches any characters (including `/`), `*` matches any character except `/`. A pattern with an explicit path and no glob matches that path literally (e.g. `https://x.com/v1` matches only `/v1`, not `/v1/a`).
|
|
956
|
+
- Matching ignores the query string and fragment (only scheme + host + port + path are compared); the original query/fragment are still sent.
|
|
957
|
+
- Binding allowlists should be path-based (`/v1/docs/**`); a model-supplied absolute URL is only allowed if it matches the binding's allowlist.
|
|
958
|
+
- `json` responses are bounded by `maxBytes` (not `maxModelChars`, which only truncates `text`). For large JSON APIs, lower `maxBytes` or use `response: "workspace"`.
|
|
959
|
+
|
|
960
|
+
You do not need new machinery to gate egress: `beforeToolCall` can `block`/`substitute` a fetch, and channel `tools(...)` policy can narrow the available tools.
|
|
961
|
+
|
|
962
|
+
### When to use what
|
|
963
|
+
|
|
964
|
+
- **Fetch tool** — read a known, allowlisted URL or service binding. No code generation.
|
|
965
|
+
- **Code execution tool** — compose or transform several calls in sandboxed code (set `globalOutbound` to control its network access).
|
|
966
|
+
- **Browser Run** (`@cloudflare/think/tools/browser`) — rendered pages, auth flows, screenshots, CDP automation.
|
|
967
|
+
- **Typed tools / `agentTool()`** — call a `WorkerEntrypoint`/Durable Object method with a typed schema, or delegate work to a sub-agent. Do not route these through fetch.
|
|
968
|
+
|
|
906
969
|
## Extensions
|
|
907
970
|
|
|
908
971
|
Dynamic tool loading at runtime. The LLM can write extension source code, load it as a sandboxed Worker, and use the new tools on the next turn.
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { JSONValue, ToolSet } from "ai";
|
|
2
|
+
|
|
3
|
+
//#region src/tools/fetch.d.ts
|
|
4
|
+
type FetchResponseMode = "text" | "json" | "auto" | "workspace";
|
|
5
|
+
type FetchRedirectPolicy = "allowlisted" | "same-origin" | "none";
|
|
6
|
+
type FetchErrorCode =
|
|
7
|
+
| "disallowed_url"
|
|
8
|
+
| "disallowed_redirect"
|
|
9
|
+
| "timeout"
|
|
10
|
+
| "aborted"
|
|
11
|
+
| "non_2xx"
|
|
12
|
+
| "unsupported_content_type"
|
|
13
|
+
| "invalid_json"
|
|
14
|
+
| "too_large"
|
|
15
|
+
| "request_failed";
|
|
16
|
+
type FetchResult =
|
|
17
|
+
| {
|
|
18
|
+
ok: true;
|
|
19
|
+
status: number;
|
|
20
|
+
finalUrl: string;
|
|
21
|
+
contentType: string;
|
|
22
|
+
bytes: number;
|
|
23
|
+
truncated: boolean;
|
|
24
|
+
response: "text" | "json" | "workspace";
|
|
25
|
+
body?: string;
|
|
26
|
+
json?: JSONValue;
|
|
27
|
+
path?: string;
|
|
28
|
+
}
|
|
29
|
+
| {
|
|
30
|
+
ok: false;
|
|
31
|
+
code: FetchErrorCode;
|
|
32
|
+
status?: number;
|
|
33
|
+
finalUrl?: string;
|
|
34
|
+
message: string;
|
|
35
|
+
};
|
|
36
|
+
interface FetchToolEvent {
|
|
37
|
+
tool: string;
|
|
38
|
+
ok: boolean;
|
|
39
|
+
requestedUrl: string;
|
|
40
|
+
finalUrl?: string;
|
|
41
|
+
status?: number;
|
|
42
|
+
bytes?: number;
|
|
43
|
+
truncated?: boolean;
|
|
44
|
+
response?: FetchResponseMode;
|
|
45
|
+
code?: FetchErrorCode;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Minimal workspace surface the fetch tool needs to spill large/binary
|
|
49
|
+
* responses to a file. A concrete `Workspace` from `@cloudflare/shell`
|
|
50
|
+
* satisfies this.
|
|
51
|
+
*/
|
|
52
|
+
interface FetchWorkspace {
|
|
53
|
+
writeFile(path: string, content: string): Promise<void> | void;
|
|
54
|
+
writeFileBytes?(path: string, content: Uint8Array): Promise<void> | void;
|
|
55
|
+
mkdir(
|
|
56
|
+
path: string,
|
|
57
|
+
opts?: {
|
|
58
|
+
recursive?: boolean;
|
|
59
|
+
}
|
|
60
|
+
): Promise<void> | void;
|
|
61
|
+
}
|
|
62
|
+
interface FetchBindingTarget {
|
|
63
|
+
/** The service binding / Fetcher requests are routed through. */
|
|
64
|
+
binding: Fetcher;
|
|
65
|
+
/** Documented purpose — surfaced in the generated tool description. */
|
|
66
|
+
description?: string;
|
|
67
|
+
/**
|
|
68
|
+
* Allowlist for this target. Entries starting with `/` match the request
|
|
69
|
+
* pathname (e.g. `/v1/docs/**`); entries starting with `http(s)://` match
|
|
70
|
+
* the full canonical URL.
|
|
71
|
+
*/
|
|
72
|
+
allowlist: string[];
|
|
73
|
+
/** Fixed, server-side headers. Never settable by the model, never echoed. */
|
|
74
|
+
headers?: Record<string, string>;
|
|
75
|
+
/** Base URL used to resolve relative paths. Defaults to `https://binding.local`. */
|
|
76
|
+
baseUrl?: string;
|
|
77
|
+
}
|
|
78
|
+
interface CreateFetchToolsOptions {
|
|
79
|
+
/**
|
|
80
|
+
* Allowlist for the generic public `fetch_url` tool. Entries are absolute
|
|
81
|
+
* URL/origin/path globs (e.g. `https://developers.cloudflare.com/**`). When
|
|
82
|
+
* omitted/empty, `fetch_url` is not registered.
|
|
83
|
+
*/
|
|
84
|
+
allowlist?: string[];
|
|
85
|
+
/**
|
|
86
|
+
* Named binding targets. Each entry generates a `fetch_<name>` tool with the
|
|
87
|
+
* binding, allowlist, and fixed headers baked in.
|
|
88
|
+
*/
|
|
89
|
+
bindings?: Record<string, FetchBindingTarget>;
|
|
90
|
+
/** Hard download cap in bytes. Default 1_000_000. */
|
|
91
|
+
maxBytes?: number;
|
|
92
|
+
/** Model-facing text truncation in characters. Default 24_000. */
|
|
93
|
+
maxModelChars?: number;
|
|
94
|
+
/** Allow large/binary bodies to spill to a workspace file. Default false. */
|
|
95
|
+
spillToWorkspace?: boolean;
|
|
96
|
+
/** Workspace used for `response: "workspace"` / spill. */
|
|
97
|
+
workspace?: FetchWorkspace;
|
|
98
|
+
/** Per-request timeout in ms. Default 10_000. */
|
|
99
|
+
timeoutMs?: number;
|
|
100
|
+
/** Default response handling. Default `"auto"`. */
|
|
101
|
+
response?: FetchResponseMode;
|
|
102
|
+
/** Redirect policy. Default `"allowlisted"`. */
|
|
103
|
+
followRedirects?: FetchRedirectPolicy;
|
|
104
|
+
/** Header names the model may set. Default `["accept", "accept-language", "range"]`. */
|
|
105
|
+
modelHeaderAllowlist?: string[];
|
|
106
|
+
/**
|
|
107
|
+
* Default `Accept` header sent when neither the binding's fixed headers nor
|
|
108
|
+
* the model already set one. Defaults to a markdown-first, weighted value so
|
|
109
|
+
* content-negotiating endpoints return clean markdown/plain text/JSON instead
|
|
110
|
+
* of HTML. Set to `""` to send no default `Accept` header.
|
|
111
|
+
*/
|
|
112
|
+
defaultAccept?: string;
|
|
113
|
+
/** Observability hook. Fires once per fetch (success or failure/block). */
|
|
114
|
+
onEvent?: (event: FetchToolEvent) => void;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Create the Think fetch tools.
|
|
118
|
+
*
|
|
119
|
+
* Returns a generic `fetch_url` tool (when a public `allowlist` is configured)
|
|
120
|
+
* plus one `fetch_<name>` tool per configured binding target. Throws when no
|
|
121
|
+
* allowlist and no bindings are configured, so a misconfiguration fails loudly
|
|
122
|
+
* instead of silently registering nothing.
|
|
123
|
+
*
|
|
124
|
+
* @example
|
|
125
|
+
* ```ts
|
|
126
|
+
* createFetchTools({
|
|
127
|
+
* allowlist: ["https://developers.cloudflare.com/**"],
|
|
128
|
+
* bindings: {
|
|
129
|
+
* docsApi: { binding: env.DOCS_API, allowlist: ["/v1/docs/**"] }
|
|
130
|
+
* }
|
|
131
|
+
* });
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
134
|
+
declare function createFetchTools(options: CreateFetchToolsOptions): ToolSet;
|
|
135
|
+
//#endregion
|
|
136
|
+
export {
|
|
137
|
+
FetchResponseMode as a,
|
|
138
|
+
FetchWorkspace as c,
|
|
139
|
+
FetchRedirectPolicy as i,
|
|
140
|
+
createFetchTools as l,
|
|
141
|
+
FetchBindingTarget as n,
|
|
142
|
+
FetchResult as o,
|
|
143
|
+
FetchErrorCode as r,
|
|
144
|
+
FetchToolEvent as s,
|
|
145
|
+
CreateFetchToolsOptions as t
|
|
146
|
+
};
|
|
147
|
+
//# sourceMappingURL=fetch-By3eIQ-a.d.ts.map
|
|
@@ -6,9 +6,11 @@ import {
|
|
|
6
6
|
D as createWorkspaceTools,
|
|
7
7
|
h as WorkspaceLike
|
|
8
8
|
} from "./workspace-BZXdZcuw.js";
|
|
9
|
+
import { t as CreateFetchToolsOptions } from "./fetch-By3eIQ-a.js";
|
|
9
10
|
import {
|
|
10
11
|
FlexibleSchema,
|
|
11
12
|
InferSchema,
|
|
13
|
+
InferToolOutput,
|
|
12
14
|
LanguageModel,
|
|
13
15
|
ModelMessage,
|
|
14
16
|
PrepareStepFunction,
|
|
@@ -987,7 +989,9 @@ type StepConfig<TOOLS extends ToolSet = ToolSet> = PrepareStepResult<TOOLS>;
|
|
|
987
989
|
* - `messages` — conversation messages visible at tool execution time
|
|
988
990
|
* - `abortSignal` — signal that aborts if the turn is cancelled
|
|
989
991
|
*
|
|
990
|
-
* Pass an explicit `TOOLS` generic for full input typing
|
|
992
|
+
* Pass an explicit `TOOLS` generic for full input typing. With a concrete
|
|
993
|
+
* tool set, narrowing on `ctx.toolName` narrows `ctx.input` to that tool's
|
|
994
|
+
* input shape:
|
|
991
995
|
*
|
|
992
996
|
* ```ts
|
|
993
997
|
* import type { ToolCallContext } from "@cloudflare/think";
|
|
@@ -995,18 +999,43 @@ type StepConfig<TOOLS extends ToolSet = ToolSet> = PrepareStepResult<TOOLS>;
|
|
|
995
999
|
*
|
|
996
1000
|
* beforeToolCall(ctx: ToolCallContext<typeof tools>) {
|
|
997
1001
|
* if (ctx.toolName === "search") {
|
|
998
|
-
* ctx.input.query; // typed
|
|
1002
|
+
* ctx.input.query; // typed as string
|
|
999
1003
|
* }
|
|
1000
1004
|
* }
|
|
1001
1005
|
* ```
|
|
1002
1006
|
*/
|
|
1003
|
-
type ToolCallContext<TOOLS extends ToolSet = ToolSet> =
|
|
1007
|
+
type ToolCallContext<TOOLS extends ToolSet = ToolSet> = PerToolCall<TOOLS> &
|
|
1008
|
+
ToolCallContextExtras;
|
|
1009
|
+
/** Per-call event extras attached to every {@link ToolCallContext}. */
|
|
1010
|
+
type ToolCallContextExtras = {
|
|
1004
1011
|
/** Zero-based index of the current step where this tool call occurs. */ readonly stepNumber:
|
|
1005
1012
|
| number
|
|
1006
1013
|
| undefined /** The conversation messages available at tool execution time. */;
|
|
1007
1014
|
readonly messages: ReadonlyArray<ModelMessage> /** Signal for cancelling the operation. */;
|
|
1008
1015
|
readonly abortSignal: AbortSignal | undefined;
|
|
1009
1016
|
};
|
|
1017
|
+
/**
|
|
1018
|
+
* The `TypedToolCall<TOOLS>` union, re-keyed so that discriminating on
|
|
1019
|
+
* `toolName` narrows `input` per tool.
|
|
1020
|
+
*
|
|
1021
|
+
* The AI SDK's `TypedToolCall` includes a `DynamicToolCall` arm whose
|
|
1022
|
+
* `toolName: string` / `input: unknown` overlaps every static tool name —
|
|
1023
|
+
* leaving it in the union collapses `ctx.input` to `unknown` even after a
|
|
1024
|
+
* `toolName` check. When an explicit `TOOLS` generic is passed (so the keys
|
|
1025
|
+
* are a literal union), we distribute over those keys and drop the dynamic
|
|
1026
|
+
* arm so narrowing works. With the default `ToolSet` (keys are `string`) we
|
|
1027
|
+
* fall back to the raw union, preserving the prior loose behavior.
|
|
1028
|
+
*/
|
|
1029
|
+
type PerToolCall<TOOLS extends ToolSet> = string extends keyof TOOLS
|
|
1030
|
+
? TypedToolCall<TOOLS>
|
|
1031
|
+
: {
|
|
1032
|
+
[K in keyof TOOLS]: Extract<
|
|
1033
|
+
TypedToolCall<TOOLS>,
|
|
1034
|
+
{
|
|
1035
|
+
toolName: K;
|
|
1036
|
+
}
|
|
1037
|
+
>;
|
|
1038
|
+
}[keyof TOOLS];
|
|
1010
1039
|
/**
|
|
1011
1040
|
* Decision returned by `beforeToolCall` to control tool execution.
|
|
1012
1041
|
* Return void/undefined to allow execution with original input.
|
|
@@ -1042,41 +1071,58 @@ type ToolCallDecision =
|
|
|
1042
1071
|
* - `messages` — conversation messages visible at tool execution time
|
|
1043
1072
|
* - `durationMs` — wall-clock execution time in milliseconds
|
|
1044
1073
|
* - `success`/`output`/`error` — discriminated outcome:
|
|
1045
|
-
* - on success: `success: true`, `output
|
|
1074
|
+
* - on success: `success: true`, `output` typed per tool
|
|
1046
1075
|
* - on failure: `success: false`, `error: unknown`
|
|
1047
1076
|
*
|
|
1048
|
-
* Pass an explicit `TOOLS` generic for full input typing
|
|
1077
|
+
* Pass an explicit `TOOLS` generic for full input **and** output typing.
|
|
1078
|
+
* On the success branch, narrowing on `ctx.toolName` narrows `ctx.output`
|
|
1079
|
+
* to that tool's inferred output type (dynamic tools stay `unknown`):
|
|
1049
1080
|
*
|
|
1050
1081
|
* ```ts
|
|
1051
1082
|
* import type { ToolCallResultContext } from "@cloudflare/think";
|
|
1052
1083
|
* import type { tools } from "./my-tools";
|
|
1053
1084
|
*
|
|
1054
1085
|
* afterToolCall(ctx: ToolCallResultContext<typeof tools>) {
|
|
1055
|
-
* if (ctx.success) {
|
|
1056
|
-
*
|
|
1057
|
-
* } else {
|
|
1058
|
-
* console.error(`${ctx.toolName} failed:`, ctx.error);
|
|
1086
|
+
* if (ctx.toolName === "search" && ctx.success) {
|
|
1087
|
+
* ctx.output.results; // typed as the `search` tool's output
|
|
1059
1088
|
* }
|
|
1060
1089
|
* }
|
|
1061
1090
|
* ```
|
|
1062
1091
|
*/
|
|
1063
1092
|
type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1093
|
+
string extends keyof TOOLS
|
|
1094
|
+
? TypedToolCall<TOOLS> & ToolCallResultBase & ToolCallOutcome<unknown>
|
|
1095
|
+
: {
|
|
1096
|
+
[K in keyof TOOLS]: Extract<
|
|
1097
|
+
TypedToolCall<TOOLS>,
|
|
1098
|
+
{
|
|
1099
|
+
toolName: K;
|
|
1100
|
+
}
|
|
1101
|
+
> &
|
|
1102
|
+
ToolCallResultBase &
|
|
1103
|
+
ToolCallOutcome<InferToolOutput<TOOLS[K]>>;
|
|
1104
|
+
}[keyof TOOLS];
|
|
1105
|
+
/** Per-call extras attached to every {@link ToolCallResultContext}. */
|
|
1106
|
+
type ToolCallResultBase = {
|
|
1107
|
+
readonly stepNumber: number | undefined;
|
|
1108
|
+
readonly messages: ReadonlyArray<ModelMessage> /** Wall-clock execution time in milliseconds. */;
|
|
1109
|
+
readonly durationMs: number;
|
|
1110
|
+
};
|
|
1111
|
+
/**
|
|
1112
|
+
* The discriminated success/failure outcome of a tool call. On success the
|
|
1113
|
+
* `output` is typed (`O`); on failure the `error` is `unknown`.
|
|
1114
|
+
*/
|
|
1115
|
+
type ToolCallOutcome<O> =
|
|
1116
|
+
| {
|
|
1117
|
+
readonly success: true;
|
|
1118
|
+
readonly output: O;
|
|
1119
|
+
readonly error?: never;
|
|
1120
|
+
}
|
|
1121
|
+
| {
|
|
1122
|
+
readonly success: false;
|
|
1123
|
+
readonly output?: never;
|
|
1124
|
+
readonly error: unknown;
|
|
1125
|
+
};
|
|
1080
1126
|
/**
|
|
1081
1127
|
* Context passed to the `onStepFinish` hook after each step completes.
|
|
1082
1128
|
*
|
|
@@ -1315,6 +1361,22 @@ declare class Think<
|
|
|
1315
1361
|
workspaceBash:
|
|
1316
1362
|
| boolean
|
|
1317
1363
|
| NonNullable<Parameters<typeof createWorkspaceTools>[1]>["bash"];
|
|
1364
|
+
/**
|
|
1365
|
+
* Opt-in HTTP fetch tools. Disabled by default — set to a config object to
|
|
1366
|
+
* register a generic `fetch_url` tool (when `allowlist` is provided) and one
|
|
1367
|
+
* `fetch_<name>` tool per `bindings` target. Read-only (GET), allowlisted,
|
|
1368
|
+
* and bounded; see {@link createFetchTools}.
|
|
1369
|
+
*
|
|
1370
|
+
* The workspace and an observability hook are injected automatically, so omit
|
|
1371
|
+
* `workspace`/`onEvent` here. This property is evaluated at construction, so
|
|
1372
|
+
* use it for static config — for per-tenant/dynamic allowlists call
|
|
1373
|
+
* `createFetchTools()` inside `getTools()` instead (it runs every turn).
|
|
1374
|
+
*
|
|
1375
|
+
* ```ts
|
|
1376
|
+
* fetchTools = { allowlist: ["https://developers.cloudflare.com/**"] };
|
|
1377
|
+
* ```
|
|
1378
|
+
*/
|
|
1379
|
+
fetchTools: false | Omit<CreateFetchToolsOptions, "workspace" | "onEvent">;
|
|
1318
1380
|
constructor(ctx: DurableObjectState, env: Env);
|
|
1319
1381
|
/**
|
|
1320
1382
|
* Conversation history as Think's live in-memory view.
|
|
@@ -2303,16 +2365,30 @@ declare class Think<
|
|
|
2303
2365
|
*
|
|
2304
2366
|
* **Streaming tools (AsyncIterable):** the AI SDK supports tools whose
|
|
2305
2367
|
* `execute` returns `AsyncIterable<output>` to emit preliminary
|
|
2306
|
-
* results before a final value.
|
|
2307
|
-
*
|
|
2308
|
-
* a
|
|
2309
|
-
*
|
|
2310
|
-
*
|
|
2311
|
-
*
|
|
2312
|
-
*
|
|
2313
|
-
*
|
|
2368
|
+
* results before a final value. The canonical form is an async
|
|
2369
|
+
* generator (`async function* execute(...)`), where calling `execute`
|
|
2370
|
+
* synchronously returns a direct `AsyncIterable`. For that form Think
|
|
2371
|
+
* preserves preliminary streaming: the wrapper is itself an async
|
|
2372
|
+
* generator that `await`s `beforeToolCall` and then yields every
|
|
2373
|
+
* chunk through unchanged. Non-streaming tools keep a scalar wrapper
|
|
2374
|
+
* so they never emit a synthetic `preliminary` tool-result chunk.
|
|
2375
|
+
*
|
|
2376
|
+
* The non-canonical `async function execute(...) { return makeIter(); }`
|
|
2377
|
+
* form returns a `Promise<AsyncIterable>`, which does not stream even
|
|
2378
|
+
* in the raw AI SDK (it would surface the iterator object as the final
|
|
2379
|
+
* output). Think collapses it to the last yielded value instead. If
|
|
2380
|
+
* you need preliminary streaming, use an `async function*` `execute`.
|
|
2314
2381
|
*/
|
|
2315
2382
|
private _wrapToolsWithDecision;
|
|
2383
|
+
/**
|
|
2384
|
+
* Shared `beforeToolCall` resolution for both the scalar and streaming
|
|
2385
|
+
* tool wrappers (see {@link _wrapToolsWithDecision}). Builds the
|
|
2386
|
+
* `ToolCallContext`, consults the subclass `beforeToolCall` hook,
|
|
2387
|
+
* dispatches the extension observation snapshot, and resolves the
|
|
2388
|
+
* returned `ToolCallDecision` into either "run `execute` with this
|
|
2389
|
+
* input" or "short-circuit with this output".
|
|
2390
|
+
*/
|
|
2391
|
+
private _resolveToolCallDecision;
|
|
2316
2392
|
private _pipelineExtensionToolCallStart;
|
|
2317
2393
|
private _pipelineExtensionToolCallFinish;
|
|
2318
2394
|
private _pipelineExtensionStepFinish;
|
|
@@ -3311,6 +3387,19 @@ declare class Think<
|
|
|
3311
3387
|
* broadcast — the deferred re-run re-fires `onExhausted` + the banner
|
|
3312
3388
|
* (the terminal writes themselves are idempotent).
|
|
3313
3389
|
*/
|
|
3390
|
+
/**
|
|
3391
|
+
* Recovery continuation callbacks the alarm-boundary OOM circuit breaker may
|
|
3392
|
+
* back off / purge (#1825). See `Agent._cf_handleAlarmMemoryLimitReset`.
|
|
3393
|
+
*/
|
|
3394
|
+
protected _cf_recoveryAlarmCallbacks(): string[];
|
|
3395
|
+
/**
|
|
3396
|
+
* Seal any still-live recovery incident as an out-of-memory exhaustion when
|
|
3397
|
+
* the alarm circuit breaker trips at its strike budget (#1825). Runs at the
|
|
3398
|
+
* outermost alarm frame (post-unwind), so the terminal banner / `onExhausted`
|
|
3399
|
+
* and the sealed-incident write can land where the mid-turn give-up's writes
|
|
3400
|
+
* OOMed. Reuses the shared give-up spine via `_exhaustRecoveryGiveUp`.
|
|
3401
|
+
*/
|
|
3402
|
+
protected _cf_sealMemoryLimitedRecovery(): Promise<void>;
|
|
3314
3403
|
private _exhaustRecoveryGiveUp;
|
|
3315
3404
|
/**
|
|
3316
3405
|
* Give-up after the stable-state-timeout retry budget drained. Thin wrapper
|
|
@@ -3318,6 +3407,30 @@ declare class Think<
|
|
|
3318
3407
|
* `stable_timeout`.
|
|
3319
3408
|
*/
|
|
3320
3409
|
private _exhaustRecoveryAfterStableTimeout;
|
|
3410
|
+
/**
|
|
3411
|
+
* Apply the tight OOM-retry budget to a recovery error (#1825). Invoked from
|
|
3412
|
+
* `_handleRecoveryCallbackError`, i.e. for an OOM that is *thrown* out of a
|
|
3413
|
+
* recovery turn (typically from recovery bookkeeping or storage/SQL ops that
|
|
3414
|
+
* reject with the memory-limit-reset message after an isolate reset). An OOM
|
|
3415
|
+
* that surfaces as a returned `error` result means `continueLastTurn` already
|
|
3416
|
+
* terminalized the turn (client error frame + `onError`), so it is NOT routed
|
|
3417
|
+
* here — re-driving a terminalized turn would be wasteful and risk a second
|
|
3418
|
+
* terminal signal. `error` may be an Error or a wrapper with a `cause` chain.
|
|
3419
|
+
*
|
|
3420
|
+
* The reliable terminator is the begin-path (`evaluateChatRecoveryIncident`),
|
|
3421
|
+
* which seals once `oomAttempts` exceeds the budget; that runs before the
|
|
3422
|
+
* memory-heavy turn, in the low-memory window where writes succeed. This
|
|
3423
|
+
* method's job is to persist `oomAttempts` (small writes) so the begin path
|
|
3424
|
+
* can act on it, and to schedule a delayed re-run while under budget.
|
|
3425
|
+
*
|
|
3426
|
+
* Returns `true` when the error was an OOM and this method owns the outcome:
|
|
3427
|
+
* - under budget → a delayed re-run was scheduled (best-effort: a transient
|
|
3428
|
+
* spike may clear);
|
|
3429
|
+
* - over budget (or untrackable, or the bookkeeping itself OOMed) →
|
|
3430
|
+
* terminalized via the give-up path with `reason="out_of_memory"`.
|
|
3431
|
+
* Returns `false` for non-OOM errors so the caller proceeds normally.
|
|
3432
|
+
*/
|
|
3433
|
+
private _handleRecoveryOom;
|
|
3321
3434
|
/**
|
|
3322
3435
|
* Handle an error thrown by `_chatRecoveryContinue` / `_chatRecoveryRetry`
|
|
3323
3436
|
* after the incident was opened.
|
|
@@ -4106,4 +4219,4 @@ export {
|
|
|
4106
4219
|
ThinkChannels as zn,
|
|
4107
4220
|
ResolvedChatRecoveryConfig as zt
|
|
4108
4221
|
};
|
|
4109
|
-
//# sourceMappingURL=index-
|
|
4222
|
+
//# sourceMappingURL=index-CR4-ffm_.d.ts.map
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
F as TextStreamCallback,
|
|
3
3
|
n as ChatSdkMessengerOptions,
|
|
4
4
|
o as MessengerDefinition
|
|
5
|
-
} from "../index-
|
|
5
|
+
} from "../index-CR4-ffm_.js";
|
|
6
6
|
import { TelegramAdapterConfig } from "@chat-adapter/telegram";
|
|
7
7
|
|
|
8
8
|
//#region src/messengers/telegram.d.ts
|
package/dist/think.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
import { $t as StepResult, An as skills, At as FiberRecoveryContext, Bn as messengerChannel, Bt as RunTurnBase, Cn as TurnResult, Ct as ChunkContext, Dn as action, Dt as DeliverNoticeOptions, En as Workspace, Et as DeleteSubmissionsOptions, Fn as ChannelDeliverySurface, Ft as PrepareStepContext, Gt as SaveMessagesOptions, Ht as RunTurnStream, In as ChannelIngress, It as PrepareStepFunction, Jt as SessionMessage, Kt as SaveMessagesResult, Ln as ChannelKind, Lt as PrepareStepResult, Mn as ChannelContext, Mt as MessageConcurrency, Nn as ChannelDefinition, Nt as OnStartDegradation, On as defaultContextOverflowClassifier, Ot as ExtensionConfig, Pn as ChannelDeliveryPolicy, Pt as PendingApproval, Qt as StepContext, Rn as NormalizedChannelDefinition, Rt as ReplyAttachment, Sn as TurnInputMessages, St as ChatStartEvent, T as DeliveryTag, Tn as TypedToolResult, Tt as ContextOverflowConfig, Ut as RunTurnSubmit, Vn as MediaEvictionConfig, Vt as RunTurnOptions, Wt as RunTurnWait, Xt as SkillSource, Yt as SkillRunContext, Zt as StepConfig, _n as ToolCallDecision, _t as ChatRecoveryContext, an as TextStreamPart, at as ActionAuthorizationContext, bn as TurnContext, bt as ChatRecoveryProgressContext, cn as ThinkScheduledTask, ct as ActionContext, dn as ThinkScheduledTasks, dt as ActionPermissionSpec, en as StopCondition, fn as ThinkSubmissionInspection, ft as AddMessagesOptions, gn as ToolCallContext, gt as ChatRecoveryConfig, hn as ThinkWallClockSchedule, ht as ChatOptions, in as SubmitMessagesResult, it as ActionApprovalPolicy, jn as ChannelCapabilities, jt as ListSubmissionsOptions, kn as isAction, kt as FiberContext, ln as ThinkScheduledTaskContext, lt as ActionIdempotencyKey, mn as ThinkTime, mt as ChatErrorContext, nn as StreamableResult, nt as Action, on as Think, ot as ActionAuthorizationDecision, pn as ThinkSubmissionStatus, pt as ChatErrorClassification, qt as Session, rn as SubmitMessagesOptions, rt as ActionApprovalDescriptor, sn as ThinkIntervalSchedule, st as ActionConfig, tn as StreamCallback, un as ThinkScheduledTaskSchedule, ut as ActionKind, vn as ToolCallResultContext, vt as ChatRecoveryExhaustedContext, w as DeliveryKind, wn as TypedToolCall, wt as ChunkPart, xn as TurnInput, xt as ChatResponseResult, yn as TurnConfig, yt as ChatRecoveryOptions, zn as ThinkChannels, zt as ResolvedChatRecoveryConfig } from "./index-
|
|
1
|
+
import { $t as StepResult, An as skills, At as FiberRecoveryContext, Bn as messengerChannel, Bt as RunTurnBase, Cn as TurnResult, Ct as ChunkContext, Dn as action, Dt as DeliverNoticeOptions, En as Workspace, Et as DeleteSubmissionsOptions, Fn as ChannelDeliverySurface, Ft as PrepareStepContext, Gt as SaveMessagesOptions, Ht as RunTurnStream, In as ChannelIngress, It as PrepareStepFunction, Jt as SessionMessage, Kt as SaveMessagesResult, Ln as ChannelKind, Lt as PrepareStepResult, Mn as ChannelContext, Mt as MessageConcurrency, Nn as ChannelDefinition, Nt as OnStartDegradation, On as defaultContextOverflowClassifier, Ot as ExtensionConfig, Pn as ChannelDeliveryPolicy, Pt as PendingApproval, Qt as StepContext, Rn as NormalizedChannelDefinition, Rt as ReplyAttachment, Sn as TurnInputMessages, St as ChatStartEvent, T as DeliveryTag, Tn as TypedToolResult, Tt as ContextOverflowConfig, Ut as RunTurnSubmit, Vn as MediaEvictionConfig, Vt as RunTurnOptions, Wt as RunTurnWait, Xt as SkillSource, Yt as SkillRunContext, Zt as StepConfig, _n as ToolCallDecision, _t as ChatRecoveryContext, an as TextStreamPart, at as ActionAuthorizationContext, bn as TurnContext, bt as ChatRecoveryProgressContext, cn as ThinkScheduledTask, ct as ActionContext, dn as ThinkScheduledTasks, dt as ActionPermissionSpec, en as StopCondition, fn as ThinkSubmissionInspection, ft as AddMessagesOptions, gn as ToolCallContext, gt as ChatRecoveryConfig, hn as ThinkWallClockSchedule, ht as ChatOptions, in as SubmitMessagesResult, it as ActionApprovalPolicy, jn as ChannelCapabilities, jt as ListSubmissionsOptions, kn as isAction, kt as FiberContext, ln as ThinkScheduledTaskContext, lt as ActionIdempotencyKey, mn as ThinkTime, mt as ChatErrorContext, nn as StreamableResult, nt as Action, on as Think, ot as ActionAuthorizationDecision, pn as ThinkSubmissionStatus, pt as ChatErrorClassification, qt as Session, rn as SubmitMessagesOptions, rt as ActionApprovalDescriptor, sn as ThinkIntervalSchedule, st as ActionConfig, tn as StreamCallback, un as ThinkScheduledTaskSchedule, ut as ActionKind, vn as ToolCallResultContext, vt as ChatRecoveryExhaustedContext, w as DeliveryKind, wn as TypedToolCall, wt as ChunkPart, xn as TurnInput, xt as ChatResponseResult, yn as TurnConfig, yt as ChatRecoveryOptions, zn as ThinkChannels, zt as ResolvedChatRecoveryConfig } from "./index-CR4-ffm_.js";
|
|
2
2
|
import { h as WorkspaceLike } from "./workspace-BZXdZcuw.js";
|
|
3
|
-
|
|
3
|
+
import { a as FetchResponseMode, i as FetchRedirectPolicy, n as FetchBindingTarget, o as FetchResult, r as FetchErrorCode, s as FetchToolEvent, t as CreateFetchToolsOptions } from "./fetch-By3eIQ-a.js";
|
|
4
|
+
export { Action, ActionApprovalDescriptor, ActionApprovalPolicy, ActionAuthorizationContext, ActionAuthorizationDecision, ActionConfig, ActionContext, ActionIdempotencyKey, ActionKind, ActionPermissionSpec, AddMessagesOptions, type ChannelCapabilities, type ChannelContext, type ChannelDefinition, type ChannelDeliveryPolicy, type ChannelDeliverySurface, type ChannelIngress, type ChannelKind, ChatErrorClassification, ChatErrorContext, ChatOptions, type ChatRecoveryConfig, type ChatRecoveryContext, type ChatRecoveryExhaustedContext, type ChatRecoveryOptions, type ChatRecoveryProgressContext, type ChatResponseResult, ChatStartEvent, ChunkContext, ChunkPart, ContextOverflowConfig, type CreateFetchToolsOptions, DeleteSubmissionsOptions, DeliverNoticeOptions, type DeliveryKind, type DeliveryTag, ExtensionConfig, type FetchBindingTarget, type FetchErrorCode, type FetchRedirectPolicy, type FetchResponseMode, type FetchResult, type FetchToolEvent, type FiberContext, type FiberRecoveryContext, ListSubmissionsOptions, type MediaEvictionConfig, type MessageConcurrency, type NormalizedChannelDefinition, OnStartDegradation, PendingApproval, PrepareStepContext, type PrepareStepFunction, type PrepareStepResult, ReplyAttachment, type ResolvedChatRecoveryConfig, RunTurnBase, RunTurnOptions, RunTurnStream, RunTurnSubmit, RunTurnWait, type SaveMessagesOptions, type SaveMessagesResult, Session, type SessionMessage, type SkillRunContext, type SkillSource, StepConfig, StepContext, type StepResult, type StopCondition, StreamCallback, StreamableResult, SubmitMessagesOptions, SubmitMessagesResult, type TextStreamPart, Think, type ThinkChannels, ThinkIntervalSchedule, ThinkScheduledTask, ThinkScheduledTaskContext, ThinkScheduledTaskSchedule, ThinkScheduledTasks, ThinkSubmissionInspection, ThinkSubmissionStatus, ThinkTime, ThinkWallClockSchedule, ToolCallContext, ToolCallDecision, ToolCallResultContext, TurnConfig, TurnContext, TurnInput, TurnInputMessages, TurnResult, type TypedToolCall, type TypedToolResult, Workspace, type WorkspaceLike, action, defaultContextOverflowClassifier, isAction, messengerChannel, skills };
|