@cloudflare/think 0.7.0 → 0.7.2

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,24 @@ 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);
946
+ this._broadcastMessages();
944
947
  const chatBody = async () => {
945
948
  let result;
946
949
  try {
@@ -968,12 +971,12 @@ var Think = class Think extends Agent {
968
971
  await chatBody();
969
972
  });
970
973
  else await chatBody();
971
- } finally {
972
- detachExternal();
973
- this._aborts.remove(requestId);
974
- }
974
+ });
975
975
  });
976
- });
976
+ } finally {
977
+ detachExternal();
978
+ this._aborts.remove(requestId);
979
+ }
977
980
  }
978
981
  /** Get the conversation history as UIMessage[]. */
979
982
  async getMessages() {
@@ -983,6 +986,7 @@ var Think = class Think extends Agent {
983
986
  async clearMessages() {
984
987
  this.resetTurnState();
985
988
  await this._clearHistory();
989
+ this._broadcast({ type: MSG_CHAT_CLEAR });
986
990
  }
987
991
  _ensureAgentToolChildRunTable() {
988
992
  this.sql`
@@ -2150,16 +2154,21 @@ var Think = class Think extends Agent {
2150
2154
  * No-op if no controller exists for `requestId` (the turn already
2151
2155
  * completed, was never started, or used a different id).
2152
2156
  *
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).
2157
+ * `chat()` callers can read the request id from
2158
+ * {@link StreamCallback.onStart} and later pass it here from another
2159
+ * RPC call.
2158
2160
  *
2159
2161
  * Prefer {@link SaveMessagesOptions.signal} when driving a turn
2160
2162
  * programmatically — it threads the abort intent in from the start
2161
2163
  * without requiring the caller to know the id.
2162
2164
  */
2165
+ cancelChat(requestId, reason) {
2166
+ this._aborts.cancel(requestId, reason);
2167
+ }
2168
+ /** Abort every in-flight chat turn on this agent. */
2169
+ cancelAllChats() {
2170
+ this._aborts.destroyAll();
2171
+ }
2163
2172
  abortRequest(requestId, reason) {
2164
2173
  this._aborts.cancel(requestId, reason);
2165
2174
  }
@@ -2195,6 +2204,7 @@ var Think = class Think extends Agent {
2195
2204
  let streamFinalized = false;
2196
2205
  let assistantMsg = null;
2197
2206
  let aborted = false;
2207
+ let doneSent = false;
2198
2208
  try {
2199
2209
  this._insideInferenceLoop = true;
2200
2210
  let chunksSinceFlush = 0;
@@ -2206,7 +2216,17 @@ var Think = class Think extends Agent {
2206
2216
  break;
2207
2217
  }
2208
2218
  const streamChunk = chunk;
2209
- accumulator.applyChunk(streamChunk);
2219
+ const { action } = accumulator.applyChunk(streamChunk);
2220
+ if (action?.type === "error") {
2221
+ this._broadcastChat({
2222
+ type: MSG_CHAT_RESPONSE,
2223
+ id: requestId,
2224
+ body: action.error,
2225
+ done: false,
2226
+ error: true
2227
+ });
2228
+ continue;
2229
+ }
2210
2230
  const chunkBody = JSON.stringify(chunk);
2211
2231
  this._resumableStream.storeChunk(streamId, chunkBody);
2212
2232
  chunksSinceFlush++;
@@ -2215,6 +2235,12 @@ var Think = class Think extends Agent {
2215
2235
  chunksSinceFlush = 0;
2216
2236
  hasFlushedContent = true;
2217
2237
  }
2238
+ this._broadcastChat({
2239
+ type: MSG_CHAT_RESPONSE,
2240
+ id: requestId,
2241
+ body: chunkBody,
2242
+ done: false
2243
+ });
2218
2244
  await callback.onEvent(chunkBody);
2219
2245
  }
2220
2246
  } finally {
@@ -2222,8 +2248,16 @@ var Think = class Think extends Agent {
2222
2248
  }
2223
2249
  this._resumableStream.complete(streamId);
2224
2250
  streamFinalized = true;
2251
+ this._broadcastChat({
2252
+ type: MSG_CHAT_RESPONSE,
2253
+ id: requestId,
2254
+ body: "",
2255
+ done: true
2256
+ });
2257
+ doneSent = true;
2225
2258
  assistantMsg = accumulator.toMessage();
2226
2259
  await this._persistAssistantMessage(assistantMsg);
2260
+ this._broadcastMessages();
2227
2261
  if (!aborted) {
2228
2262
  await callback.onDone();
2229
2263
  await this._fireResponseHook({
@@ -2243,9 +2277,21 @@ var Think = class Think extends Agent {
2243
2277
  this._resumableStream.markError(streamId);
2244
2278
  streamFinalized = true;
2245
2279
  }
2280
+ if (!doneSent) {
2281
+ const streamError = error instanceof Error ? error.message : "Stream error";
2282
+ this._broadcastChat({
2283
+ type: MSG_CHAT_RESPONSE,
2284
+ id: requestId,
2285
+ body: streamError,
2286
+ done: true,
2287
+ error: true
2288
+ });
2289
+ doneSent = true;
2290
+ }
2246
2291
  if (!assistantMsg && accumulator.parts.length > 0) {
2247
2292
  assistantMsg = accumulator.toMessage();
2248
2293
  await this._persistAssistantMessage(assistantMsg);
2294
+ this._broadcastMessages();
2249
2295
  }
2250
2296
  const wrapped = this.onChatError(error);
2251
2297
  const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);