@cloudflare/think 0.5.3 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
  /**
@@ -187,12 +205,53 @@ var Think = class Think extends Agent {
187
205
  * Used as fallback when no context blocks are configured via `configureSession`.
188
206
  */
189
207
  getSystemPrompt() {
190
- return "You are a helpful assistant.";
208
+ return [
209
+ "You are a careful, capable assistant helping the user complete their task.",
210
+ "Use available tools when they materially improve accuracy or let you act on the user's request. Before changing code, understand the relevant context: existing patterns, dependencies, tests, and nearby conventions.",
211
+ "Keep changes focused on the user's request. Prefer small, idiomatic edits over broad rewrites or new abstractions. Do not introduce new dependencies, secrets, destructive actions, or persistent side effects unless the user clearly asks or approves.",
212
+ "When the task is complex, briefly state your approach and keep the user informed with concise progress updates. If you modify code, verify with the smallest relevant test, build, typecheck, lint, or runtime check available, and report any checks you could not run.",
213
+ "Be direct and useful in your final response: summarize the outcome, mention important files or commands, and call out real blockers or risks."
214
+ ].join("\n\n");
191
215
  }
192
216
  /** Return the tools available to the assistant. */
193
217
  getTools() {
194
218
  return {};
195
219
  }
220
+ _systemPromptForTurn(baseSystem, tools) {
221
+ if (baseSystem.includes("You are running inside a Think agent.")) return baseSystem;
222
+ return `${baseSystem.trimEnd()}\n\n${this._buildThinkCapabilityBlock(tools)}`;
223
+ }
224
+ _buildThinkCapabilityBlock(tools) {
225
+ const toolNames = new Set(Object.keys(tools));
226
+ const hasTools = toolNames.size > 0;
227
+ const hasWorkspaceTools = [
228
+ "read",
229
+ "write",
230
+ "edit",
231
+ "list",
232
+ "find",
233
+ "grep",
234
+ "delete"
235
+ ].some((toolName) => toolNames.has(toolName));
236
+ const hasContextTools = toolNames.has("load_context") || toolNames.has("unload_context");
237
+ const hasExtensionTools = toolNames.has("load_extension") || toolNames.has("list_extensions");
238
+ const hasExecuteTool = toolNames.has("execute");
239
+ const lines = [
240
+ "You are running inside a Think agent.",
241
+ "",
242
+ "Capabilities available in this turn:"
243
+ ];
244
+ if (hasWorkspaceTools) lines.push("- You can inspect and edit the agent workspace using the available file tools.");
245
+ if (hasTools) {
246
+ lines.push("- Use the tools exposed in this turn when they materially improve accuracy or let you act on the user's request. Treat tool descriptions and schemas as the source of truth.");
247
+ lines.push("- Some tools may call server code, browser/client code, MCP servers, extensions, or delegated agents. Use them according to their descriptions.");
248
+ }
249
+ if (hasContextTools) lines.push("- If context-loading tools are available, use them to load relevant memory, skills, or project context before acting on incomplete information.");
250
+ if (hasExtensionTools) lines.push("- If extension tools are available, use them only when loading or inspecting extensions directly helps with the task.");
251
+ if (hasExecuteTool) lines.push("- If sandboxed execution is available, prefer it for safe, bounded checks or coordinated multi-step operations.");
252
+ lines.push("- Do not claim access to capabilities that are not exposed as tools in this turn.");
253
+ return lines.join("\n");
254
+ }
196
255
  /**
197
256
  * Configure the session. Called once during `onStart`.
198
257
  * Override to add context blocks, compaction, search, skills.
@@ -375,8 +434,8 @@ var Think = class Think extends Agent {
375
434
  return error;
376
435
  }
377
436
  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);
437
+ const { ExtensionManager } = await import("./manager-BypfrNX0.js").then((n) => n.n);
438
+ const { sanitizeName } = await import("./manager-BypfrNX0.js").then((n) => n.n);
380
439
  const agentClassName = this.constructor.name;
381
440
  const agentId = this.ctx.id.toString();
382
441
  const ctxExports = this.ctx.exports;
@@ -432,14 +491,11 @@ var Think = class Think extends Agent {
432
491
  ...extensionTools,
433
492
  ...contextTools,
434
493
  ...this.mcp?.getAITools?.() ?? {},
435
- ...clientToolSet,
436
- ...input.callerTools
494
+ ...clientToolSet
437
495
  };
438
- 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
- });
496
+ const baseSystem = await this.session.freezeSystemPrompt() || this.getSystemPrompt();
497
+ const system = this._systemPromptForTurn(baseSystem, tools);
498
+ const messages = await convertToModelMessages(truncateOlderMessages(this.session.getHistory()), { tools });
443
499
  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
500
  const model = this.getModel();
445
501
  const ctx = {
@@ -453,7 +509,10 @@ var Think = class Think extends Agent {
453
509
  const subclassConfig = await this.beforeTurn(ctx) ?? {};
454
510
  const config = await this._pipelineExtensionBeforeTurn(ctx, subclassConfig);
455
511
  const finalModel = config.model ?? model;
456
- const finalSystem = config.system ?? system;
512
+ const finalSystem = config.system ?? this._systemPromptForTurn(baseSystem, config.tools ? {
513
+ ...tools,
514
+ ...config.tools
515
+ } : tools);
457
516
  const finalMessages = config.messages ?? messages;
458
517
  const mergedTools = config.tools ? {
459
518
  ...tools,
@@ -787,73 +846,54 @@ var Think = class Think extends Agent {
787
846
  */
788
847
  async chat(userMessage, callback, options) {
789
848
  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;
849
+ const ignoredTools = options?.tools;
850
+ 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.");
851
+ await this.keepAliveWhile(async () => {
852
+ await this._turnQueue.enqueue(requestId, async () => {
853
+ const userMsg = typeof userMessage === "string" ? {
854
+ id: crypto.randomUUID(),
855
+ role: "user",
856
+ parts: [{
857
+ type: "text",
858
+ text: userMessage
859
+ }]
860
+ } : userMessage;
861
+ await this.session.appendMessage(userMsg);
862
+ const abortSignal = this._aborts.getSignal(requestId);
863
+ const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
814
864
  try {
815
- for await (const chunk of result.toUIMessageStream()) {
816
- if (options?.signal?.aborted) {
817
- aborted = true;
818
- break;
865
+ const chatBody = async () => {
866
+ let result;
867
+ try {
868
+ result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
869
+ agent: this,
870
+ connection: void 0,
871
+ request: void 0,
872
+ email: void 0
873
+ }, () => this._runInferenceLoop({
874
+ signal: abortSignal,
875
+ continuation: false
876
+ }));
877
+ } catch (error) {
878
+ const wrapped = this.onChatError(error);
879
+ const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
880
+ if (callback.onError) {
881
+ await callback.onError(errorMessage);
882
+ return;
883
+ }
884
+ throw wrapped;
819
885
  }
820
- accumulator.applyChunk(chunk);
821
- await callback.onEvent(JSON.stringify(chunk));
822
- }
886
+ await this._streamResultToRpcCallback(requestId, result, callback, abortSignal);
887
+ };
888
+ if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
889
+ await chatBody();
890
+ });
891
+ else await chatBody();
823
892
  } finally {
824
- this._insideInferenceLoop = false;
893
+ detachExternal();
894
+ this._aborts.remove(requestId);
825
895
  }
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
- }
896
+ });
857
897
  });
