@cloudflare/think 0.13.0 → 0.15.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 +39 -21
- package/dist/cli/index.js +1 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/extensions/index.d.ts +100 -8
- package/dist/{hook-proxy-CkF0EhRO.js → hook-proxy-Dogs9wbj.js} +3 -3
- package/dist/{hook-proxy-CkF0EhRO.js.map → hook-proxy-Dogs9wbj.js.map} +1 -1
- package/dist/{index-Cm0jriTY.d.ts → index-s3Pl812H.d.ts} +82 -21
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/studio/assets/{angular-html--XgCyfPu.js → angular-html-B26lsrRw.js} +1 -1
- package/dist/studio/assets/{angular-ts-Dt-feQIe.js → angular-ts-B0BTTyHo.js} +1 -1
- package/dist/studio/assets/{apl-B7ymkyp4.js → apl-W5hJk0fj.js} +1 -1
- package/dist/studio/assets/{astro-Ce5cw2JI.js → astro-ChkXCqsA.js} +1 -1
- package/dist/studio/assets/{blade-DL-aXwjv.js → blade-Dy0zTtr6.js} +1 -1
- package/dist/studio/assets/{c-CFfr09UF.js → c-DOHYbsuN.js} +1 -1
- package/dist/studio/assets/{cobol-Ba1f5ZqR.js → cobol-DtGo7U_-.js} +1 -1
- package/dist/studio/assets/{coffee-BG2_viYI.js → coffee-Uf9fkZqI.js} +1 -1
- package/dist/studio/assets/{cpp-pU5HgBva.js → cpp-CVwmol0l.js} +1 -1
- package/dist/studio/assets/{crystal-Dlm_uR4r.js → crystal-ChHObCtF.js} +1 -1
- package/dist/studio/assets/{css-tUC4TMTn.js → css-DYjZAj5w.js} +1 -1
- package/dist/studio/assets/{edge-CQuSKMUt.js → edge-C2J43zbu.js} +1 -1
- package/dist/studio/assets/{elixir-BmIB-Wi1.js → elixir-B7WZ8XhB.js} +1 -1
- package/dist/studio/assets/{elm-ByVNCtDB.js → elm-PN4qGuR2.js} +1 -1
- package/dist/studio/assets/{erb-DO4uDxTq.js → erb-CkbjE2OZ.js} +1 -1
- package/dist/studio/assets/{git-rebase-CT8LXapC.js → git-rebase-CsGmQhFO.js} +1 -1
- package/dist/studio/assets/{glimmer-js-DzIT0v-m.js → glimmer-js-D85-ZYXa.js} +1 -1
- package/dist/studio/assets/{glimmer-ts-znG2j9R4.js → glimmer-ts-B_0SLVPe.js} +1 -1
- package/dist/studio/assets/{glsl-C1p8U_gW.js → glsl-BE5n0T0t.js} +1 -1
- package/dist/studio/assets/{graphql-CFqegryf.js → graphql-BVcCJEBO.js} +1 -1
- package/dist/studio/assets/{hack-BfVsNhqs.js → hack-CyUu15_C.js} +1 -1
- package/dist/studio/assets/{haml-DVcEksY5.js → haml-Dj54pugT.js} +1 -1
- package/dist/studio/assets/{handlebars-DSWgWCJ4.js → handlebars-l3llPaCT.js} +1 -1
- package/dist/studio/assets/{highlighted-body-OFNGDK62-BIm4UpTS.js → highlighted-body-OFNGDK62-D_z62he-.js} +1 -1
- package/dist/studio/assets/{html-C-lP7-T4.js → html--Tmh4628.js} +1 -1
- package/dist/studio/assets/{html-derivative-ByukJopb.js → html-derivative-B0Q_m8BM.js} +1 -1
- package/dist/studio/assets/{http-Bax2fYIk.js → http-BXKW9YQL.js} +1 -1
- package/dist/studio/assets/{hurl-BrI2qfvy.js → hurl-C60QjgUE.js} +1 -1
- package/dist/studio/assets/index-Cd4PgOFu.js +390 -0
- package/dist/studio/assets/{java-ZiR-uym-.js → java-aXeLcVht.js} +1 -1
- package/dist/studio/assets/{javascript-Dhhw85Vr.js → javascript-BQcRH4fE.js} +1 -1
- package/dist/studio/assets/{jinja-DqSGkgE4.js → jinja-DGNUkEt-.js} +1 -1
- package/dist/studio/assets/{jison-CwQ0BO-q.js → jison-DwfSvoKv.js} +1 -1
- package/dist/studio/assets/{json-Je3YfUTE.js → json-B0ukOVyl.js} +1 -1
- package/dist/studio/assets/{jsx-Da-dLbW1.js → jsx-CzJUnsSO.js} +1 -1
- package/dist/studio/assets/{julia-CBJ0H-0z.js → julia-D8zt_FEP.js} +1 -1
- package/dist/studio/assets/{just-CnuRC_nd.js → just-nn4e9Gpd.js} +1 -1
- package/dist/studio/assets/{latex-gZANCito.js → latex-OBwqlec5.js} +1 -1
- package/dist/studio/assets/{liquid-0U9aXoFI.js → liquid-CktG-Iuw.js} +1 -1
- package/dist/studio/assets/{lua-CX_TqMxt.js → lua-ZqavSetL.js} +1 -1
- package/dist/studio/assets/{marko-StSURz0o.js → marko-CxDLRfNz.js} +1 -1
- package/dist/studio/assets/{mdc-CXZpf9k1.js → mdc-COZbBQqS.js} +1 -1
- package/dist/studio/assets/mermaid-GHXKKRXX-ChY6AJ7l.js +1 -0
- package/dist/studio/assets/{nginx-3Q2L4366.js → nginx-DB8A8-iZ.js} +1 -1
- package/dist/studio/assets/{nim-CqX_5eXP.js → nim-Cs5VB9QZ.js} +1 -1
- package/dist/studio/assets/{perl-CLOu1GnZ.js → perl-pV-3Dli_.js} +1 -1
- package/dist/studio/assets/{php-C1vkiu4h.js → php-CFSq0mhc.js} +1 -1
- package/dist/studio/assets/{pug-Cg3cFp5y.js → pug-DuCfu-AK.js} +1 -1
- package/dist/studio/assets/{qml-DhKeHMwt.js → qml-Gqte1OeW.js} +1 -1
- package/dist/studio/assets/{r--Lg2-Sir.js → r-B8XqafmU.js} +1 -1
- package/dist/studio/assets/{razor-Cjptf146.js → razor-HyK7qWun.js} +1 -1
- package/dist/studio/assets/{regexp-fS0DAwei.js → regexp-Bdipf9Ks.js} +1 -1
- package/dist/studio/assets/{rst-BBajBzk-.js → rst-DtdOQB-0.js} +1 -1
- package/dist/studio/assets/{ruby-KvFedogM.js → ruby-DOExsDws.js} +1 -1
- package/dist/studio/assets/{sas-D6p27LWr.js → sas-BLRRJVWF.js} +1 -1
- package/dist/studio/assets/{scss-6jXfJVsd.js → scss-BILH_sWZ.js} +1 -1
- package/dist/studio/assets/{shellscript-BK0Qbt1B.js → shellscript-CC2KTOv4.js} +1 -1
- package/dist/studio/assets/{shellsession-BsXmVRU4.js → shellsession-CiGs-_qT.js} +1 -1
- package/dist/studio/assets/{soy-BKtGCXkJ.js → soy-QSSlYQhf.js} +1 -1
- package/dist/studio/assets/{sql-vSUKslBj.js → sql-CPD_IP3i.js} +1 -1
- package/dist/studio/assets/{stata-BQ0iXcs9.js → stata-jhUDP248.js} +1 -1
- package/dist/studio/assets/{surrealql-v5pXHIwP.js → surrealql-CEI1vHaO.js} +1 -1
- package/dist/studio/assets/{svelte-BMFjqgJb.js → svelte-BqMghnvQ.js} +1 -1
- package/dist/studio/assets/{templ-DYMTOmIJ.js → templ-DhMt3Gd_.js} +1 -1
- package/dist/studio/assets/{tex-BoQem9gj.js → tex-B2oLGu4M.js} +1 -1
- package/dist/studio/assets/{ts-tags-Kp2pAlsd.js → ts-tags-DbXbAuWo.js} +1 -1
- package/dist/studio/assets/{tsx-DaB2J5uo.js → tsx-BWdjt-eB.js} +1 -1
- package/dist/studio/assets/{twig-DohCGJPH.js → twig-b7sZE9-Z.js} +1 -1
- package/dist/studio/assets/{typescript-BGG-5I-T.js → typescript-B5gQukXY.js} +1 -1
- package/dist/studio/assets/{vue-CCDLUl9R.js → vue-DGv3yRD9.js} +1 -1
- package/dist/studio/assets/{vue-html-et9GYlaF.js → vue-html-Cx5Ph-Io.js} +1 -1
- package/dist/studio/assets/{vue-vine-C561z6bx.js → vue-vine-G05O51ag.js} +1 -1
- package/dist/studio/assets/{xml-CJBA1ZPm.js → xml-Bd8eSLdt.js} +1 -1
- package/dist/studio/assets/{xsl-De-lf9XG.js → xsl-DVLXYJQL.js} +1 -1
- package/dist/studio/assets/{yaml-BcMKxf75.js → yaml-CO0sPwby.js} +1 -1
- package/dist/studio/index.html +1 -1
- package/dist/think.d.ts +2 -2
- package/dist/think.js +419 -123
- package/dist/think.js.map +1 -1
- package/dist/tools/execute.d.ts +1 -1
- package/dist/tools/extensions.d.ts +4 -37
- package/dist/tools/extensions.js.map +1 -1
- package/dist/tools/workspace.d.ts +1 -1
- package/dist/tools/workspace.js +1 -13
- package/dist/tools/workspace.js.map +1 -1
- package/dist/workflows.d.ts +1 -1
- package/dist/{workspace-BZXdZcuw.d.ts → workspace-DxZQSbko.d.ts} +10 -157
- package/docs/index.md +16 -0
- package/docs/tools.md +19 -2
- package/package.json +13 -13
- package/dist/index-B-zgBVj2.d.ts +0 -109
- package/dist/studio/assets/index-DNSTOyBe.js +0 -390
- package/dist/studio/assets/mermaid-GHXKKRXX-CqDQH2-r.js +0 -1
package/dist/think.js
CHANGED
|
@@ -4,7 +4,9 @@ import { createFetchTools } from "./tools/fetch.js";
|
|
|
4
4
|
import { truncatePausedExecutionOutput } from "./tools/execute.js";
|
|
5
5
|
import { t as ThinkMessengerRuntime } from "./chat-sdk-iuBa-CGM.js";
|
|
6
6
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
7
|
-
import
|
|
7
|
+
import * as aiSdk from "ai";
|
|
8
|
+
import { convertToModelMessages, hasToolCall, jsonSchema, stepCountIs, streamText, tool, wrapLanguageModel } from "ai";
|
|
9
|
+
import { createAISDKTelemetry, wrapAISDK } from "agents/observability/ai";
|
|
8
10
|
import { createWorkersAI } from "workers-ai-provider";
|
|
9
11
|
import { anthropic } from "workers-ai-provider/anthropic";
|
|
10
12
|
import { openai } from "workers-ai-provider/openai";
|
|
@@ -224,7 +226,7 @@ function resolveChannels(configured, messengers) {
|
|
|
224
226
|
* Configuration overrides:
|
|
225
227
|
* - getModel() — return a model id string (resolved via the
|
|
226
228
|
* built-in workers-ai-provider) or a LanguageModel
|
|
227
|
-
* - getSystemPrompt() — return the
|
|
229
|
+
* - getSystemPrompt() — return the legacy fallback system prompt
|
|
228
230
|
* - getTools() — return the ToolSet for the agentic loop
|
|
229
231
|
* - maxSteps — max tool-call rounds per turn (default: 10)
|
|
230
232
|
* - configureSession() — add context blocks, compaction, search, skills
|
|
@@ -295,6 +297,8 @@ function resolveChannels(configured, messengers) {
|
|
|
295
297
|
* ```
|
|
296
298
|
*/
|
|
297
299
|
const agentToolChunkEncoder = new TextEncoder();
|
|
300
|
+
const agentsAISDKTelemetryBrand = Symbol.for("cloudflare.agents.ai-sdk-telemetry");
|
|
301
|
+
const usesAISDKV7Telemetry = "registerTelemetry" in aiSdk;
|
|
298
302
|
/**
|
|
299
303
|
* The recent-message span the model sees at FULL fidelity each turn —
|
|
300
304
|
* `truncateOlderMessages`' default `keepRecent` (see `_assembleModelMessages`).
|
|
@@ -317,6 +321,9 @@ const ACTION_PENDING_SWEEP_INTERVAL_MS = 3600 * 1e3;
|
|
|
317
321
|
const ACTION_PENDING_LAST_SWEPT_KEY = "cf_think_action_pending_approvals:last_swept_at";
|
|
318
322
|
/** Prefix for durable-pause action execution ids (vs codemode execution ids). */
|
|
319
323
|
const ACTION_PAUSE_ID_PREFIX = "actpause_";
|
|
324
|
+
function withAgentSpan(host, operation, storagePhase, attributes, run) {
|
|
325
|
+
return host._withAgentSpan(operation, storagePhase, attributes, run);
|
|
326
|
+
}
|
|
320
327
|
const MSG_CHAT_MESSAGES = CHAT_MESSAGE_TYPES.CHAT_MESSAGES;
|
|
321
328
|
const MSG_CHAT_RESPONSE = CHAT_MESSAGE_TYPES.USE_CHAT_RESPONSE;
|
|
322
329
|
const MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;
|
|
@@ -378,6 +385,58 @@ function streamErrorToString(error) {
|
|
|
378
385
|
return String(error);
|
|
379
386
|
}
|
|
380
387
|
}
|
|
388
|
+
/**
|
|
389
|
+
* Normalizes the AI SDK tool-execution-finished event across major versions.
|
|
390
|
+
*
|
|
391
|
+
* Think registers a single `experimental_onToolCallFinish` callback, which is
|
|
392
|
+
* the native option in AI SDK v6 and a supported alias for `onToolExecutionEnd`
|
|
393
|
+
* in AI SDK v7 (resolved internally — see `ai`'s `streamText`). The two majors
|
|
394
|
+
* hand the callback different event shapes:
|
|
395
|
+
*
|
|
396
|
+
* - v6: `{ toolCall, messages, success, output, error, durationMs, stepNumber }`
|
|
397
|
+
* - v7: `{ toolCall, messages, toolExecutionMs, toolOutput: { type, output|error } }`
|
|
398
|
+
* (no `stepNumber`)
|
|
399
|
+
*
|
|
400
|
+
* This collapses both into one shape so the rest of Think stays version-agnostic.
|
|
401
|
+
*/
|
|
402
|
+
function normalizeToolFinishEvent(event) {
|
|
403
|
+
const e = event;
|
|
404
|
+
const toolExecutionMs = e.toolExecutionMs ?? e.durationMs ?? 0;
|
|
405
|
+
if (e.toolOutput) {
|
|
406
|
+
const success = e.toolOutput.type === "tool-result";
|
|
407
|
+
return {
|
|
408
|
+
toolCall: e.toolCall,
|
|
409
|
+
messages: e.messages,
|
|
410
|
+
toolExecutionMs,
|
|
411
|
+
stepNumber: void 0,
|
|
412
|
+
success,
|
|
413
|
+
output: success ? e.toolOutput.output : void 0,
|
|
414
|
+
error: success ? void 0 : e.toolOutput.error
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
const success = e.success ?? false;
|
|
418
|
+
return {
|
|
419
|
+
toolCall: e.toolCall,
|
|
420
|
+
messages: e.messages,
|
|
421
|
+
toolExecutionMs,
|
|
422
|
+
stepNumber: e.stepNumber,
|
|
423
|
+
success,
|
|
424
|
+
output: success ? e.output : void 0,
|
|
425
|
+
error: success ? void 0 : e.error
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
async function* readableStreamToAsyncIterable(stream) {
|
|
429
|
+
const reader = stream.getReader();
|
|
430
|
+
try {
|
|
431
|
+
while (true) {
|
|
432
|
+
const next = await reader.read();
|
|
433
|
+
if (next.done) return;
|
|
434
|
+
yield next.value;
|
|
435
|
+
}
|
|
436
|
+
} finally {
|
|
437
|
+
reader.releaseLock();
|
|
438
|
+
}
|
|
439
|
+
}
|
|
381
440
|
function actionAuthorizationErrorEnvelope(reason, permissions) {
|
|
382
441
|
return { error: {
|
|
383
442
|
name: "ActionAuthorizationError",
|
|
@@ -738,6 +797,7 @@ function isAction(value) {
|
|
|
738
797
|
return typeof value === "object" && value !== null && value[ACTION_BRAND] === true;
|
|
739
798
|
}
|
|
740
799
|
const admittedTurnContext = new AsyncLocalStorage();
|
|
800
|
+
const inferenceStreamFinalizers = /* @__PURE__ */ new WeakMap();
|
|
741
801
|
const THINK_WORKFLOW_PROMPT_METADATA_KEY = "__thinkWorkflowPrompt";
|
|
742
802
|
/**
|
|
743
803
|
* Message-metadata keys that are server-written turn context (stamped by
|
|
@@ -847,7 +907,10 @@ var Think = class Think extends Agent {
|
|
|
847
907
|
}
|
|
848
908
|
constructor(ctx, env) {
|
|
849
909
|
super(ctx, env);
|
|
910
|
+
this.includeMcpTools = true;
|
|
850
911
|
this.waitForMcpConnections = false;
|
|
912
|
+
this.storeMessages = false;
|
|
913
|
+
this.storeTools = false;
|
|
851
914
|
this._skillRegistry = null;
|
|
852
915
|
this._loggedSkillWarnings = /* @__PURE__ */ new Set();
|
|
853
916
|
this._loggedProtocolWarnings = /* @__PURE__ */ new Set();
|
|
@@ -931,54 +994,67 @@ var Think = class Think extends Agent {
|
|
|
931
994
|
this._streamProgressCredit = new StreamProgressCreditThrottle();
|
|
932
995
|
this._agentToolStreamProgress = new AgentToolStreamProgressThrottle();
|
|
933
996
|
const _onStart = this.onStart.bind(this);
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
997
|
+
const startThink = async (props, update) => {
|
|
998
|
+
await withAgentSpan(this, "initialize_think_session", "startup", { "cloudflare.agents.component": "think" }, async () => {
|
|
999
|
+
if (!this.workspace) this.workspace = new Workspace$1({
|
|
1000
|
+
sql: this.ctx.storage.sql,
|
|
1001
|
+
name: () => this.name
|
|
1002
|
+
});
|
|
1003
|
+
const baseSession = Session$1.create(this);
|
|
1004
|
+
this.session = await this.configureSession(baseSession);
|
|
1005
|
+
this.session.internal_onMessagesChanged(async (event) => {
|
|
1006
|
+
switch (event.type) {
|
|
1007
|
+
case "append":
|
|
1008
|
+
if (!event.inserted || event.parentId !== void 0) await this._syncMessages();
|
|
1009
|
+
else this._upsertCachedMessage(event.message);
|
|
1010
|
+
this._scheduleMediaEvictionAfterAppend(event.message);
|
|
1011
|
+
break;
|
|
1012
|
+
case "update":
|
|
1013
|
+
this._patchCachedMessage(event.message);
|
|
1014
|
+
break;
|
|
1015
|
+
case "clear":
|
|
1016
|
+
this._replaceCachedMessages([]);
|
|
1017
|
+
break;
|
|
1018
|
+
case "delete":
|
|
1019
|
+
case "compact":
|
|
1020
|
+
await this._syncMessages();
|
|
1021
|
+
break;
|
|
1022
|
+
}
|
|
1023
|
+
});
|
|
1024
|
+
await this._initializeSkills();
|
|
959
1025
|
});
|
|
960
|
-
await this._initializeSkills();
|
|
961
1026
|
this._onStartDegradations = [];
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
this.
|
|
967
|
-
this.
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
1027
|
+
await withAgentSpan(this, "hydrate_think_session", "startup", { "cloudflare.agents.component": "think" }, async () => {
|
|
1028
|
+
if (!await this._runBestEffortOnStartStep("transcript-hydration", () => this._syncMessages(), "The agent is starting with an empty in-memory message view; persisted history is untouched. If the error is SQLITE_NOMEM, the stored transcript is too large to hydrate (often inline base64 media in tool results) — compact or clear the session to recover.")) this._replaceCachedMessages([]);
|
|
1029
|
+
this._refreshMediaEvictionSignalFromCache();
|
|
1030
|
+
});
|
|
1031
|
+
if (this.extensionLoader) await withAgentSpan(this, "initialize_think_extensions", "startup", { "cloudflare.agents.component": "think" }, () => this._initializeExtensions());
|
|
1032
|
+
await withAgentSpan(this, "initialize_think_chat", "startup", { "cloudflare.agents.component": "think" }, async () => {
|
|
1033
|
+
this._resumableStream = new ResumableStream(this.sql.bind(this));
|
|
1034
|
+
this._restoreClientTools();
|
|
1035
|
+
this._restoreBody();
|
|
1036
|
+
this._setupProtocolHandlers();
|
|
1037
|
+
await this._initializeChannels();
|
|
1038
|
+
});
|
|
1039
|
+
await _onStart(props);
|
|
1040
|
+
await withAgentSpan(this, "reconcile_think_schedules", "startup", { "cloudflare.agents.component": "think" }, () => this._runBestEffortOnStartStep("scheduled-task-reconcile", () => this._reconcileDeclaredScheduledTasks(), "Declared scheduled tasks were not reconciled on this wake; the next successful wake will reconcile them."));
|
|
1041
|
+
await withAgentSpan(this, "recover_think_durable_work", "startup", { "cloudflare.agents.component": "think" }, () => this._runBestEffortOnStartStep("durable-work-recovery", async () => {
|
|
973
1042
|
await this._sweepActionLedger();
|
|
974
1043
|
await this._sweepActionPendingApprovals();
|
|
975
1044
|
await this._recoverSubmissionsOnStart();
|
|
976
1045
|
this._recoverWorkflowNotifications();
|
|
977
|
-
if (this._hasPendingSubmissions()) this.
|
|
1046
|
+
if (this._hasPendingSubmissions()) await this._scheduleSubmissionDrain();
|
|
978
1047
|
if (this._hasPendingWorkflowNotifications()) this._startWorkflowNotificationDrain();
|
|
979
|
-
}, "Pending submissions / workflow notifications were not recovered on this wake; the next successful wake will recover them.");
|
|
1048
|
+
}, "Pending submissions / workflow notifications were not recovered on this wake; the next successful wake will recover them."));
|
|
980
1049
|
if (this._lastHydration?.truncated) this._scheduleMediaEvictionPass({ force: true });
|
|
1050
|
+
update({
|
|
1051
|
+
"cloudflare.agents.hydration.messages": this._lastHydration?.hydratedMessages,
|
|
1052
|
+
"cloudflare.agents.hydration.content_bytes": this._lastHydration?.totalContentBytes,
|
|
1053
|
+
"cloudflare.agents.hydration.truncated": this._lastHydration?.truncated,
|
|
1054
|
+
"cloudflare.agents.start.degradations": this._onStartDegradations.length
|
|
1055
|
+
});
|
|
981
1056
|
};
|
|
1057
|
+
this.onStart = (props) => withAgentSpan(this, "think_start", "startup", { "cloudflare.agents.component": "think" }, (update) => startThink(props, update));
|
|
982
1058
|
}
|
|
983
1059
|
/**
|
|
984
1060
|
* Conversation history as Think's live in-memory view.
|
|
@@ -1595,8 +1671,10 @@ var Think = class Think extends Agent {
|
|
|
1595
1671
|
return model.startsWith("@cf/") ? this._defaultProvider(model, { sessionAffinity: this.sessionAffinity }) : this._defaultProvider(model);
|
|
1596
1672
|
}
|
|
1597
1673
|
/**
|
|
1598
|
-
* Return the system prompt for the assistant.
|
|
1599
|
-
*
|
|
1674
|
+
* Return the fallback system prompt for the assistant.
|
|
1675
|
+
* Ignored when Session context blocks are configured. Use
|
|
1676
|
+
* `configureSession().withContext()` for always-on instructions that should
|
|
1677
|
+
* coexist with context blocks or skills.
|
|
1600
1678
|
*/
|
|
1601
1679
|
getSystemPrompt() {
|
|
1602
1680
|
return [
|
|
@@ -1953,6 +2031,13 @@ var Think = class Think extends Agent {
|
|
|
1953
2031
|
try {
|
|
1954
2032
|
const sources = await this.getSkills();
|
|
1955
2033
|
if (sources.length === 0) return;
|
|
2034
|
+
if (this.getSystemPrompt !== Think.prototype.getSystemPrompt) {
|
|
2035
|
+
const warning = "getSystemPrompt() is only used as a fallback when no Session context blocks are configured. getSkills() registers a skills context block, so move always-on instructions into configureSession().withContext(...) instead.";
|
|
2036
|
+
if (!this._loggedSkillWarnings.has(warning)) {
|
|
2037
|
+
this._loggedSkillWarnings.add(warning);
|
|
2038
|
+
console.warn(`[think] ${warning}`);
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
1956
2041
|
const registry = new SkillRegistry(sources, this.getSkillScriptRunner());
|
|
1957
2042
|
await registry.load();
|
|
1958
2043
|
this._logSkillWarnings(registry);
|
|
@@ -2183,6 +2268,14 @@ var Think = class Think extends Agent {
|
|
|
2183
2268
|
* Called after each step completes (initial, continue, tool-result).
|
|
2184
2269
|
* Override for step-level logging or analytics.
|
|
2185
2270
|
*/
|
|
2271
|
+
onStepEnd(ctx) {
|
|
2272
|
+
return this.onStepFinish(ctx);
|
|
2273
|
+
}
|
|
2274
|
+
/**
|
|
2275
|
+
* Called after each step completes (initial, continue, tool-result).
|
|
2276
|
+
* Override for step-level logging or analytics.
|
|
2277
|
+
* @deprecated Prefer `onStepEnd`.
|
|
2278
|
+
*/
|
|
2186
2279
|
onStepFinish(_ctx) {}
|
|
2187
2280
|
/**
|
|
2188
2281
|
* Called for each streaming chunk. High-frequency — fires per token.
|
|
@@ -2423,11 +2516,111 @@ var Think = class Think extends Agent {
|
|
|
2423
2516
|
}
|
|
2424
2517
|
}
|
|
2425
2518
|
/**
|
|
2519
|
+
* Finalizes the traced inference stream after a drain loop exits: drains the
|
|
2520
|
+
* abandoned tee branch so the operation span closes even on early exits.
|
|
2521
|
+
* Idempotent (the finalizer is removed before it runs); the drain rides
|
|
2522
|
+
* `ctx.waitUntil` so it survives turn completion without blocking it.
|
|
2523
|
+
*/
|
|
2524
|
+
_drainInferenceStream(result) {
|
|
2525
|
+
const finalizer = inferenceStreamFinalizers.get(result);
|
|
2526
|
+
inferenceStreamFinalizers.delete(result);
|
|
2527
|
+
if (!finalizer || finalizer.started) return;
|
|
2528
|
+
finalizer.started = true;
|
|
2529
|
+
const completion = finalizer.run();
|
|
2530
|
+
try {
|
|
2531
|
+
this.ctx.waitUntil(completion);
|
|
2532
|
+
} catch {}
|
|
2533
|
+
}
|
|
2534
|
+
/**
|
|
2535
|
+
* Adds default identity and current-turn metadata to the AI SDK telemetry
|
|
2536
|
+
* options. The class identifies the logical agent implementation, the named
|
|
2537
|
+
* instance identifies the agent resource, and the opaque Durable Object id
|
|
2538
|
+
* identifies its one persisted conversation. Caller values override defaults.
|
|
2539
|
+
*/
|
|
2540
|
+
_turnTelemetry(base) {
|
|
2541
|
+
const settings = base ?? {};
|
|
2542
|
+
const metadata = typeof settings.metadata === "object" && settings.metadata !== null ? settings.metadata : {};
|
|
2543
|
+
const turn = admittedTurnContext.getStore();
|
|
2544
|
+
return {
|
|
2545
|
+
...settings,
|
|
2546
|
+
functionId: typeof settings.functionId === "string" ? settings.functionId : this.constructor.name,
|
|
2547
|
+
metadata: {
|
|
2548
|
+
agentId: this.name,
|
|
2549
|
+
conversationId: this.ctx.id.toString(),
|
|
2550
|
+
...turn?.agent === this ? {
|
|
2551
|
+
"cloudflare.agents.turn.request_id": turn.requestId,
|
|
2552
|
+
"cloudflare.agents.turn.trigger": turn.trigger,
|
|
2553
|
+
"cloudflare.agents.turn.admission": turn.admission,
|
|
2554
|
+
...turn.channel !== void 0 && { "cloudflare.agents.turn.channel": turn.channel },
|
|
2555
|
+
...turn.continuation !== void 0 && { "cloudflare.agents.turn.continuation": turn.continuation },
|
|
2556
|
+
...turn.generation !== void 0 && { "cloudflare.agents.turn.generation": turn.generation }
|
|
2557
|
+
} : {},
|
|
2558
|
+
...metadata
|
|
2559
|
+
}
|
|
2560
|
+
};
|
|
2561
|
+
}
|
|
2562
|
+
/** Builds the native AI SDK v7 telemetry settings and identity context. */
|
|
2563
|
+
_turnTelemetryV7(base) {
|
|
2564
|
+
const settings = base ?? {};
|
|
2565
|
+
const metadata = typeof settings.metadata === "object" && settings.metadata !== null ? settings.metadata : {};
|
|
2566
|
+
const turn = admittedTurnContext.getStore();
|
|
2567
|
+
const runtimeContext = {
|
|
2568
|
+
agentId: this.name,
|
|
2569
|
+
conversationId: this.ctx.id.toString(),
|
|
2570
|
+
...turn?.agent === this ? {
|
|
2571
|
+
"cloudflare.agents.turn.request_id": turn.requestId,
|
|
2572
|
+
"cloudflare.agents.turn.trigger": turn.trigger,
|
|
2573
|
+
"cloudflare.agents.turn.admission": turn.admission,
|
|
2574
|
+
...turn.channel !== void 0 && { "cloudflare.agents.turn.channel": turn.channel },
|
|
2575
|
+
...turn.continuation !== void 0 && { "cloudflare.agents.turn.continuation": turn.continuation },
|
|
2576
|
+
...turn.generation !== void 0 && { "cloudflare.agents.turn.generation": turn.generation }
|
|
2577
|
+
} : {},
|
|
2578
|
+
...metadata
|
|
2579
|
+
};
|
|
2580
|
+
const includedContext = typeof settings.includeRuntimeContext === "object" && settings.includeRuntimeContext !== null ? settings.includeRuntimeContext : {};
|
|
2581
|
+
const localIntegrations = settings.integrations;
|
|
2582
|
+
const globalIntegrations = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS;
|
|
2583
|
+
const integrations = [...localIntegrations !== void 0 ? Array.isArray(localIntegrations) ? localIntegrations : [localIntegrations] : globalIntegrations ?? []];
|
|
2584
|
+
if (!integrations.some((integration) => typeof integration === "object" && integration !== null && agentsAISDKTelemetryBrand in integration)) integrations.push(createAISDKTelemetry({
|
|
2585
|
+
storeMessages: this.storeMessages,
|
|
2586
|
+
storeTools: this.storeTools
|
|
2587
|
+
}));
|
|
2588
|
+
const options = {
|
|
2589
|
+
...settings,
|
|
2590
|
+
functionId: typeof settings.functionId === "string" ? settings.functionId : this.constructor.name,
|
|
2591
|
+
includeRuntimeContext: {
|
|
2592
|
+
...Object.fromEntries(Object.keys(runtimeContext).map((key) => [key, true])),
|
|
2593
|
+
...includedContext
|
|
2594
|
+
},
|
|
2595
|
+
integrations
|
|
2596
|
+
};
|
|
2597
|
+
delete options.metadata;
|
|
2598
|
+
return {
|
|
2599
|
+
options,
|
|
2600
|
+
runtimeContext
|
|
2601
|
+
};
|
|
2602
|
+
}
|
|
2603
|
+
/**
|
|
2426
2604
|
* The single convergence point for all chat turn entry paths.
|
|
2427
2605
|
* Merges tools, assembles context, fires lifecycle hooks, wraps tools
|
|
2428
2606
|
* for interception, and calls streamText.
|
|
2429
2607
|
*/
|
|
2430
2608
|
async _runInferenceLoop(input) {
|
|
2609
|
+
const turn = admittedTurnContext.getStore();
|
|
2610
|
+
return (await withAgentSpan(this, "prepare_agent", "turn", {
|
|
2611
|
+
"cloudflare.agents.component": "think",
|
|
2612
|
+
...turn?.agent === this ? {
|
|
2613
|
+
"cloudflare.agents.turn.request_id": turn.requestId,
|
|
2614
|
+
"cloudflare.agents.turn.trigger": turn.trigger,
|
|
2615
|
+
"cloudflare.agents.turn.admission": turn.admission,
|
|
2616
|
+
"cloudflare.agents.turn.channel": turn.channel,
|
|
2617
|
+
"cloudflare.agents.turn.continuation": turn.continuation,
|
|
2618
|
+
"cloudflare.agents.turn.generation": turn.generation
|
|
2619
|
+
} : {}
|
|
2620
|
+
}, () => this._prepareInferenceInvocation(input)))();
|
|
2621
|
+
}
|
|
2622
|
+
async _prepareInferenceInvocation(input) {
|
|
2623
|
+
const includeMcpTools = this.includeMcpTools;
|
|
2431
2624
|
this._activeStallTimeoutMs = void 0;
|
|
2432
2625
|
this._activeTurnAuthorization = { allowed: true };
|
|
2433
2626
|
this._activeTurnApprovedActionInputs = this._approvedActionInputsFromTranscript();
|
|
@@ -2459,7 +2652,7 @@ var Think = class Think extends Agent {
|
|
|
2459
2652
|
...extensionTools,
|
|
2460
2653
|
...contextTools,
|
|
2461
2654
|
...skillTools,
|
|
2462
|
-
...this.mcp?.getAITools?.() ?? {},
|
|
2655
|
+
...includeMcpTools ? this.mcp?.getAITools?.() ?? {} : {},
|
|
2463
2656
|
...clientToolSet
|
|
2464
2657
|
};
|
|
2465
2658
|
const channelContext = this._activeChannelContext;
|
|
@@ -2486,7 +2679,7 @@ var Think = class Think extends Agent {
|
|
|
2486
2679
|
const structuredOutputSchema = workflowPrompt?.output ? jsonSchema(workflowPrompt.output.schema) : void 0;
|
|
2487
2680
|
const wantsStructuredOutput = structuredOutputSchema !== void 0;
|
|
2488
2681
|
const finalModel = config.model != null ? this.resolveModel(config.model) : model;
|
|
2489
|
-
const finalSystem = config.system ?? this._systemPromptForTurn(baseSystem, config.tools ? {
|
|
2682
|
+
const finalSystem = config.instructions ?? config.system ?? this._systemPromptForTurn(baseSystem, config.tools ? {
|
|
2490
2683
|
...tools,
|
|
2491
2684
|
...config.tools
|
|
2492
2685
|
} : tools);
|
|
@@ -2531,7 +2724,8 @@ var Think = class Think extends Agent {
|
|
|
2531
2724
|
...wantsStructuredOutput ? [hasToolCall(finalAnswerToolName)] : [],
|
|
2532
2725
|
...Array.isArray(config.stopWhen) ? config.stopWhen : config.stopWhen ? [config.stopWhen] : []
|
|
2533
2726
|
];
|
|
2534
|
-
const
|
|
2727
|
+
const turnTelemetry = config.telemetry ?? config.experimental_telemetry;
|
|
2728
|
+
const streamTextOptions = {
|
|
2535
2729
|
model: finalModel,
|
|
2536
2730
|
system: turnSystem,
|
|
2537
2731
|
messages: finalMessages,
|
|
@@ -2551,7 +2745,7 @@ var Think = class Think extends Agent {
|
|
|
2551
2745
|
headers: config.headers,
|
|
2552
2746
|
stopWhen: finalStopWhen,
|
|
2553
2747
|
providerOptions: config.providerOptions,
|
|
2554
|
-
experimental_telemetry:
|
|
2748
|
+
experimental_telemetry: usesAISDKV7Telemetry ? void 0 : this._turnTelemetry(turnTelemetry),
|
|
2555
2749
|
experimental_transform: config.experimental_transform,
|
|
2556
2750
|
output: finalOutput,
|
|
2557
2751
|
abortSignal: input.signal,
|
|
@@ -2584,45 +2778,91 @@ var Think = class Think extends Agent {
|
|
|
2584
2778
|
await this._pipelineExtensionChunk(event);
|
|
2585
2779
|
},
|
|
2586
2780
|
onStepFinish: async (event) => {
|
|
2587
|
-
await this.
|
|
2781
|
+
await this.onStepEnd(event);
|
|
2588
2782
|
await this._pipelineExtensionStepFinish(event);
|
|
2589
2783
|
},
|
|
2590
2784
|
experimental_onToolCallFinish: (async (event) => {
|
|
2591
|
-
|
|
2785
|
+
const e = normalizeToolFinishEvent(event);
|
|
2786
|
+
if (e.toolCall.toolName === finalAnswerToolName) return;
|
|
2787
|
+
const { success, output, error } = e;
|
|
2592
2788
|
const base = {
|
|
2593
|
-
...
|
|
2594
|
-
stepNumber:
|
|
2595
|
-
messages:
|
|
2596
|
-
|
|
2789
|
+
...e.toolCall,
|
|
2790
|
+
stepNumber: e.stepNumber,
|
|
2791
|
+
messages: e.messages,
|
|
2792
|
+
toolExecutionMs: e.toolExecutionMs,
|
|
2793
|
+
durationMs: e.toolExecutionMs
|
|
2597
2794
|
};
|
|
2598
|
-
const ctx =
|
|
2795
|
+
const ctx = success ? {
|
|
2599
2796
|
...base,
|
|
2797
|
+
toolOutput: {
|
|
2798
|
+
type: "tool-result",
|
|
2799
|
+
output
|
|
2800
|
+
},
|
|
2600
2801
|
success: true,
|
|
2601
|
-
output
|
|
2802
|
+
output
|
|
2602
2803
|
} : {
|
|
2603
2804
|
...base,
|
|
2805
|
+
toolOutput: {
|
|
2806
|
+
type: "tool-error",
|
|
2807
|
+
error
|
|
2808
|
+
},
|
|
2604
2809
|
success: false,
|
|
2605
|
-
error
|
|
2810
|
+
error
|
|
2606
2811
|
};
|
|
2607
2812
|
await this.afterToolCall(ctx);
|
|
2608
|
-
await this._pipelineExtensionToolCallFinish(
|
|
2813
|
+
await this._pipelineExtensionToolCallFinish({
|
|
2814
|
+
toolCall: e.toolCall,
|
|
2815
|
+
stepNumber: e.stepNumber,
|
|
2816
|
+
durationMs: e.toolExecutionMs,
|
|
2817
|
+
success,
|
|
2818
|
+
output,
|
|
2819
|
+
error
|
|
2820
|
+
});
|
|
2609
2821
|
})
|
|
2610
|
-
});
|
|
2611
|
-
const outputPromise = wantsStructuredOutput ? Promise.resolve(result.toolCalls).then((calls) => {
|
|
2612
|
-
const finalCalls = calls.filter((call) => call.toolName === finalAnswerToolName);
|
|
2613
|
-
const last = finalCalls[finalCalls.length - 1];
|
|
2614
|
-
if (!last) throw new Error(`Model ended the turn without calling the ${finalAnswerToolName} tool`);
|
|
2615
|
-
return last.input;
|
|
2616
|
-
}) : finalOutput && result.output ? Promise.resolve(result.output) : void 0;
|
|
2617
|
-
if (outputPromise) outputPromise.catch(() => {});
|
|
2618
|
-
const streamResult = {
|
|
2619
|
-
toUIMessageStream: (options) => result.toUIMessageStream({
|
|
2620
|
-
sendReasoning: options?.sendReasoning ?? finalSendReasoning,
|
|
2621
|
-
onError: options?.onError ?? streamErrorToString
|
|
2622
|
-
}),
|
|
2623
|
-
output: outputPromise
|
|
2624
2822
|
};
|
|
2625
|
-
|
|
2823
|
+
if (usesAISDKV7Telemetry) {
|
|
2824
|
+
const { options, runtimeContext } = this._turnTelemetryV7(turnTelemetry);
|
|
2825
|
+
const crossMajorOptions = streamTextOptions;
|
|
2826
|
+
delete crossMajorOptions.experimental_telemetry;
|
|
2827
|
+
crossMajorOptions.telemetry = options;
|
|
2828
|
+
crossMajorOptions.runtimeContext = runtimeContext;
|
|
2829
|
+
}
|
|
2830
|
+
const inferenceStreamText = usesAISDKV7Telemetry ? streamText : wrapAISDK({
|
|
2831
|
+
streamText,
|
|
2832
|
+
wrapLanguageModel
|
|
2833
|
+
}, {
|
|
2834
|
+
storeMessages: this.storeMessages,
|
|
2835
|
+
storeTools: this.storeTools
|
|
2836
|
+
}).streamText;
|
|
2837
|
+
return () => {
|
|
2838
|
+
const result = inferenceStreamText(streamTextOptions);
|
|
2839
|
+
const outputPromise = wantsStructuredOutput ? Promise.resolve(result.toolCalls).then((calls) => {
|
|
2840
|
+
const finalCalls = calls.filter((call) => call.toolName === finalAnswerToolName);
|
|
2841
|
+
const last = finalCalls[finalCalls.length - 1];
|
|
2842
|
+
if (!last) throw new Error(`Model ended the turn without calling the ${finalAnswerToolName} tool`);
|
|
2843
|
+
return last.input;
|
|
2844
|
+
}) : finalOutput && result.output ? Promise.resolve(result.output) : void 0;
|
|
2845
|
+
if (outputPromise) outputPromise.catch(() => {});
|
|
2846
|
+
const streamResult = {
|
|
2847
|
+
toUIMessageStream: (options) => {
|
|
2848
|
+
const sendReasoning = options?.sendReasoning ?? finalSendReasoning;
|
|
2849
|
+
const onError = options?.onError ?? streamErrorToString;
|
|
2850
|
+
return readableStreamToAsyncIterable(result.toUIMessageStream({
|
|
2851
|
+
sendReasoning,
|
|
2852
|
+
onError
|
|
2853
|
+
}));
|
|
2854
|
+
},
|
|
2855
|
+
output: outputPromise
|
|
2856
|
+
};
|
|
2857
|
+
const finalizer = {
|
|
2858
|
+
started: false,
|
|
2859
|
+
run: () => Promise.resolve(result.consumeStream({ onError: () => {} }))
|
|
2860
|
+
};
|
|
2861
|
+
inferenceStreamFinalizers.set(streamResult, finalizer);
|
|
2862
|
+
const finalized = this._transformInferenceResult(streamResult);
|
|
2863
|
+
if (finalized !== streamResult) inferenceStreamFinalizers.set(finalized, finalizer);
|
|
2864
|
+
return finalized;
|
|
2865
|
+
};
|
|
2626
2866
|
}
|
|
2627
2867
|
/** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */
|
|
2628
2868
|
_transformInferenceResult(result) {
|
|
@@ -3003,7 +3243,7 @@ var Think = class Think extends Agent {
|
|
|
3003
3243
|
if (!this.extensionManager) return subclassConfig;
|
|
3004
3244
|
const subscribers = this.extensionManager.getHookSubscribers("beforeTurn");
|
|
3005
3245
|
if (subscribers.length === 0) return subclassConfig;
|
|
3006
|
-
const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-
|
|
3246
|
+
const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-Dogs9wbj.js");
|
|
3007
3247
|
let snapshot = createTurnContextSnapshot(ctx);
|
|
3008
3248
|
let accumulated = { ...subclassConfig };
|
|
3009
3249
|
if (accumulated.system !== void 0) snapshot.system = accumulated.system;
|
|
@@ -3219,25 +3459,25 @@ var Think = class Think extends Agent {
|
|
|
3219
3459
|
async _pipelineExtensionToolCallStart(event) {
|
|
3220
3460
|
if (!this.extensionManager) return;
|
|
3221
3461
|
if (this.extensionManager.getHookSubscribers("beforeToolCall").length === 0) return;
|
|
3222
|
-
const { createToolCallStartSnapshot } = await import("./hook-proxy-
|
|
3462
|
+
const { createToolCallStartSnapshot } = await import("./hook-proxy-Dogs9wbj.js");
|
|
3223
3463
|
await this._dispatchExtensionObservation("beforeToolCall", createToolCallStartSnapshot(event));
|
|
3224
3464
|
}
|
|
3225
3465
|
async _pipelineExtensionToolCallFinish(event) {
|
|
3226
3466
|
if (!this.extensionManager) return;
|
|
3227
3467
|
if (this.extensionManager.getHookSubscribers("afterToolCall").length === 0) return;
|
|
3228
|
-
const { createToolCallFinishSnapshot } = await import("./hook-proxy-
|
|
3468
|
+
const { createToolCallFinishSnapshot } = await import("./hook-proxy-Dogs9wbj.js");
|
|
3229
3469
|
await this._dispatchExtensionObservation("afterToolCall", createToolCallFinishSnapshot(event));
|
|
3230
3470
|
}
|
|
3231
3471
|
async _pipelineExtensionStepFinish(event) {
|
|
3232
3472
|
if (!this.extensionManager) return;
|
|
3233
3473
|
if (this.extensionManager.getHookSubscribers("onStepFinish").length === 0) return;
|
|
3234
|
-
const { createStepFinishSnapshot } = await import("./hook-proxy-
|
|
3474
|
+
const { createStepFinishSnapshot } = await import("./hook-proxy-Dogs9wbj.js");
|
|
3235
3475
|
await this._dispatchExtensionObservation("onStepFinish", createStepFinishSnapshot(event));
|
|
3236
3476
|
}
|
|
3237
3477
|
async _pipelineExtensionChunk(event) {
|
|
3238
3478
|
if (!this.extensionManager) return;
|
|
3239
3479
|
if (this.extensionManager.getHookSubscribers("onChunk").length === 0) return;
|
|
3240
|
-
const { createChunkSnapshot } = await import("./hook-proxy-
|
|
3480
|
+
const { createChunkSnapshot } = await import("./hook-proxy-Dogs9wbj.js");
|
|
3241
3481
|
await this._dispatchExtensionObservation("onChunk", createChunkSnapshot(event));
|
|
3242
3482
|
}
|
|
3243
3483
|
async _hostReadFile(path) {
|
|
@@ -3291,7 +3531,17 @@ var Think = class Think extends Agent {
|
|
|
3291
3531
|
return { messageCount: this.messages.length };
|
|
3292
3532
|
}
|
|
3293
3533
|
async _admitTurn(spec) {
|
|
3294
|
-
if (spec.admission !== "queue") return this
|
|
3534
|
+
if (spec.admission !== "queue") return withAgentSpan(this, "chat_submission", "submission", {
|
|
3535
|
+
"cloudflare.agents.component": "think",
|
|
3536
|
+
"cloudflare.agents.turn.trigger": spec.trigger,
|
|
3537
|
+
"cloudflare.agents.turn.admission": spec.admission,
|
|
3538
|
+
"cloudflare.agents.turn.channel": spec.channel
|
|
3539
|
+
}, () => withAgentSpan(this, spec.admission === "submit" ? "accept_chat_submission" : "execute_chat_submission", "submission", {
|
|
3540
|
+
"cloudflare.agents.component": "think",
|
|
3541
|
+
"cloudflare.agents.turn.trigger": spec.trigger,
|
|
3542
|
+
"cloudflare.agents.turn.admission": spec.admission,
|
|
3543
|
+
"cloudflare.agents.turn.channel": spec.channel
|
|
3544
|
+
}, () => this._withChannelContext(spec.channel, () => spec.execute())));
|
|
3295
3545
|
if (!spec.allowNested) this._assertNotInsideAdmittedTurn(spec.trigger);
|
|
3296
3546
|
return this.keepAliveWhile(async () => {
|
|
3297
3547
|
const turnPromise = this._turnQueue.enqueue(spec.requestId, () => this._runInsideAdmittedTurnBody(spec), spec.generation === void 0 ? void 0 : { generation: spec.generation });
|
|
@@ -3304,9 +3554,22 @@ var Think = class Think extends Agent {
|
|
|
3304
3554
|
throw new Error(`Think turn admission (${trigger}) cannot be called from inside an active turn; use runTurn({ mode: "submit" }) or addMessages() instead`);
|
|
3305
3555
|
}
|
|
3306
3556
|
async _runInsideAdmittedTurnBody(spec) {
|
|
3307
|
-
return
|
|
3557
|
+
return withAgentSpan(this, "chat_turn", "turn", {
|
|
3558
|
+
"cloudflare.agents.component": "think",
|
|
3559
|
+
"cloudflare.agents.turn.request_id": spec.requestId,
|
|
3560
|
+
"cloudflare.agents.turn.trigger": spec.trigger,
|
|
3561
|
+
"cloudflare.agents.turn.admission": spec.admission,
|
|
3562
|
+
"cloudflare.agents.turn.channel": spec.channel,
|
|
3563
|
+
"cloudflare.agents.turn.continuation": spec.continuation,
|
|
3564
|
+
"cloudflare.agents.turn.generation": spec.generation
|
|
3565
|
+
}, (update) => admittedTurnContext.run({
|
|
3308
3566
|
agent: this,
|
|
3309
|
-
requestId: spec.requestId
|
|
3567
|
+
requestId: spec.requestId,
|
|
3568
|
+
trigger: spec.trigger,
|
|
3569
|
+
admission: spec.admission,
|
|
3570
|
+
channel: spec.channel,
|
|
3571
|
+
continuation: spec.continuation,
|
|
3572
|
+
generation: spec.generation
|
|
3310
3573
|
}, async () => {
|
|
3311
3574
|
const startedAt = Date.now();
|
|
3312
3575
|
this._emit("chat:turn:start", {
|
|
@@ -3320,15 +3583,17 @@ var Think = class Think extends Agent {
|
|
|
3320
3583
|
this._activeTurnReplyAttachmentsRequestId = spec.requestId;
|
|
3321
3584
|
try {
|
|
3322
3585
|
const value = await this._withChannelContext(spec.channel, () => spec.execute());
|
|
3586
|
+
const status = spec.getStatus?.() ?? "completed";
|
|
3323
3587
|
this._emit("chat:turn:finish", {
|
|
3324
3588
|
requestId: spec.requestId,
|
|
3325
3589
|
trigger: spec.trigger,
|
|
3326
3590
|
admission: spec.admission,
|
|
3327
3591
|
...spec.continuation !== void 0 && { continuation: spec.continuation },
|
|
3328
3592
|
...spec.generation !== void 0 && { generation: spec.generation },
|
|
3329
|
-
status
|
|
3593
|
+
status,
|
|
3330
3594
|
durationMs: Date.now() - startedAt
|
|
3331
3595
|
});
|
|
3596
|
+
update({ "cloudflare.agents.turn.status": status });
|
|
3332
3597
|
return value;
|
|
3333
3598
|
} catch (error) {
|
|
3334
3599
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -3342,9 +3607,10 @@ var Think = class Think extends Agent {
|
|
|
3342
3607
|
durationMs: Date.now() - startedAt,
|
|
3343
3608
|
error: message
|
|
3344
3609
|
});
|
|
3610
|
+
update({ "cloudflare.agents.turn.status": "error" });
|
|
3345
3611
|
throw error;
|
|
3346
3612
|
}
|
|
3347
|
-
});
|
|
3613
|
+
}));
|
|
3348
3614
|
}
|
|
3349
3615
|
/**
|
|
3350
3616
|
* Run a chat turn: persist the user message, run the agentic loop,
|
|
@@ -5181,10 +5447,7 @@ var Think = class Think extends Agent {
|
|
|
5181
5447
|
if (existingById && options?.idempotencyKey && existingById.idempotency_key !== null && existingById.idempotency_key !== options.idempotencyKey) throw new Error("submissionId and idempotencyKey refer to different submissions");
|
|
5182
5448
|
const existing = existingById ?? existingByKey;
|
|
5183
5449
|
if (existing) {
|
|
5184
|
-
if (existing.status === "pending")
|
|
5185
|
-
await this._scheduleSubmissionDrain();
|
|
5186
|
-
this._startSubmissionDrain();
|
|
5187
|
-
}
|
|
5450
|
+
if (existing.status === "pending") await this._scheduleSubmissionDrain();
|
|
5188
5451
|
return {
|
|
5189
5452
|
...this._inspectionFromSubmissionRow(existing),
|
|
5190
5453
|
accepted: false
|
|
@@ -5216,7 +5479,6 @@ var Think = class Think extends Agent {
|
|
|
5216
5479
|
});
|
|
5217
5480
|
await this._emitSubmissionStatus(row);
|
|
5218
5481
|
await this._scheduleSubmissionDrain();
|
|
5219
|
-
this._startSubmissionDrain();
|
|
5220
5482
|
return {
|
|
5221
5483
|
...this._inspectionFromSubmissionRow(row),
|
|
5222
5484
|
accepted: true
|
|
@@ -5227,11 +5489,6 @@ var Think = class Think extends Agent {
|
|
|
5227
5489
|
async _scheduleSubmissionDrain() {
|
|
5228
5490
|
await this.schedule(0, "_drainThinkSubmissions", void 0, { idempotent: true });
|
|
5229
5491
|
}
|
|
5230
|
-
_startSubmissionDrain() {
|
|
5231
|
-
this.keepAliveWhile(() => this._drainSubmissions()).catch((error) => {
|
|
5232
|
-
console.error("[Think] Failed to drain submissions", error);
|
|
5233
|
-
});
|
|
5234
|
-
}
|
|
5235
5492
|
_hasPendingSubmissions() {
|
|
5236
5493
|
this._ensureSubmissionTable();
|
|
5237
5494
|
return this.sql`
|
|
@@ -5869,7 +6126,11 @@ var Think = class Think extends Agent {
|
|
|
5869
6126
|
if (typeof message === "string") {
|
|
5870
6127
|
const event = parseProtocolMessage(message);
|
|
5871
6128
|
if (event) {
|
|
5872
|
-
await this
|
|
6129
|
+
if (event.type === "chat-request") await withAgentSpan(this, "chat_interaction", "interaction", {
|
|
6130
|
+
"cloudflare.agents.component": "think",
|
|
6131
|
+
"cloudflare.agents.turn.request_id": event.id
|
|
6132
|
+
}, () => this._handleProtocolEvent(connection, event));
|
|
6133
|
+
else await this._handleProtocolEvent(connection, event);
|
|
5873
6134
|
return;
|
|
5874
6135
|
}
|
|
5875
6136
|
}
|
|
@@ -5887,7 +6148,7 @@ var Think = class Think extends Agent {
|
|
|
5887
6148
|
async _handleProtocolEvent(connection, event) {
|
|
5888
6149
|
switch (event.type) {
|
|
5889
6150
|
case "stream-resume-request":
|
|
5890
|
-
await this._handleStreamResumeRequest(connection);
|
|
6151
|
+
await this._handleStreamResumeRequest(connection, event.probeId);
|
|
5891
6152
|
break;
|
|
5892
6153
|
case "stream-resume-ack":
|
|
5893
6154
|
await this._handleStreamResumeAck(connection, event.id);
|
|
@@ -5923,8 +6184,8 @@ var Think = class Think extends Agent {
|
|
|
5923
6184
|
break;
|
|
5924
6185
|
}
|
|
5925
6186
|
}
|
|
5926
|
-
async _handleStreamResumeRequest(connection) {
|
|
5927
|
-
await this._resumeHandshake().handleResumeRequest(connection);
|
|
6187
|
+
async _handleStreamResumeRequest(connection, probeId) {
|
|
6188
|
+
await this._resumeHandshake().handleResumeRequest(connection, probeId);
|
|
5928
6189
|
}
|
|
5929
6190
|
async _handleStreamResumeAck(connection, requestId) {
|
|
5930
6191
|
await this._resumeHandshake().handleResumeAck(connection, requestId);
|
|
@@ -5961,7 +6222,11 @@ var Think = class Think extends Agent {
|
|
|
5961
6222
|
this._completeSkippedRequest(connection, requestId);
|
|
5962
6223
|
return;
|
|
5963
6224
|
}
|
|
5964
|
-
await this
|
|
6225
|
+
await withAgentSpan(this, "clear_previous_chat_state", "interaction", {
|
|
6226
|
+
"cloudflare.agents.component": "think",
|
|
6227
|
+
"cloudflare.agents.turn.request_id": requestId,
|
|
6228
|
+
"cloudflare.agents.turn.trigger": "ws-chat"
|
|
6229
|
+
}, () => this._clearChatTerminal());
|
|
5965
6230
|
this._preStream.begin(requestId);
|
|
5966
6231
|
const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
|
|
5967
6232
|
let pendingEnqueue = true;
|
|
@@ -5973,38 +6238,49 @@ var Think = class Think extends Agent {
|
|
|
5973
6238
|
};
|
|
5974
6239
|
try {
|
|
5975
6240
|
const requestClientTools = rawClientTools && rawClientTools.length > 0 ? rawClientTools : void 0;
|
|
5976
|
-
if (requestClientTools) {
|
|
5977
|
-
this._lastClientTools = requestClientTools;
|
|
5978
|
-
this._persistClientTools();
|
|
5979
|
-
} else if (rawClientTools !== void 0) {
|
|
5980
|
-
this._lastClientTools = void 0;
|
|
5981
|
-
this._persistClientTools();
|
|
5982
|
-
}
|
|
5983
6241
|
const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
|
|
5984
|
-
this
|
|
5985
|
-
|
|
6242
|
+
withAgentSpan(this, "persist_chat_request_context", "interaction", {
|
|
6243
|
+
"cloudflare.agents.component": "think",
|
|
6244
|
+
"cloudflare.agents.turn.request_id": requestId,
|
|
6245
|
+
"cloudflare.agents.turn.trigger": "ws-chat"
|
|
6246
|
+
}, () => {
|
|
6247
|
+
if (requestClientTools) {
|
|
6248
|
+
this._lastClientTools = requestClientTools;
|
|
6249
|
+
this._persistClientTools();
|
|
6250
|
+
} else if (rawClientTools !== void 0) {
|
|
6251
|
+
this._lastClientTools = void 0;
|
|
6252
|
+
this._persistClientTools();
|
|
6253
|
+
}
|
|
6254
|
+
this._lastBody = requestBody;
|
|
6255
|
+
this._persistBody();
|
|
6256
|
+
});
|
|
5986
6257
|
const clientToolsForTurn = this._lastClientTools;
|
|
5987
6258
|
const bodyForTurn = this._lastBody;
|
|
5988
|
-
const serverMessages = await this
|
|
6259
|
+
const serverMessages = await withAgentSpan(this, "load_chat_history", "interaction", {
|
|
6260
|
+
"cloudflare.agents.component": "think",
|
|
6261
|
+
"cloudflare.agents.turn.request_id": requestId,
|
|
6262
|
+
"cloudflare.agents.turn.trigger": "ws-chat"
|
|
6263
|
+
}, () => this._readMessagesFromStorage());
|
|
5989
6264
|
const reconciled = reconcileMessages(incomingMessages, serverMessages, sanitizeMessage);
|
|
5990
6265
|
let branchParentId;
|
|
5991
6266
|
if (isRegeneration && reconciled.length > 0) branchParentId = reconciled[reconciled.length - 1].id;
|
|
5992
|
-
if (this
|
|
5993
|
-
|
|
5994
|
-
|
|
5995
|
-
|
|
5996
|
-
|
|
5997
|
-
if (this._turnQueue.generation !== epoch)
|
|
5998
|
-
|
|
5999
|
-
return;
|
|
6267
|
+
if (!await withAgentSpan(this, "persist_incoming_messages", "interaction", {
|
|
6268
|
+
"cloudflare.agents.component": "think",
|
|
6269
|
+
"cloudflare.agents.turn.request_id": requestId,
|
|
6270
|
+
"cloudflare.agents.turn.trigger": "ws-chat"
|
|
6271
|
+
}, async () => {
|
|
6272
|
+
if (this._turnQueue.generation !== epoch) return false;
|
|
6273
|
+
for (const msg of reconciled) {
|
|
6274
|
+
if (this._turnQueue.generation !== epoch) return false;
|
|
6275
|
+
await this._persistIncomingMessage(msg, serverMessages);
|
|
6000
6276
|
}
|
|
6001
|
-
|
|
6002
|
-
|
|
6003
|
-
|
|
6277
|
+
if (this._turnQueue.generation !== epoch) return false;
|
|
6278
|
+
await this._syncMessages();
|
|
6279
|
+
return true;
|
|
6280
|
+
})) {
|
|
6004
6281
|
this._completeSkippedRequest(connection, requestId);
|
|
6005
6282
|
return;
|
|
6006
6283
|
}
|
|
6007
|
-
await this._syncMessages();
|
|
6008
6284
|
this._broadcastMessages([connection.id]);
|
|
6009
6285
|
messagesPersisted = true;
|
|
6010
6286
|
failureStage = "turn";
|
|
@@ -6061,16 +6337,30 @@ var Think = class Think extends Agent {
|
|
|
6061
6337
|
overflowRequested = true;
|
|
6062
6338
|
overflowError = error;
|
|
6063
6339
|
} } : void 0;
|
|
6064
|
-
await this
|
|
6340
|
+
await withAgentSpan(this, "persist_chat_result", "turn", {
|
|
6341
|
+
"cloudflare.agents.component": "think",
|
|
6342
|
+
"cloudflare.agents.turn.request_id": requestId,
|
|
6343
|
+
"cloudflare.agents.turn.trigger": "ws-chat",
|
|
6344
|
+
"cloudflare.agents.turn.admission": "queue",
|
|
6345
|
+
"cloudflare.agents.turn.generation": epoch,
|
|
6346
|
+
"cloudflare.agents.turn.continuation": false
|
|
6347
|
+
}, () => this._streamResult(requestId, result, abortSignal, {
|
|
6065
6348
|
parentId: branchParentId,
|
|
6066
6349
|
overflowRecovery
|
|
6067
|
-
});
|
|
6350
|
+
}));
|
|
6068
6351
|
if (overflowRequested) {
|
|
6069
6352
|
if (attempt < this._overflowMaxRetries && !abortSignal?.aborted) {
|
|
6070
|
-
if (await this
|
|
6353
|
+
if (await withAgentSpan(this, "compact_chat_history", "turn", {
|
|
6354
|
+
"cloudflare.agents.component": "think",
|
|
6355
|
+
"cloudflare.agents.turn.request_id": requestId,
|
|
6356
|
+
"cloudflare.agents.turn.trigger": "ws-chat",
|
|
6357
|
+
"cloudflare.agents.turn.admission": "queue",
|
|
6358
|
+
"cloudflare.agents.turn.generation": epoch,
|
|
6359
|
+
"cloudflare.agents.turn.continuation": false
|
|
6360
|
+
}, () => this._compactForContextOverflow("reactive", {
|
|
6071
6361
|
requestId,
|
|
6072
6362
|
attempt: attempt + 1
|
|
6073
|
-
})) continue;
|
|
6363
|
+
}))) continue;
|
|
6074
6364
|
}
|
|
6075
6365
|
const message = this._finalizeContextOverflowError(requestId, overflowError);
|
|
6076
6366
|
this._broadcastChat({
|
|
@@ -6348,6 +6638,7 @@ var Think = class Think extends Agent {
|
|
|
6348
6638
|
let skipFinalizeRearm = false;
|
|
6349
6639
|
let overflowRetry = false;
|
|
6350
6640
|
const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
|
|
6641
|
+
let streamDrainedNaturally = false;
|
|
6351
6642
|
try {
|
|
6352
6643
|
this._insideInferenceLoop = true;
|
|
6353
6644
|
const flushState = {
|
|
@@ -6404,8 +6695,10 @@ var Think = class Think extends Agent {
|
|
|
6404
6695
|
});
|
|
6405
6696
|
await callback.onEvent(chunkBody);
|
|
6406
6697
|
}
|
|
6698
|
+
streamDrainedNaturally = !(aborted || overflowRetry || streamError !== void 0);
|
|
6407
6699
|
} finally {
|
|
6408
6700
|
this._insideInferenceLoop = false;
|
|
6701
|
+
if (!streamDrainedNaturally) this._drainInferenceStream(result);
|
|
6409
6702
|
}
|
|
6410
6703
|
if (overflowRetry) {
|
|
6411
6704
|
this._completeResumableStream(streamId);
|
|
@@ -6602,6 +6895,7 @@ var Think = class Think extends Agent {
|
|
|
6602
6895
|
};
|
|
6603
6896
|
const pendingActionCalls = /* @__PURE__ */ new Map();
|
|
6604
6897
|
const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
|
|
6898
|
+
let streamDrainedNaturally = false;
|
|
6605
6899
|
try {
|
|
6606
6900
|
this._insideInferenceLoop = true;
|
|
6607
6901
|
try {
|
|
@@ -6656,8 +6950,10 @@ var Think = class Think extends Agent {
|
|
|
6656
6950
|
...continuation && { continuation: true }
|
|
6657
6951
|
});
|
|
6658
6952
|
}
|
|
6953
|
+
streamDrainedNaturally = !(streamAborted || overflowRetry || streamError !== void 0);
|
|
6659
6954
|
} finally {
|
|
6660
6955
|
this._insideInferenceLoop = false;
|
|
6956
|
+
if (!streamDrainedNaturally) this._drainInferenceStream(result);
|
|
6661
6957
|
}
|
|
6662
6958
|
if (overflowRetry && options?.overflowRecovery) {
|
|
6663
6959
|
this._completeResumableStream(streamId);
|