@cloudflare/think 0.4.1 → 0.5.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 +42 -1
- package/dist/think.d.ts +134 -3
- package/dist/think.js +277 -4
- package/dist/think.js.map +1 -1
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -27,6 +27,42 @@ export class MyAgent extends Think<Env> {
|
|
|
27
27
|
|
|
28
28
|
That's it. Think handles the WebSocket chat protocol, message persistence, the agentic loop, message sanitization, stream resumption, client tool support, and workspace file tools. Connect from the browser with `useAgentChat` from `@cloudflare/ai-chat`.
|
|
29
29
|
|
|
30
|
+
## Agent tools
|
|
31
|
+
|
|
32
|
+
Think subclasses can be dispatched as agent tools from another Agent. The parent
|
|
33
|
+
uses `runAgentTool()` or `agentTool()` from `agents/agent-tools`; the child Think
|
|
34
|
+
instance owns its own messages, resumable stream, tools, and storage.
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { Think } from "@cloudflare/think";
|
|
38
|
+
import { agentTool } from "agents/agent-tools";
|
|
39
|
+
import { z } from "zod";
|
|
40
|
+
|
|
41
|
+
export class Researcher extends Think<Env> {
|
|
42
|
+
getSystemPrompt() {
|
|
43
|
+
return "Research the requested topic and end with a concise summary.";
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class Assistant extends Think<Env> {
|
|
48
|
+
getTools() {
|
|
49
|
+
return {
|
|
50
|
+
research: agentTool(Researcher, {
|
|
51
|
+
description: "Research one topic in depth.",
|
|
52
|
+
inputSchema: z.object({ query: z.string().min(3) }),
|
|
53
|
+
displayName: "Researcher"
|
|
54
|
+
})
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
The parent broadcasts `agent-tool-event` frames for live UI rendering and keeps
|
|
61
|
+
the child facet until `clearAgentToolRuns()` deletes retained runs.
|
|
62
|
+
|
|
63
|
+
See the full [Agent Tools guide](../../docs/agent-tools.md) for rendering,
|
|
64
|
+
drill-in, and cleanup patterns.
|
|
65
|
+
|
|
30
66
|
## Built-in workspace
|
|
31
67
|
|
|
32
68
|
Every Think agent gets `this.workspace` — a virtual filesystem backed by the DO's SQLite storage. Workspace tools (`read`, `write`, `edit`, `list`, `find`, `grep`, `delete`) are automatically available to the model.
|
|
@@ -71,6 +107,7 @@ export class MyAgent extends Think<Env> {
|
|
|
71
107
|
| `getSystemPrompt()` | `"You are a helpful assistant."` | System prompt (fallback when no context blocks) |
|
|
72
108
|
| `getTools()` | `{}` | AI SDK `ToolSet` for the agentic loop |
|
|
73
109
|
| `maxSteps` | `10` | Max tool-call rounds per turn (property) |
|
|
110
|
+
| `sendReasoning` | `true` | Send reasoning chunks to chat clients |
|
|
74
111
|
| `configureSession()` | identity | Add context blocks, compaction, search, skills |
|
|
75
112
|
| `getExtensions()` | `[]` | Sandboxed extension declarations (load order) |
|
|
76
113
|
| `extensionLoader` | `undefined` | `WorkerLoader` binding — enables extensions |
|
|
@@ -102,7 +139,9 @@ The AI SDK-derived contexts spread the SDK's own types at the top level — no i
|
|
|
102
139
|
|
|
103
140
|
`beforeStep` is wired to the AI SDK's `prepareStep` callback. Return a `StepConfig` to override `model`, `toolChoice`, `activeTools`, `system`, `messages`, `experimental_context`, or `providerOptions` for the current step. The AI SDK does not expose `output` or `maxSteps` per step — set those at the turn level via `TurnConfig` (returned from `beforeTurn`). `beforeStep` is subclass-only; it is not dispatched to extensions because the prepareStep event surface includes a live `LanguageModel` instance which is not JSON-safe to snapshot.
|
|
104
141
|
|
|
105
|
-
`TurnConfig` also accepts
|
|
142
|
+
`TurnConfig` also accepts `sendReasoning` to override whether reasoning chunks are emitted for the current UI message stream. The instance-level `sendReasoning` property defaults to `true`; return `{ sendReasoning: false }` from `beforeTurn` to hide reasoning for a single turn, for example on internal continuation turns.
|
|
143
|
+
|
|
144
|
+
`TurnConfig` also accepts an `output` field that is forwarded to `streamText` as the AI SDK's structured-output spec. Combine with `activeTools: []` for providers (e.g. `workers-ai-provider`) that strip tools when `responseFormat: "json"` is active. Use `experimental_telemetry` to pass the AI SDK's per-call telemetry settings through to `streamText`; consider disabling `recordInputs` or `recordOutputs` if prompts or outputs may contain sensitive data.
|
|
106
145
|
|
|
107
146
|
Per-tool hooks are wired so `beforeToolCall` fires _before_ `execute` (Think wraps every tool's `execute`) and `afterToolCall` fires _after_ (via the AI SDK's `experimental_onToolCallFinish`) with `durationMs` and a discriminated outcome. `beforeToolCall` can return a `ToolCallDecision` to:
|
|
108
147
|
|
|
@@ -217,7 +256,9 @@ interface TurnConfig {
|
|
|
217
256
|
activeTools?: string[]; // limit which tools the model can call
|
|
218
257
|
toolChoice?: ToolChoice; // force a specific tool
|
|
219
258
|
maxSteps?: number; // override maxSteps for this turn
|
|
259
|
+
sendReasoning?: boolean; // send reasoning chunks for this turn
|
|
220
260
|
providerOptions?: Record<string, unknown>;
|
|
261
|
+
experimental_telemetry?: TelemetrySettings;
|
|
221
262
|
}
|
|
222
263
|
```
|
|
223
264
|
|
package/dist/think.d.ts
CHANGED
|
@@ -38,6 +38,8 @@ import {
|
|
|
38
38
|
MessageConcurrency,
|
|
39
39
|
MessageConcurrency as MessageConcurrency$1,
|
|
40
40
|
ResumableStream,
|
|
41
|
+
SaveMessagesOptions,
|
|
42
|
+
SaveMessagesOptions as SaveMessagesOptions$1,
|
|
41
43
|
SaveMessagesResult,
|
|
42
44
|
SaveMessagesResult as SaveMessagesResult$1
|
|
43
45
|
} from "agents/chat";
|
|
@@ -64,7 +66,9 @@ interface StreamCallback {
|
|
|
64
66
|
* The AI SDK's `streamText()` result satisfies this interface.
|
|
65
67
|
*/
|
|
66
68
|
interface StreamableResult {
|
|
67
|
-
toUIMessageStream(
|
|
69
|
+
toUIMessageStream(options?: {
|
|
70
|
+
sendReasoning?: boolean;
|
|
71
|
+
}): AsyncIterable<unknown>;
|
|
68
72
|
}
|
|
69
73
|
/**
|
|
70
74
|
* Options for a chat turn (sub-agent RPC entry point).
|
|
@@ -73,6 +77,27 @@ interface ChatOptions {
|
|
|
73
77
|
signal?: AbortSignal;
|
|
74
78
|
tools?: ToolSet;
|
|
75
79
|
}
|
|
80
|
+
type AgentToolChildRunStatus =
|
|
81
|
+
| "starting"
|
|
82
|
+
| "running"
|
|
83
|
+
| "completed"
|
|
84
|
+
| "error"
|
|
85
|
+
| "aborted";
|
|
86
|
+
type AgentToolRunInspection<Output = unknown> = {
|
|
87
|
+
runId: string;
|
|
88
|
+
status: AgentToolChildRunStatus;
|
|
89
|
+
requestId?: string;
|
|
90
|
+
streamId?: string;
|
|
91
|
+
output?: Output;
|
|
92
|
+
summary?: string;
|
|
93
|
+
error?: string;
|
|
94
|
+
startedAt: number;
|
|
95
|
+
completedAt?: number;
|
|
96
|
+
};
|
|
97
|
+
type AgentToolStoredChunk = {
|
|
98
|
+
sequence: number;
|
|
99
|
+
body: string;
|
|
100
|
+
};
|
|
76
101
|
/**
|
|
77
102
|
* A chat turn request. Built automatically by each entry path
|
|
78
103
|
* (WebSocket, chat(), saveMessages, auto-continuation) and passed
|
|
@@ -126,8 +151,17 @@ interface TurnConfig {
|
|
|
126
151
|
toolChoice?: Parameters<typeof streamText>[0]["toolChoice"];
|
|
127
152
|
/** Override maxSteps for this turn. */
|
|
128
153
|
maxSteps?: number;
|
|
154
|
+
/**
|
|
155
|
+
* Controls whether reasoning chunks are included in the UI message stream
|
|
156
|
+
* for this turn. Defaults to the instance-level `sendReasoning` setting.
|
|
157
|
+
*/
|
|
158
|
+
sendReasoning?: boolean;
|
|
129
159
|
/** Provider-specific options (AI SDK providerOptions). */
|
|
130
160
|
providerOptions?: Record<string, unknown>;
|
|
161
|
+
/** Optional AI SDK telemetry configuration for this turn. */
|
|
162
|
+
experimental_telemetry?: Parameters<
|
|
163
|
+
typeof streamText
|
|
164
|
+
>[0]["experimental_telemetry"];
|
|
131
165
|
/**
|
|
132
166
|
* Optional structured-output specification (AI SDK `output`).
|
|
133
167
|
* Forwarded to `streamText` so the model's final response is parsed
|
|
@@ -400,6 +434,16 @@ declare class Think<
|
|
|
400
434
|
private _pendingInteractionPromise;
|
|
401
435
|
private _submitConcurrency;
|
|
402
436
|
private static MESSAGE_DEBOUNCE_MS;
|
|
437
|
+
private _agentToolForwarders;
|
|
438
|
+
private _agentToolClosers;
|
|
439
|
+
private _agentToolAbortControllers;
|
|
440
|
+
private _agentToolLastErrors;
|
|
441
|
+
private _agentToolPreTurnAssistantIds;
|
|
442
|
+
private _agentToolLiveSequences;
|
|
443
|
+
broadcast(
|
|
444
|
+
msg: string | ArrayBuffer | ArrayBufferView,
|
|
445
|
+
without?: string[]
|
|
446
|
+
): void;
|
|
403
447
|
/**
|
|
404
448
|
* Persist an arbitrary JSON-serializable configuration object for this
|
|
405
449
|
* agent instance. Stored in the Think-private `think_config` table —
|
|
@@ -444,6 +488,11 @@ declare class Think<
|
|
|
444
488
|
getTools(): ToolSet;
|
|
445
489
|
/** Maximum number of tool-call steps per turn. Override via property or per-turn via TurnConfig. */
|
|
446
490
|
maxSteps: number;
|
|
491
|
+
/**
|
|
492
|
+
* Whether reasoning chunks are sent to chat clients by default. Override
|
|
493
|
+
* per turn by returning `sendReasoning` from `beforeTurn`.
|
|
494
|
+
*/
|
|
495
|
+
sendReasoning: boolean;
|
|
447
496
|
/**
|
|
448
497
|
* Configure the session. Called once during `onStart`.
|
|
449
498
|
* Override to add context blocks, compaction, search, skills.
|
|
@@ -738,6 +787,32 @@ declare class Think<
|
|
|
738
787
|
getMessages(): UIMessage[];
|
|
739
788
|
/** Clear all messages from storage. */
|
|
740
789
|
clearMessages(): void;
|
|
790
|
+
private _ensureAgentToolChildRunTable;
|
|
791
|
+
private _readAgentToolChildRun;
|
|
792
|
+
private _inspectionFromChildRow;
|
|
793
|
+
protected formatAgentToolInput(input: unknown): UIMessage;
|
|
794
|
+
protected getAgentToolOutput(_runId: string): unknown;
|
|
795
|
+
startAgentToolRun(
|
|
796
|
+
input: unknown,
|
|
797
|
+
options: {
|
|
798
|
+
runId: string;
|
|
799
|
+
}
|
|
800
|
+
): Promise<AgentToolRunInspection>;
|
|
801
|
+
cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
|
|
802
|
+
inspectAgentToolRun(runId: string): Promise<AgentToolRunInspection | null>;
|
|
803
|
+
getAgentToolChunks(
|
|
804
|
+
runId: string,
|
|
805
|
+
options?: {
|
|
806
|
+
afterSequence?: number;
|
|
807
|
+
}
|
|
808
|
+
): Promise<AgentToolStoredChunk[]>;
|
|
809
|
+
tailAgentToolRun(
|
|
810
|
+
runId: string,
|
|
811
|
+
options?: {
|
|
812
|
+
afterSequence?: number;
|
|
813
|
+
}
|
|
814
|
+
): Promise<ReadableStream<AgentToolStoredChunk>>;
|
|
815
|
+
private _getAgentToolFinalText;
|
|
741
816
|
/**
|
|
742
817
|
* Inject messages and trigger a model turn — without a WebSocket request.
|
|
743
818
|
*
|
|
@@ -748,6 +823,13 @@ declare class Think<
|
|
|
748
823
|
* current state (useful when multiple calls queue up — the callback runs
|
|
749
824
|
* with the latest messages when the turn actually starts).
|
|
750
825
|
*
|
|
826
|
+
* Pass `options.signal` to cancel the turn from outside without knowing
|
|
827
|
+
* the internally-generated request id. The signal is linked to the
|
|
828
|
+
* registry's controller for this turn — when it aborts, the inference
|
|
829
|
+
* loop's signal aborts and the result reports `status: "aborted"`.
|
|
830
|
+
* Pre-aborted signals short-circuit before any model work runs. See
|
|
831
|
+
* {@link SaveMessagesOptions} for the integration point.
|
|
832
|
+
*
|
|
751
833
|
* @example Scheduled follow-up
|
|
752
834
|
* ```typescript
|
|
753
835
|
* async onScheduled() {
|
|
@@ -766,11 +848,19 @@ declare class Think<
|
|
|
766
848
|
* { id: crypto.randomUUID(), role: "user", parts: [{ type: "text", text: "Continue." }] }
|
|
767
849
|
* ]);
|
|
768
850
|
* ```
|
|
851
|
+
*
|
|
852
|
+
* @example External cancellation (helper-as-sub-agent)
|
|
853
|
+
* ```typescript
|
|
854
|
+
* // Inside a parent agent's tool execute — forward the AI SDK's
|
|
855
|
+
* // abortSignal so a parent stop / tab close cancels the helper.
|
|
856
|
+
* await helper.saveMessages([userMsg], { signal: abortSignal });
|
|
857
|
+
* ```
|
|
769
858
|
*/
|
|
770
859
|
saveMessages(
|
|
771
860
|
messages:
|
|
772
861
|
| UIMessage[]
|
|
773
|
-
| ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>)
|
|
862
|
+
| ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),
|
|
863
|
+
options?: SaveMessagesOptions$1
|
|
774
864
|
): Promise<SaveMessagesResult$1>;
|
|
775
865
|
/**
|
|
776
866
|
* Run a new LLM call following the last assistant message.
|
|
@@ -785,9 +875,13 @@ declare class Think<
|
|
|
785
875
|
*
|
|
786
876
|
* Returns early with `status: "skipped"` if there is no assistant message
|
|
787
877
|
* to continue from.
|
|
878
|
+
*
|
|
879
|
+
* Pass `options.signal` to cancel the continuation from outside —
|
|
880
|
+
* matches the {@link saveMessages} contract.
|
|
788
881
|
*/
|
|
789
882
|
protected continueLastTurn(
|
|
790
|
-
body?: Record<string, unknown
|
|
883
|
+
body?: Record<string, unknown>,
|
|
884
|
+
options?: SaveMessagesOptions$1
|
|
791
885
|
): Promise<SaveMessagesResult$1>;
|
|
792
886
|
private _setupProtocolHandlers;
|
|
793
887
|
private _handleProtocolEvent;
|
|
@@ -803,6 +897,42 @@ declare class Think<
|
|
|
803
897
|
* only turn execution state.
|
|
804
898
|
*/
|
|
805
899
|
protected resetTurnState(): void;
|
|
900
|
+
/**
|
|
901
|
+
* Abort a single in-flight chat turn by request id.
|
|
902
|
+
*
|
|
903
|
+
* Equivalent to the cancel path that fires when a client sends a
|
|
904
|
+
* `chat-request-cancel` WebSocket message — the inference loop's
|
|
905
|
+
* signal aborts, partial chunks already streamed are still
|
|
906
|
+
* persisted, and the turn's `ChatResponseResult` reports
|
|
907
|
+
* `status: "aborted"`.
|
|
908
|
+
*
|
|
909
|
+
* No-op if no controller exists for `requestId` (the turn already
|
|
910
|
+
* completed, was never started, or used a different id).
|
|
911
|
+
*
|
|
912
|
+
* Most callers don't have the request id and want
|
|
913
|
+
* {@link abortAllRequests} instead. This method is here for
|
|
914
|
+
* symmetry with the WebSocket cancel surface and for callers that
|
|
915
|
+
* happen to know the id (e.g. via a stash from an earlier
|
|
916
|
+
* `saveMessages` return).
|
|
917
|
+
*
|
|
918
|
+
* Prefer {@link SaveMessagesOptions.signal} when driving a turn
|
|
919
|
+
* programmatically — it threads the abort intent in from the start
|
|
920
|
+
* without requiring the caller to know the id.
|
|
921
|
+
*/
|
|
922
|
+
protected abortRequest(requestId: string, reason?: unknown): void;
|
|
923
|
+
/**
|
|
924
|
+
* Abort every in-flight chat turn on this agent.
|
|
925
|
+
*
|
|
926
|
+
* Aborts all controllers in the registry and clears it. Used by
|
|
927
|
+
* subclasses that drive single-purpose turns (e.g. a sub-agent
|
|
928
|
+
* helper that runs one turn at a time over RPC) and want a coarse
|
|
929
|
+
* "cancel whatever is running" handle without tracking request ids.
|
|
930
|
+
*
|
|
931
|
+
* Does NOT reset queued turns, continuation timers, or submit
|
|
932
|
+
* concurrency state — use {@link resetTurnState} for the full
|
|
933
|
+
* teardown that runs on `chat-clear`.
|
|
934
|
+
*/
|
|
935
|
+
protected abortAllRequests(): void;
|
|
806
936
|
private _handleClear;
|
|
807
937
|
private _streamResult;
|
|
808
938
|
private _persistAssistantMessage;
|
|
@@ -860,6 +990,7 @@ export {
|
|
|
860
990
|
PrepareStepContext,
|
|
861
991
|
type PrepareStepFunction,
|
|
862
992
|
type PrepareStepResult,
|
|
993
|
+
type SaveMessagesOptions,
|
|
863
994
|
type SaveMessagesResult,
|
|
864
995
|
Session,
|
|
865
996
|
StepConfig,
|