858
898
  }
859
899
  /** Get the conversation history as UIMessage[]. */
@@ -862,6 +902,7 @@ var Think = class Think extends Agent {
862
902
  }
863
903
  /** Clear all messages from storage. */
864
904
  clearMessages() {
905
+ this.resetTurnState();
865
906
  this.session.clearMessages();
866
907
  }
867
908
  _ensureAgentToolChildRunTable() {
@@ -872,29 +913,39 @@ var Think = class Think extends Agent {
872
913
  stream_id TEXT,
873
914
  status TEXT NOT NULL,
874
915
  summary TEXT,
916
+ output_json TEXT,
875
917
  error_message TEXT,
876
918
  started_at INTEGER NOT NULL,
877
919
  completed_at INTEGER
878
920
  )
879
921
  `;
922
+ this._addAgentToolChildRunColumnIfMissing("ALTER TABLE cf_agent_tool_child_runs ADD COLUMN output_json TEXT");
923
+ }
924
+ _addAgentToolChildRunColumnIfMissing(sql) {
925
+ try {
926
+ this.ctx.storage.sql.exec(sql);
927
+ } catch (error) {
928
+ if (!(error instanceof Error ? error.message : String(error)).toLowerCase().includes("duplicate column")) throw error;
929
+ }
880
930
  }
881
931
  _readAgentToolChildRun(runId) {
882
932
  this._ensureAgentToolChildRunTable();
883
933
  return this.sql`
884
- SELECT run_id, request_id, stream_id, status, summary, error_message,
885
- started_at, completed_at
934
+ SELECT run_id, request_id, stream_id, status, summary, output_json,
935
+ error_message, started_at, completed_at
886
936
  FROM cf_agent_tool_child_runs
887
937
  WHERE run_id = ${runId}
888
938
  LIMIT 1
889
939
  `[0] ?? null;
890
940
  }
891
941
  _inspectionFromChildRow(row, output) {
942
+ const storedOutput = row.output_json === null ? output : Think._parseAgentToolOutput(row.output_json);
892
943
  return {
893
944
  runId: row.run_id,
894
945
  status: row.status,
895
946
  requestId: row.request_id ?? void 0,
896
947
  streamId: row.stream_id ?? void 0,
897
- output,
948
+ output: storedOutput,
898
949
  summary: row.summary ?? void 0,
899
950
  error: row.error_message ?? void 0,
900
951
  startedAt: row.started_at,
@@ -913,6 +964,17 @@ var Think = class Think extends Agent {
913
964
  };
914
965
  }
915
966
  getAgentToolOutput(_runId) {}
967
+ getAgentToolSummary(runId, output) {
968
+ const text = this._getAgentToolFinalText(runId);
969
+ if (text) return text;
970
+ if (typeof output === "string") return output;
971
+ if (output !== void 0) try {
972
+ return JSON.stringify(output);
973
+ } catch {
974
+ return String(output);
975
+ }
976
+ return "";
977
+ }
916
978
  async startAgentToolRun(input, options) {
917
979
  const existing = this._readAgentToolChildRun(options.runId);
918
980
  if (existing) return this._inspectionFromChildRow(existing);
@@ -934,16 +996,19 @@ var Think = class Think extends Agent {
934
996
  `;
935
997
  const result = await this.saveMessages([this.formatAgentToolInput(input)], { signal: controller.signal });
936
998
  const streamId = this._resumableStream.getAllStreamMetadata().find((m) => m.request_id === result.requestId)?.id ?? null;
937
- const summary = this._getAgentToolFinalText(options.runId);
999
+ const output = this.getAgentToolOutput(options.runId);
1000
+ const summary = this.getAgentToolSummary(options.runId, output);
938
1001
  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;
1002
+ const skipped = result.status === "skipped";
1003
+ const status = result.status === "aborted" ? "aborted" : skipped || streamError ? "error" : "completed";
1004
+ const error = status === "error" ? streamError ?? "Agent tool run was skipped before the child could finish." : null;
941
1005
  this.sql`
942
1006
  UPDATE cf_agent_tool_child_runs
943
1007
  SET request_id = ${result.requestId},
944
1008
  stream_id = ${streamId},
945
1009
  status = ${status},
946
1010
  summary = ${summary},
1011
+ output_json = ${Think._stringifyAgentToolOutput(output)},
947
1012
  error_message = ${error},
948
1013
  completed_at = ${Date.now()}
949
1014
  WHERE run_id = ${options.runId}
@@ -1031,6 +1096,22 @@ var Think = class Think extends Agent {
1031
1096
  }
1032
1097
  });
1033
1098
  }
1099
+ static _stringifyAgentToolOutput(output) {
1100
+ if (output === void 0) return null;
1101
+ try {
1102
+ return JSON.stringify(output);
1103
+ } catch {
1104
+ return JSON.stringify(String(output));
1105
+ }
1106
+ }
1107
+ static _parseAgentToolOutput(value) {
1108
+ if (value === null) return void 0;
1109
+ try {
1110
+ return JSON.parse(value);
1111
+ } catch {
1112
+ return;
1113
+ }
1114
+ }
1034
1115
  _getAgentToolFinalText(runId) {
1035
1116
  const before = this._agentToolPreTurnAssistantIds.get(runId);
1036
1117
  if (!before) return null;
@@ -1041,6 +1122,514 @@ var Think = class Think extends Agent {
1041
1122
  }
1042
1123
  return null;
1043
1124
  }
1125
+ _ensureSubmissionTable() {
1126
+ if (this._submissionTableEnsured) return;
1127
+ this.sql`
1128
+ CREATE TABLE IF NOT EXISTS cf_think_submissions (
1129
+ submission_id TEXT PRIMARY KEY,
1130
+ idempotency_key TEXT UNIQUE,
1131
+ request_id TEXT,
1132
+ stream_id TEXT,
1133
+ status TEXT NOT NULL,
1134
+ messages_json TEXT NOT NULL,
1135
+ metadata_json TEXT,
1136
+ error_message TEXT,
1137
+ created_at INTEGER NOT NULL,
1138
+ messages_applied_at INTEGER,
1139
+ started_at INTEGER,
1140
+ completed_at INTEGER
1141
+ )
1142
+ `;
1143
+ this.sql`
1144
+ CREATE INDEX IF NOT EXISTS cf_think_submissions_status_created_idx
1145
+ ON cf_think_submissions (status, created_at, submission_id)
1146
+ `;
1147
+ this.sql`
1148
+ CREATE INDEX IF NOT EXISTS cf_think_submissions_request_status_idx
1149
+ ON cf_think_submissions (request_id, status)
1150
+ `;
1151
+ this.sql`
1152
+ CREATE INDEX IF NOT EXISTS cf_think_submissions_status_completed_idx
1153
+ ON cf_think_submissions (status, completed_at, created_at)
1154
+ `;
1155
+ this._submissionTableEnsured = true;
1156
+ }
1157
+ _readSubmission(submissionId) {
1158
+ this._ensureSubmissionTable();
1159
+ return this.sql`
1160
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1161
+ messages_json, metadata_json, error_message, created_at,
1162
+ messages_applied_at, started_at, completed_at
1163
+ FROM cf_think_submissions
1164
+ WHERE submission_id = ${submissionId}
1165
+ LIMIT 1
1166
+ `[0] ?? null;
1167
+ }
1168
+ _readSubmissionByIdempotencyKey(idempotencyKey) {
1169
+ this._ensureSubmissionTable();
1170
+ return this.sql`
1171
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1172
+ messages_json, metadata_json, error_message, created_at,
1173
+ messages_applied_at, started_at, completed_at
1174
+ FROM cf_think_submissions
1175
+ WHERE idempotency_key = ${idempotencyKey}
1176
+ LIMIT 1
1177
+ `[0] ?? null;
1178
+ }
1179
+ _normalizeStatusFilter(status) {
1180
+ if (!status) return null;
1181
+ return new Set(Array.isArray(status) ? status : [status]);
1182
+ }
1183
+ _listSubmissionRows(options) {
1184
+ this._ensureSubmissionTable();
1185
+ const limit = Math.min(Math.max(options?.limit ?? 50, 1), 100);
1186
+ const statuses = this._normalizeStatusFilter(options?.status);
1187
+ 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);
1188
+ return this.sql`
1189
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1190
+ messages_json, metadata_json, error_message, created_at,
1191
+ messages_applied_at, started_at, completed_at
1192
+ FROM cf_think_submissions
1193
+ ORDER BY created_at DESC, submission_id DESC
1194
+ LIMIT ${limit}
1195
+ `;
1196
+ }
1197
+ _listSubmissionRowsByStatus(status, limit) {
1198
+ return this.sql`
1199
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1200
+ messages_json, metadata_json, error_message, created_at,
1201
+ messages_applied_at, started_at, completed_at
1202
+ FROM cf_think_submissions
1203
+ WHERE status = ${status}
1204
+ ORDER BY created_at DESC, submission_id DESC
1205
+ LIMIT ${limit}
1206
+ `;
1207
+ }
1208
+ _inspectionFromSubmissionRow(row) {
1209
+ const metadata = this._parseJsonObject(row.metadata_json);
1210
+ return {
1211
+ submissionId: row.submission_id,
1212
+ idempotencyKey: row.idempotency_key ?? void 0,
1213
+ requestId: row.request_id ?? void 0,
1214
+ status: row.status,
1215
+ error: row.error_message ?? void 0,
1216
+ metadata: metadata ?? void 0,
1217
+ createdAt: row.created_at,
1218
+ startedAt: row.started_at ?? void 0,
1219
+ completedAt: row.completed_at ?? void 0
1220
+ };
1221
+ }
1222
+ _parseJsonObject(value) {
1223
+ if (value === null) return null;
1224
+ try {
1225
+ const parsed = JSON.parse(value);
1226
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
1227
+ } catch {}
1228
+ return null;
1229
+ }
1230
+ _parseSubmissionMessages(value) {
1231
+ const parsed = JSON.parse(value);
1232
+ if (!Array.isArray(parsed)) throw new Error("Stored submission messages are invalid");
1233
+ return parsed;
1234
+ }
1235
+ _serializeSubmissionMessages(messages) {
1236
+ return JSON.stringify(messages.map((message) => enforceRowSizeLimit(sanitizeMessage(message))));
1237
+ }
1238
+ _serializeMetadata(metadata) {
1239
+ return metadata === void 0 ? null : JSON.stringify(metadata);
1240
+ }
1241
+ async _emitSubmissionStatus(row) {
1242
+ const inspection = this._inspectionFromSubmissionRow(row);
1243
+ this._emit("submission:status", {
1244
+ submissionId: inspection.submissionId,
1245
+ requestId: inspection.requestId,
1246
+ status: inspection.status
1247
+ });
1248
+ if (inspection.status === "error" && inspection.error) this._emit("submission:error", {
1249
+ submissionId: inspection.submissionId,
1250
+ requestId: inspection.requestId,
1251
+ error: inspection.error
1252
+ });
1253
+ await this.keepAliveWhile(async () => {
1254
+ try {
1255
+ await this.onSubmissionStatus(inspection);
1256
+ } catch (error) {
1257
+ console.error("[Think] onSubmissionStatus failed", error);
1258
+ }
1259
+ });
1260
+ }
1261
+ onSubmissionStatus(_submission) {}
1262
+ async inspectSubmission(submissionId) {
1263
+ const row = this._readSubmission(submissionId);
1264
+ return row ? this._inspectionFromSubmissionRow(row) : null;
1265
+ }
1266
+ async listSubmissions(options) {
1267
+ return this._listSubmissionRows(options).map((row) => this._inspectionFromSubmissionRow(row));
1268
+ }
1269
+ async deleteSubmission(submissionId) {
1270
+ const row = this._readSubmission(submissionId);
1271
+ if (!row || !this._isTerminalSubmissionStatus(row.status)) return false;
1272
+ this.sql`
1273
+ DELETE FROM cf_think_submissions
1274
+ WHERE submission_id = ${submissionId}
1275
+ AND status IN ('completed', 'aborted', 'skipped', 'error')
1276
+ `;
1277
+ return true;
1278
+ }
1279
+ async deleteSubmissions(options) {
1280
+ this._ensureSubmissionTable();
1281
+ const statuses = this._normalizeStatusFilter(options?.status) ?? new Set([
1282
+ "completed",
1283
+ "aborted",
1284
+ "skipped",
1285
+ "error"
1286
+ ]);
1287
+ const limit = Math.min(Math.max(options?.limit ?? 100, 1), 500);
1288
+ const completedBefore = options?.completedBefore?.getTime();
1289
+ 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);
1290
+ let deleted = 0;
1291
+ for (const row of rows) {
1292
+ if (!this._isTerminalSubmissionStatus(row.status)) continue;
1293
+ this.sql`
1294
+ DELETE FROM cf_think_submissions
1295
+ WHERE submission_id = ${row.submission_id}
1296
+ AND status IN ('completed', 'aborted', 'skipped', 'error')
1297
+ `;
1298
+ deleted++;
1299
+ }
1300
+ return deleted;
1301
+ }
1302
+ _listTerminalSubmissionRowsForDelete(status, limit, completedBefore) {
1303
+ if (completedBefore === void 0) return this.sql`
1304
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1305
+ messages_json, metadata_json, error_message, created_at,
1306
+ messages_applied_at, started_at, completed_at
1307
+ FROM cf_think_submissions
1308
+ WHERE status = ${status}
1309
+ ORDER BY completed_at ASC, created_at ASC
1310
+ LIMIT ${limit}
1311
+ `;
1312
+ return this.sql`
1313
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1314
+ messages_json, metadata_json, error_message, created_at,
1315
+ messages_applied_at, started_at, completed_at
1316
+ FROM cf_think_submissions
1317
+ WHERE status = ${status}
1318
+ AND completed_at IS NOT NULL
1319
+ AND completed_at < ${completedBefore}
1320
+ ORDER BY completed_at ASC, created_at ASC
1321
+ LIMIT ${limit}
1322
+ `;
1323
+ }
1324
+ _isTerminalSubmissionStatus(status) {
1325
+ return status === "completed" || status === "aborted" || status === "skipped" || status === "error";
1326
+ }
1327
+ async cancelSubmission(submissionId, reason) {
1328
+ const row = this._readSubmission(submissionId);
1329
+ if (!row || this._isTerminalSubmissionStatus(row.status)) return;
1330
+ const completedAt = Date.now();
1331
+ const errorMessage = reason === void 0 ? null : reason instanceof Error ? reason.message : String(reason);
1332
+ this._submissionAbortControllers.get(submissionId)?.abort(reason);
1333
+ if (row.request_id) this.abortRequest(row.request_id, reason);
1334
+ this.sql`
1335
+ UPDATE cf_think_submissions
1336
+ SET status = 'aborted',
1337
+ error_message = ${errorMessage},
1338
+ completed_at = ${completedAt}
1339
+ WHERE submission_id = ${submissionId}
1340
+ AND status IN ('pending', 'running')
1341
+ `;
1342
+ const updated = this._readSubmission(submissionId);
1343
+ if (updated?.status === "aborted") await this._emitSubmissionStatus(updated);
1344
+ }
1345
+ async submitMessages(messages, options) {
1346
+ this._ensureSubmissionTable();
1347
+ if (messages.length === 0) throw new Error("submitMessages requires at least one message");
1348
+ const existingById = options?.submissionId ? this._readSubmission(options.submissionId) : null;
1349
+ const existingByKey = options?.idempotencyKey ? this._readSubmissionByIdempotencyKey(options.idempotencyKey) : null;
1350
+ if (existingById && existingByKey && existingById.submission_id !== existingByKey.submission_id) throw new Error("submissionId and idempotencyKey refer to different submissions");
1351
+ if (existingByKey && options?.submissionId && existingByKey.submission_id !== options.submissionId) throw new Error("submissionId and idempotencyKey refer to different submissions");
1352
+ if (existingById && options?.idempotencyKey && existingById.idempotency_key !== null && existingById.idempotency_key !== options.idempotencyKey) throw new Error("submissionId and idempotencyKey refer to different submissions");
1353
+ const existing = existingById ?? existingByKey;
1354
+ if (existing) {
1355
+ if (existing.status === "pending") {
1356
+ await this._scheduleSubmissionDrain();
1357
+ this._startSubmissionDrain();
1358
+ }
1359
+ return {
1360
+ ...this._inspectionFromSubmissionRow(existing),
1361
+ accepted: false
1362
+ };
1363
+ }
1364
+ const submissionId = options?.submissionId ?? crypto.randomUUID();
1365
+ const requestId = submissionId;
1366
+ const now = Date.now();
1367
+ const messagesJson = this._serializeSubmissionMessages(messages);
1368
+ const metadataJson = this._serializeMetadata(options?.metadata);
1369
+ this.sql`
1370
+ INSERT INTO cf_think_submissions (
1371
+ submission_id, idempotency_key, request_id, stream_id, status,
1372
+ messages_json, metadata_json, error_message, created_at,
1373
+ messages_applied_at, started_at, completed_at
1374
+ )
1375
+ VALUES (
1376
+ ${submissionId}, ${options?.idempotencyKey ?? null}, ${requestId},
1377
+ NULL, 'pending', ${messagesJson}, ${metadataJson}, NULL, ${now},
1378
+ NULL, NULL, NULL
1379
+ )
1380
+ `;
1381
+ const row = this._readSubmission(submissionId);
1382
+ if (!row) throw new Error("Failed to persist submission");
1383
+ this._emit("submission:create", {
1384
+ submissionId: row.submission_id,
1385
+ requestId: row.request_id ?? void 0,
1386
+ idempotencyKey: row.idempotency_key ?? void 0
1387
+ });
1388
+ await this._emitSubmissionStatus(row);
1389
+ await this._scheduleSubmissionDrain();
1390
+ this._startSubmissionDrain();
1391
+ return {
1392
+ ...this._inspectionFromSubmissionRow(row),
1393
+ accepted: true
1394
+ };
1395
+ }
1396
+ async _scheduleSubmissionDrain() {
1397
+ await this.schedule(0, "_drainThinkSubmissions", void 0, { idempotent: true });
1398
+ }
1399
+ _startSubmissionDrain() {
1400
+ this.keepAliveWhile(() => this._drainSubmissions()).catch((error) => {
1401
+ console.error("[Think] Failed to drain submissions", error);
1402
+ });
1403
+ }
1404
+ async _drainThinkSubmissions() {
1405
+ await this._drainSubmissions();
1406
+ }
1407
+ async _drainSubmissions() {
1408
+ this._ensureSubmissionTable();
1409
+ if (this._drainingSubmissions) return;
1410
+ this._drainingSubmissions = true;
1411
+ try {
1412
+ while (true) {
1413
+ const row = this.sql`
1414
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1415
+ messages_json, metadata_json, error_message, created_at,
1416
+ messages_applied_at, started_at, completed_at
1417
+ FROM cf_think_submissions
1418
+ WHERE status = 'pending'
1419
+ ORDER BY created_at ASC, submission_id ASC
1420
+ LIMIT 1
1421
+ `[0];
1422
+ if (!row) break;
1423
+ await this._runSubmission(row);
1424
+ }
1425
+ } finally {
1426
+ this._drainingSubmissions = false;
1427
+ }
1428
+ }
1429
+ async _runSubmission(row) {
1430
+ const requestId = row.request_id ?? row.submission_id;
1431
+ const startedAt = Date.now();
1432
+ this.sql`
1433
+ UPDATE cf_think_submissions
1434
+ SET status = 'running',
1435
+ request_id = ${requestId},
1436
+ started_at = ${startedAt}
1437
+ WHERE submission_id = ${row.submission_id}
1438
+ AND status = 'pending'
1439
+ `;
1440
+ const claimed = this._readSubmission(row.submission_id);
1441
+ if (!claimed || claimed.status !== "running") return;
1442
+ await this._emitSubmissionStatus(claimed);
1443
+ const controller = new AbortController();
1444
+ this._submissionAbortControllers.set(row.submission_id, controller);
1445
+ try {
1446
+ const messages = this._parseSubmissionMessages(row.messages_json);
1447
+ const result = await this._runProgrammaticMessagesTurn(requestId, messages, {
1448
+ signal: controller.signal,
1449
+ captureProgrammaticStreamError: true,
1450
+ onMessagesApplied: () => {
1451
+ this.sql`
1452
+ UPDATE cf_think_submissions
1453
+ SET messages_applied_at = ${Date.now()}
1454
+ WHERE submission_id = ${row.submission_id}
1455
+ AND status = 'running'
1456
+ AND messages_applied_at IS NULL
1457
+ `;
1458
+ }
1459
+ });
1460
+ const streamId = this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === result.requestId)?.id ?? null;
1461
+ const streamError = this._programmaticStreamErrors.get(result.requestId);
1462
+ const finalStatus = this._getSubmissionFinalStatus(result.status, streamError);
1463
+ this.sql`
1464
+ UPDATE cf_think_submissions
1465
+ SET status = ${finalStatus},
1466
+ request_id = ${result.requestId},
1467
+ stream_id = ${streamId},
1468
+ error_message = ${finalStatus === "error" ? streamError ?? null : null},
1469
+ completed_at = ${Date.now()}
1470
+ WHERE submission_id = ${row.submission_id}
1471
+ AND status = 'running'
1472
+ `;
1473
+ } catch (error) {
1474
+ this.sql`
1475
+ UPDATE cf_think_submissions
1476
+ SET status = 'error',
1477
+ error_message = ${error instanceof Error ? error.message : String(error)},
1478
+ completed_at = ${Date.now()}
1479
+ WHERE submission_id = ${row.submission_id}
1480
+ AND status = 'running'
1481
+ `;
1482
+ } finally {
1483
+ this._programmaticStreamErrors.delete(requestId);
1484
+ this._submissionAbortControllers.delete(row.submission_id);
1485
+ const updated = this._readSubmission(row.submission_id);
1486
+ if (updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated);
1487
+ }
1488
+ }
1489
+ _getSubmissionFinalStatus(resultStatus, streamError) {
1490
+ return resultStatus === "completed" && streamError ? "error" : resultStatus;
1491
+ }
1492
+ _markPendingSubmissionsSkipped() {
1493
+ this._ensureSubmissionTable();
1494
+ const pending = this.sql`
1495
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1496
+ messages_json, metadata_json, error_message, created_at,
1497
+ messages_applied_at, started_at, completed_at
1498
+ FROM cf_think_submissions
1499
+ WHERE status = 'pending'
1500
+ `;
1501
+ this.sql`
1502
+ UPDATE cf_think_submissions
1503
+ SET status = 'skipped',
1504
+ error_message = 'Submission was skipped by turn reset.',
1505
+ completed_at = ${Date.now()}
1506
+ WHERE status = 'pending'
1507
+ `;
1508
+ return pending;
1509
+ }
1510
+ async _emitSkippedSubmissions(skipped) {
1511
+ for (const row of skipped) {
1512
+ const updated = this._readSubmission(row.submission_id);
1513
+ if (updated?.status === "skipped") await this._emitSubmissionStatus(updated);
1514
+ }
1515
+ }
1516
+ async _recoverSubmissionsOnStart() {
1517
+ this._ensureSubmissionTable();
1518
+ const running = this.sql`
1519
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
1520
+ messages_json, metadata_json, error_message, created_at,
1521
+ messages_applied_at, started_at, completed_at
1522
+ FROM cf_think_submissions
1523
+ WHERE status = 'running'
1524
+ `;
1525
+ for (const row of running) {
1526
+ if (row.messages_applied_at === null) {
1527
+ let appliedState;
1528
+ try {
1529
+ appliedState = this._getSubmissionMessagesAppliedState(row);
1530
+ } catch (error) {
1531
+ this.sql`
1532
+ UPDATE cf_think_submissions
1533
+ SET status = 'error',
1534
+ error_message = ${error instanceof Error ? error.message : String(error)},
1535
+ completed_at = ${Date.now()}
1536
+ WHERE submission_id = ${row.submission_id}
1537
+ AND status = 'running'
1538
+ `;
1539
+ const updated = this._readSubmission(row.submission_id);
1540
+ if (updated?.status === "error") await this._emitSubmissionStatus(updated);
1541
+ continue;
1542
+ }
1543
+ if (appliedState !== "none") {
1544
+ this.sql`
1545
+ UPDATE cf_think_submissions
1546
+ SET status = 'error',
1547
+ error_message = ${appliedState === "all" ? "Submission was interrupted after messages were applied." : "Submission was interrupted after messages were partially applied."},
1548
+ completed_at = ${Date.now()}
1549
+ WHERE submission_id = ${row.submission_id}
1550
+ AND status = 'running'
1551
+ `;
1552
+ const updated = this._readSubmission(row.submission_id);
1553
+ if (updated?.status === "error") await this._emitSubmissionStatus(updated);
1554
+ continue;
1555
+ }
1556
+ this.sql`
1557
+ UPDATE cf_think_submissions
1558
+ SET status = 'pending',
1559
+ started_at = NULL
1560
+ WHERE submission_id = ${row.submission_id}
1561
+ AND status = 'running'
1562
+ `;
1563
+ const updated = this._readSubmission(row.submission_id);
1564
+ if (updated?.status === "pending") await this._emitSubmissionStatus(updated);
1565
+ continue;
1566
+ }
1567
+ if (row.request_id && (this._hasRecoverableChatTurn(row.request_id) && this._hasFreshRecoverableSubmissionEvidence(row) || this._hasScheduledRecoveredContinuation(row.request_id))) continue;
1568
+ this.sql`
1569
+ UPDATE cf_think_submissions
1570
+ SET status = 'error',
1571
+ error_message = 'Submission was interrupted after messages were applied.',
1572
+ completed_at = ${Date.now()}
1573
+ WHERE submission_id = ${row.submission_id}
1574
+ AND status = 'running'
1575
+ `;
1576
+ const updated = this._readSubmission(row.submission_id);
1577
+ if (updated?.status === "error") await this._emitSubmissionStatus(updated);
1578
+ }
1579
+ }
1580
+ _getSubmissionMessagesAppliedState(row) {
1581
+ const messages = this._parseSubmissionMessages(row.messages_json);
1582
+ if (messages.length === 0) return "all";
1583
+ let applied = 0;
1584
+ for (const message of messages) if (this.session.getMessage(message.id)) applied++;
1585
+ if (applied === 0) return "none";
1586
+ return applied === messages.length ? "all" : "partial";
1587
+ }
1588
+ _hasRecoverableChatTurn(requestId) {
1589
+ if (this.sql`
1590
+ SELECT id FROM cf_agents_runs
1591
+ WHERE name = ${this.constructor.CHAT_FIBER_NAME + ":" + requestId}
1592
+ LIMIT 1
1593
+ `.length > 0) return true;
1594
+ return this.sql`
1595
+ SELECT id FROM cf_ai_chat_stream_metadata
1596
+ WHERE request_id = ${requestId}
1597
+ AND status = 'streaming'
1598
+ LIMIT 1
1599
+ `.length > 0;
1600
+ }
1601
+ _hasFreshRecoverableSubmissionEvidence(row) {
1602
+ if (!row.request_id) return false;
1603
+ const cutoff = Date.now() - this.constructor.submissionRecoveryStaleMs;
1604
+ const fiberRows = this.sql`
1605
+ SELECT created_at FROM cf_agents_runs
1606
+ WHERE name = ${this.constructor.CHAT_FIBER_NAME + ":" + row.request_id}
1607
+ LIMIT 1
1608
+ `;
1609
+ if (fiberRows[0] && fiberRows[0].created_at >= cutoff) return true;
1610
+ const streamRows = this.sql`
1611
+ SELECT created_at FROM cf_ai_chat_stream_metadata
1612
+ WHERE request_id = ${row.request_id}
1613
+ AND status = 'streaming'
1614
+ ORDER BY created_at DESC
1615
+ LIMIT 1
1616
+ `;
1617
+ return streamRows[0] ? streamRows[0].created_at >= cutoff : false;
1618
+ }
1619
+ _hasScheduledRecoveredContinuation(requestId) {
1620
+ return this.sql`
1621
+ SELECT payload FROM cf_agents_schedules
1622
+ WHERE callback = '_chatRecoveryContinue'
1623
+ `.some((row) => {
1624
+ if (!row.payload) return false;
1625
+ try {
1626
+ const payload = JSON.parse(row.payload);
1627
+ return payload !== null && typeof payload === "object" && "recoveredRequestId" in payload && payload.recoveredRequestId === requestId;
1628
+ } catch {
1629
+ return false;
1630
+ }
1631
+ });
1632
+ }
1044
1633
  /**
1045
1634
  * Inject messages and trigger a model turn — without a WebSocket request.
1046
1635
  *
@@ -1086,6 +1675,9 @@ var Think = class Think extends Agent {
1086
1675
  */
1087
1676
  async saveMessages(messages, options) {
1088
1677
  const requestId = crypto.randomUUID();
1678
+ return this._runProgrammaticMessagesTurn(requestId, messages, options);
1679
+ }
1680
+ async _runProgrammaticMessagesTurn(requestId, messages, options) {
1089
1681
  const clientTools = this._lastClientTools;
1090
1682
  const body = this._lastBody;
1091
1683
  const epoch = this._turnQueue.generation;
@@ -1099,6 +1691,7 @@ var Think = class Think extends Agent {
1099
1691
  return;
1100
1692
  }
1101
1693
  for (const msg of resolved) await this.session.appendMessage(msg);
1694
+ options?.onMessagesApplied?.();
1102
1695
  this._broadcastMessages();
1103
1696
  if (this._turnQueue.generation !== epoch) {
1104
1697
  status = "skipped";
@@ -1119,7 +1712,7 @@ var Think = class Think extends Agent {
1119
1712
  body,
1120
1713
  continuation: false
1121
1714
  }));
1122
- if (result) await this._streamResult(requestId, result, abortSignal);
1715
+ if (result) await this._streamResult(requestId, result, abortSignal, { captureProgrammaticStreamError: options?.captureProgrammaticStreamError });
1123
1716
  };
1124
1717
  if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
1125
1718
  await programmaticBody();
@@ -1296,17 +1889,17 @@ var Think = class Think extends Agent {
1296
1889
  }
1297
1890
  }
1298
1891
  _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 }));
1892
+ 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
1893
  else this._notifyStreamResuming(connection);
1301
1894
  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 }));
1895
+ else sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
1303
1896
  }
1304
1897
  _handleStreamResumeAck(connection, requestId) {
1305
1898
  this._pendingResumeConnections.delete(connection.id);
1306
1899
  if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === requestId) {
1307
1900
  const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
1308
1901
  if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
1309
- } else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, requestId)) connection.send(JSON.stringify({
1902
+ } else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, requestId)) sendIfOpen(connection, JSON.stringify({
1310
1903
  body: "",
1311
1904
  done: true,
1312
1905
  id: requestId,
@@ -1450,6 +2043,12 @@ var Think = class Think extends Agent {
1450
2043
  resetTurnState() {
1451
2044
  this._turnQueue.reset();
1452
2045
  this._aborts.destroyAll();
2046
+ for (const controller of this._submissionAbortControllers.values()) controller.abort(/* @__PURE__ */ new Error("Turn state reset"));
2047
+ this._submissionAbortControllers.clear();
2048
+ const skippedSubmissions = this._markPendingSubmissionsSkipped();
2049
+ this.keepAliveWhile(() => this._emitSkippedSubmissions(skippedSubmissions)).catch((error) => {
2050
+ console.error("[Think] Failed to skip pending submissions", error);
2051
+ });
1453
2052
  if (this._continuationTimer) {
1454
2053
  clearTimeout(this._continuationTimer);
1455
2054
  this._continuationTimer = null;
@@ -1510,6 +2109,80 @@ var Think = class Think extends Agent {
1510
2109
  this.session.clearMessages();
1511
2110
  this._broadcast({ type: MSG_CHAT_CLEAR }, connection ? [connection.id] : void 0);
1512
2111
  }
2112
+ async _streamResultToRpcCallback(requestId, result, callback, abortSignal) {
2113
+ const streamId = this._resumableStream.start(requestId);
2114
+ const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
2115
+ let streamFinalized = false;
2116
+ let assistantMsg = null;
2117
+ let aborted = false;
2118
+ try {
2119
+ this._insideInferenceLoop = true;
2120
+ let chunksSinceFlush = 0;
2121
+ let hasFlushedContent = false;
2122
+ try {
2123
+ for await (const chunk of result.toUIMessageStream()) {
2124
+ if (abortSignal?.aborted) {
2125
+ aborted = true;
2126
+ break;
2127
+ }
2128
+ const streamChunk = chunk;
2129
+ accumulator.applyChunk(streamChunk);
2130
+ const chunkBody = JSON.stringify(chunk);
2131
+ this._resumableStream.storeChunk(streamId, chunkBody);
2132
+ chunksSinceFlush++;
2133
+ if (this._shouldFlushRpcStreamChunk(streamChunk, chunksSinceFlush, hasFlushedContent)) {
2134
+ this._resumableStream.flushBuffer();
2135
+ chunksSinceFlush = 0;
2136
+ hasFlushedContent = true;
2137
+ }
2138
+ await callback.onEvent(chunkBody);
2139
+ }
2140
+ } finally {
2141
+ this._insideInferenceLoop = false;
2142
+ }
2143
+ this._resumableStream.complete(streamId);
2144
+ streamFinalized = true;
2145
+ assistantMsg = accumulator.toMessage();
2146
+ this._persistAssistantMessage(assistantMsg);
2147
+ if (!aborted) {
2148
+ await callback.onDone();
2149
+ await this._fireResponseHook({
2150
+ message: assistantMsg,
2151
+ requestId,
2152
+ continuation: false,
2153
+ status: "completed"
2154
+ });
2155
+ } else await this._fireResponseHook({
2156
+ message: assistantMsg,
2157
+ requestId,
2158
+ continuation: false,
2159
+ status: "aborted"
2160
+ });
2161
+ } catch (error) {
2162
+ if (!streamFinalized) {
2163
+ this._resumableStream.markError(streamId);
2164
+ streamFinalized = true;
2165
+ }
2166
+ if (!assistantMsg && accumulator.parts.length > 0) {
2167
+ assistantMsg = accumulator.toMessage();
2168
+ this._persistAssistantMessage(assistantMsg);
2169
+ }
2170
+ const wrapped = this.onChatError(error);
2171
+ const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
2172
+ if (assistantMsg) await this._fireResponseHook({
2173
+ message: assistantMsg,
2174
+ requestId,
2175
+ continuation: false,
2176
+ status: "error",
2177
+ error: errorMessage
2178
+ });
2179
+ if (callback.onError) await callback.onError(errorMessage);
2180
+ else throw wrapped;
2181
+ }
2182
+ }
2183
+ _shouldFlushRpcStreamChunk(chunk, chunksSinceFlush, hasFlushedContent) {
2184
+ 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);
2185
+ }
1513
2186
  async _streamResult(requestId, result, abortSignal, options) {
1514
2187
  const clearGen = this._turnQueue.generation;
1515
2188
  const streamId = this._resumableStream.start(requestId);
@@ -1565,6 +2238,7 @@ var Think = class Think extends Agent {
1565
2238
  doneSent = true;
1566
2239
  } catch (error) {
1567
2240
  streamError = error instanceof Error ? error.message : "Stream error";
2241
+ if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
1568
2242
  this._resumableStream.markError(streamId);
1569
2243
  this._pendingResumeConnections.clear();
1570
2244
  if (!doneSent) {
@@ -1711,15 +2385,22 @@ var Think = class Think extends Agent {
1711
2385
  if (!ctx.name.startsWith(chatPrefix)) return false;
1712
2386
  const requestId = ctx.name.slice(chatPrefix.length);
1713
2387
  let streamId = "";
2388
+ let streamStatus;
1714
2389
  if (requestId) {
1715
2390
  const rows = this.sql`
1716
- SELECT id FROM cf_ai_chat_stream_metadata
2391
+ SELECT id, status FROM cf_ai_chat_stream_metadata
1717
2392
  WHERE request_id = ${requestId}
1718
2393
  ORDER BY created_at DESC LIMIT 1
1719
2394
  `;
1720
- if (rows.length > 0) streamId = rows[0].id;
2395
+ if (rows.length > 0) {
2396
+ streamId = rows[0].id;
2397
+ streamStatus = rows[0].status;
2398
+ }
2399
+ }
2400
+ if (!streamId && this._resumableStream.hasActiveStream()) {
2401
+ streamId = this._resumableStream.activeStreamId ?? "";
2402
+ streamStatus = "streaming";
1721
2403
  }
1722
- if (!streamId && this._resumableStream.hasActiveStream()) streamId = this._resumableStream.activeStreamId ?? "";
1723
2404
  const partial = streamId ? this._getPartialStreamText(streamId) : {
1724
2405
  text: "",
1725
2406
  parts: []
@@ -1736,27 +2417,114 @@ var Think = class Think extends Agent {
1736
2417
  createdAt: ctx.createdAt
1737
2418
  });
1738
2419
  const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
1739
- if (options.persist !== false && streamStillActive) this._persistOrphanedStream(streamId);
2420
+ const streamIsTerminal = streamStatus === "completed" || streamStatus === "error";
2421
+ if (options.persist !== false && (streamStillActive || streamIsTerminal)) this._persistOrphanedStream(streamId);
1740
2422
  if (streamStillActive) this._resumableStream.complete(streamId);
1741
- if (options.continue !== false) {
2423
+ const canContinue = options.continue !== false && !streamIsTerminal;
2424
+ const hasRunningSubmission = this._hasRunningSubmission(requestId);
2425
+ if (streamIsTerminal && hasRunningSubmission) await this._completeRecoveredSubmission(requestId, streamStatus === "completed" ? "completed" : "error", requestId, streamStatus === "completed" ? null : "Recovered chat stream had already errored.");
2426
+ const recoveredRequestId = canContinue && hasRunningSubmission ? requestId : void 0;
2427
+ if (canContinue) {
1742
2428
  const lastLeaf = this.session.getLatestLeaf();
1743
2429
  const targetId = lastLeaf?.role === "assistant" ? lastLeaf.id : void 0;
1744
- await this.schedule(0, "_chatRecoveryContinue", targetId ? { targetAssistantId: targetId } : void 0, { idempotent: true });
1745
- }
2430
+ await this.schedule(0, "_chatRecoveryContinue", {
2431
+ ...targetId ? { targetAssistantId: targetId } : {},
2432
+ ...recoveredRequestId ? { recoveredRequestId } : {}
2433
+ }, { idempotent: true });
2434
+ } else if (options.continue === false && !streamIsTerminal) await this._markRecoveredSubmissionInterrupted(requestId, "Submission was interrupted and chat recovery was disabled.");
1746
2435
  return true;
1747
2436
  }
2437
+ _hasRunningSubmission(requestId) {
2438
+ return this._readRunningSubmissionByRequestId(requestId) !== null;
2439
+ }
2440
+ _readRunningSubmissionByRequestId(requestId) {
2441
+ this._ensureSubmissionTable();
2442
+ return this.sql`
2443
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
2444
+ messages_json, metadata_json, error_message, created_at,
2445
+ messages_applied_at, started_at, completed_at
2446
+ FROM cf_think_submissions
2447
+ WHERE request_id = ${requestId}
2448
+ AND status = 'running'
2449
+ LIMIT 1
2450
+ `[0] ?? null;
2451
+ }
2452
+ async _markRecoveredSubmissionInterrupted(requestId, message) {
2453
+ this._ensureSubmissionTable();
2454
+ const row = this.sql`
2455
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
2456
+ messages_json, metadata_json, error_message, created_at,
2457
+ messages_applied_at, started_at, completed_at
2458
+ FROM cf_think_submissions
2459
+ WHERE request_id = ${requestId}
2460
+ AND status = 'running'
2461
+ LIMIT 1
2462
+ `[0];
2463
+ if (!row) return;
2464
+ this.sql`
2465
+ UPDATE cf_think_submissions
2466
+ SET status = 'error',
2467
+ error_message = ${message},
2468
+ completed_at = ${Date.now()}
2469
+ WHERE submission_id = ${row.submission_id}
2470
+ AND status = 'running'
2471
+ `;
2472
+ const updated = this._readSubmission(row.submission_id);
2473
+ if (updated) await this._emitSubmissionStatus(updated);
2474
+ }
2475
+ async _completeRecoveredSubmission(originalRequestId, status, requestId, errorMessage) {
2476
+ this._ensureSubmissionTable();
2477
+ const completedAt = Date.now();
2478
+ const streamId = requestId ? this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === requestId)?.id ?? null : null;
2479
+ this.sql`
2480
+ UPDATE cf_think_submissions
2481
+ SET status = ${status},
2482
+ request_id = COALESCE(${requestId}, request_id),
2483
+ stream_id = COALESCE(${streamId}, stream_id),
2484
+ error_message = ${errorMessage},
2485
+ completed_at = ${completedAt}
2486
+ WHERE request_id = ${originalRequestId}
2487
+ AND status = 'running'
2488
+ `;
2489
+ const updated = this.sql`
2490
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
2491
+ messages_json, metadata_json, error_message, created_at,
2492
+ messages_applied_at, started_at, completed_at
2493
+ FROM cf_think_submissions
2494
+ WHERE request_id = COALESCE(${requestId}, ${originalRequestId})
2495
+ ORDER BY completed_at DESC
2496
+ LIMIT 1
2497
+ `[0];
2498
+ if (updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated);
2499
+ }
1748
2500
  async onChatRecovery(_ctx) {
1749
2501
  return {};
1750
2502
  }
1751
2503
  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;
2504
+ const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
2505
+ if (data?.recoveredRequestId && !recoveredSubmission) return;
2506
+ const controller = recoveredSubmission ? new AbortController() : null;
2507
+ if (recoveredSubmission && controller) this._submissionAbortControllers.set(recoveredSubmission.submission_id, controller);
2508
+ try {
2509
+ if (!await this.waitUntilStable({ timeout: 1e4 })) {
2510
+ console.warn("[Think] _chatRecoveryContinue timed out waiting for stable state, skipping continuation");
2511
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat continuation timed out waiting for stable state.");
2512
+ return;
2513
+ }
2514
+ const targetId = data?.targetAssistantId;
2515
+ const lastLeaf = this.session.getLatestLeaf();
2516
+ if (targetId && lastLeaf?.id !== targetId) {
2517
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat continuation was skipped because the conversation changed.");
2518
+ return;
2519
+ }
2520
+ const result = await this.continueLastTurn(void 0, controller ? { signal: controller.signal } : void 0);
2521
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : `Recovery ${result.status}.`);
2522
+ } catch (error) {
2523
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, error instanceof Error ? error.message : String(error));
2524
+ throw error;
2525
+ } finally {
2526
+ if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
1755
2527
  }
1756
- const targetId = data?.targetAssistantId;
1757
- const lastLeaf = this.session.getLatestLeaf();
1758
- if (targetId && lastLeaf?.id !== targetId) return;
1759
- await this.continueLastTurn();
1760
2528
  }
1761
2529
  _getPartialStreamText(streamId) {
1762
2530
  const chunks = this._resumableStream.getStreamChunks(streamId);
@@ -1888,11 +2656,10 @@ var Think = class Think extends Agent {
1888
2656
  }
1889
2657
  _notifyStreamResuming(connection) {
1890
2658
  if (!this._resumableStream.hasActiveStream()) return;
1891
- this._pendingResumeConnections.add(connection.id);
1892
- connection.send(JSON.stringify({
2659
+ if (sendIfOpen(connection, JSON.stringify({
1893
2660
  type: MSG_STREAM_RESUMING,
1894
2661
  id: this._resumableStream.activeRequestId
1895
- }));
2662
+ }))) this._pendingResumeConnections.add(connection.id);
1896
2663
  }
1897
2664
  _persistOrphanedStream(streamId) {
1898
2665
  this._resumableStream.flushBuffer();
@@ -1928,6 +2695,7 @@ Think.CONFIG_KEYS = [
1928
2695
  ];
1929
2696
  Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
1930
2697
  Think.MESSAGE_DEBOUNCE_MS = 750;
2698
+ Think.submissionRecoveryStaleMs = 900 * 1e3;
1931
2699
  //#endregion
1932
2700
  export { Session, Think, Workspace };
1933
2701