@cloudflare/think 0.5.3 → 0.6.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/dist/think.js CHANGED
@@ -1,6 +1,6 @@
1
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-Bvcn7kEw.js";
1
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-CCiYk1x3.js";
2
2
  import { createWorkspaceTools } from "./tools/workspace.js";
3
- import { convertToModelMessages, pruneMessages, stepCountIs, streamText } from "ai";
3
+ import { convertToModelMessages, stepCountIs, streamText } from "ai";
4
4
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
5
5
  import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, SubmitConcurrencyController, TurnQueue, applyChunkToParts, applyToolUpdate, createToolsFromClientSchemas, enforceRowSizeLimit, parseProtocolMessage, reconcileMessages, resolveToolMergeId, sanitizeMessage, toolApprovalUpdate, toolResultUpdate } from "agents/chat";
6
6
  import { Session, Session as Session$1 } from "agents/experimental/memory/session";
@@ -14,6 +14,18 @@ const MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;
14
14
  const MSG_STREAM_RESUMING = CHAT_MESSAGE_TYPES.STREAM_RESUMING;
15
15
  const MSG_STREAM_RESUME_NONE = CHAT_MESSAGE_TYPES.STREAM_RESUME_NONE;
16
16
  const MSG_MESSAGE_UPDATED = CHAT_MESSAGE_TYPES.MESSAGE_UPDATED;
17
+ function sendIfOpen(connection, message) {
18
+ try {
19
+ connection.send(message);
20
+ return true;
21
+ } catch (error) {
22
+ if (isWebSocketClosedSendError(error)) return false;
23
+ throw error;
24
+ }
25
+ }
26
+ function isWebSocketClosedSendError(error) {
27
+ return error instanceof TypeError && error.message.includes("WebSocket send() after close");
28
+ }
17
29
  const TIMED_OUT = Symbol("timed-out");
18
30
  var _configCache = /* @__PURE__ */ new WeakMap();
19
31
  var _configTableReady = /* @__PURE__ */ new WeakMap();
@@ -43,6 +55,10 @@ var Think = class Think extends Agent {
43
55
  this._agentToolLastErrors = /* @__PURE__ */ new Map();
44
56
  this._agentToolPreTurnAssistantIds = /* @__PURE__ */ new Map();
45
57
  this._agentToolLiveSequences = /* @__PURE__ */ new Map();
58
+ this._submissionTableEnsured = false;
59
+ this._drainingSubmissions = false;
60
+ this._submissionAbortControllers = /* @__PURE__ */ new Map();
61
+ this._programmaticStreamErrors = /* @__PURE__ */ new Map();
46
62
  _classPrivateFieldInitSpec(this, _configCache, null);
47
63
  _classPrivateFieldInitSpec(this, _configTableReady, false);
48
64
  this.maxSteps = 10;
@@ -63,6 +79,8 @@ var Think = class Think extends Agent {
63
79
  this._restoreBody();
64
80
  this._setupProtocolHandlers();
65
81
  await _onStart();
82
+ await this._recoverSubmissionsOnStart();
83
+ this._startSubmissionDrain();
66
84
  };
67
85
  }
68
86
  /**
@@ -375,8 +393,8 @@ var Think = class Think extends Agent {
375
393
  return error;
376
394
  }
377
395
  async _initializeExtensions() {
378
- const { ExtensionManager } = await import("./manager-DDC3Gb0V.js").then((n) => n.n);
379
- const { sanitizeName } = await import("./manager-DDC3Gb0V.js").then((n) => n.n);
396
+ const { ExtensionManager } = await import("./manager-BypfrNX0.js").then((n) => n.n);
397
+ const { sanitizeName } = await import("./manager-BypfrNX0.js").then((n) => n.n);
380
398
  const agentClassName = this.constructor.name;
381
399
  const agentId = this.ctx.id.toString();
382
400
  const ctxExports = this.ctx.exports;
@@ -432,14 +450,10 @@ var Think = class Think extends Agent {
432
450
  ...extensionTools,
433
451
  ...contextTools,
434
452
  ...this.mcp?.getAITools?.() ?? {},
435
- ...clientToolSet,
436
- ...input.callerTools
453
+ ...clientToolSet
437
454
  };
438
455
  const system = await this.session.freezeSystemPrompt() || this.getSystemPrompt();
439
- const messages = pruneMessages({
440
- messages: await convertToModelMessages(truncateOlderMessages(this.session.getHistory()), { tools }),
441
- toolCalls: "before-last-2-messages"
442
- });
456
+ const messages = await convertToModelMessages(truncateOlderMessages(this.session.getHistory()), { tools });
443
457
  if (messages.length === 0) throw new Error("No messages to send to the model. This usually means the chat request arrived before any messages were persisted.");
444
458
  const model = this.getModel();
445
459
  const ctx = {
@@ -787,73 +801,54 @@ var Think = class Think extends Agent {
787
801
  */
788
802
  async chat(userMessage, callback, options) {
789
803
  const requestId = crypto.randomUUID();
790
- await this._turnQueue.enqueue(requestId, async () => {
791
- const userMsg = typeof userMessage === "string" ? {
792
- id: crypto.randomUUID(),
793
- role: "user",
794
- parts: [{
795
- type: "text",
796
- text: userMessage
797
- }]
798
- } : userMessage;
799
- await this.session.appendMessage(userMsg);
800
- const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
801
- try {
802
- const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
803
- agent: this,
804
- connection: void 0,
805
- request: void 0,
806
- email: void 0
807
- }, () => this._runInferenceLoop({
808
- signal: options?.signal,
809
- callerTools: options?.tools,
810
- continuation: false
811
- }));
812
- this._insideInferenceLoop = true;
813
- let aborted = false;
804
+ const ignoredTools = options?.tools;
805
+ 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.");
806
+ await this.keepAliveWhile(async () => {
807
+ await this._turnQueue.enqueue(requestId, async () => {
808
+ const userMsg = typeof userMessage === "string" ? {
809
+ id: crypto.randomUUID(),
810
+ role: "user",
811
+ parts: [{
812
+ type: "text",
813
+ text: userMessage
814
+ }]
815
+ } : userMessage;
816
+ await this.session.appendMessage(userMsg);
817
+ const abortSignal = this._aborts.getSignal(requestId);
818
+ const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
814
819
  try {
815
- for await (const chunk of result.toUIMessageStream()) {
816
- if (options?.signal?.aborted) {
817
- aborted = true;
818
- break;
820
+ const chatBody = async () => {
821
+ let result;
822
+ try {
823
+ result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
824
+ agent: this,
825
+ connection: void 0,
826
+ request: void 0,
827
+ email: void 0
828
+ }, () => this._runInferenceLoop({
829
+ signal: abortSignal,
830
+ continuation: false
831
+ }));
832
+ } catch (error) {
833
+ const wrapped = this.onChatError(error);
834
+ const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
835
+ if (callback.onError) {
836
+ await callback.onError(errorMessage);
837
+ return;
838
+ }
839
+ throw wrapped;
819
840
  }
820
- accumulator.applyChunk(chunk);
821
- await callback.onEvent(JSON.stringify(chunk));
822
- }
841
+ await this._streamResultToRpcCallback(requestId, result, callback, abortSignal);
842
+ };
843
+ if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
844
+ await chatBody();
845
+ });
846
+ else await chatBody();
823
847
  } finally {
824
- this._insideInferenceLoop = false;
848
+ detachExternal();
849
+ this._aborts.remove(requestId);
825
850
  }
826
- const assistantMsg = accumulator.toMessage();
827
- this._persistAssistantMessage(assistantMsg);
828
- if (!aborted) {
829
- await callback.onDone();
830
- await this._fireResponseHook({
831
- message: assistantMsg,
832
- requestId,
833
- continuation: false,
834
- status: "completed"
835
- });
836
- } else await this._fireResponseHook({
837
- message: assistantMsg,
838
- requestId,
839
- continuation: false,
840
- status: "aborted"
841
- });
842
- } catch (error) {
843
- const assistantMsg = accumulator.parts.length > 0 ? accumulator.toMessage() : null;
844
- if (assistantMsg) this._persistAssistantMessage(assistantMsg);
845
- const wrapped = this.onChatError(error);
846
- const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
847
- if (assistantMsg) await this._fireResponseHook({
848
- message: assistantMsg,
849
- requestId,
850
- continuation: false,
851
- status: "error",
852
- error: errorMessage
853
- });
854
- if (callback.onError) await callback.onError(errorMessage);
855
- else throw wrapped;
856
- }
851
+ });
857
852
  });
