@cloudflare/ai-chat 0.8.0 → 0.8.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/dist/index.js CHANGED
@@ -7,15 +7,16 @@ import { nanoid } from "nanoid";
7
7
  const CHAT_RECOVERY_INCIDENT_KEY_PREFIX = "cf:chat-recovery:incident:";
8
8
  const CHAT_RECOVERY_PROGRESS_KEY = "cf:chat-recovery:progress";
9
9
  const DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS = 10;
10
+ const DEFAULT_CHAT_RECOVERY_MAX_WORK = Number.POSITIVE_INFINITY;
10
11
  const DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS = 1e4;
11
12
  const AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS = 6e4;
12
13
  const CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;
13
14
  const DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE = "The assistant was interrupted and could not recover. Please try again.";
14
15
  const CHAT_RECOVERING_KEY = "cf:chat:recovering";
15
16
  const CHAT_RECOVERY_INCIDENT_TTL_MS = 3600 * 1e3;
16
- const CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS = 300 * 1e3;
17
+ const DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS = 300 * 1e3;
17
18
  const CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1e3;
18
- const CHAT_RECOVERY_MAX_WINDOW_MS = 900 * 1e3;
19
+ const CHAT_RECOVERING_FLAG_TTL_MS = 900 * 1e3;
19
20
  const AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5e3;
20
21
  function sendIfOpen(connection, message) {
21
22
  try {
@@ -117,6 +118,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
117
118
  this._pendingChatResponseResults = [];
118
119
  this._insideResponseHook = false;
119
120
  this._pendingInteractionPromise = null;
121
+ this._interactionApplyTail = Promise.resolve();
120
122
  this._approvalPersistedMessageId = null;
121
123
  this._turnQueue = new TurnQueue();
122
124
  this.chatRecovery = false;
@@ -340,11 +342,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
340
342
  toolCallId,
341
343
  toolName
342
344
  });
343
- const applyPromise = this._applyToolResult(toolCallId, toolName, output, overrideState, errorText);
344
- this._pendingInteractionPromise = applyPromise;
345
- applyPromise.finally(() => {
346
- if (this._pendingInteractionPromise === applyPromise) this._pendingInteractionPromise = null;
347
- }).catch(() => {});
345
+ const applyPromise = this._enqueueInteractionApply(() => this._applyToolResult(toolCallId, toolName, output, overrideState, errorText));
348
346
  if (autoContinue) this._enqueueAutoContinuation(connection, clientTools ?? this._lastClientTools, this._lastBody, "[AIChatAgent] Tool continuation failed:", applyPromise);
349
347
  return;
350
348
  }
@@ -354,11 +352,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
354
352
  toolCallId,
355
353
  approved
356
354
  });
357
- const approvalPromise = this._applyToolApproval(toolCallId, approved);
358
- this._pendingInteractionPromise = approvalPromise;
359
- approvalPromise.finally(() => {
360
- if (this._pendingInteractionPromise === approvalPromise) this._pendingInteractionPromise = null;
361
- }).catch(() => {});
355
+ const approvalPromise = this._enqueueInteractionApply(() => this._applyToolApproval(toolCallId, approved));
362
356
  if (autoContinue) this._enqueueAutoContinuation(connection, this._lastClientTools, this._lastBody, "[AIChatAgent] Tool approval continuation failed:", approvalPromise);
363
357
  return;
364
358
  }
@@ -808,6 +802,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
808
802
  this._abortRegistry.destroyAll();
809
803
  this._submitConcurrency.reset();
810
804
  this._pendingInteractionPromise = null;
805
+ this._interactionApplyTail = Promise.resolve();
811
806
  this._continuation.sendResumeNone();
812
807
  this._continuation.clearAll();
813
808
  this._pendingChatResponseResults.length = 0;
@@ -841,8 +836,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
841
836
  * concurrency state — use {@link resetTurnState} for the full
842
837
  * teardown that runs on `chat-clear`.
843
838
  */
