@cloudflare/think 0.7.0 → 0.7.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 CHANGED
@@ -148,6 +148,8 @@ The AI SDK-derived contexts spread the SDK's own types at the top level — no i
148
148
 
149
149
  `TurnConfig` also accepts stable AI SDK `streamText` call settings such as `maxOutputTokens`, `temperature`, `stopSequences`, `seed`, `maxRetries`, `timeout`, and `headers`. Use them to tune model behavior per turn, for example disabling retries or adding a chunk timeout during recovery flows.
150
150
 
151
+ `TurnConfig.stopWhen` accepts AI SDK stop conditions such as `hasToolCall("finalAnswer")` for ending a turn early. Think composes these with its own `maxSteps` bound, so a custom condition can stop before the cap without removing the safety limit. Because stop conditions are functions, return `stopWhen` from a Think subclass's `beforeTurn`; sandboxed extension hooks cannot provide it over RPC.
152
+
151
153
  `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.
152
154
 
153
155
  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:
@@ -263,6 +265,7 @@ interface TurnConfig {
263
265
  activeTools?: string[]; // limit which tools the model can call
264
266
  toolChoice?: ToolChoice; // force a specific tool
265
267
  maxSteps?: number; // override maxSteps for this turn
268
+ stopWhen?: StopCondition | StopCondition[]; // additional early-exit conditions
266
269
  sendReasoning?: boolean; // send reasoning chunks for this turn
267
270
  maxOutputTokens?: number;
268
271
  temperature?: number;
@@ -355,6 +358,12 @@ your code owns forwarding and replay policy. Use `agentTool()` or
355
358
  `runAgentTool()` when a parent agent delegates work to a retained child and you
356
359
  want event replay, abort bridging, and UI drill-in.
357
360
 
361
+ Use `startFiber()` from `agents` outside Think when the durable unit is an
362
+ application-owned job around a turn, such as accepting a webhook once, restoring
363
+ provider state, and posting a visible reply. `submitMessages()` owns Think's
364
+ conversation admission; managed fibers own external side effects and recovery
365
+ policy around that turn.
366
+
358
367
  See [Choosing a turn API](../../docs/think/index.md#choosing-a-turn-api) and
359
368
  [Programmatic Submissions](../../docs/think/programmatic-submissions.md) for the
360
369
  full API comparison.
@@ -365,17 +374,20 @@ When used as a sub-agent (via `this.subAgent()`), the `chat()` method runs a ful
365
374
 
366
375
  ```ts
367
376
  interface StreamCallback {
377
+ onStart?(event: { requestId: string }): void | Promise<void>;
368
378
  onEvent(json: string): void | Promise<void>;
369
379
  onDone(): void | Promise<void>;
370
380
  onError?(error: string): void | Promise<void>;
371
381
  }
372
382
 
373
383
  const agent = await this.subAgent(MyAgent, "thread-1");