858
853
  }
859
854
  /** Get the conversation history as UIMessage[]. */
@@ -862,6 +857,7 @@ var Think = class Think extends Agent {
862
857
  }
863
858
  /** Clear all messages from storage. */
864
859
  clearMessages() {
860
+ this.resetTurnState();
865
861
  this.session.clearMessages();
866
862
  }
867
863
  _ensureAgentToolChildRunTable() {
@@ -872,29 +868,39 @@ var Think = class Think extends Agent {
872
868
  stream_id TEXT,
873
869
  status TEXT NOT NULL,
874
870
  summary TEXT,
871
+ output_json TEXT,
875
872
  error_message TEXT,
876
873
  started_at INTEGER NOT NULL,
877
874
  completed_at INTEGER
878
875
  )
879
876
  `;
877
+ this._addAgentToolChildRunColumnIfMissing("ALTER TABLE cf_agent_tool_child_runs ADD COLUMN output_json TEXT");
878
+ }
879
+ _addAgentToolChildRunColumnIfMissing(sql) {
880
+ try {
881
+ this.ctx.storage.sql.exec(sql);
882
+ } catch (error) {
883
+ if (!(error instanceof Error ? error.message : String(error)).toLowerCase().includes("duplicate column")) throw error;
884
+ }
880
885
  }
881
886
  _readAgentToolChildRun(runId) {
882
887
  this._ensureAgentToolChildRunTable();
883
888
  return this.sql`
884
- SELECT run_id, request_id, stream_id, status, summary, error_message,
885
- started_at, completed_at
889
+ SELECT run_id, request_id, stream_id, status, summary, output_json,
890
+ error_message, started_at, completed_at
886
891
  FROM cf_agent_tool_child_runs
887
892
  WHERE run_id = ${runId}
888
893
  LIMIT 1
889
894
  `[0] ?? null;
890
895
  }
891
896
  _inspectionFromChildRow(row, output) {
897
+ const storedOutput = row.output_json === null ? output : Think._parseAgentToolOutput(row.output_json);
892
898
  return {
893
899
  runId: row.run_id,
894
900
  status: row.status,
895
901
  requestId: row.request_id ?? void 0,
896
902
  streamId: row.stream_id ?? void 0,
897
- output,
903
+ output: storedOutput,
898
904
  summary: row.summary ?? void 0,
899
905
  error: row.error_message ?? void 0,
900
906
  startedAt: row.started_at,
@@ -913,6 +919,17 @@ var Think = class Think extends Agent {
913
919
  };
914
920
  }
915
921
  getAgentToolOutput(_runId) {}
922
+ getAgentToolSummary(runId, output) {
923
+ const text = this._getAgentToolFinalText(runId);
924
+ if (text) return text;
925
+ if (typeof output === "string") return output;
926
+ if (output !== void 0) try {
927
+ return JSON.stringify(output);
928
+ } catch {
929
+ return String(output);
930
+ }
931
+ return "";
932
+ }
916
933
  async startAgentToolRun(input, options) {
917
934
  const existing = this._readAgentToolChildRun(options.runId);
918
935
  if (existing) return this._inspectionFromChildRow(existing);
@@ -934,16 +951,19 @@ var Think = class Think extends Agent {
934
951
  `;
935
952
  const result = await this.saveMessages([this.formatAgentToolInput(input)], { signal: controller.signal });
936
953
  const streamId = this._resumableStream.getAllStreamMetadata().find((m) => m.request_id === result.requestId)?.id ?? null;
937
- const summary = this._getAgentToolFinalText(options.runId);
954
+ const output = this.getAgentToolOutput(options.runId);
955
+ const summary = this.getAgentToolSummary(options.runId, output);
938
956
  const streamError = this._agentToolLastErrors.get(options.runId);
939
- const status = result.status === "aborted" ? "aborted" : streamError || !summary ? "error" : "completed";
940
- const error = status === "error" ? streamError ?? `${this.constructor.name} finished without producing assistant text.` : null;
957
+ const skipped = result.status === "skipped";
958
+ const status = result.status === "aborted" ? "aborted" : skipped || streamError ? "error" : "completed";
959
+ const error = status === "error" ? streamError ?? "Agent tool run was skipped before the child could finish." : null;
941
960
  this.sql`
942
961
  UPDATE cf_agent_tool_child_runs
943
962
  SET request_id = ${result.requestId},
944
963
  stream_id = ${streamId},
945
964
  status = ${status},
946
965
  summary = ${summary},
966
+ output_json = ${Think._stringifyAgentToolOutput(output)},
947
967
  error_message = ${error},
948
968
  completed_at = ${Date.now()}
949
969
  WHERE run_id = ${options.runId}
@@ -1031,6 +1051,22 @@ var Think = class Think extends Agent {
1031
1051
  }
1032
1052
  });
1033
1053
  }
1054
+ static _stringifyAgentToolOutput(output) {
1055
+ if (output === void 0) return null;
1056
+ try {
1057
+ return JSON.stringify(output);
1058
+ } catch {
1059
+ return JSON.stringify(String(output));
1060
+ }
1061
+ }
1062
+ static _parseAgentToolOutput(value) {
1063
+ if (value === null) return void 0;
1064
+ try {
1065
+ return JSON.parse(value);
1066
+ } catch {
1067
+ return;
1068
+ }
1069
+ }
1034
1070
  _getAgentToolFinalText(runId) {
1035
1071
  const before = this._agentToolPreTurnAssistantIds.get(runId);
1036
1072
  if (!before) return null;
@@ -1041,6 +1077,514 @@ var Think = class Think extends Agent {
1041
1077
  }
1042
1078
  return null;
1043
1079
  }
1080
+ _ensureSubmissionTable() {
1081
+ if (this._submissionTableEnsured) return;
1082
+ this.sql`
1083
+ CREATE TABLE IF NOT EXISTS cf_think_submissions (
1084
+ submission_id TEXT PRIMARY KEY,
1085
+ idempotency_key TEXT UNIQUE,
1086
+ request_id TEXT,
1087
+ stream_id TEXT,
1088
+ status TEXT NOT NULL,
1089
+ messages_json TEXT NOT NULL,
1090
+ metadata_json TEXT,
1091
+ error_message TEXT,
1092
+ created_at INTEGER NOT NULL,
1093
+ messages_applied_at INTEGER,
1094
+ started_at INTEGER,
1095
+ completed_at INTEGER
1096
+ )
1097
+ `;
1098
+ this.sql`
1099
+ CREATE INDEX IF NOT EXISTS cf_think_submissions_status_created_idx
1100
+ ON cf_think_submissions (status, created_at, submission_id)
1101
+ `;
1102
+ this.sql`
1103
+ CREATE INDEX IF NOT EXISTS cf_think_submissions_request_status_idx
1104
+ ON cf_think_submissions (request_id, status)
1105
+ `;
1106
+ this.sql`
1107
+ CREATE INDEX IF NOT EXISTS cf_think_submissions_status_completed_idx
1108
+ ON cf_think_submissions (status, completed_at, created_at)
1109
+ `;
1110
+ this._submissionTableEnsured = true;
1111
+ }
1112
+ _readSubmission(submissionId) {
1113
+ this._ensureSubmissionTable();
1114
+ return this.sql`
1115
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1116
+ messages_json, metadata_json, error_message, created_at,
1117
+ messages_applied_at, started_at, completed_at
1118
+ FROM cf_think_submissions
1119
+ WHERE submission_id = ${submissionId}
1120
+ LIMIT 1
1121
+ `[0] ?? null;
1122
+ }
1123
+ _readSubmissionByIdempotencyKey(idempotencyKey) {
1124
+ this._ensureSubmissionTable();
1125
+ return this.sql`
1126
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1127
+ messages_json, metadata_json, error_message, created_at,
1128
+ messages_applied_at, started_at, completed_at
1129
+ FROM cf_think_submissions
1130
+ WHERE idempotency_key = ${idempotencyKey}
1131
+ LIMIT 1
1132
+ `[0] ?? null;
1133
+ }
1134
+ _normalizeStatusFilter(status) {
1135
+ if (!status) return null;
1136
+ return new Set(Array.isArray(status) ? status : [status]);
1137
+ }
1138
+ _listSubmissionRows(options) {
1139
+ this._ensureSubmissionTable();
1140
+ const limit = Math.min(Math.max(options?.limit ?? 50, 1), 100);
1141
+ const statuses = this._normalizeStatusFilter(options?.status);
1142
+ if (statuses) return [...statuses].flatMap((status) => this._listSubmissionRowsByStatus(status, limit)).sort((a, b) => b.created_at === a.created_at ? b.submission_id.localeCompare(a.submission_id) : b.created_at - a.created_at).slice(0, limit);
1143
+ return this.sql`
1144
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1145
+ messages_json, metadata_json, error_message, created_at,
1146
+ messages_applied_at, started_at, completed_at
1147
+ FROM cf_think_submissions
1148
+ ORDER BY created_at DESC, submission_id DESC
1149
+ LIMIT ${limit}
1150
+ `;
1151
+ }
1152
+ _listSubmissionRowsByStatus(status, limit) {
1153
+ return this.sql`
1154
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1155
+ messages_json, metadata_json, error_message, created_at,
1156
+ messages_applied_at, started_at, completed_at
1157
+ FROM cf_think_submissions
1158
+ WHERE status = ${status}
1159
+ ORDER BY created_at DESC, submission_id DESC
1160
+ LIMIT ${limit}
1161
+ `;
1162
+ }
1163
+ _inspectionFromSubmissionRow(row) {
1164
+ const metadata = this._parseJsonObject(row.metadata_json);
1165
+ return {
1166
+ submissionId: row.submission_id,
1167
+ idempotencyKey: row.idempotency_key ?? void 0,
1168
+ requestId: row.request_id ?? void 0,
1169
+ status: row.status,
1170
+ error: row.error_message ?? void 0,
1171
+ metadata: metadata ?? void 0,
1172
+ createdAt: row.created_at,
1173
+ startedAt: row.started_at ?? void 0,
1174
+ completedAt: row.completed_at ?? void 0
1175
+ };
1176
+ }
1177
+ _parseJsonObject(value) {
1178
+ if (value === null) return null;
1179
+ try {
1180
+ const parsed = JSON.parse(value);
1181
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
1182
+ } catch {}
1183
+ return null;
1184
+ }
1185
+ _parseSubmissionMessages(value) {
1186
+ const parsed = JSON.parse(value);
1187
+ if (!Array.isArray(parsed)) throw new Error("Stored submission messages are invalid");
1188
+ return parsed;
1189
+ }
1190
+ _serializeSubmissionMessages(messages) {
1191
+ return JSON.stringify(messages.map((message) => enforceRowSizeLimit(sanitizeMessage(message))));
1192
+ }
1193
+ _serializeMetadata(metadata) {
1194
+ return metadata === void 0 ? null : JSON.stringify(metadata);
1195
+ }
1196
+ async _emitSubmissionStatus(row) {
1197
+ const inspection = this._inspectionFromSubmissionRow(row);
1198
+ this._emit("submission:status", {
1199
+ submissionId: inspection.submissionId,
1200
+ requestId: inspection.requestId,
1201
+ status: inspection.status
1202
+ });
1203
+ if (inspection.status === "error" && inspection.error) this._emit("submission:error", {
1204
+ submissionId: inspection.submissionId,
1205
+ requestId: inspection.requestId,
1206
+ error: inspection.error
1207
+ });
1208
+ await this.keepAliveWhile(async () => {
1209
+ try {
1210
+ await this.onSubmissionStatus(inspection);
1211
+ } catch (error) {
1212
+ console.error("[Think] onSubmissionStatus failed", error);
1213
+ }
1214
+ });
1215
+ }
1216
+ onSubmissionStatus(_submission) {}
1217
+ async inspectSubmission(submissionId) {
1218
+ const row = this._readSubmission(submissionId);
1219
+ return row ? this._inspectionFromSubmissionRow(row) : null;
1220
+ }
1221
+ async listSubmissions(options) {
1222
+ return this._listSubmissionRows(options).map((row) => this._inspectionFromSubmissionRow(row));
1223
+ }
1224
+ async deleteSubmission(submissionId) {
1225
+ const row = this._readSubmission(submissionId);
1226
+ if (!row || !this._isTerminalSubmissionStatus(row.status)) return false;
1227
+ this.sql`
1228
+ DELETE FROM cf_think_submissions
1229
+ WHERE submission_id = ${submissionId}
1230
+ AND status IN ('completed', 'aborted', 'skipped', 'error')
1231
+ `;
1232
+ return true;
1233
+ }
1234
+ async deleteSubmissions(options) {
1235
+ this._ensureSubmissionTable();
1236
+ const statuses = this._normalizeStatusFilter(options?.status) ?? new Set([
1237
+ "completed",
1238
+ "aborted",
1239
+ "skipped",
1240
+ "error"
1241
+ ]);
1242
+ const limit = Math.min(Math.max(options?.limit ?? 100, 1), 500);
1243
+ const completedBefore = options?.completedBefore?.getTime();
1244
+ const rows = [...statuses].flatMap((status) => this._listTerminalSubmissionRowsForDelete(status, limit, completedBefore)).sort((a, b) => (a.completed_at ?? a.created_at) === (b.completed_at ?? b.created_at) ? a.created_at - b.created_at : (a.completed_at ?? a.created_at) - (b.completed_at ?? b.created_at)).slice(0, limit);
1245
+ let deleted = 0;
1246
+ for (const row of rows) {
1247
+ if (!this._isTerminalSubmissionStatus(row.status)) continue;
1248
+ this.sql`
1249
+ DELETE FROM cf_think_submissions
1250
+ WHERE submission_id = ${row.submission_id}
1251
+ AND status IN ('completed', 'aborted', 'skipped', 'error')
1252
+ `;
1253
+ deleted++;
1254
+ }
1255
+ return deleted;
1256
+ }
1257
+ _listTerminalSubmissionRowsForDelete(status, limit, completedBefore) {
1258
+ if (completedBefore === void 0) return this.sql`
1259
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1260
+ messages_json, metadata_json, error_message, created_at,
1261
+ messages_applied_at, started_at, completed_at
1262
+ FROM cf_think_submissions
1263
+ WHERE status = ${status}
1264
+ ORDER BY completed_at ASC, created_at ASC
1265
+ LIMIT ${limit}
1266
+ `;
1267
+ return this.sql`
1268
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1269
+ messages_json, metadata_json, error_message, created_at,
1270
+ messages_applied_at, started_at, completed_at
1271
+ FROM cf_think_submissions
1272
+ WHERE status = ${status}
1273
+ AND completed_at IS NOT NULL
1274
+ AND completed_at < ${completedBefore}
1275
+ ORDER BY completed_at ASC, created_at ASC
1276
+ LIMIT ${limit}
1277
+ `;
1278
+ }
1279
+ _isTerminalSubmissionStatus(status) {
1280
+ return status === "completed" || status === "aborted" || status === "skipped" || status === "error";
1281
+ }
1282
+ async cancelSubmission(submissionId, reason) {
1283
+ const row = this._readSubmission(submissionId);
1284
+ if (!row || this._isTerminalSubmissionStatus(row.status)) return;
1285
+ const completedAt = Date.now();
1286
+ const errorMessage = reason === void 0 ? null : reason instanceof Error ? reason.message : String(reason);
1287
+ this._submissionAbortControllers.get(submissionId)?.abort(reason);
1288
+ if (row.request_id) this.abortRequest(row.request_id, reason);
1289
+ this.sql`
1290
+ UPDATE cf_think_submissions
1291
+ SET status = 'aborted',
1292
+ error_message = ${errorMessage},
1293
+ completed_at = ${completedAt}
1294
+ WHERE submission_id = ${submissionId}
1295
+ AND status IN ('pending', 'running')
1296
+ `;
1297
+ const updated = this._readSubmission(submissionId);
1298
+ if (updated?.status === "aborted") await this._emitSubmissionStatus(updated);
1299
+ }
1300
+ async submitMessages(messages, options) {
1301
+ this._ensureSubmissionTable();
1302
+ if (messages.length === 0) throw new Error("submitMessages requires at least one message");
1303
+ const existingById = options?.submissionId ? this._readSubmission(options.submissionId) : null;
1304
+ const existingByKey = options?.idempotencyKey ? this._readSubmissionByIdempotencyKey(options.idempotencyKey) : null;
1305
+ if (existingById && existingByKey && existingById.submission_id !== existingByKey.submission_id) throw new Error("submissionId and idempotencyKey refer to different submissions");
1306
+ if (existingByKey && options?.submissionId && existingByKey.submission_id !== options.submissionId) throw new Error("submissionId and idempotencyKey refer to different submissions");
1307
+ if (existingById && options?.idempotencyKey && existingById.idempotency_key !== null && existingById.idempotency_key !== options.idempotencyKey) throw new Error("submissionId and idempotencyKey refer to different submissions");
1308
+ const existing = existingById ?? existingByKey;
1309
+ if (existing) {
1310
+ if (existing.status === "pending") {
1311
+ await this._scheduleSubmissionDrain();
1312
+ this._startSubmissionDrain();
1313
+ }
1314
+ return {
1315
+ ...this._inspectionFromSubmissionRow(existing),
1316
+ accepted: false
1317
+ };
1318
+ }
1319
+ const submissionId = options?.submissionId ?? crypto.randomUUID();
1320
+ const requestId = submissionId;
1321
+ const now = Date.now();
1322
+ const messagesJson = this._serializeSubmissionMessages(messages);
1323
+ const metadataJson = this._serializeMetadata(options?.metadata);
1324
+ this.sql`
1325
+ INSERT INTO cf_think_submissions (
1326
+ submission_id, idempotency_key, request_id, stream_id, status,
1327
+ messages_json, metadata_json, error_message, created_at,
1328
+ messages_applied_at, started_at, completed_at
1329
+ )
1330
+ VALUES (
1331
+ ${submissionId}, ${options?.idempotencyKey ?? null}, ${requestId},
1332
+ NULL, 'pending', ${messagesJson}, ${metadataJson}, NULL, ${now},
1333
+ NULL, NULL, NULL
1334
+ )
1335
+ `;
1336
+ const row = this._readSubmission(submissionId);
1337
+ if (!row) throw new Error("Failed to persist submission");
1338
+ this._emit("submission:create", {
1339
+ submissionId: row.submission_id,
1340
+ requestId: row.request_id ?? void 0,
1341
+ idempotencyKey: row.idempotency_key ?? void 0
1342
+ });
1343
+ await this._emitSubmissionStatus(row);
1344
+ await this._scheduleSubmissionDrain();
1345
+ this._startSubmissionDrain();
1346
+ return {
1347
+ ...this._inspectionFromSubmissionRow(row),
1348
+ accepted: true
1349
+ };
1350
+ }
1351
+ async _scheduleSubmissionDrain() {
1352
+ await this.schedule(0, "_drainThinkSubmissions", void 0, { idempotent: true });
1353
+ }
1354
+ _startSubmissionDrain() {
1355
+ this.keepAliveWhile(() => this._drainSubmissions()).catch((error) => {
1356
+ console.error("[Think] Failed to drain submissions", error);
1357
+ });
1358
+ }
1359
+ async _drainThinkSubmissions() {
1360
+ await this._drainSubmissions();
1361
+ }
1362
+ async _drainSubmissions() {
1363
+ this._ensureSubmissionTable();
1364
+ if (this._drainingSubmissions) return;
1365
+ this._drainingSubmissions = true;
1366
+ try {
1367
+ while (true) {
1368
+ const row = this.sql`
1369
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1370
+ messages_json, metadata_json, error_message, created_at,
1371
+ messages_applied_at, started_at, completed_at
1372
+ FROM cf_think_submissions
1373
+ WHERE status = 'pending'
1374
+ ORDER BY created_at ASC, submission_id ASC
1375
+ LIMIT 1
1376
+ `[0];
1377
+ if (!row) break;
1378
+ await this._runSubmission(row);
1379
+ }
1380
+ } finally {
1381
+ this._drainingSubmissions = false;
1382
+ }
1383
+ }
1384
+ async _runSubmission(row) {
1385
+ const requestId = row.request_id ?? row.submission_id;
1386
+ const startedAt = Date.now();
1387
+ this.sql`
1388
+ UPDATE cf_think_submissions
1389
+ SET status = 'running',
1390
+ request_id = ${requestId},
1391
+ started_at = ${startedAt}
1392
+ WHERE submission_id = ${row.submission_id}
1393
+ AND status = 'pending'
1394
+ `;
1395
+ const claimed = this._readSubmission(row.submission_id);
1396
+ if (!claimed || claimed.status !== "running") return;
1397
+ await this._emitSubmissionStatus(claimed);
1398
+ const controller = new AbortController();
1399
+ this._submissionAbortControllers.set(row.submission_id, controller);
1400
+ try {
1401
+ const messages = this._parseSubmissionMessages(row.messages_json);
1402
+ const result = await this._runProgrammaticMessagesTurn(requestId, messages, {
1403
+ signal: controller.signal,
1404
+ captureProgrammaticStreamError: true,
1405
+ onMessagesApplied: () => {
1406
+ this.sql`
1407
+ UPDATE cf_think_submissions
1408
+ SET messages_applied_at = ${Date.now()}
1409
+ WHERE submission_id = ${row.submission_id}
1410
+ AND status = 'running'
1411
+ AND messages_applied_at IS NULL
1412
+ `;
1413
+ }
1414
+ });
1415
+ const streamId = this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === result.requestId)?.id ?? null;
1416
+ const streamError = this._programmaticStreamErrors.get(result.requestId);
1417
+ const finalStatus = this._getSubmissionFinalStatus(result.status, streamError);
1418
+ this.sql`
1419
+ UPDATE cf_think_submissions
1420
+ SET status = ${finalStatus},
1421
+ request_id = ${result.requestId},
1422
+ stream_id = ${streamId},
1423
+ error_message = ${finalStatus === "error" ? streamError ?? null : null},
1424
+ completed_at = ${Date.now()}
1425
+ WHERE submission_id = ${row.submission_id}
1426
+ AND status = 'running'
1427
+ `;
1428
+ } catch (error) {
1429
+ this.sql`
1430
+ UPDATE cf_think_submissions
1431
+ SET status = 'error',
1432
+ error_message = ${error instanceof Error ? error.message : String(error)},
1433
+ completed_at = ${Date.now()}
1434
+ WHERE submission_id = ${row.submission_id}
1435
+ AND status = 'running'
1436
+ `;
1437
+ } finally {
1438
+ this._programmaticStreamErrors.delete(requestId);
1439
+ this._submissionAbortControllers.delete(row.submission_id);
1440
+ const updated = this._readSubmission(row.submission_id);
1441
+ if (updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated);
1442
+ }
1443
+ }
1444
+ _getSubmissionFinalStatus(resultStatus, streamError) {
1445
+ return resultStatus === "completed" && streamError ? "error" : resultStatus;
1446
+ }
1447
+ _markPendingSubmissionsSkipped() {
1448
+ this._ensureSubmissionTable();
1449
+ const pending = this.sql`
1450
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1451
+ messages_json, metadata_json, error_message, created_at,
1452
+ messages_applied_at, started_at, completed_at
1453
+ FROM cf_think_submissions
1454
+ WHERE status = 'pending'
1455
+ `;
1456
+ this.sql`
1457
+ UPDATE cf_think_submissions
1458
+ SET status = 'skipped',
1459
+ error_message = 'Submission was skipped by turn reset.',
1460
+ completed_at = ${Date.now()}
1461
+ WHERE status = 'pending'
1462
+ `;
1463
+ return pending;
1464
+ }
1465
+ async _emitSkippedSubmissions(skipped) {
1466
+ for (const row of skipped) {
1467
+ const updated = this._readSubmission(row.submission_id);
1468
+ if (updated?.status === "skipped") await this._emitSubmissionStatus(updated);
1469
+ }
1470
+ }
1471
+ async _recoverSubmissionsOnStart() {
1472
+ this._ensureSubmissionTable();
1473
+ const running = this.sql`
1474
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1475
+ messages_json, metadata_json, error_message, created_at,
1476
+ messages_applied_at, started_at, completed_at
1477
+ FROM cf_think_submissions
1478
+ WHERE status = 'running'
1479
+ `;
1480
+ for (const row of running) {
1481
+ if (row.messages_applied_at === null) {
1482
+ let appliedState;
1483
+ try {
1484
+ appliedState = this._getSubmissionMessagesAppliedState(row);
1485
+ } catch (error) {
1486
+ this.sql`
1487
+ UPDATE cf_think_submissions
1488
+ SET status = 'error',
1489
+ error_message = ${error instanceof Error ? error.message : String(error)},
1490
+ completed_at = ${Date.now()}
1491
+ WHERE submission_id = ${row.submission_id}
1492
+ AND status = 'running'
1493
+ `;
1494
+ const updated = this._readSubmission(row.submission_id);
1495
+ if (updated?.status === "error") await this._emitSubmissionStatus(updated);
1496
+ continue;
1497
+ }
1498
+ if (appliedState !== "none") {
1499
+ this.sql`
1500
+ UPDATE cf_think_submissions
1501
+ SET status = 'error',
1502
+ error_message = ${appliedState === "all" ? "Submission was interrupted after messages were applied." : "Submission was interrupted after messages were partially applied."},
1503
+ completed_at = ${Date.now()}
1504
+ WHERE submission_id = ${row.submission_id}
1505
+ AND status = 'running'
1506
+ `;
1507
+ const updated = this._readSubmission(row.submission_id);
1508
+ if (updated?.status === "error") await this._emitSubmissionStatus(updated);
1509
+ continue;
1510
+ }
1511
+ this.sql`
1512
+ UPDATE cf_think_submissions
1513
+ SET status = 'pending',
1514
+ started_at = NULL
1515
+ WHERE submission_id = ${row.submission_id}
1516
+ AND status = 'running'
1517
+ `;
1518
+ const updated = this._readSubmission(row.submission_id);
1519
+ if (updated?.status === "pending") await this._emitSubmissionStatus(updated);
1520
+ continue;
1521
+ }
1522
+ if (row.request_id && (this._hasRecoverableChatTurn(row.request_id) && this._hasFreshRecoverableSubmissionEvidence(row) || this._hasScheduledRecoveredContinuation(row.request_id))) continue;
1523
+ this.sql`
1524
+ UPDATE cf_think_submissions
1525
+ SET status = 'error',
1526
+ error_message = 'Submission was interrupted after messages were applied.',
1527
+ completed_at = ${Date.now()}
1528
+ WHERE submission_id = ${row.submission_id}
1529
+ AND status = 'running'
1530
+ `;
1531
+ const updated = this._readSubmission(row.submission_id);
1532
+ if (updated?.status === "error") await this._emitSubmissionStatus(updated);
1533
+ }
1534
+ }
1535
+ _getSubmissionMessagesAppliedState(row) {
1536
+ const messages = this._parseSubmissionMessages(row.messages_json);
1537
+ if (messages.length === 0) return "all";
1538
+ let applied = 0;
1539
+ for (const message of messages) if (this.session.getMessage(message.id)) applied++;
1540
+ if (applied === 0) return "none";
1541
+ return applied === messages.length ? "all" : "partial";
1542
+ }
1543
+ _hasRecoverableChatTurn(requestId) {
1544
+ if (this.sql`
1545
+ SELECT id FROM cf_agents_runs
1546
+ WHERE name = ${this.constructor.CHAT_FIBER_NAME + ":" + requestId}
1547
+ LIMIT 1
1548
+ `.length > 0) return true;
1549
+ return this.sql`
1550
+ SELECT id FROM cf_ai_chat_stream_metadata
1551
+ WHERE request_id = ${requestId}
1552
+ AND status = 'streaming'
1553
+ LIMIT 1
1554
+ `.length > 0;
1555
+ }
1556
+ _hasFreshRecoverableSubmissionEvidence(row) {
1557
+ if (!row.request_id) return false;
1558
+ const cutoff = Date.now() - this.constructor.submissionRecoveryStaleMs;
1559
+ const fiberRows = this.sql`
1560
+ SELECT created_at FROM cf_agents_runs
1561
+ WHERE name = ${this.constructor.CHAT_FIBER_NAME + ":" + row.request_id}
1562
+ LIMIT 1
1563
+ `;
1564
+ if (fiberRows[0] && fiberRows[0].created_at >= cutoff) return true;
1565
+ const streamRows = this.sql`
1566
+ SELECT created_at FROM cf_ai_chat_stream_metadata
1567
+ WHERE request_id = ${row.request_id}
1568
+ AND status = 'streaming'
1569
+ ORDER BY created_at DESC
1570
+ LIMIT 1
1571
+ `;
1572
+ return streamRows[0] ? streamRows[0].created_at >= cutoff : false;
1573
+ }
1574
+ _hasScheduledRecoveredContinuation(requestId) {
1575
+ return this.sql`
1576
+ SELECT payload FROM cf_agents_schedules
1577
+ WHERE callback = '_chatRecoveryContinue'
1578
+ `.some((row) => {
1579
+ if (!row.payload) return false;
1580
+ try {
1581
+ const payload = JSON.parse(row.payload);
1582
+ return payload !== null && typeof payload === "object" && "recoveredRequestId" in payload && payload.recoveredRequestId === requestId;
1583
+ } catch {
1584
+ return false;
1585
+ }
1586
+ });
1587
+ }
1044
1588
  /**
1045
1589
  * Inject messages and trigger a model turn — without a WebSocket request.
1046
1590
  *
@@ -1086,6 +1630,9 @@ var Think = class Think extends Agent {
1086
1630
  */
1087
1631
  async saveMessages(messages, options) {
1088
1632
  const requestId = crypto.randomUUID();
1633
+ return this._runProgrammaticMessagesTurn(requestId, messages, options);
1634
+ }
1635
+ async _runProgrammaticMessagesTurn(requestId, messages, options) {
1089
1636
  const clientTools = this._lastClientTools;
1090
1637
  const body = this._lastBody;
1091
1638
  const epoch = this._turnQueue.generation;
@@ -1099,6 +1646,7 @@ var Think = class Think extends Agent {
1099
1646
  return;
1100
1647
  }
1101
1648
  for (const msg of resolved) await this.session.appendMessage(msg);
1649
+ options?.onMessagesApplied?.();
1102
1650
  this._broadcastMessages();
1103
1651
  if (this._turnQueue.generation !== epoch) {
1104
1652
  status = "skipped";
@@ -1119,7 +1667,7 @@ var Think = class Think extends Agent {
1119
1667
  body,
1120
1668
  continuation: false
1121
1669
  }));
1122
- if (result) await this._streamResult(requestId, result, abortSignal);
1670
+ if (result) await this._streamResult(requestId, result, abortSignal, { captureProgrammaticStreamError: options?.captureProgrammaticStreamError });
1123
1671
  };
1124
1672
  if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
1125
1673
  await programmaticBody();
@@ -1296,17 +1844,17 @@ var Think = class Think extends Agent {
1296
1844
  }
1297
1845
  }
1298
1846
  _handleStreamResumeRequest(connection) {
1299
- if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) connection.send(JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
1847
+ 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 }));
1300
1848
  else this._notifyStreamResuming(connection);
1301
1849
  else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
1302
- else connection.send(JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
1850
+ else sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
1303
1851
  }
1304
1852
  _handleStreamResumeAck(connection, requestId) {
1305
1853
  this._pendingResumeConnections.delete(connection.id);
1306
1854
  if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === requestId) {
1307
1855
  const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
1308
1856
  if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
1309
- } else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, requestId)) connection.send(JSON.stringify({
1857
+ } else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, requestId)) sendIfOpen(connection, JSON.stringify({
1310
1858
  body: "",
1311
1859
  done: true,
1312
1860
  id: requestId,
@@ -1450,6 +1998,12 @@ var Think = class Think extends Agent {
1450
1998
  resetTurnState() {
1451
1999
  this._turnQueue.reset();
1452
2000
  this._aborts.destroyAll();
2001
+ for (const controller of this._submissionAbortControllers.values()) controller.abort(/* @__PURE__ */ new Error("Turn state reset"));
2002
+ this._submissionAbortControllers.clear();
2003
+ const skippedSubmissions = this._markPendingSubmissionsSkipped();
2004
+ this.keepAliveWhile(() => this._emitSkippedSubmissions(skippedSubmissions)).catch((error) => {
2005
+ console.error("[Think] Failed to skip pending submissions", error);
2006
+ });
1453
2007
  if (this._continuationTimer) {
1454
2008
  clearTimeout(this._continuationTimer);
1455
2009
  this._continuationTimer = null;
@@ -1510,6 +2064,80 @@ var Think = class Think extends Agent {
1510
2064
  this.session.clearMessages();
1511
2065
  this._broadcast({ type: MSG_CHAT_CLEAR }, connection ? [connection.id] : void 0);
1512
2066
  }
2067
+ async _streamResultToRpcCallback(requestId, result, callback, abortSignal) {
2068
+ const streamId = this._resumableStream.start(requestId);
2069
+ const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
2070
+ let streamFinalized = false;
2071
+ let assistantMsg = null;
2072
+ let aborted = false;
2073
+ try {
2074
+ this._insideInferenceLoop = true;
2075
+ let chunksSinceFlush = 0;
2076
+ let hasFlushedContent = false;
2077
+ try {
2078
+ for await (const chunk of result.toUIMessageStream()) {
2079
+ if (abortSignal?.aborted) {
2080
+ aborted = true;
2081
+ break;
2082
+ }
2083
+ const streamChunk = chunk;
2084
+ accumulator.applyChunk(streamChunk);
2085
+ const chunkBody = JSON.stringify(chunk);
2086
+ this._resumableStream.storeChunk(streamId, chunkBody);
2087
+ chunksSinceFlush++;
2088
+ if (this._shouldFlushRpcStreamChunk(streamChunk, chunksSinceFlush, hasFlushedContent)) {
2089
+ this._resumableStream.flushBuffer();
2090
+ chunksSinceFlush = 0;
2091
+ hasFlushedContent = true;
2092
+ }
2093
+ await callback.onEvent(chunkBody);
2094
+ }
2095
+ } finally {
2096
+ this._insideInferenceLoop = false;
2097
+ }
2098
+ this._resumableStream.complete(streamId);
2099
+ streamFinalized = true;
2100
+ assistantMsg = accumulator.toMessage();
2101
+ this._persistAssistantMessage(assistantMsg);
2102
+ if (!aborted) {
2103
+ await callback.onDone();
2104
+ await this._fireResponseHook({
2105
+ message: assistantMsg,
2106
+ requestId,
2107
+ continuation: false,
2108
+ status: "completed"
2109
+ });
2110
+ } else await this._fireResponseHook({
2111
+ message: assistantMsg,
2112
+ requestId,
2113
+ continuation: false,
2114
+ status: "aborted"
2115
+ });
2116
+ } catch (error) {
2117
+ if (!streamFinalized) {
2118
+ this._resumableStream.markError(streamId);
2119
+ streamFinalized = true;
2120
+ }
2121
+ if (!assistantMsg && accumulator.parts.length > 0) {
2122
+ assistantMsg = accumulator.toMessage();
2123
+ this._persistAssistantMessage(assistantMsg);
2124
+ }
2125
+ const wrapped = this.onChatError(error);
2126
+ const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
2127
+ if (assistantMsg) await this._fireResponseHook({
2128
+ message: assistantMsg,
2129
+ requestId,
2130
+ continuation: false,
2131
+ status: "error",
2132
+ error: errorMessage
2133
+ });
2134
+ if (callback.onError) await callback.onError(errorMessage);
2135
+ else throw wrapped;
2136
+ }
2137
+ }
2138
+ _shouldFlushRpcStreamChunk(chunk, chunksSinceFlush, hasFlushedContent) {
2139
+ return (chunk.type === "text-delta" || chunk.type === "reasoning-delta" || chunk.type === "tool-input-available" || chunk.type === "tool-output-available" || chunk.type === "tool-output-error") && (!hasFlushedContent || chunksSinceFlush >= 10);
2140
+ }
1513
2141
  async _streamResult(requestId, result, abortSignal, options) {
1514
2142
  const clearGen = this._turnQueue.generation;
1515
2143
  const streamId = this._resumableStream.start(requestId);
@@ -1565,6 +2193,7 @@ var Think = class Think extends Agent {
1565
2193
  doneSent = true;
1566
2194
  } catch (error) {
1567
2195
  streamError = error instanceof Error ? error.message : "Stream error";
2196
+ if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
1568
2197
  this._resumableStream.markError(streamId);
1569
2198
  this._pendingResumeConnections.clear();
1570
2199
  if (!doneSent) {
@@ -1711,15 +2340,22 @@ var Think = class Think extends Agent {
1711
2340
  if (!ctx.name.startsWith(chatPrefix)) return false;
1712
2341
  const requestId = ctx.name.slice(chatPrefix.length);
1713
2342
  let streamId = "";
2343
+ let streamStatus;
1714
2344
  if (requestId) {
1715
2345
  const rows = this.sql`
1716
- SELECT id FROM cf_ai_chat_stream_metadata
2346
+ SELECT id, status FROM cf_ai_chat_stream_metadata
1717
2347
  WHERE request_id = ${requestId}
1718
2348
  ORDER BY created_at DESC LIMIT 1
1719
2349
  `;
1720
- if (rows.length > 0) streamId = rows[0].id;
2350
+ if (rows.length > 0) {
2351
+ streamId = rows[0].id;
2352
+ streamStatus = rows[0].status;
2353
+ }
2354
+ }
2355
+ if (!streamId && this._resumableStream.hasActiveStream()) {
2356
+ streamId = this._resumableStream.activeStreamId ?? "";
2357
+ streamStatus = "streaming";
1721
2358
  }
1722
- if (!streamId && this._resumableStream.hasActiveStream()) streamId = this._resumableStream.activeStreamId ?? "";
1723
2359
  const partial = streamId ? this._getPartialStreamText(streamId) : {
1724
2360
  text: "",
1725
2361
  parts: []
@@ -1736,27 +2372,114 @@ var Think = class Think extends Agent {
1736
2372
  createdAt: ctx.createdAt
1737
2373
  });
1738
2374
  const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
1739
- if (options.persist !== false && streamStillActive) this._persistOrphanedStream(streamId);
2375
+ const streamIsTerminal = streamStatus === "completed" || streamStatus === "error";
2376
+ if (options.persist !== false && (streamStillActive || streamIsTerminal)) this._persistOrphanedStream(streamId);
1740
2377
  if (streamStillActive) this._resumableStream.complete(streamId);
1741
- if (options.continue !== false) {
2378
+ const canContinue = options.continue !== false && !streamIsTerminal;
2379
+ const hasRunningSubmission = this._hasRunningSubmission(requestId);
2380
+ if (streamIsTerminal && hasRunningSubmission) await this._completeRecoveredSubmission(requestId, streamStatus === "completed" ? "completed" : "error", requestId, streamStatus === "completed" ? null : "Recovered chat stream had already errored.");
2381
+ const recoveredRequestId = canContinue && hasRunningSubmission ? requestId : void 0;
2382
+ if (canContinue) {
1742
2383
  const lastLeaf = this.session.getLatestLeaf();
1743
2384
  const targetId = lastLeaf?.role === "assistant" ? lastLeaf.id : void 0;
1744
- await this.schedule(0, "_chatRecoveryContinue", targetId ? { targetAssistantId: targetId } : void 0, { idempotent: true });
1745
- }
2385
+ await this.schedule(0, "_chatRecoveryContinue", {
2386
+ ...targetId ? { targetAssistantId: targetId } : {},
2387
+ ...recoveredRequestId ? { recoveredRequestId } : {}
2388
+ }, { idempotent: true });
2389
+ } else if (options.continue === false && !streamIsTerminal) await this._markRecoveredSubmissionInterrupted(requestId, "Submission was interrupted and chat recovery was disabled.");
1746
2390
  return true;
1747
2391
  }
2392
+ _hasRunningSubmission(requestId) {
2393
+ return this._readRunningSubmissionByRequestId(requestId) !== null;
2394
+ }
2395
+ _readRunningSubmissionByRequestId(requestId) {
2396
+ this._ensureSubmissionTable();
2397
+ return this.sql`
2398
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
2399
+ messages_json, metadata_json, error_message, created_at,
2400
+ messages_applied_at, started_at, completed_at
2401
+ FROM cf_think_submissions
2402
+ WHERE request_id = ${requestId}
2403
+ AND status = 'running'
2404
+ LIMIT 1
2405
+ `[0] ?? null;
2406
+ }
2407
+ async _markRecoveredSubmissionInterrupted(requestId, message) {
2408
+ this._ensureSubmissionTable();
2409
+ const row = this.sql`
2410
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
2411
+ messages_json, metadata_json, error_message, created_at,
2412
+ messages_applied_at, started_at, completed_at
2413
+ FROM cf_think_submissions
2414
+ WHERE request_id = ${requestId}
2415
+ AND status = 'running'
2416
+ LIMIT 1
2417
+ `[0];
2418
+ if (!row) return;
2419
+ this.sql`
2420
+ UPDATE cf_think_submissions
2421
+ SET status = 'error',
2422
+ error_message = ${message},
2423
+ completed_at = ${Date.now()}
2424
+ WHERE submission_id = ${row.submission_id}
2425
+ AND status = 'running'
2426
+ `;
2427
+ const updated = this._readSubmission(row.submission_id);
2428
+ if (updated) await this._emitSubmissionStatus(updated);
2429
+ }
2430
+ async _completeRecoveredSubmission(originalRequestId, status, requestId, errorMessage) {
2431
+ this._ensureSubmissionTable();
2432
+ const completedAt = Date.now();
2433
+ const streamId = requestId ? this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === requestId)?.id ?? null : null;
2434
+ this.sql`
2435
+ UPDATE cf_think_submissions
2436
+ SET status = ${status},
2437
+ request_id = COALESCE(${requestId}, request_id),
2438
+ stream_id = COALESCE(${streamId}, stream_id),
2439
+ error_message = ${errorMessage},
2440
+ completed_at = ${completedAt}
2441
+ WHERE request_id = ${originalRequestId}
2442
+ AND status = 'running'
2443
+ `;
2444
+ const updated = this.sql`
2445
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
2446
+ messages_json, metadata_json, error_message, created_at,
2447
+ messages_applied_at, started_at, completed_at
2448
+ FROM cf_think_submissions
2449
+ WHERE request_id = COALESCE(${requestId}, ${originalRequestId})
2450
+ ORDER BY completed_at DESC
2451
+ LIMIT 1
2452
+ `[0];
2453
+ if (updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated);
2454
+ }
1748
2455
  async onChatRecovery(_ctx) {
1749
2456
  return {};
1750
2457
  }
1751
2458
  async _chatRecoveryContinue(data) {
1752
- if (!await this.waitUntilStable({ timeout: 1e4 })) {
1753
- console.warn("[Think] _chatRecoveryContinue timed out waiting for stable state, skipping continuation");
1754
- return;
2459
+ const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
2460
+ if (data?.recoveredRequestId && !recoveredSubmission) return;
2461
+ const controller = recoveredSubmission ? new AbortController() : null;
2462
+ if (recoveredSubmission && controller) this._submissionAbortControllers.set(recoveredSubmission.submission_id, controller);
2463
+ try {
2464
+ if (!await this.waitUntilStable({ timeout: 1e4 })) {
2465
+ console.warn("[Think] _chatRecoveryContinue timed out waiting for stable state, skipping continuation");
2466
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat continuation timed out waiting for stable state.");
2467
+ return;
2468
+ }
2469
+ const targetId = data?.targetAssistantId;
2470
+ const lastLeaf = this.session.getLatestLeaf();
2471
+ if (targetId && lastLeaf?.id !== targetId) {
2472
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat continuation was skipped because the conversation changed.");
2473
+ return;
2474
+ }
2475
+ const result = await this.continueLastTurn(void 0, controller ? { signal: controller.signal } : void 0);
2476
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : `Recovery ${result.status}.`);
2477
+ } catch (error) {
2478
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, error instanceof Error ? error.message : String(error));
2479
+ throw error;
2480
+ } finally {
2481
+ if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
1755
2482
  }
1756
- const targetId = data?.targetAssistantId;
1757
- const lastLeaf = this.session.getLatestLeaf();
1758
- if (targetId && lastLeaf?.id !== targetId) return;
1759
- await this.continueLastTurn();
1760
2483
  }
1761
2484
  _getPartialStreamText(streamId) {
1762
2485
  const chunks = this._resumableStream.getStreamChunks(streamId);
@@ -1888,11 +2611,10 @@ var Think = class Think extends Agent {
1888
2611
  }
1889
2612
  _notifyStreamResuming(connection) {
1890
2613
  if (!this._resumableStream.hasActiveStream()) return;
1891
- this._pendingResumeConnections.add(connection.id);
1892
- connection.send(JSON.stringify({
2614
+ if (sendIfOpen(connection, JSON.stringify({
1893
2615
  type: MSG_STREAM_RESUMING,
1894
2616
  id: this._resumableStream.activeRequestId
1895
- }));
2617
+ }))) this._pendingResumeConnections.add(connection.id);
1896
2618
  }
1897
2619
  _persistOrphanedStream(streamId) {
1898
2620
  this._resumableStream.flushBuffer();
@@ -1928,6 +2650,7 @@ Think.CONFIG_KEYS = [
1928
2650
  ];
1929
2651
  Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
1930
2652
  Think.MESSAGE_DEBOUNCE_MS = 750;
2653
+ Think.submissionRecoveryStaleMs = 900 * 1e3;
1931
2654
  //#endregion
1932
2655
  export { Session, Think, Workspace };
1933
2656