@cloudflare/think 0.5.2 → 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/README.md +35 -2
- package/dist/{classPrivateFieldGet2-Bvcn7kEw.js → classPrivateFieldGet2-CCiYk1x3.js} +5 -5
- package/dist/extensions/index.js +2 -2
- package/dist/extensions/index.js.map +1 -1
- package/dist/hook-proxy-5248W-ea.js.map +1 -1
- package/dist/{manager-DDC3Gb0V.js → manager-BypfrNX0.js} +3 -3
- package/dist/{manager-DDC3Gb0V.js.map → manager-BypfrNX0.js.map} +1 -1
- package/dist/think.d.ts +126 -4
- package/dist/think.js +848 -100
- package/dist/think.js.map +1 -1
- package/dist/tools/browser.js.map +1 -1
- package/dist/tools/execute.js.map +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/extensions.js.map +1 -1
- package/dist/tools/sandbox.js.map +1 -1
- package/dist/tools/workspace.js +42 -12
- package/dist/tools/workspace.js.map +1 -1
- package/package.json +4 -4
package/dist/think.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-
|
|
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,
|
|
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-
|
|
379
|
-
const { sanitizeName } = await import("./manager-
|
|
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 =
|
|
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 = {
|
|
@@ -469,6 +483,17 @@ var Think = class Think extends Agent {
|
|
|
469
483
|
tools: finalTools,
|
|
470
484
|
activeTools: config.activeTools,
|
|
471
485
|
toolChoice: config.toolChoice,
|
|
486
|
+
maxOutputTokens: config.maxOutputTokens,
|
|
487
|
+
temperature: config.temperature,
|
|
488
|
+
topP: config.topP,
|
|
489
|
+
topK: config.topK,
|
|
490
|
+
presencePenalty: config.presencePenalty,
|
|
491
|
+
frequencyPenalty: config.frequencyPenalty,
|
|
492
|
+
stopSequences: config.stopSequences,
|
|
493
|
+
seed: config.seed,
|
|
494
|
+
maxRetries: config.maxRetries,
|
|
495
|
+
timeout: config.timeout,
|
|
496
|
+
headers: config.headers,
|
|
472
497
|
stopWhen: stepCountIs(finalMaxSteps),
|
|
473
498
|
providerOptions: config.providerOptions,
|
|
474
499
|
experimental_telemetry: config.experimental_telemetry,
|
|
@@ -541,6 +566,20 @@ var Think = class Think extends Agent {
|
|
|
541
566
|
if (parsed.config.toolChoice !== void 0) accumulated.toolChoice = parsed.config.toolChoice;
|
|
542
567
|
if (parsed.config.maxSteps !== void 0) accumulated.maxSteps = parsed.config.maxSteps;
|
|
543
568
|
if (parsed.config.sendReasoning !== void 0) accumulated.sendReasoning = parsed.config.sendReasoning;
|
|
569
|
+
if (parsed.config.maxOutputTokens !== void 0) accumulated.maxOutputTokens = parsed.config.maxOutputTokens;
|
|
570
|
+
if (parsed.config.temperature !== void 0) accumulated.temperature = parsed.config.temperature;
|
|
571
|
+
if (parsed.config.topP !== void 0) accumulated.topP = parsed.config.topP;
|
|
572
|
+
if (parsed.config.topK !== void 0) accumulated.topK = parsed.config.topK;
|
|
573
|
+
if (parsed.config.presencePenalty !== void 0) accumulated.presencePenalty = parsed.config.presencePenalty;
|
|
574
|
+
if (parsed.config.frequencyPenalty !== void 0) accumulated.frequencyPenalty = parsed.config.frequencyPenalty;
|
|
575
|
+
if (parsed.config.stopSequences !== void 0) accumulated.stopSequences = parsed.config.stopSequences;
|
|
576
|
+
if (parsed.config.seed !== void 0) accumulated.seed = parsed.config.seed;
|
|
577
|
+
if (parsed.config.maxRetries !== void 0) accumulated.maxRetries = parsed.config.maxRetries;
|
|
578
|
+
if (parsed.config.timeout !== void 0) accumulated.timeout = parsed.config.timeout;
|
|
579
|
+
if (parsed.config.headers !== void 0) accumulated.headers = {
|
|
580
|
+
...accumulated.headers ?? {},
|
|
581
|
+
...parsed.config.headers
|
|
582
|
+
};
|
|
544
583
|
if (parsed.config.providerOptions !== void 0) accumulated.providerOptions = {
|
|
545
584
|
...accumulated.providerOptions ?? {},
|
|
546
585
|
...parsed.config.providerOptions
|
|
@@ -762,73 +801,54 @@ var Think = class Think extends Agent {
|
|
|
762
801
|
*/
|
|
763
802
|
async chat(userMessage, callback, options) {
|
|
764
803
|
const requestId = crypto.randomUUID();
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
request: void 0,
|
|
781
|
-
email: void 0
|
|
782
|
-
}, () => this._runInferenceLoop({
|
|
783
|
-
signal: options?.signal,
|
|
784
|
-
callerTools: options?.tools,
|
|
785
|
-
continuation: false
|
|
786
|
-
}));
|
|
787
|
-
this._insideInferenceLoop = true;
|
|
788
|
-
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);
|
|
789
819
|
try {
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
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;
|
|
794
840
|
}
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
}
|
|
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();
|
|
798
847
|
} finally {
|
|
799
|
-
|
|
848
|
+
detachExternal();
|
|
849
|
+
this._aborts.remove(requestId);
|
|
800
850
|
}
|
|
801
|
-
|
|
802
|
-
this._persistAssistantMessage(assistantMsg);
|
|
803
|
-
if (!aborted) {
|
|
804
|
-
await callback.onDone();
|
|
805
|
-
await this._fireResponseHook({
|
|
806
|
-
message: assistantMsg,
|
|
807
|
-
requestId,
|
|
808
|
-
continuation: false,
|
|
809
|
-
status: "completed"
|
|
810
|
-
});
|
|
811
|
-
} else await this._fireResponseHook({
|
|
812
|
-
message: assistantMsg,
|
|
813
|
-
requestId,
|
|
814
|
-
continuation: false,
|
|
815
|
-
status: "aborted"
|
|
816
|
-
});
|
|
817
|
-
} catch (error) {
|
|
818
|
-
const assistantMsg = accumulator.parts.length > 0 ? accumulator.toMessage() : null;
|
|
819
|
-
if (assistantMsg) this._persistAssistantMessage(assistantMsg);
|
|
820
|
-
const wrapped = this.onChatError(error);
|
|
821
|
-
const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
|
|
822
|
-
if (assistantMsg) await this._fireResponseHook({
|
|
823
|
-
message: assistantMsg,
|
|
824
|
-
requestId,
|
|
825
|
-
continuation: false,
|
|
826
|
-
status: "error",
|
|
827
|
-
error: errorMessage
|
|
828
|
-
});
|
|
829
|
-
if (callback.onError) await callback.onError(errorMessage);
|
|
830
|
-
else throw wrapped;
|
|
831
|
-
}
|
|
851
|
+
});
|
|
832
852
|
});
|
|
833
853
|
}
|
|
834
854
|
/** Get the conversation history as UIMessage[]. */
|
|
@@ -837,6 +857,7 @@ var Think = class Think extends Agent {
|
|
|
837
857
|
}
|
|
838
858
|
/** Clear all messages from storage. */
|
|
839
859
|
clearMessages() {
|
|
860
|
+
this.resetTurnState();
|
|
840
861
|
this.session.clearMessages();
|
|
841
862
|
}
|
|
842
863
|
_ensureAgentToolChildRunTable() {
|
|
@@ -847,29 +868,39 @@ var Think = class Think extends Agent {
|
|
|
847
868
|
stream_id TEXT,
|
|
848
869
|
status TEXT NOT NULL,
|
|
849
870
|
summary TEXT,
|
|
871
|
+
output_json TEXT,
|
|
850
872
|
error_message TEXT,
|
|
851
873
|
started_at INTEGER NOT NULL,
|
|
852
874
|
completed_at INTEGER
|
|
853
875
|
)
|
|
854
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
|
+
}
|
|
855
885
|
}
|
|
856
886
|
_readAgentToolChildRun(runId) {
|
|
857
887
|
this._ensureAgentToolChildRunTable();
|
|
858
888
|
return this.sql`
|
|
859
|
-
SELECT run_id, request_id, stream_id, status, summary,
|
|
860
|
-
started_at, completed_at
|
|
889
|
+
SELECT run_id, request_id, stream_id, status, summary, output_json,
|
|
890
|
+
error_message, started_at, completed_at
|
|
861
891
|
FROM cf_agent_tool_child_runs
|
|
862
892
|
WHERE run_id = ${runId}
|
|
863
893
|
LIMIT 1
|
|
864
894
|
`[0] ?? null;
|
|
865
895
|
}
|
|
866
896
|
_inspectionFromChildRow(row, output) {
|
|
897
|
+
const storedOutput = row.output_json === null ? output : Think._parseAgentToolOutput(row.output_json);
|
|
867
898
|
return {
|
|
868
899
|
runId: row.run_id,
|
|
869
900
|
status: row.status,
|
|
870
901
|
requestId: row.request_id ?? void 0,
|
|
871
902
|
streamId: row.stream_id ?? void 0,
|
|
872
|
-
output,
|
|
903
|
+
output: storedOutput,
|
|
873
904
|
summary: row.summary ?? void 0,
|
|
874
905
|
error: row.error_message ?? void 0,
|
|
875
906
|
startedAt: row.started_at,
|
|
@@ -888,6 +919,17 @@ var Think = class Think extends Agent {
|
|
|
888
919
|
};
|
|
889
920
|
}
|
|
890
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
|
+
}
|
|
891
933
|
async startAgentToolRun(input, options) {
|
|
892
934
|
const existing = this._readAgentToolChildRun(options.runId);
|
|
893
935
|
if (existing) return this._inspectionFromChildRow(existing);
|
|
@@ -909,16 +951,19 @@ var Think = class Think extends Agent {
|
|
|
909
951
|
`;
|
|
910
952
|
const result = await this.saveMessages([this.formatAgentToolInput(input)], { signal: controller.signal });
|
|
911
953
|
const streamId = this._resumableStream.getAllStreamMetadata().find((m) => m.request_id === result.requestId)?.id ?? null;
|
|
912
|
-
const
|
|
954
|
+
const output = this.getAgentToolOutput(options.runId);
|
|
955
|
+
const summary = this.getAgentToolSummary(options.runId, output);
|
|
913
956
|
const streamError = this._agentToolLastErrors.get(options.runId);
|
|
914
|
-
const
|
|
915
|
-
const
|
|
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;
|
|
916
960
|
this.sql`
|
|
917
961
|
UPDATE cf_agent_tool_child_runs
|
|
918
962
|
SET request_id = ${result.requestId},
|
|
919
963
|
stream_id = ${streamId},
|
|
920
964
|
status = ${status},
|
|
921
965
|
summary = ${summary},
|
|
966
|
+
output_json = ${Think._stringifyAgentToolOutput(output)},
|
|
922
967
|
error_message = ${error},
|
|
923
968
|
completed_at = ${Date.now()}
|
|
924
969
|
WHERE run_id = ${options.runId}
|
|
@@ -1006,6 +1051,22 @@ var Think = class Think extends Agent {
|
|
|
1006
1051
|
}
|
|
1007
1052
|
});
|
|
1008
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
|
+
}
|
|
1009
1070
|
_getAgentToolFinalText(runId) {
|
|
1010
1071
|
const before = this._agentToolPreTurnAssistantIds.get(runId);
|
|
1011
1072
|
if (!before) return null;
|
|
@@ -1016,6 +1077,514 @@ var Think = class Think extends Agent {
|
|
|
1016
1077
|
}
|
|
1017
1078
|
return null;
|
|
1018
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
|
+
}
|
|
1019
1588
|
/**
|
|
1020
1589
|
* Inject messages and trigger a model turn — without a WebSocket request.
|
|
1021
1590
|
*
|
|
@@ -1061,6 +1630,9 @@ var Think = class Think extends Agent {
|
|
|
1061
1630
|
*/
|
|
1062
1631
|
async saveMessages(messages, options) {
|
|
1063
1632
|
const requestId = crypto.randomUUID();
|
|
1633
|
+
return this._runProgrammaticMessagesTurn(requestId, messages, options);
|
|
1634
|
+
}
|
|
1635
|
+
async _runProgrammaticMessagesTurn(requestId, messages, options) {
|
|
1064
1636
|
const clientTools = this._lastClientTools;
|
|
1065
1637
|
const body = this._lastBody;
|
|
1066
1638
|
const epoch = this._turnQueue.generation;
|
|
@@ -1074,6 +1646,7 @@ var Think = class Think extends Agent {
|
|
|
1074
1646
|
return;
|
|
1075
1647
|
}
|
|
1076
1648
|
for (const msg of resolved) await this.session.appendMessage(msg);
|
|
1649
|
+
options?.onMessagesApplied?.();
|
|
1077
1650
|
this._broadcastMessages();
|
|
1078
1651
|
if (this._turnQueue.generation !== epoch) {
|
|
1079
1652
|
status = "skipped";
|
|
@@ -1094,7 +1667,7 @@ var Think = class Think extends Agent {
|
|
|
1094
1667
|
body,
|
|
1095
1668
|
continuation: false
|
|
1096
1669
|
}));
|
|
1097
|
-
if (result) await this._streamResult(requestId, result, abortSignal);
|
|
1670
|
+
if (result) await this._streamResult(requestId, result, abortSignal, { captureProgrammaticStreamError: options?.captureProgrammaticStreamError });
|
|
1098
1671
|
};
|
|
1099
1672
|
if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
|
|
1100
1673
|
await programmaticBody();
|
|
@@ -1271,17 +1844,17 @@ var Think = class Think extends Agent {
|
|
|
1271
1844
|
}
|
|
1272
1845
|
}
|
|
1273
1846
|
_handleStreamResumeRequest(connection) {
|
|
1274
|
-
if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) connection
|
|
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 }));
|
|
1275
1848
|
else this._notifyStreamResuming(connection);
|
|
1276
1849
|
else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
|
|
1277
|
-
else connection
|
|
1850
|
+
else sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
|
|
1278
1851
|
}
|
|
1279
1852
|
_handleStreamResumeAck(connection, requestId) {
|
|
1280
1853
|
this._pendingResumeConnections.delete(connection.id);
|
|
1281
1854
|
if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === requestId) {
|
|
1282
1855
|
const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
|
|
1283
1856
|
if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
|
|
1284
|
-
} else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, requestId)) connection
|
|
1857
|
+
} else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, requestId)) sendIfOpen(connection, JSON.stringify({
|
|
1285
1858
|
body: "",
|
|
1286
1859
|
done: true,
|
|
1287
1860
|
id: requestId,
|
|
@@ -1425,6 +1998,12 @@ var Think = class Think extends Agent {
|
|
|
1425
1998
|
resetTurnState() {
|
|
1426
1999
|
this._turnQueue.reset();
|
|
1427
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
|
+
});
|
|
1428
2007
|
if (this._continuationTimer) {
|
|
1429
2008
|
clearTimeout(this._continuationTimer);
|
|
1430
2009
|
this._continuationTimer = null;
|
|
@@ -1485,6 +2064,80 @@ var Think = class Think extends Agent {
|
|
|
1485
2064
|
this.session.clearMessages();
|
|
1486
2065
|
this._broadcast({ type: MSG_CHAT_CLEAR }, connection ? [connection.id] : void 0);
|
|
1487
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
|
+
}
|
|
1488
2141
|
async _streamResult(requestId, result, abortSignal, options) {
|
|
1489
2142
|
const clearGen = this._turnQueue.generation;
|
|
1490
2143
|
const streamId = this._resumableStream.start(requestId);
|
|
@@ -1540,6 +2193,7 @@ var Think = class Think extends Agent {
|
|
|
1540
2193
|
doneSent = true;
|
|
1541
2194
|
} catch (error) {
|
|
1542
2195
|
streamError = error instanceof Error ? error.message : "Stream error";
|
|
2196
|
+
if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
|
|
1543
2197
|
this._resumableStream.markError(streamId);
|
|
1544
2198
|
this._pendingResumeConnections.clear();
|
|
1545
2199
|
if (!doneSent) {
|
|
@@ -1686,15 +2340,22 @@ var Think = class Think extends Agent {
|
|
|
1686
2340
|
if (!ctx.name.startsWith(chatPrefix)) return false;
|
|
1687
2341
|
const requestId = ctx.name.slice(chatPrefix.length);
|
|
1688
2342
|
let streamId = "";
|
|
2343
|
+
let streamStatus;
|
|
1689
2344
|
if (requestId) {
|
|
1690
2345
|
const rows = this.sql`
|
|
1691
|
-
SELECT id FROM cf_ai_chat_stream_metadata
|
|
2346
|
+
SELECT id, status FROM cf_ai_chat_stream_metadata
|
|
1692
2347
|
WHERE request_id = ${requestId}
|
|
1693
2348
|
ORDER BY created_at DESC LIMIT 1
|
|
1694
2349
|
`;
|
|
1695
|
-
if (rows.length > 0)
|
|
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";
|
|
1696
2358
|
}
|
|
1697
|
-
if (!streamId && this._resumableStream.hasActiveStream()) streamId = this._resumableStream.activeStreamId ?? "";
|
|
1698
2359
|
const partial = streamId ? this._getPartialStreamText(streamId) : {
|
|
1699
2360
|
text: "",
|
|
1700
2361
|
parts: []
|
|
@@ -1711,27 +2372,114 @@ var Think = class Think extends Agent {
|
|
|
1711
2372
|
createdAt: ctx.createdAt
|
|
1712
2373
|
});
|
|
1713
2374
|
const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
|
|
1714
|
-
|
|
2375
|
+
const streamIsTerminal = streamStatus === "completed" || streamStatus === "error";
|
|
2376
|
+
if (options.persist !== false && (streamStillActive || streamIsTerminal)) this._persistOrphanedStream(streamId);
|
|
1715
2377
|
if (streamStillActive) this._resumableStream.complete(streamId);
|
|
1716
|
-
|
|
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) {
|
|
1717
2383
|
const lastLeaf = this.session.getLatestLeaf();
|
|
1718
2384
|
const targetId = lastLeaf?.role === "assistant" ? lastLeaf.id : void 0;
|
|
1719
|
-
await this.schedule(0, "_chatRecoveryContinue",
|
|
1720
|
-
|
|
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.");
|
|
1721
2390
|
return true;
|
|
1722
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
|
+
}
|
|
1723
2455
|
async onChatRecovery(_ctx) {
|
|
1724
2456
|
return {};
|
|
1725
2457
|
}
|
|
1726
2458
|
async _chatRecoveryContinue(data) {
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
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);
|
|
1730
2482
|
}
|
|
1731
|
-
const targetId = data?.targetAssistantId;
|
|
1732
|
-
const lastLeaf = this.session.getLatestLeaf();
|
|
1733
|
-
if (targetId && lastLeaf?.id !== targetId) return;
|
|
1734
|
-
await this.continueLastTurn();
|
|
1735
2483
|
}
|
|
1736
2484
|
_getPartialStreamText(streamId) {
|
|
1737
2485
|
const chunks = this._resumableStream.getStreamChunks(streamId);
|
|
@@ -1863,11 +2611,10 @@ var Think = class Think extends Agent {
|
|
|
1863
2611
|
}
|
|
1864
2612
|
_notifyStreamResuming(connection) {
|
|
1865
2613
|
if (!this._resumableStream.hasActiveStream()) return;
|
|
1866
|
-
|
|
1867
|
-
connection.send(JSON.stringify({
|
|
2614
|
+
if (sendIfOpen(connection, JSON.stringify({
|
|
1868
2615
|
type: MSG_STREAM_RESUMING,
|
|
1869
2616
|
id: this._resumableStream.activeRequestId
|
|
1870
|
-
}));
|
|
2617
|
+
}))) this._pendingResumeConnections.add(connection.id);
|
|
1871
2618
|
}
|
|
1872
2619
|
_persistOrphanedStream(streamId) {
|
|
1873
2620
|
this._resumableStream.flushBuffer();
|
|
@@ -1903,6 +2650,7 @@ Think.CONFIG_KEYS = [
|
|
|
1903
2650
|
];
|
|
1904
2651
|
Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
|
|
1905
2652
|
Think.MESSAGE_DEBOUNCE_MS = 750;
|
|
2653
|
+
Think.submissionRecoveryStaleMs = 900 * 1e3;
|
|
1906
2654
|
//#endregion
|
|
1907
2655
|
export { Session, Think, Workspace };
|
|
1908
2656
|
|