844
- abortAllRequests() {
845
- this._abortRegistry.destroyAll();
839
+ abortAllRequests(reason) {
840
+ this._abortRegistry.destroyAll(reason);
846
841
  }
847
842
  async _awaitWithDeadline(promise, deadline) {
848
843
  if (deadline == null) return promise;
@@ -858,6 +853,61 @@ var AIChatAgent = class AIChatAgent extends Agent {
858
853
  return message.parts.some((part) => "state" in part && (part.state === "input-available" || part.state === "approval-requested"));
859
854
  }
860
855
  /**
856
+ * `true` when the turn is parked on a pending interaction that the CLIENT can
857
+ * still resolve after a restart — an `approval-requested` part, or an
858
+ * `input-available` part for a CLIENT tool (no server `execute`) whose
859
+ * `tool-result` the SPA replays over the WebSocket on reconnect.
860
+ *
861
+ * This is intentionally NARROWER than `hasPendingInteraction()` (which
862
+ * `waitUntilStable` uses): a SERVER tool's `input-available` orphan is
863
+ * excluded, because its `execute()` promise died with the evicted isolate and
864
+ * nothing will ever post its result — so it must NOT be treated as a healthy
865
+ * "waiting on the human" wait. Used to make a HITL turn budget-free during
866
+ * recovery so a slow human can't trip the no-progress / attempt / stable-
867
+ * timeout budgets; see `_beginChatRecoveryIncident` and
868
+ * `_parkRecoveryForPendingInteraction`. Mirrors `@cloudflare/think`'s
869
+ * `hasPendingInteraction`, which is already client-only by construction.
870
+ */
871
+ hasPendingClientInteraction() {
872
+ const clientResolvable = this._clientResolvableToolNames();
873
+ if (this._streamingMessage && this._messageAwaitsClientInteraction(this._streamingMessage, clientResolvable)) return true;
874
+ return this.messages.some((message) => message.role === "assistant" && this._messageAwaitsClientInteraction(message, clientResolvable));
875
+ }
876
+ _messageAwaitsClientInteraction(message, clientResolvable) {
877
+ return message.parts.some((part) => this._partAwaitsClientInteraction(part, clientResolvable));
878
+ }
879
+ /**
880
+ * Whether a part is still awaiting a CLIENT interaction that can genuinely
881
+ * arrive after a restart: an `approval-requested` part (a reconnecting client
882
+ * replays the approval) or an `input-available` part for a CLIENT tool (the
883
+ * SPA replays the `tool-result`). A SERVER tool's `input-available` is NOT
884
+ * pending — its `execute()` died with the isolate. Mirrors `@cloudflare/think`.
885
+ */
886
+ _partAwaitsClientInteraction(part, clientResolvable) {
887
+ if (!("state" in part)) return false;
888
+ const record = part;
889
+ const state = record.state;
890
+ if (state === "approval-requested") return true;
891
+ if (state !== "input-available") return false;
892
+ const toolName = this._toolPartName(record);
893
+ return toolName != null && clientResolvable.has(toolName);
894
+ }
895
+ /** Extract a tool part's name from its `tool-<name>` / `dynamic-tool` shape. */
896
+ _toolPartName(record) {
897
+ const type = typeof record.type === "string" ? record.type : "";
898
+ if (type === "dynamic-tool") return typeof record.toolName === "string" ? record.toolName : void 0;
899
+ if (type.startsWith("tool-")) return type.slice(5);
900
+ }
901
+ /**
902
+ * Names of the CLIENT-resolvable tools (the client-provided schemas from the
903
+ * last request, which have no server `execute`). Mirrors `@cloudflare/think`.
904
+ */
905
+ _clientResolvableToolNames() {
906
+ const names = /* @__PURE__ */ new Set();
907
+ for (const tool of this._lastClientTools ?? []) if (tool?.name) names.add(tool.name);
908
+ return names;
909
+ }
910
+ /**
861
911
  * Run a chat turn exclusively so `_reply()` never overlaps with another
862
912
  * streaming turn.
863
913
  */
@@ -1319,6 +1369,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1319
1369
  }
1320
1370
  async cancelAgentToolRun(runId, reason) {
1321
1371
  this._agentToolAbortControllers.get(runId)?.abort(reason);
1372
+ this.abortAllRequests(reason);
1322
1373
  this.sql`
1323
1374
  update cf_ai_chat_agent_tool_runs
1324
1375
  set status = 'aborted', completed_at = coalesce(completed_at, ${Date.now()})
@@ -1397,6 +1448,40 @@ var AIChatAgent = class AIChatAgent extends Agent {
1397
1448
  this._closeAgentToolTailers(runId);
1398
1449
  }
1399
1450
  }
1451
+ /**
1452
+ * Eagerly terminalize this child facet's OWN agent-tool run row(s) once a
1453
+ * recovered turn has settled. A recovered turn re-runs via either
1454
+ * `_chatRecoveryContinue` → `continueLastTurn` or, for a pre-stream eviction,
1455
+ * `_chatRecoveryRetry` → `_retryLastUserTurn` — neither flows through
1456
+ * `startAgentToolRun`'s finalizer, so without this the row strands `running`
1457
+ * and its tailers stay open until a parent inspect lazily reconciles it —
1458
+ * forcing a re-attached parent to wait out a full no-progress window before
1459
+ * collecting an already-finished result (#1630 follow-up). Reconciling here
1460
+ * closes the tail promptly so the parent collects the terminal immediately.
1461
+ * No-op on non-child facets (their `cf_ai_chat_agent_tool_runs` table is
1462
+ * empty) and on rows whose in-memory run is still live; the underlying
1463
+ * reconcile leaves a row `running` while its recovery is still in progress.
1464
+ * Mirrors `@cloudflare/think`.
1465
+ */
1466
+ async _reconcileOwnStaleAgentToolChildRuns() {
1467
+ let rows;
1468
+ try {
1469
+ rows = this.sql`
1470
+ select run_id from cf_ai_chat_agent_tool_runs
1471
+ where status = 'running'
1472
+ `;
1473
+ } catch {
1474
+ return;
1475
+ }
1476
+ for (const { run_id } of rows) {
1477
+ if (this._agentToolAbortControllers.has(run_id)) continue;
1478
+ const row = this._getAgentToolRunRow(run_id);
1479
+ if (!row || row.status !== "running") continue;
1480
+ try {
1481
+ await this._reconcileStaleAgentToolChildRun(run_id, row);
1482
+ } catch {}
1483
+ }
1484
+ }
1400
1485
  async inspectAgentToolRun(runId) {
1401
1486
  const row = this._getAgentToolRunRow(runId);
1402
1487
  if (!row) return null;
@@ -1708,6 +1793,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1708
1793
  maxAttempts: Math.max(1, Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)),
1709
1794
  stableTimeoutMs: Math.max(0, Math.floor(custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS)),
1710
1795
  terminalMessage: custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,
1796
+ noProgressTimeoutMs: Math.max(0, Math.floor(custom?.noProgressTimeoutMs ?? DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS)),
1797
+ maxRecoveryWork: typeof custom?.maxRecoveryWork === "number" && custom.maxRecoveryWork >= 0 ? custom.maxRecoveryWork : DEFAULT_CHAT_RECOVERY_MAX_WORK,
1798
+ ...custom?.shouldKeepRecovering ? { shouldKeepRecovering: custom.shouldKeepRecovering } : {},
1711
1799
  ...custom?.onExhausted ? { onExhausted: custom.onExhausted } : {}
1712
1800
  };
1713
1801
  }
@@ -1788,12 +1876,31 @@ var AIChatAgent = class AIChatAgent extends Agent {
1788
1876
  const prevProgress = existing?.progress ?? 0;
1789
1877
  const currentProgress = await this._chatRecoveryProgressMarker();
1790
1878
  const madeProgress = existing != null && currentProgress > prevProgress;
1791
- const lastProgressAt = madeProgress ? now : existing?.lastProgressAt ?? existing?.firstSeenAt ?? now;
1792
- const noProgressExceeded = existing != null && now - lastProgressAt > CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS;
1793
- const incidentAgeExceeded = existing != null && now - existing.firstSeenAt > CHAT_RECOVERY_MAX_WINDOW_MS;
1879
+ const awaitingClientInteraction = this.hasPendingClientInteraction();
1880
+ const lastProgressAt = madeProgress || awaitingClientInteraction ? now : existing?.lastProgressAt ?? existing?.firstSeenAt ?? now;
1881
+ const noProgressExceeded = existing != null && !awaitingClientInteraction && now - lastProgressAt > config.noProgressTimeoutMs;
1882
+ const workBaseline = existing?.workBaseline ?? currentProgress;
1883
+ const progress = Math.max(prevProgress, currentProgress);
1884
+ const work = progress - workBaseline;
1885
+ const workBudgetExceeded = existing != null && Number.isFinite(config.maxRecoveryWork) && work > config.maxRecoveryWork;
1794
1886
  const debounced = existing != null && !madeProgress && now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;
1795
1887
  const attempt = madeProgress ? 1 : debounced ? existing?.attempt ?? 1 : (existing?.attempt ?? 0) + 1;
1796
- const exhausted = noProgressExceeded || incidentAgeExceeded || attempt > config.maxAttempts;
1888
+ let abortedByCaller = false;
1889
+ if (existing != null && !awaitingClientInteraction && config.shouldKeepRecovering && !noProgressExceeded && !workBudgetExceeded && attempt <= config.maxAttempts) try {
1890
+ abortedByCaller = await config.shouldKeepRecovering({
1891
+ incidentId,
1892
+ requestId: input.requestId,
1893
+ recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,
1894
+ attempt,
1895
+ maxAttempts: config.maxAttempts,
1896
+ recoveryKind: input.recoveryKind,
1897
+ work,
1898
+ ageMs: now - (existing.firstSeenAt ?? now)
1899
+ }) === false;
1900
+ } catch (error) {
1901
+ console.error("[AIChatAgent] chatRecovery shouldKeepRecovering hook threw", error);
1902
+ }
1903
+ const exhausted = !awaitingClientInteraction && (noProgressExceeded || workBudgetExceeded || abortedByCaller || attempt > config.maxAttempts);
1797
1904
  const incident = {
1798
1905
  incidentId,
1799
1906
  requestId: input.requestId,
@@ -1805,8 +1912,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1805
1912
  firstSeenAt: existing?.firstSeenAt ?? now,
1806
1913
  lastAttemptAt: now,
1807
1914
  lastProgressAt,
1808
- progress: Math.max(prevProgress, currentProgress),
1809
- ...exhausted ? { reason: incidentAgeExceeded ? "max_recovery_window_exceeded" : noProgressExceeded ? "no_progress_timeout" : "max_attempts_exceeded" } : {}
1915
+ progress,
1916
+ workBaseline,
1917
+ ...exhausted ? { reason: workBudgetExceeded ? "work_budget_exceeded" : noProgressExceeded ? "no_progress_timeout" : abortedByCaller ? "recovery_aborted" : "max_attempts_exceeded" } : {}
1810
1918
  };
1811
1919
  await this.ctx.storage.put(key, incident);
1812
1920
  if (!existing) this._emit("chat:recovery:detected", {
@@ -1894,7 +2002,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1894
2002
  */
1895
2003
  async _setChatRecovering(active, requestId) {
1896
2004
  const existing = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
1897
- const activeExisting = existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS;
2005
+ const activeExisting = existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERING_FLAG_TTL_MS;
1898
2006
  if (active) {
1899
2007
  if (activeExisting) return;
1900
2008
  await this.ctx.storage.put(CHAT_RECOVERING_KEY, {
@@ -2030,6 +2138,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2030
2138
  try {
2031
2139
  const recoveryConfig = this._resolveChatRecoveryConfig();
2032
2140
  if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
2141
+ if (await this._parkRecoveryForPendingInteraction(data)) return;
2033
2142
  console.warn("[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state");
2034
2143
  if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryContinue", data, recoveryConfig.maxAttempts)) return;
2035
2144
  await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryContinue", data);
@@ -2045,6 +2154,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2045
2154
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2046
2155
  } finally {
2047
2156
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
2157
+ await this._reconcileOwnStaleAgentToolChildRuns();
2048
2158
  }
2049
2159
  }
2050
2160
  _applyRecoveredRequestContext(data) {
@@ -2075,6 +2185,37 @@ var AIChatAgent = class AIChatAgent extends Agent {
2075
2185
  return true;
2076
2186
  }
2077
2187
  /**
2188
+ * Park a recovery continuation that timed out waiting for stable state
2189
+ * because the turn is holding a pending CLIENT interaction (an
2190
+ * `input-available` client-tool part or an `approval-requested` part — see
2191
+ * `hasPendingClientInteraction`). Such a turn is WAITING ON THE HUMAN, not
2192
+ * stuck: the client replays the interrupted tool-result / approval after
2193
+ * reconnect, which drives a fresh continuation independently of the recovery
2194
+ * retry loop. Burning the attempt budget on that wait (each `waitUntilStable`
2195
+ * times out because the human hasn't answered) would seal a perfectly healthy
2196
+ * turn on `stable_timeout` — the symptom behind HITL "session recovery errors"
2197
+ * under deploy churn.
2198
+ *
2199
+ * So instead of rescheduling or exhausting, we stop the loop and mark the
2200
+ * incident `skipped` (reason `awaiting_client_interaction`). That retains the
2201
+ * incident record (a later genuine interruption re-evaluates it) while
2202
+ * resolving the live "recovering…" indicator via `_updateChatRecoveryIncident`
2203
+ * so the client sees the parked tool-call UI rather than an eternal spinner.
2204
+ * A client that never returns is reclaimed by the incident TTL sweep and DO
2205
+ * idle-eviction. SERVER-tool orphans are excluded by `hasPendingClientInteraction`
2206
+ * (their `execute` died with the isolate), so they still reschedule / exhaust
2207
+ * via the normal path. Mirrors the same helper in `@cloudflare/think`.
2208
+ *
2209
+ * Returns `true` when the recovery was parked (caller must return), `false`
2210
+ * when there is no pending client interaction (caller proceeds to the normal
2211
+ * reschedule / exhaustion path).
2212
+ */
2213
+ async _parkRecoveryForPendingInteraction(data) {
2214
+ if (!this.hasPendingClientInteraction()) return false;
2215
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "awaiting_client_interaction");
2216
+ return true;
2217
+ }
2218
+ /**
2078
2219
  * Resolve the stream id for a recovery turn so the give-up terminalization
2079
2220
  * can surface whatever partial the turn produced. Prefers the durable stream
2080
2221
  * row keyed by the recovery-root request id; falls back to the live active
@@ -2157,6 +2298,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2157
2298
  try {
2158
2299
  const recoveryConfig = this._resolveChatRecoveryConfig();
2159
2300
  if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
2301
+ if (await this._parkRecoveryForPendingInteraction(data)) return;
2160
2302
  console.warn("[AIChatAgent] _chatRecoveryRetry timed out waiting for stable state");
2161
2303
  if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryRetry", data, recoveryConfig.maxAttempts)) return;
2162
2304
  await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryRetry", data);
@@ -2176,6 +2318,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2176
2318
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2177
2319
  } finally {
2178
2320
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
2321
+ await this._reconcileOwnStaleAgentToolChildRuns();
2179
2322
  }
2180
2323
  }
2181
2324
  /**
@@ -2569,6 +2712,32 @@ var AIChatAgent = class AIChatAgent extends Agent {
2569
2712
  return false;
2570
2713
  }
2571
2714
  /**
2715
+ * Serialize a client-tool result/approval apply behind any in-flight apply
2716
+ * (#1649, defensive). Each apply is a read-modify-write of the message and
2717
+ * parallel tool results arrive as independent WebSocket messages. Today
2718
+ * `_findAndUpdateToolPart` performs that read-modify-write synchronously (no
2719
+ * await between reading `this.messages` and the SQLite write), so concurrent
2720
+ * applies can't actually interleave — unlike Think, ai-chat does not exhibit
2721
+ * the #1649 clobber. This queue is a guard so the invariant survives if the
2722
+ * apply ever gains an await between read and write (e.g. async storage): each
2723
+ * apply commits atomically in arrival order.
2724
+ *
2725
+ * `_pendingInteractionPromise` is set to the newest link so the barrier's
2726
+ * single-slot wake-up observes the latest apply; because the chain is serial,
2727
+ * awaiting it transitively waits for every predecessor.
2728
+ *
2729
+ * @internal
2730
+ */
2731
+ _enqueueInteractionApply(apply) {
2732
+ const resultPromise = this._interactionApplyTail.then(apply, apply);
2733
+ this._interactionApplyTail = resultPromise.then(() => void 0, () => void 0);
2734
+ this._pendingInteractionPromise = resultPromise;
2735
+ resultPromise.finally(() => {
2736
+ if (this._pendingInteractionPromise === resultPromise) this._pendingInteractionPromise = null;
2737
+ }).catch(() => {});
2738
+ return resultPromise;
2739
+ }
2740
+ /**
2572
2741
  * Applies a tool result to an existing assistant message.
2573
2742
  * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
2574
2743
  * The server is the source of truth, so we update the message here and broadcast