@cloudflare/think 0.8.4 → 0.8.5

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.
@@ -1796,6 +1796,16 @@ declare class Think<
1796
1796
  private _iterateWithStallWatchdog;
1797
1797
  private _streamResult;
1798
1798
  private _persistAssistantMessage;
1799
+ /**
1800
+ * Remove parts belonging to Think's internal structured-output final-answer
1801
+ * tool (`think_final_answer`, or a collision-suffixed variant) from a UI
1802
+ * message so the internal call/result never enters the persisted conversation
1803
+ * (and is never re-fed to the model on later turns). Stateless and matched by
1804
+ * the reserved name so it also covers recovery re-persist paths. Handles both
1805
+ * the static (`tool-<name>`) and dynamic (`dynamic-tool`) part shapes the AI
1806
+ * SDK can emit.
1807
+ */
1808
+ private _stripInternalFinalAnswerParts;
1799
1809
  /**
1800
1810
  * Persist an incoming message after reconciliation. For assistant
1801
1811
  * messages, also resolve their ID against any server-side row that
@@ -2182,14 +2192,44 @@ declare class Think<
2182
2192
  private _activateDeferredContinuation;
2183
2193
  private _fireResponseHook;
2184
2194
  /**
2185
- * Persist (on `error`) or clear (on `completed`/`aborted`) a durable record of
2186
- * the last terminal turn so it can be replayed to clients on connect. A
2187
- * `completed`/`aborted` turn is conveyed by the persisted messages, so the
2188
- * record is cleared; an `error`/`interrupted` turn has no durable trace
2189
- * otherwise, so it is kept until a later turn resolves.
2195
+ * Persist (on `error`/`interrupted`) or clear (on `completed`/`aborted`) the
2196
+ * durable terminal record so it can be replayed to clients on reconnect, and
2197
+ * resolve any in-progress "recovering…" indicator. A `completed`/`aborted`
2198
+ * turn is conveyed by the persisted messages, so the record is cleared; an
2199
+ * `error`/`interrupted` turn has no durable trace otherwise, so it is kept
2200
+ * until a later turn supersedes it.
2201
+ *
2202
+ * The storage primitives are shared with `@cloudflare/ai-chat`
2203
+ * (`_recordChatTerminal` / `_clearChatTerminal` / `_pendingChatTerminal`).
2190
2204
  */
2191
2205
  private _recordTerminalChatStatus;
2192
- private _pendingTerminalChatResponse;
2206
+ /**
2207
+ * Persist a durable record of the last terminal turn so a client that
2208
+ * (re)connects after the turn ended still learns its outcome (#1645). Kept
2209
+ * until a later turn supersedes it (`_clearChatTerminal`); a single record is
2210
+ * sufficient because only the most recent terminal is relevant.
2211
+ */
2212
+ private _recordChatTerminal;
2213
+ /** Clear the durable terminal record once a later turn supersedes it (#1645). */
2214
+ private _clearChatTerminal;
2215
+ private _pendingChatTerminal;
2216
+ /**
2217
+ * Replay a pending terminal outcome (#1645) over the resume handshake so a
2218
+ * reconnecting client surfaces it exactly like a live exhaustion. A bare
2219
+ * terminal frame sent on connect is dropped by the `useAgentChat` client
2220
+ * because it never reaches a transport stream reader; only a frame delivered
2221
+ * on a resumed stream becomes `useChat.error` (this is why the terminal is
2222
+ * NOT included in `_buildIdleConnectMessages`). So we drive `STREAM_RESUMING`
2223
+ * here and send the error frame once the client ACKs (see
2224
+ * `_replayTerminalOnAck`). Returns true if a terminal was pending.
2225
+ */
2226
+ private _replayTerminalOnResume;
2227
+ /**
2228
+ * Deliver the pending terminal error frame on the resumed stream the client
2229
+ * ACKed (#1645). The record is retained (cleared only when a later turn
2230
+ * supersedes it) so concurrent reconnects each learn the outcome.
2231
+ */
2232
+ private _replayTerminalOnAck;
2193
2233
  /**
2194
2234
  * Set or clear the live "recovering…" status for a durable chat turn (#1620).
2195
2235
  * Persists a durable record (replayed on connect via `_buildIdleConnectMessages`)
@@ -2201,9 +2241,15 @@ declare class Think<
2201
2241
  private _setChatRecovering;
2202
2242
  /**
2203
2243
  * Messages sent to a client on connect when no stream is active: the current
2204
- * transcript, plus a replay of the last terminal error (if any) so a turn
2205
- * that failed while the client was disconnected is surfaced rather than
2206
- * silently frozen.
2244
+ * transcript, plus a replay of an in-progress "recovering…" status (if any).
2245
+ *
2246
+ * A terminal error is deliberately NOT replayed here. A bare
2247
+ * `MSG_CHAT_RESPONSE` frame on connect is dropped by the `useAgentChat`
2248
+ * client because it never reaches a transport stream reader, so it cannot
2249
+ * become `useChat.error` — a failed turn would still look frozen (#1645).
2250
+ * The terminal outcome is instead surfaced over the resume handshake
2251
+ * (`_replayTerminalOnResume` → ACK → `_replayTerminalOnAck`), the only path
2252
+ * that lands on the stream reader.
2207
2253
  */
