@cloudflare/think 0.4.1 → 0.5.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 +42 -1
- package/dist/think.d.ts +134 -3
- package/dist/think.js +277 -4
- package/dist/think.js.map +1 -1
- package/package.json +7 -7
package/dist/think.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { createWorkspaceTools } from "./tools/workspace.js";
|
|
2
1
|
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-Bvcn7kEw.js";
|
|
2
|
+
import { createWorkspaceTools } from "./tools/workspace.js";
|
|
3
3
|
import { convertToModelMessages, pruneMessages, 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";
|
|
@@ -7,6 +7,7 @@ import { Session, Session as Session$1 } from "agents/experimental/memory/sessio
|
|
|
7
7
|
import { truncateOlderMessages } from "agents/experimental/memory/utils";
|
|
8
8
|
import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
|
|
9
9
|
//#region src/think.ts
|
|
10
|
+
const agentToolChunkEncoder = new TextEncoder();
|
|
10
11
|
const MSG_CHAT_MESSAGES = CHAT_MESSAGE_TYPES.CHAT_MESSAGES;
|
|
11
12
|
const MSG_CHAT_RESPONSE = CHAT_MESSAGE_TYPES.USE_CHAT_RESPONSE;
|
|
12
13
|
const MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;
|
|
@@ -36,9 +37,16 @@ var Think = class Think extends Agent {
|
|
|
36
37
|
this._insideInferenceLoop = false;
|
|
37
38
|
this._pendingInteractionPromise = null;
|
|
38
39
|
this._submitConcurrency = new SubmitConcurrencyController({ defaultDebounceMs: Think.MESSAGE_DEBOUNCE_MS });
|
|
40
|
+
this._agentToolForwarders = /* @__PURE__ */ new Map();
|
|
41
|
+
this._agentToolClosers = /* @__PURE__ */ new Map();
|
|
42
|
+
this._agentToolAbortControllers = /* @__PURE__ */ new Map();
|
|
43
|
+
this._agentToolLastErrors = /* @__PURE__ */ new Map();
|
|
44
|
+
this._agentToolPreTurnAssistantIds = /* @__PURE__ */ new Map();
|
|
45
|
+
this._agentToolLiveSequences = /* @__PURE__ */ new Map();
|
|
39
46
|
_classPrivateFieldInitSpec(this, _configCache, null);
|
|
40
47
|
_classPrivateFieldInitSpec(this, _configTableReady, false);
|
|
41
48
|
this.maxSteps = 10;
|
|
49
|
+
this.sendReasoning = true;
|
|
42
50
|
this.hookTimeout = 5e3;
|
|
43
51
|
const _onStart = this.onStart.bind(this);
|
|
44
52
|
this.onStart = async () => {
|
|
@@ -64,6 +72,24 @@ var Think = class Think extends Agent {
|
|
|
64
72
|
get messages() {
|
|
65
73
|
return this.session.getHistory();
|
|
66
74
|
}
|
|
75
|
+
broadcast(msg, without) {
|
|
76
|
+
if (this._agentToolForwarders.size > 0 && typeof msg === "string") try {
|
|
77
|
+
const parsed = JSON.parse(msg);
|
|
78
|
+
if (parsed.type === MSG_CHAT_RESPONSE) {
|
|
79
|
+
if (parsed.error === true && typeof parsed.body === "string") for (const runId of this._agentToolForwarders.keys()) this._agentToolLastErrors.set(runId, parsed.body);
|
|
80
|
+
else if (typeof parsed.body === "string" && parsed.body.length > 0) for (const [runId, forwarders] of this._agentToolForwarders) {
|
|
81
|
+
const sequence = this._agentToolLiveSequences.get(runId) ?? 0;
|
|
82
|
+
this._agentToolLiveSequences.set(runId, sequence + 1);
|
|
83
|
+
const chunk = {
|
|
84
|
+
sequence,
|
|
85
|
+
body: parsed.body
|
|
86
|
+
};
|
|
87
|
+
for (const forward of forwarders) forward(chunk);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
} catch {}
|
|
91
|
+
super.broadcast(msg, without);
|
|
92
|
+
}
|
|
67
93
|
/**
|
|
68
94
|
* Persist an arbitrary JSON-serializable configuration object for this
|
|
69
95
|
* agent instance. Stored in the Think-private `think_config` table —
|
|
@@ -435,6 +461,7 @@ var Think = class Think extends Agent {
|
|
|
435
461
|
} : tools;
|
|
436
462
|
const finalTools = this._wrapToolsWithDecision(mergedTools);
|
|
437
463
|
const finalMaxSteps = config.maxSteps ?? this.maxSteps;
|
|
464
|
+
const finalSendReasoning = config.sendReasoning ?? this.sendReasoning;
|
|
438
465
|
const result = streamText({
|
|
439
466
|
model: finalModel,
|
|
440
467
|
system: finalSystem,
|
|
@@ -444,6 +471,7 @@ var Think = class Think extends Agent {
|
|
|
444
471
|
toolChoice: config.toolChoice,
|
|
445
472
|
stopWhen: stepCountIs(finalMaxSteps),
|
|
446
473
|
providerOptions: config.providerOptions,
|
|
474
|
+
experimental_telemetry: config.experimental_telemetry,
|
|
447
475
|
output: config.output,
|
|
448
476
|
abortSignal: input.signal,
|
|
449
477
|
prepareStep: (async (event) => {
|
|
@@ -478,7 +506,7 @@ var Think = class Think extends Agent {
|
|
|
478
506
|
await this._pipelineExtensionToolCallFinish(event);
|
|
479
507
|
})
|
|
480
508
|
});
|
|
481
|
-
return this._transformInferenceResult(result);
|
|
509
|
+
return this._transformInferenceResult({ toUIMessageStream: () => result.toUIMessageStream({ sendReasoning: finalSendReasoning }) });
|
|
482
510
|
}
|
|
483
511
|
/** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */
|
|
484
512
|
_transformInferenceResult(result) {
|
|
@@ -512,6 +540,7 @@ var Think = class Think extends Agent {
|
|
|
512
540
|
if (parsed.config.activeTools !== void 0) accumulated.activeTools = parsed.config.activeTools;
|
|
513
541
|
if (parsed.config.toolChoice !== void 0) accumulated.toolChoice = parsed.config.toolChoice;
|
|
514
542
|
if (parsed.config.maxSteps !== void 0) accumulated.maxSteps = parsed.config.maxSteps;
|
|
543
|
+
if (parsed.config.sendReasoning !== void 0) accumulated.sendReasoning = parsed.config.sendReasoning;
|
|
515
544
|
if (parsed.config.providerOptions !== void 0) accumulated.providerOptions = {
|
|
516
545
|
...accumulated.providerOptions ?? {},
|
|
517
546
|
...parsed.config.providerOptions
|
|
@@ -810,6 +839,183 @@ var Think = class Think extends Agent {
|
|
|
810
839
|
clearMessages() {
|
|
811
840
|
this.session.clearMessages();
|
|
812
841
|
}
|
|
842
|
+
_ensureAgentToolChildRunTable() {
|
|
843
|
+
this.sql`
|
|
844
|
+
CREATE TABLE IF NOT EXISTS cf_agent_tool_child_runs (
|
|
845
|
+
run_id TEXT PRIMARY KEY,
|
|
846
|
+
request_id TEXT,
|
|
847
|
+
stream_id TEXT,
|
|
848
|
+
status TEXT NOT NULL,
|
|
849
|
+
summary TEXT,
|
|
850
|
+
error_message TEXT,
|
|
851
|
+
started_at INTEGER NOT NULL,
|
|
852
|
+
completed_at INTEGER
|
|
853
|
+
)
|
|
854
|
+
`;
|
|
855
|
+
}
|
|
856
|
+
_readAgentToolChildRun(runId) {
|
|
857
|
+
this._ensureAgentToolChildRunTable();
|
|
858
|
+
return this.sql`
|
|
859
|
+
SELECT run_id, request_id, stream_id, status, summary, error_message,
|
|
860
|
+
started_at, completed_at
|
|
861
|
+
FROM cf_agent_tool_child_runs
|
|
862
|
+
WHERE run_id = ${runId}
|
|
863
|
+
LIMIT 1
|
|
864
|
+
`[0] ?? null;
|
|
865
|
+
}
|
|
866
|
+
_inspectionFromChildRow(row, output) {
|
|
867
|
+
return {
|
|
868
|
+
runId: row.run_id,
|
|
869
|
+
status: row.status,
|
|
870
|
+
requestId: row.request_id ?? void 0,
|
|
871
|
+
streamId: row.stream_id ?? void 0,
|
|
872
|
+
output,
|
|
873
|
+
summary: row.summary ?? void 0,
|
|
874
|
+
error: row.error_message ?? void 0,
|
|
875
|
+
startedAt: row.started_at,
|
|
876
|
+
completedAt: row.completed_at ?? void 0
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
formatAgentToolInput(input) {
|
|
880
|
+
const text = typeof input === "string" ? input : JSON.stringify(input, null, 2);
|
|
881
|
+
return {
|
|
882
|
+
id: crypto.randomUUID(),
|
|
883
|
+
role: "user",
|
|
884
|
+
parts: [{
|
|
885
|
+
type: "text",
|
|
886
|
+
text
|
|
887
|
+
}]
|
|
888
|
+
};
|
|
889
|
+
}
|
|
890
|
+
getAgentToolOutput(_runId) {}
|
|
891
|
+
async startAgentToolRun(input, options) {
|
|
892
|
+
const existing = this._readAgentToolChildRun(options.runId);
|
|
893
|
+
if (existing) return this._inspectionFromChildRow(existing);
|
|
894
|
+
const startedAt = Date.now();
|
|
895
|
+
this.sql`
|
|
896
|
+
INSERT INTO cf_agent_tool_child_runs (run_id, status, started_at)
|
|
897
|
+
VALUES (${options.runId}, 'starting', ${startedAt})
|
|
898
|
+
`;
|
|
899
|
+
const controller = new AbortController();
|
|
900
|
+
this._agentToolAbortControllers.set(options.runId, controller);
|
|
901
|
+
this._agentToolLiveSequences.set(options.runId, 0);
|
|
902
|
+
this._agentToolPreTurnAssistantIds.set(options.runId, new Set(this.messages.filter((m) => m.role === "assistant").map((m) => m.id)));
|
|
903
|
+
this.keepAliveWhile(async () => {
|
|
904
|
+
try {
|
|
905
|
+
this.sql`
|
|
906
|
+
UPDATE cf_agent_tool_child_runs
|
|
907
|
+
SET status = 'running'
|
|
908
|
+
WHERE run_id = ${options.runId} AND status = 'starting'
|
|
909
|
+
`;
|
|
910
|
+
const result = await this.saveMessages([this.formatAgentToolInput(input)], { signal: controller.signal });
|
|
911
|
+
const streamId = this._resumableStream.getAllStreamMetadata().find((m) => m.request_id === result.requestId)?.id ?? null;
|
|
912
|
+
const summary = this._getAgentToolFinalText(options.runId);
|
|
913
|
+
const streamError = this._agentToolLastErrors.get(options.runId);
|
|
914
|
+
const status = result.status === "aborted" ? "aborted" : streamError || !summary ? "error" : "completed";
|
|
915
|
+
const error = status === "error" ? streamError ?? `${this.constructor.name} finished without producing assistant text.` : null;
|
|
916
|
+
this.sql`
|
|
917
|
+
UPDATE cf_agent_tool_child_runs
|
|
918
|
+
SET request_id = ${result.requestId},
|
|
919
|
+
stream_id = ${streamId},
|
|
920
|
+
status = ${status},
|
|
921
|
+
summary = ${summary},
|
|
922
|
+
error_message = ${error},
|
|
923
|
+
completed_at = ${Date.now()}
|
|
924
|
+
WHERE run_id = ${options.runId}
|
|
925
|
+
`;
|
|
926
|
+
} catch (error) {
|
|
927
|
+
this.sql`
|
|
928
|
+
UPDATE cf_agent_tool_child_runs
|
|
929
|
+
SET status = 'error',
|
|
930
|
+
error_message = ${error instanceof Error ? error.message : String(error)},
|
|
931
|
+
completed_at = ${Date.now()}
|
|
932
|
+
WHERE run_id = ${options.runId}
|
|
933
|
+
`;
|
|
934
|
+
} finally {
|
|
935
|
+
this._agentToolAbortControllers.delete(options.runId);
|
|
936
|
+
this._agentToolForwarders.delete(options.runId);
|
|
937
|
+
this._agentToolLiveSequences.delete(options.runId);
|
|
938
|
+
this._agentToolLastErrors.delete(options.runId);
|
|
939
|
+
this._agentToolPreTurnAssistantIds.delete(options.runId);
|
|
940
|
+
for (const close of this._agentToolClosers.get(options.runId) ?? []) close();
|
|
941
|
+
this._agentToolClosers.delete(options.runId);
|
|
942
|
+
}
|
|
943
|
+
});
|
|
944
|
+
return {
|
|
945
|
+
runId: options.runId,
|
|
946
|
+
status: "running",
|
|
947
|
+
startedAt
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
async cancelAgentToolRun(runId, reason) {
|
|
951
|
+
const row = this._readAgentToolChildRun(runId);
|
|
952
|
+
if (!row || row.completed_at !== null) return;
|
|
953
|
+
this._agentToolAbortControllers.get(runId)?.abort(reason);
|
|
954
|
+
this.sql`
|
|
955
|
+
UPDATE cf_agent_tool_child_runs
|
|
956
|
+
SET status = 'aborted',
|
|
957
|
+
error_message = ${reason instanceof Error ? reason.message : reason === void 0 ? null : String(reason)},
|
|
958
|
+
completed_at = ${Date.now()}
|
|
959
|
+
WHERE run_id = ${runId}
|
|
960
|
+
AND status NOT IN ('completed', 'error', 'aborted')
|
|
961
|
+
`;
|
|
962
|
+
}
|
|
963
|
+
async inspectAgentToolRun(runId) {
|
|
964
|
+
const row = this._readAgentToolChildRun(runId);
|
|
965
|
+
return row ? this._inspectionFromChildRow(row, this.getAgentToolOutput(runId)) : null;
|
|
966
|
+
}
|
|
967
|
+
async getAgentToolChunks(runId, options) {
|
|
968
|
+
const row = this._readAgentToolChildRun(runId);
|
|
969
|
+
if (!row?.stream_id) return [];
|
|
970
|
+
this._resumableStream.flushBuffer();
|
|
971
|
+
return this._resumableStream.getStreamChunks(row.stream_id).filter((chunk) => chunk.chunk_index > (options?.afterSequence ?? -1)).map((chunk) => ({
|
|
972
|
+
sequence: chunk.chunk_index,
|
|
973
|
+
body: chunk.body
|
|
974
|
+
}));
|
|
975
|
+
}
|
|
976
|
+
async tailAgentToolRun(runId, options) {
|
|
977
|
+
const self = this;
|
|
978
|
+
return new ReadableStream({
|
|
979
|
+
async start(controller) {
|
|
980
|
+
const replayed = await self.getAgentToolChunks(runId, options);
|
|
981
|
+
for (const chunk of replayed) controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
|
|
982
|
+
const lastReplay = replayed[replayed.length - 1]?.sequence;
|
|
983
|
+
if (lastReplay !== void 0) self._agentToolLiveSequences.set(runId, lastReplay + 1);
|
|
984
|
+
const row = self._readAgentToolChildRun(runId);
|
|
985
|
+
if (!row || row.completed_at !== null) {
|
|
986
|
+
controller.close();
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
989
|
+
const forward = (chunk) => {
|
|
990
|
+
if (chunk.sequence > (options?.afterSequence ?? -1)) controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
|
|
991
|
+
};
|
|
992
|
+
const close = () => {
|
|
993
|
+
try {
|
|
994
|
+
controller.close();
|
|
995
|
+
} catch {}
|
|
996
|
+
};
|
|
997
|
+
const forwarders = self._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
|
|
998
|
+
forwarders.add(forward);
|
|
999
|
+
self._agentToolForwarders.set(runId, forwarders);
|
|
1000
|
+
const closers = self._agentToolClosers.get(runId) ?? /* @__PURE__ */ new Set();
|
|
1001
|
+
closers.add(close);
|
|
1002
|
+
self._agentToolClosers.set(runId, closers);
|
|
1003
|
+
},
|
|
1004
|
+
cancel(reason) {
|
|
1005
|
+
self.cancelAgentToolRun(runId, reason);
|
|
1006
|
+
}
|
|
1007
|
+
});
|
|
1008
|
+
}
|
|
1009
|
+
_getAgentToolFinalText(runId) {
|
|
1010
|
+
const before = this._agentToolPreTurnAssistantIds.get(runId);
|
|
1011
|
+
if (!before) return null;
|
|
1012
|
+
for (const msg of this.messages) {
|
|
1013
|
+
if (msg.role !== "assistant" || before.has(msg.id)) continue;
|
|
1014
|
+
const text = msg.parts.map((part) => part.type === "text" ? part.text : "").filter((part) => part.length > 0).join("\n");
|
|
1015
|
+
if (text.length > 0) return text;
|
|
1016
|
+
}
|
|
1017
|
+
return null;
|
|
1018
|
+
}
|
|
813
1019
|
/**
|
|
814
1020
|
* Inject messages and trigger a model turn — without a WebSocket request.
|
|
815
1021
|
*
|
|
@@ -820,6 +1026,13 @@ var Think = class Think extends Agent {
|
|
|
820
1026
|
* current state (useful when multiple calls queue up — the callback runs
|
|
821
1027
|
* with the latest messages when the turn actually starts).
|
|
822
1028
|
*
|
|
1029
|
+
* Pass `options.signal` to cancel the turn from outside without knowing
|
|
1030
|
+
* the internally-generated request id. The signal is linked to the
|
|
1031
|
+
* registry's controller for this turn — when it aborts, the inference
|
|
1032
|
+
* loop's signal aborts and the result reports `status: "aborted"`.
|
|
1033
|
+
* Pre-aborted signals short-circuit before any model work runs. See
|
|
1034
|
+
* {@link SaveMessagesOptions} for the integration point.
|
|
1035
|
+
*
|
|
823
1036
|
* @example Scheduled follow-up
|
|
824
1037
|
* ```typescript
|
|
825
1038
|
* async onScheduled() {
|
|
@@ -838,13 +1051,21 @@ var Think = class Think extends Agent {
|
|
|
838
1051
|
* { id: crypto.randomUUID(), role: "user", parts: [{ type: "text", text: "Continue." }] }
|
|
839
1052
|
* ]);
|
|
840
1053
|
* ```
|
|
1054
|
+
*
|
|
1055
|
+
* @example External cancellation (helper-as-sub-agent)
|
|
1056
|
+
* ```typescript
|
|
1057
|
+
* // Inside a parent agent's tool execute — forward the AI SDK's
|
|
1058
|
+
* // abortSignal so a parent stop / tab close cancels the helper.
|
|
1059
|
+
* await helper.saveMessages([userMsg], { signal: abortSignal });
|
|
1060
|
+
* ```
|
|
841
1061
|
*/
|
|
842
|
-
async saveMessages(messages) {
|
|
1062
|
+
async saveMessages(messages, options) {
|
|
843
1063
|
const requestId = crypto.randomUUID();
|
|
844
1064
|
const clientTools = this._lastClientTools;
|
|
845
1065
|
const body = this._lastBody;
|
|
846
1066
|
const epoch = this._turnQueue.generation;
|
|
847
1067
|
let status = "completed";
|
|
1068
|
+
let wasAborted = false;
|
|
848
1069
|
await this.keepAliveWhile(async () => {
|
|
849
1070
|
await this._turnQueue.enqueue(requestId, async () => {
|
|
850
1071
|
const resolved = typeof messages === "function" ? await messages(this.messages) : messages;
|
|
@@ -859,6 +1080,7 @@ var Think = class Think extends Agent {
|
|
|
859
1080
|
return;
|
|
860
1081
|
}
|
|
861
1082
|
const abortSignal = this._aborts.getSignal(requestId);
|
|
1083
|
+
const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
|
|
862
1084
|
try {
|
|
863
1085
|
const programmaticBody = async () => {
|
|
864
1086
|
const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
@@ -879,11 +1101,14 @@ var Think = class Think extends Agent {
|
|
|
879
1101
|
});
|
|
880
1102
|
else await programmaticBody();
|
|
881
1103
|
} finally {
|
|
1104
|
+
if (abortSignal?.aborted) wasAborted = true;
|
|
1105
|
+
detachExternal();
|
|
882
1106
|
this._aborts.remove(requestId);
|
|
883
1107
|
}
|
|
884
1108
|
});
|
|
885
1109
|
});
|
|
886
1110
|
if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
|
|
1111
|
+
else if (wasAborted && status === "completed") status = "aborted";
|
|
887
1112
|
return {
|
|
888
1113
|
requestId,
|
|
889
1114
|
status
|
|
@@ -902,8 +1127,11 @@ var Think = class Think extends Agent {
|
|
|
902
1127
|
*
|
|
903
1128
|
* Returns early with `status: "skipped"` if there is no assistant message
|
|
904
1129
|
* to continue from.
|
|
1130
|
+
*
|
|
1131
|
+
* Pass `options.signal` to cancel the continuation from outside —
|
|
1132
|
+
* matches the {@link saveMessages} contract.
|
|
905
1133
|
*/
|
|
906
|
-
async continueLastTurn(body) {
|
|
1134
|
+
async continueLastTurn(body, options) {
|
|
907
1135
|
const lastLeaf = this.session.getLatestLeaf();
|
|
908
1136
|
if (!lastLeaf || lastLeaf.role !== "assistant") return {
|
|
909
1137
|
requestId: "",
|
|
@@ -914,6 +1142,7 @@ var Think = class Think extends Agent {
|
|
|
914
1142
|
const resolvedBody = body ?? this._lastBody;
|
|
915
1143
|
const epoch = this._turnQueue.generation;
|
|
916
1144
|
let status = "completed";
|
|
1145
|
+
let wasAborted = false;
|
|
917
1146
|
await this.keepAliveWhile(async () => {
|
|
918
1147
|
await this._turnQueue.enqueue(requestId, async () => {
|
|
919
1148
|
if (this._turnQueue.generation !== epoch) {
|
|
@@ -921,6 +1150,7 @@ var Think = class Think extends Agent {
|
|
|
921
1150
|
return;
|
|
922
1151
|
}
|
|
923
1152
|
const abortSignal = this._aborts.getSignal(requestId);
|
|
1153
|
+
const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
|
|
924
1154
|
try {
|
|
925
1155
|
const continueTurnBody = async () => {
|
|
926
1156
|
const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
@@ -941,11 +1171,14 @@ var Think = class Think extends Agent {
|
|
|
941
1171
|
});
|
|
942
1172
|
else await continueTurnBody();
|
|
943
1173
|
} finally {
|
|
1174
|
+
if (abortSignal?.aborted) wasAborted = true;
|
|
1175
|
+
detachExternal();
|
|
944
1176
|
this._aborts.remove(requestId);
|
|
945
1177
|
}
|
|
946
1178
|
});
|
|
947
1179
|
});
|
|
948
1180
|
if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
|
|
1181
|
+
else if (wasAborted && status === "completed") status = "aborted";
|
|
949
1182
|
return {
|
|
950
1183
|
requestId,
|
|
951
1184
|
status
|
|
@@ -1193,6 +1426,46 @@ var Think = class Think extends Agent {
|
|
|
1193
1426
|
this._continuation.sendResumeNone();
|
|
1194
1427
|
this._continuation.clearAll();
|
|
1195
1428
|
}
|
|
1429
|
+
/**
|
|
1430
|
+
* Abort a single in-flight chat turn by request id.
|
|
1431
|
+
*
|
|
1432
|
+
* Equivalent to the cancel path that fires when a client sends a
|
|
1433
|
+
* `chat-request-cancel` WebSocket message — the inference loop's
|
|
1434
|
+
* signal aborts, partial chunks already streamed are still
|
|
1435
|
+
* persisted, and the turn's `ChatResponseResult` reports
|
|
1436
|
+
* `status: "aborted"`.
|
|
1437
|
+
*
|
|
1438
|
+
* No-op if no controller exists for `requestId` (the turn already
|
|
1439
|
+
* completed, was never started, or used a different id).
|
|
1440
|
+
*
|
|
1441
|
+
* Most callers don't have the request id and want
|
|
1442
|
+
* {@link abortAllRequests} instead. This method is here for
|
|
1443
|
+
* symmetry with the WebSocket cancel surface and for callers that
|
|
1444
|
+
* happen to know the id (e.g. via a stash from an earlier
|
|
1445
|
+
* `saveMessages` return).
|
|
1446
|
+
*
|
|
1447
|
+
* Prefer {@link SaveMessagesOptions.signal} when driving a turn
|
|
1448
|
+
* programmatically — it threads the abort intent in from the start
|
|
1449
|
+
* without requiring the caller to know the id.
|
|
1450
|
+
*/
|
|
1451
|
+
abortRequest(requestId, reason) {
|
|
1452
|
+
this._aborts.cancel(requestId, reason);
|
|
1453
|
+
}
|
|
1454
|
+
/**
|
|
1455
|
+
* Abort every in-flight chat turn on this agent.
|
|
1456
|
+
*
|
|
1457
|
+
* Aborts all controllers in the registry and clears it. Used by
|
|
1458
|
+
* subclasses that drive single-purpose turns (e.g. a sub-agent
|
|
1459
|
+
* helper that runs one turn at a time over RPC) and want a coarse
|
|
1460
|
+
* "cancel whatever is running" handle without tracking request ids.
|
|
1461
|
+
*
|
|
1462
|
+
* Does NOT reset queued turns, continuation timers, or submit
|
|
1463
|
+
* concurrency state — use {@link resetTurnState} for the full
|
|
1464
|
+
* teardown that runs on `chat-clear`.
|
|
1465
|
+
*/
|
|
1466
|
+
abortAllRequests() {
|
|
1467
|
+
this._aborts.destroyAll();
|
|
1468
|
+
}
|
|
1196
1469
|
_handleClear(connection) {
|
|
1197
1470
|
this.resetTurnState();
|
|
1198
1471
|
this._resumableStream.clearAll();
|