374
- await agent.chat("Summarize the project", relay, {
375
- signal: abortController.signal
376
- });
384
+ await agent.chat("Summarize the project", relay);
377
385
  ```
378
386
 
387
+ `onStart` exposes the request id for RPC-safe cancellation. Call
388
+ `agent.cancelChat(requestId, reason)` if the parent needs to stop the child turn
389
+ after it has started.
390
+
379
391
  Tools belong to the child agent; define them with `getTools()` or use
380
392
  `agentTool()` / `runAgentTool()` for parent-child orchestration.
381
393
 
package/dist/think.d.ts CHANGED
@@ -11,6 +11,8 @@ import {
11
11
  PrepareStepResult,
12
12
  PrepareStepResult as PrepareStepResult$1,
13
13
  StepResult,
14
+ StopCondition,
15
+ StopCondition as StopCondition$1,
14
16
  StreamTextOnChunkCallback,
15
17
  StreamTextOnStepFinishCallback,
16
18
  TextStreamPart,
@@ -56,7 +58,11 @@ import { Workspace } from "@cloudflare/shell";
56
58
  * Designed to work across the sub-agent RPC boundary — implement as
57
59
  * an RpcTarget in the parent agent and pass to `chat()`.
58
60
  */
61
+ interface ChatStartEvent {
62
+ requestId: string;
63
+ }
59
64
  interface StreamCallback {
65
+ onStart?(event: ChatStartEvent): void | Promise<void>;
60
66
  onEvent(json: string): void | Promise<void>;
61
67
  onDone(): void | Promise<void>;
62
68
  onError?(error: string): void | Promise<void>;
@@ -183,6 +189,11 @@ interface TurnConfig {
183
189
  toolChoice?: Parameters<typeof streamText>[0]["toolChoice"];
184
190
  /** Override maxSteps for this turn. */
185
191
  maxSteps?: number;
192
+ /**
193
+ * Additional AI SDK stop conditions for ending the turn early.
194
+ * Think always keeps its `maxSteps` stop condition as a safety bound.
195
+ */
196
+ stopWhen?: StopCondition$1<ToolSet> | Array<StopCondition$1<ToolSet>>;
186
197
  /**
187
198
  * Controls whether reasoning chunks are included in the UI message stream
188
199
  * for this turn. Defaults to the instance-level `sendReasoning` setting.
@@ -1053,16 +1064,17 @@ declare class Think<
1053
1064
  * No-op if no controller exists for `requestId` (the turn already
1054
1065
  * completed, was never started, or used a different id).
1055
1066
  *
1056
- * Most callers don't have the request id and want
1057
- * {@link abortAllRequests} instead. This method is here for
1058
- * symmetry with the WebSocket cancel surface and for callers that
1059
- * happen to know the id (e.g. via a stash from an earlier
1060
- * `saveMessages` return).
1067
+ * `chat()` callers can read the request id from
1068
+ * {@link StreamCallback.onStart} and later pass it here from another
1069
+ * RPC call.
1061
1070
  *
1062
1071
  * Prefer {@link SaveMessagesOptions.signal} when driving a turn
1063
1072
  * programmatically — it threads the abort intent in from the start
1064
1073
  * without requiring the caller to know the id.
1065
1074
  */
1075
+ cancelChat(requestId: string, reason?: string): void;
1076
+ /** Abort every in-flight chat turn on this agent. */
1077
+ cancelAllChats(): void;
1066
1078
  protected abortRequest(requestId: string, reason?: unknown): void;
1067
1079
  /**
1068
1080
  * Abort every in-flight chat turn on this agent.
@@ -1134,6 +1146,7 @@ export {
1134
1146
  type ChatRecoveryContext,
1135
1147
  type ChatRecoveryOptions,
1136
1148
  type ChatResponseResult,
1149
+ ChatStartEvent,
1137
1150
  ChunkContext,
1138
1151
  ChunkPart,
1139
1152
  DeleteSubmissionsOptions,
@@ -1151,6 +1164,7 @@ export {
1151
1164
  StepConfig,
1152
1165
  StepContext,
1153
1166
  type StepResult,
1167
+ type StopCondition,
1154
1168
  StreamCallback,
1155
1169
  StreamableResult,
1156
1170
  SubmitMessagesOptions,
package/dist/think.js CHANGED
@@ -600,6 +600,7 @@ var Think = class Think extends Agent {
600
600
  const finalTools = this._wrapToolsWithDecision(mergedTools);
601
601
  const finalMaxSteps = config.maxSteps ?? this.maxSteps;
602
602
  const finalSendReasoning = config.sendReasoning ?? this.sendReasoning;
603
+ const finalStopWhen = [stepCountIs(finalMaxSteps), ...Array.isArray(config.stopWhen) ? config.stopWhen : config.stopWhen ? [config.stopWhen] : []];
603
604
  const result = streamText({
604
605
  model: finalModel,
605
606
  system: finalSystem,
@@ -618,7 +619,7 @@ var Think = class Think extends Agent {
618
619
  maxRetries: config.maxRetries,
619
620
  timeout: config.timeout,
620
621
  headers: config.headers,
621
- stopWhen: stepCountIs(finalMaxSteps),
622
+ stopWhen: finalStopWhen,
622
623
  providerOptions: config.providerOptions,
623
624
  experimental_telemetry: config.experimental_telemetry,
624
625
  output: config.output,
@@ -925,22 +926,23 @@ var Think = class Think extends Agent {
925
926
  */
926
927
  async chat(userMessage, callback, options) {
927
928
  const requestId = crypto.randomUUID();
929
+ const abortSignal = this._aborts.getSignal(requestId);
930
+ const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
928
931
  const ignoredTools = options?.tools;
929
932
  if (ignoredTools != null && typeof ignoredTools === "object" && Object.keys(ignoredTools).length > 0) console.warn("[Think] chat() no longer accepts options.tools. Define durable tools on the child agent with getTools(), or use runAgentTool()/agentTool() for parent-child orchestration.");
930
- await this.keepAliveWhile(async () => {
931
- await this._turnQueue.enqueue(requestId, async () => {
932
- const userMsg = typeof userMessage === "string" ? {
933
- id: crypto.randomUUID(),
934
- role: "user",
935
- parts: [{
936
- type: "text",
937
- text: userMessage
938
- }]
939
- } : userMessage;
940
- await this._appendMessageToHistory(userMsg);
941
- const abortSignal = this._aborts.getSignal(requestId);
942
- const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
943
- try {
933
+ try {
934
+ await callback.onStart?.({ requestId });
935
+ await this.keepAliveWhile(async () => {
936
+ await this._turnQueue.enqueue(requestId, async () => {
937
+ const userMsg = typeof userMessage === "string" ? {
938
+ id: crypto.randomUUID(),
939
+ role: "user",
940
+ parts: [{
941
+ type: "text",
942
+ text: userMessage
943
+ }]
944
+ } : userMessage;
945
+ await this._appendMessageToHistory(userMsg);
944
946
  const chatBody = async () => {
945
947
  let result;
946
948
  try {
@@ -968,12 +970,12 @@ var Think = class Think extends Agent {
968
970
  await chatBody();
969
971
  });
970
972
  else await chatBody();
971
- } finally {
972
- detachExternal();
973
- this._aborts.remove(requestId);
974
- }
973
+ });
975
974
  });
976
- });
975
+ } finally {
976
+ detachExternal();
977
+ this._aborts.remove(requestId);
978
+ }
977
979
  }
978
980
  /** Get the conversation history as UIMessage[]. */
979
981
  async getMessages() {
@@ -2150,16 +2152,21 @@ var Think = class Think extends Agent {
2150
2152
  * No-op if no controller exists for `requestId` (the turn already
2151
2153
  * completed, was never started, or used a different id).
2152
2154
  *
2153
- * Most callers don't have the request id and want
2154
- * {@link abortAllRequests} instead. This method is here for
2155
- * symmetry with the WebSocket cancel surface and for callers that
2156
- * happen to know the id (e.g. via a stash from an earlier
2157
- * `saveMessages` return).
2155
+ * `chat()` callers can read the request id from
2156
+ * {@link StreamCallback.onStart} and later pass it here from another
2157
+ * RPC call.
2158
2158
  *
2159
2159
  * Prefer {@link SaveMessagesOptions.signal} when driving a turn
2160
2160
  * programmatically — it threads the abort intent in from the start
2161
2161
  * without requiring the caller to know the id.
2162
2162
  */
2163
+ cancelChat(requestId, reason) {
2164
+ this._aborts.cancel(requestId, reason);
2165
+ }
2166
+ /** Abort every in-flight chat turn on this agent. */
2167
+ cancelAllChats() {
2168
+ this._aborts.destroyAll();
2169
+ }
2163
2170
  abortRequest(requestId, reason) {
2164
2171
  this._aborts.cancel(requestId, reason);
2165
2172
  }