2208
2254
  private _buildIdleConnectMessages;
2209
2255
  private _notifyStreamResuming;
@@ -2675,4 +2721,4 @@ export {
2675
2721
  messengerReplySnapshot as z,
2676
2722
  ThinkScheduledTask as zt
2677
2723
  };
2678
- //# sourceMappingURL=index-By2rkaOh.d.ts.map
2724
+ //# sourceMappingURL=index-BzPfnYMr.d.ts.map
@@ -52,7 +52,7 @@ import {
52
52
  x as toMessengerAuthor,
53
53
  y as normalizeMessengers,
54
54
  z as messengerReplySnapshot
55
- } from "../index-By2rkaOh.js";
55
+ } from "../index-BzPfnYMr.js";
56
56
  export {
57
57
  type ChatSdkMessengerEventInput,
58
58
  type ChatSdkMessengerOptions,
@@ -2,7 +2,7 @@ import {
2
2
  P as TextStreamCallback,
3
3
  n as ChatSdkMessengerOptions,
4
4
  o as MessengerDefinition
5
- } from "../index-By2rkaOh.js";
5
+ } from "../index-BzPfnYMr.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
@@ -59,7 +59,7 @@ import {
59
59
  xt as PrepareStepResult,
60
60
  yt as PrepareStepContext,
61
61
  zt as ThinkScheduledTask
62
- } from "./index-By2rkaOh.js";
62
+ } from "./index-BzPfnYMr.js";
63
63
  export {
64
64
  ChatErrorClassification,
65
65
  ChatErrorContext,
package/dist/think.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { a as _classPrivateFieldSet2, i as _classPrivateFieldGet2, n as sanitizeName, s as _classPrivateFieldInitSpec, t as ExtensionManager } from "./manager-EBL4uMVp.js";
2
2
  import { createWorkspaceTools } from "./tools/workspace.js";
3
3
  import { t as ThinkMessengerRuntime } from "./chat-sdk-Bb93yaZh.js";
4
- import { Output, convertToModelMessages, jsonSchema, stepCountIs, streamText } from "ai";
4
+ import { convertToModelMessages, hasToolCall, jsonSchema, stepCountIs, streamText, tool } from "ai";
5
5
  import * as skills from "agents/skills";
6
6
  import { SkillRegistry } from "agents/skills";
7
7
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
@@ -328,6 +328,39 @@ function defineScheduledTasks(tasks) {
328
328
  }
329
329
  const THINK_WORKFLOW_PROMPT_METADATA_KEY = "__thinkWorkflowPrompt";
330
330
  /**
331
+ * Reserved name for the synthetic tool a workflow `step.prompt` turn uses to
332
+ * deliver its structured final answer. The agent runs a full multi-step,
333
+ * tool-using turn and ends it by calling this tool with arguments matching the
334
+ * requested schema — exactly the way a sub-agent returns a result.
335
+ *
336
+ * Why a tool instead of the AI SDK `output`/`response_format` path: streaming a
337
+ * JSON Schema `response_format` is rejected by some providers (Workers AI
338
+ * returns `AiError 5023: JSON Schema mode is not supported with stream mode`),
339
+ * whereas plain tool-calling streams on every provider. Capturing the tool
340
+ * call's INPUT as the result keeps Think's single streaming engine intact
341
+ * (persistence, recovery, resumable streams) and works uniformly across
342
+ * Workers AI, OpenAI, and Anthropic.
343
+ *
344
+ * The name is namespaced to avoid clashing with user tools; if a user tool
345
+ * already uses it, the turn picks a suffixed variant (see `_handleTurn`).
346
+ */
347
+ const THINK_FINAL_ANSWER_TOOL_NAME = "think_final_answer";
348
+ /**
349
+ * Whether `name` is (or is a collision-suffixed variant of) the reserved
350
+ * structured-output final-answer tool. Used to strip the internal tool's parts
351
+ * from persisted assistant messages regardless of which per-turn name was used.
352
+ */
353
+ function isThinkFinalAnswerToolName(name) {
354
+ return name === THINK_FINAL_ANSWER_TOOL_NAME || name.startsWith(`${THINK_FINAL_ANSWER_TOOL_NAME}_`);
355
+ }
356
+ /**
357
+ * Build the system-prompt instruction that tells the model to terminate a
358
+ * structured workflow turn by calling the given final-answer tool.
359
+ */
360
+ function thinkFinalAnswerInstruction(toolName) {
361
+ return `When you have everything you need to answer, you MUST call the \`${toolName}\` tool exactly once with arguments that match the required schema. Do not write the final answer as plain text — the \`${toolName}\` tool call IS the answer and ends the task.`;
362
+ }
363
+ /**
331
364
  * Matches the context-window-overflow error messages of the common providers.
332
365
  * Anthropic (`prompt is too long`), OpenAI (`context_length_exceeded`,
333
366
  * `maximum context length`, `reduce the length of …`), Google Gemini (`exceeds
@@ -686,6 +719,7 @@ var Think = class Think extends Agent {
686
719
  }
687
720
  async _clearHistory() {
688
721
  await this.session.clearMessages();
722
+ await this._clearChatTerminal();
689
723
  }
690
724
  /** Append a message while keeping Think's live message cache coherent. */
691
725
  appendMessageToHistory(message, parentId) {
@@ -1445,7 +1479,8 @@ var Think = class Think extends Agent {
1445
1479
  const subclassConfig = await this.beforeTurn(ctx) ?? {};
1446
1480
  const config = await this._pipelineExtensionBeforeTurn(ctx, subclassConfig);
1447
1481
  const workflowPrompt = input.workflowPrompt;
1448
- const workflowOutput = workflowPrompt?.output ? Output.object({ schema: jsonSchema(workflowPrompt.output.schema) }) : void 0;
1482
+ const structuredOutputSchema = workflowPrompt?.output ? jsonSchema(workflowPrompt.output.schema) : void 0;
1483
+ const wantsStructuredOutput = structuredOutputSchema !== void 0;
1449
1484
  const finalModel = config.model ?? model;
1450
1485
  const finalSystem = config.system ?? this._systemPromptForTurn(baseSystem, config.tools ? {
1451
1486
  ...tools,
@@ -1457,20 +1492,40 @@ var Think = class Think extends Agent {
1457
1492
  ...config.tools
1458
1493
  } : tools;
1459
1494
  const finalTools = this._wrapToolsWithDecision(mergedTools);
1495
+ let finalAnswerToolName = THINK_FINAL_ANSWER_TOOL_NAME;
1496
+ if (structuredOutputSchema) {
1497
+ let suffix = 1;
1498
+ while (finalAnswerToolName in finalTools) finalAnswerToolName = `${THINK_FINAL_ANSWER_TOOL_NAME}_${suffix++}`;
1499
+ finalTools[finalAnswerToolName] = tool({
1500
+ description: "Provide your final answer. The arguments MUST match the required schema. Calling this tool ends the task — call it exactly once when you have everything you need.",
1501
+ inputSchema: structuredOutputSchema,
1502
+ execute: async () => "Final answer recorded."
1503
+ });
1504
+ }
1460
1505
  this._turnModelMessageBaseline = finalMessages.length;
1461
1506
  this._activeTurnTools = mergedTools;
1462
1507
  const finalMaxSteps = config.maxSteps ?? this.maxSteps;
1463
1508
  const finalSendReasoning = config.sendReasoning ?? this.sendReasoning;
1464
1509
  this._activeStallTimeoutMs = config.chatStreamStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
1465
- const finalOutput = workflowOutput ?? config.output;
1466
- const finalStopWhen = [stepCountIs(finalMaxSteps), ...Array.isArray(config.stopWhen) ? config.stopWhen : config.stopWhen ? [config.stopWhen] : []];
1510
+ const finalOutput = config.output;
1511
+ const turnSystem = wantsStructuredOutput ? [finalSystem, thinkFinalAnswerInstruction(finalAnswerToolName)].filter(Boolean).join("\n\n") : finalSystem;
1512
+ const structuredHasRealTools = wantsStructuredOutput && Object.keys(finalTools).some((name) => name !== finalAnswerToolName);
1513
+ const finalToolChoice = wantsStructuredOutput ? config.toolChoice ?? (structuredHasRealTools ? "required" : {
1514
+ type: "tool",
1515
+ toolName: finalAnswerToolName
1516
+ }) : config.toolChoice;
1517
+ const finalStopWhen = [
1518
+ stepCountIs(finalMaxSteps),
1519
+ ...wantsStructuredOutput ? [hasToolCall(finalAnswerToolName)] : [],
1520
+ ...Array.isArray(config.stopWhen) ? config.stopWhen : config.stopWhen ? [config.stopWhen] : []
1521
+ ];
1467
1522
  const result = streamText({
1468
1523
  model: finalModel,
1469
- system: finalSystem,
1524
+ system: turnSystem,
1470
1525
  messages: finalMessages,
1471
1526
  tools: finalTools,
1472
- activeTools: config.activeTools,
1473
- toolChoice: config.toolChoice,
1527
+ activeTools: wantsStructuredOutput && config.activeTools ? [...config.activeTools, finalAnswerToolName] : config.activeTools,
1528
+ toolChoice: finalToolChoice,
1474
1529
  maxOutputTokens: config.maxOutputTokens,
1475
1530
  temperature: config.temperature,
1476
1531
  topP: config.topP,
@@ -1492,11 +1547,19 @@ var Think = class Think extends Agent {
1492
1547
  const result = await this.beforeStep(event);
1493
1548
  const base = result == null ? {} : result;
1494
1549
  const baseMessages = base.messages;
1495
- if (guarded && baseMessages === void 0) return {
1550
+ const withMessages = guarded && baseMessages === void 0 ? {
1496
1551
  ...base,
1497
1552
  messages: guarded
1553
+ } : base;
1554
+ if (wantsStructuredOutput && event.stepNumber >= finalMaxSteps - 1 && withMessages.toolChoice === void 0) return {
1555
+ ...withMessages,
1556
+ toolChoice: {
1557
+ type: "tool",
1558
+ toolName: finalAnswerToolName
1559
+ },
1560
+ activeTools: [finalAnswerToolName]
1498
1561
  };
1499
- return base;
1562
+ return withMessages;
1500
1563
  }),
1501
1564
  onChunk: async (event) => {
1502
1565
  await this.onChunk(event);
@@ -1507,6 +1570,7 @@ var Think = class Think extends Agent {
1507
1570
  await this._pipelineExtensionStepFinish(event);
1508
1571
  },
1509
1572
  experimental_onToolCallFinish: (async (event) => {
1573
+ if (event.toolCall.toolName === finalAnswerToolName) return;
1510
1574
  const base = {
1511
1575
  ...event.toolCall,
1512
1576
  stepNumber: event.stepNumber,
@@ -1526,7 +1590,12 @@ var Think = class Think extends Agent {
1526
1590
  await this._pipelineExtensionToolCallFinish(event);
1527
1591
  })
1528
1592
  });
1529
- const outputPromise = finalOutput && result.output ? Promise.resolve(result.output) : void 0;
1593
+ const outputPromise = wantsStructuredOutput ? Promise.resolve(result.toolCalls).then((calls) => {
1594
+ const finalCalls = calls.filter((call) => call.toolName === finalAnswerToolName);
1595
+ const last = finalCalls[finalCalls.length - 1];
1596
+ if (!last) throw new Error(`Model ended the turn without calling the ${finalAnswerToolName} tool`);
1597
+ return last.input;
1598
+ }) : finalOutput && result.output ? Promise.resolve(result.output) : void 0;
1530
1599
  if (outputPromise) outputPromise.catch(() => {});
1531
1600
  const streamResult = {
1532
1601
  toUIMessageStream: () => result.toUIMessageStream({ sendReasoning: finalSendReasoning }),
@@ -3518,7 +3587,7 @@ var Think = class Think extends Agent {
3518
3587
  async _handleProtocolEvent(connection, event) {
3519
3588
  switch (event.type) {
3520
3589
  case "stream-resume-request":
3521
- this._handleStreamResumeRequest(connection);
3590
+ await this._handleStreamResumeRequest(connection);
3522
3591
  break;
3523
3592
  case "stream-resume-ack":
3524
3593
  await this._handleStreamResumeAck(connection, event.id);
@@ -3549,18 +3618,18 @@ var Think = class Think extends Agent {
3549
3618
  case "messages": break;
3550
3619
  }
3551
3620
  }
3552
- _handleStreamResumeRequest(connection) {
3621
+ async _handleStreamResumeRequest(connection) {
3553
3622
  if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
3554
3623
  else this._notifyStreamResuming(connection);
3555
3624
  else if (this._continuation.pending !== null && (this._continuation.pending.connectionId === null || this._continuation.pending.connectionId === connection.id)) this._continuation.awaitingConnections.set(connection.id, connection);
3556
- else sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
3625
+ else if (await this._replayTerminalOnResume(connection)) {} else sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
3557
3626
  }
3558
3627
  async _handleStreamResumeAck(connection, requestId) {
3559
3628
  this._pendingResumeConnections.delete(connection.id);
3560
3629
  if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === requestId) {
3561
3630
  const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
3562
3631
  if (orphanedStreamId) await this._persistOrphanedStream(orphanedStreamId);
3563
- } else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, requestId)) sendIfOpen(connection, JSON.stringify({
3632
+ } else if (this._resumableStream.hasActiveStream()) {} else if (await this._replayTerminalOnAck(connection, requestId)) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, requestId)) sendIfOpen(connection, JSON.stringify({
3564
3633
  body: "",
3565
3634
  done: true,
3566
3635
  id: requestId,
@@ -3600,6 +3669,7 @@ var Think = class Think extends Agent {
3600
3669
  this._completeSkippedRequest(connection, requestId);
3601
3670
  return;
3602
3671
  }
3672
+ await this._clearChatTerminal();
3603
3673
  const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
3604
3674
  let pendingEnqueue = true;
3605
3675
  const epoch = this._turnQueue.generation;
@@ -4312,9 +4382,36 @@ var Think = class Think extends Agent {
4312
4382
  };
4313
4383
  }
4314
4384
  async _persistAssistantMessage(msg, parentId) {
4385
+ const stripped = this._stripInternalFinalAnswerParts(msg);
4386
+ if (stripped !== msg) {
4387
+ if (!stripped.parts.some((part) => part.type !== "step-start")) return;
4388
+ await this._upsertMessageInHistory(stripped, parentId);
4389
+ return;
4390
+ }
4315
4391
  await this._upsertMessageInHistory(msg, parentId);
4316
4392
  }
4317
4393
  /**
4394
+ * Remove parts belonging to Think's internal structured-output final-answer
4395
+ * tool (`think_final_answer`, or a collision-suffixed variant) from a UI
4396
+ * message so the internal call/result never enters the persisted conversation
4397
+ * (and is never re-fed to the model on later turns). Stateless and matched by
4398
+ * the reserved name so it also covers recovery re-persist paths. Handles both
4399
+ * the static (`tool-<name>`) and dynamic (`dynamic-tool`) part shapes the AI
4400
+ * SDK can emit.
4401
+ */
4402
+ _stripInternalFinalAnswerParts(msg) {
4403
+ const parts = msg.parts.filter((part) => {
4404
+ const candidate = part;
4405
+ if (typeof candidate.type === "string" && candidate.type.startsWith("tool-") && isThinkFinalAnswerToolName(candidate.type.slice(5))) return false;
4406
+ if (candidate.type === "dynamic-tool" && typeof candidate.toolName === "string" && isThinkFinalAnswerToolName(candidate.toolName)) return false;
4407
+ return true;
4408
+ });
4409
+ return parts.length === msg.parts.length ? msg : {
4410
+ ...msg,
4411
+ parts
4412
+ };
4413
+ }
4414
+ /**
4318
4415
  * Persist an incoming message after reconciliation. For assistant
4319
4416
  * messages, also resolve their ID against any server-side row that
4320
4417
  * already owns the same `toolCallId` so we update the existing row
@@ -4690,8 +4787,8 @@ var Think = class Think extends Agent {
4690
4787
  done: true,
4691
4788
  error: true
4692
4789
  });
4693
- await this._markRecoveredSubmissionInterrupted(incident.recoveryRootRequestId ?? incident.requestId, config.terminalMessage);
4694
4790
  await this._recordTerminalChatStatus("interrupted", incident.requestId, config.terminalMessage);
4791
+ await this._markRecoveredSubmissionInterrupted(incident.recoveryRootRequestId ?? incident.requestId, config.terminalMessage);
4695
4792
  }
4696
4793
  /**
4697
4794
  * Route a stream-stall watchdog abort into bounded recovery instead of a
@@ -5556,24 +5653,77 @@ var Think = class Think extends Agent {
5556
5653
  }
5557
5654
  }
5558
5655
  /**
5559
- * Persist (on `error`) or clear (on `completed`/`aborted`) a durable record of
5560
- * the last terminal turn so it can be replayed to clients on connect. A
5561
- * `completed`/`aborted` turn is conveyed by the persisted messages, so the
5562
- * record is cleared; an `error`/`interrupted` turn has no durable trace
5563
- * otherwise, so it is kept until a later turn resolves.
5656
+ * Persist (on `error`/`interrupted`) or clear (on `completed`/`aborted`) the
5657
+ * durable terminal record so it can be replayed to clients on reconnect, and
5658
+ * resolve any in-progress "recovering…" indicator. A `completed`/`aborted`
5659
+ * turn is conveyed by the persisted messages, so the record is cleared; an
5660
+ * `error`/`interrupted` turn has no durable trace otherwise, so it is kept
5661
+ * until a later turn supersedes it.
5662
+ *
5663
+ * The storage primitives are shared with `@cloudflare/ai-chat`
5664
+ * (`_recordChatTerminal` / `_clearChatTerminal` / `_pendingChatTerminal`).
5564
5665
  */
5565
5666
  async _recordTerminalChatStatus(status, requestId, body) {
5566
- if (status === "error" || status === "interrupted") await this.ctx.storage.put(CHAT_LAST_TERMINAL_KEY, {
5667
+ if (status === "error" || status === "interrupted") await this._recordChatTerminal(requestId, body);
5668
+ else await this._clearChatTerminal();
5669
+ await this._setChatRecovering(false);
5670
+ }
5671
+ /**
5672
+ * Persist a durable record of the last terminal turn so a client that
5673
+ * (re)connects after the turn ended still learns its outcome (#1645). Kept
5674
+ * until a later turn supersedes it (`_clearChatTerminal`); a single record is
5675
+ * sufficient because only the most recent terminal is relevant.
5676
+ */
5677
+ async _recordChatTerminal(requestId, body) {
5678
+ await this.ctx.storage.put(CHAT_LAST_TERMINAL_KEY, {
5567
5679
  requestId,
5568
5680
  body
5569
5681
  });
5570
- else await this.ctx.storage.delete(CHAT_LAST_TERMINAL_KEY);
5571
- await this._setChatRecovering(false);
5572
5682
  }
5573
- async _pendingTerminalChatResponse() {
5683
+ /** Clear the durable terminal record once a later turn supersedes it (#1645). */
5684
+ async _clearChatTerminal() {
5685
+ await this.ctx.storage.delete(CHAT_LAST_TERMINAL_KEY);
5686
+ }
5687
+ async _pendingChatTerminal() {
5574
5688
  return await this.ctx.storage.get(CHAT_LAST_TERMINAL_KEY) ?? null;
5575
5689
  }
5576
5690
  /**
5691
+ * Replay a pending terminal outcome (#1645) over the resume handshake so a
5692
+ * reconnecting client surfaces it exactly like a live exhaustion. A bare
5693
+ * terminal frame sent on connect is dropped by the `useAgentChat` client
5694
+ * because it never reaches a transport stream reader; only a frame delivered
5695
+ * on a resumed stream becomes `useChat.error` (this is why the terminal is
5696
+ * NOT included in `_buildIdleConnectMessages`). So we drive `STREAM_RESUMING`
5697
+ * here and send the error frame once the client ACKs (see
5698
+ * `_replayTerminalOnAck`). Returns true if a terminal was pending.
5699
+ */
5700
+ async _replayTerminalOnResume(connection) {
5701
+ const pending = await this._pendingChatTerminal();
5702
+ if (!pending) return false;
5703
+ sendIfOpen(connection, JSON.stringify({
5704
+ type: MSG_STREAM_RESUMING,
5705
+ id: pending.requestId
5706
+ }));
5707
+ return true;
5708
+ }
5709
+ /**
5710
+ * Deliver the pending terminal error frame on the resumed stream the client
5711
+ * ACKed (#1645). The record is retained (cleared only when a later turn
5712
+ * supersedes it) so concurrent reconnects each learn the outcome.
5713
+ */
5714
+ async _replayTerminalOnAck(connection, requestId) {
5715
+ const pending = await this._pendingChatTerminal();
5716
+ if (!pending || pending.requestId !== requestId) return false;
5717
+ sendIfOpen(connection, JSON.stringify({
5718
+ body: pending.body,
5719
+ done: true,
5720
+ error: true,
5721
+ id: pending.requestId,
5722
+ type: MSG_CHAT_RESPONSE
5723
+ }));
5724
+ return true;
5725
+ }
5726
+ /**
5577
5727
  * Set or clear the live "recovering…" status for a durable chat turn (#1620).
5578
5728
  * Persists a durable record (replayed on connect via `_buildIdleConnectMessages`)
5579
5729
  * and broadcasts a `MSG_CHAT_RECOVERING` frame — but only on a genuine
@@ -5603,23 +5753,21 @@ var Think = class Think extends Agent {
5603
5753
  }
5604
5754
  /**
5605
5755
  * Messages sent to a client on connect when no stream is active: the current
5606
- * transcript, plus a replay of the last terminal error (if any) so a turn
5607
- * that failed while the client was disconnected is surfaced rather than
5608
- * silently frozen.
5756
+ * transcript, plus a replay of an in-progress "recovering…" status (if any).
5757
+ *
5758
+ * A terminal error is deliberately NOT replayed here. A bare
5759
+ * `MSG_CHAT_RESPONSE` frame on connect is dropped by the `useAgentChat`
5760
+ * client because it never reaches a transport stream reader, so it cannot
5761
+ * become `useChat.error` — a failed turn would still look frozen (#1645).
5762
+ * The terminal outcome is instead surfaced over the resume handshake
5763
+ * (`_replayTerminalOnResume` → ACK → `_replayTerminalOnAck`), the only path
5764
+ * that lands on the stream reader.
5609
5765
  */
5610
5766
  async _buildIdleConnectMessages() {
5611
5767
  const messages = [{
5612
5768
  type: MSG_CHAT_MESSAGES,
5613
5769
  messages: this.messages
5614
5770
  }];
5615
- const pending = await this._pendingTerminalChatResponse();
5616
- if (pending) messages.push({
5617
- type: MSG_CHAT_RESPONSE,
5618
- id: pending.requestId,
5619
- body: pending.body,
5620
- done: true,
5621
- error: true
5622
- });
5623
5771
  const recovering = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
5624
5772
  if (recovering && Date.now() - (recovering.at ?? 0) < CHAT_RECOVERING_FLAG_TTL_MS) messages.push({
5625
5773
  type: MSG_CHAT_RECOVERING,