@cloudflare/think 0.4.2 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -1
- package/dist/think.d.ts +74 -1
- package/dist/think.js +218 -4
- package/dist/think.js.map +1 -1
- package/dist/tools/workspace.d.ts +49 -3
- package/dist/tools/workspace.js +175 -20
- package/dist/tools/workspace.js.map +1 -1
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -27,10 +27,48 @@ export class MyAgent extends Think<Env> {
|
|
|
27
27
|
|
|
28
28
|
That's it. Think handles the WebSocket chat protocol, message persistence, the agentic loop, message sanitization, stream resumption, client tool support, and workspace file tools. Connect from the browser with `useAgentChat` from `@cloudflare/ai-chat`.
|
|
29
29
|
|
|
30
|
+
## Agent tools
|
|
31
|
+
|
|
32
|
+
Think subclasses can be dispatched as agent tools from another Agent. The parent
|
|
33
|
+
uses `runAgentTool()` or `agentTool()` from `agents/agent-tools`; the child Think
|
|
34
|
+
instance owns its own messages, resumable stream, tools, and storage.
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { Think } from "@cloudflare/think";
|
|
38
|
+
import { agentTool } from "agents/agent-tools";
|
|
39
|
+
import { z } from "zod";
|
|
40
|
+
|
|
41
|
+
export class Researcher extends Think<Env> {
|
|
42
|
+
getSystemPrompt() {
|
|
43
|
+
return "Research the requested topic and end with a concise summary.";
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class Assistant extends Think<Env> {
|
|
48
|
+
getTools() {
|
|
49
|
+
return {
|
|
50
|
+
research: agentTool(Researcher, {
|
|
51
|
+
description: "Research one topic in depth.",
|
|
52
|
+
inputSchema: z.object({ query: z.string().min(3) }),
|
|
53
|
+
displayName: "Researcher"
|
|
54
|
+
})
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
The parent broadcasts `agent-tool-event` frames for live UI rendering and keeps
|
|
61
|
+
the child facet until `clearAgentToolRuns()` deletes retained runs.
|
|
62
|
+
|
|
63
|
+
See the full [Agent Tools guide](../../docs/agent-tools.md) for rendering,
|
|
64
|
+
drill-in, and cleanup patterns.
|
|
65
|
+
|
|
30
66
|
## Built-in workspace
|
|
31
67
|
|
|
32
68
|
Every Think agent gets `this.workspace` — a virtual filesystem backed by the DO's SQLite storage. Workspace tools (`read`, `write`, `edit`, `list`, `find`, `grep`, `delete`) are automatically available to the model.
|
|
33
69
|
|
|
70
|
+
The `read` tool returns line-numbered text for text files. For images and PDFs, it keeps the persisted tool result compact and passes file bytes to multimodal-capable models using AI SDK content parts.
|
|
71
|
+
|
|
34
72
|
```ts
|
|
35
73
|
export class MyAgent extends Think<Env> {
|
|
36
74
|
getModel() { ... }
|
|
@@ -71,6 +109,7 @@ export class MyAgent extends Think<Env> {
|
|
|
71
109
|
| `getSystemPrompt()` | `"You are a helpful assistant."` | System prompt (fallback when no context blocks) |
|
|
72
110
|
| `getTools()` | `{}` | AI SDK `ToolSet` for the agentic loop |
|
|
73
111
|
| `maxSteps` | `10` | Max tool-call rounds per turn (property) |
|
|
112
|
+
| `sendReasoning` | `true` | Send reasoning chunks to chat clients |
|
|
74
113
|
| `configureSession()` | identity | Add context blocks, compaction, search, skills |
|
|
75
114
|
| `getExtensions()` | `[]` | Sandboxed extension declarations (load order) |
|
|
76
115
|
| `extensionLoader` | `undefined` | `WorkerLoader` binding — enables extensions |
|
|
@@ -102,7 +141,9 @@ The AI SDK-derived contexts spread the SDK's own types at the top level — no i
|
|
|
102
141
|
|
|
103
142
|
`beforeStep` is wired to the AI SDK's `prepareStep` callback. Return a `StepConfig` to override `model`, `toolChoice`, `activeTools`, `system`, `messages`, `experimental_context`, or `providerOptions` for the current step. The AI SDK does not expose `output` or `maxSteps` per step — set those at the turn level via `TurnConfig` (returned from `beforeTurn`). `beforeStep` is subclass-only; it is not dispatched to extensions because the prepareStep event surface includes a live `LanguageModel` instance which is not JSON-safe to snapshot.
|
|
104
143
|
|
|
105
|
-
`TurnConfig` also accepts
|
|
144
|
+
`TurnConfig` also accepts `sendReasoning` to override whether reasoning chunks are emitted for the current UI message stream. The instance-level `sendReasoning` property defaults to `true`; return `{ sendReasoning: false }` from `beforeTurn` to hide reasoning for a single turn, for example on internal continuation turns.
|
|
145
|
+
|
|
146
|
+
`TurnConfig` also accepts an `output` field that is forwarded to `streamText` as the AI SDK's structured-output spec. Combine with `activeTools: []` for providers (e.g. `workers-ai-provider`) that strip tools when `responseFormat: "json"` is active. Use `experimental_telemetry` to pass the AI SDK's per-call telemetry settings through to `streamText`; consider disabling `recordInputs` or `recordOutputs` if prompts or outputs may contain sensitive data.
|
|
106
147
|
|
|
107
148
|
Per-tool hooks are wired so `beforeToolCall` fires _before_ `execute` (Think wraps every tool's `execute`) and `afterToolCall` fires _after_ (via the AI SDK's `experimental_onToolCallFinish`) with `durationMs` and a discriminated outcome. `beforeToolCall` can return a `ToolCallDecision` to:
|
|
108
149
|
|
|
@@ -217,7 +258,9 @@ interface TurnConfig {
|
|
|
217
258
|
activeTools?: string[]; // limit which tools the model can call
|
|
218
259
|
toolChoice?: ToolChoice; // force a specific tool
|
|
219
260
|
maxSteps?: number; // override maxSteps for this turn
|
|
261
|
+
sendReasoning?: boolean; // send reasoning chunks for this turn
|
|
220
262
|
providerOptions?: Record<string, unknown>;
|
|
263
|
+
experimental_telemetry?: TelemetrySettings;
|
|
221
264
|
}
|
|
222
265
|
```
|
|
223
266
|
|
package/dist/think.d.ts
CHANGED
|
@@ -66,7 +66,9 @@ interface StreamCallback {
|
|
|
66
66
|
* The AI SDK's `streamText()` result satisfies this interface.
|
|
67
67
|
*/
|
|
68
68
|
interface StreamableResult {
|
|
69
|
-
toUIMessageStream(
|
|
69
|
+
toUIMessageStream(options?: {
|
|
70
|
+
sendReasoning?: boolean;
|
|
71
|
+
}): AsyncIterable<unknown>;
|
|
70
72
|
}
|
|
71
73
|
/**
|
|
72
74
|
* Options for a chat turn (sub-agent RPC entry point).
|
|
@@ -75,6 +77,27 @@ interface ChatOptions {
|
|
|
75
77
|
signal?: AbortSignal;
|
|
76
78
|
tools?: ToolSet;
|
|
77
79
|
}
|
|
80
|
+
type AgentToolChildRunStatus =
|
|
81
|
+
| "starting"
|
|
82
|
+
| "running"
|
|
83
|
+
| "completed"
|
|
84
|
+
| "error"
|
|
85
|
+
| "aborted";
|
|
86
|
+
type AgentToolRunInspection<Output = unknown> = {
|
|
87
|
+
runId: string;
|
|
88
|
+
status: AgentToolChildRunStatus;
|
|
89
|
+
requestId?: string;
|
|
90
|
+
streamId?: string;
|
|
91
|
+
output?: Output;
|
|
92
|
+
summary?: string;
|
|
93
|
+
error?: string;
|
|
94
|
+
startedAt: number;
|
|
95
|
+
completedAt?: number;
|
|
96
|
+
};
|
|
97
|
+
type AgentToolStoredChunk = {
|
|
98
|
+
sequence: number;
|
|
99
|
+
body: string;
|
|
100
|
+
};
|
|
78
101
|
/**
|
|
79
102
|
* A chat turn request. Built automatically by each entry path
|
|
80
103
|
* (WebSocket, chat(), saveMessages, auto-continuation) and passed
|
|
@@ -128,8 +151,17 @@ interface TurnConfig {
|
|
|
128
151
|
toolChoice?: Parameters<typeof streamText>[0]["toolChoice"];
|
|
129
152
|
/** Override maxSteps for this turn. */
|
|
130
153
|
maxSteps?: number;
|
|
154
|
+
/**
|
|
155
|
+
* Controls whether reasoning chunks are included in the UI message stream
|
|
156
|
+
* for this turn. Defaults to the instance-level `sendReasoning` setting.
|
|
157
|
+
*/
|
|
158
|
+
sendReasoning?: boolean;
|
|
131
159
|
/** Provider-specific options (AI SDK providerOptions). */
|
|
132
160
|
providerOptions?: Record<string, unknown>;
|
|
161
|
+
/** Optional AI SDK telemetry configuration for this turn. */
|
|
162
|
+
experimental_telemetry?: Parameters<
|
|
163
|
+
typeof streamText
|
|
164
|
+
>[0]["experimental_telemetry"];
|
|
133
165
|
/**
|
|
134
166
|
* Optional structured-output specification (AI SDK `output`).
|
|
135
167
|
* Forwarded to `streamText` so the model's final response is parsed
|
|
@@ -402,6 +434,16 @@ declare class Think<
|
|
|
402
434
|
private _pendingInteractionPromise;
|
|
403
435
|
private _submitConcurrency;
|
|
404
436
|
private static MESSAGE_DEBOUNCE_MS;
|
|
437
|
+
private _agentToolForwarders;
|
|
438
|
+
private _agentToolClosers;
|
|
439
|
+
private _agentToolAbortControllers;
|
|
440
|
+
private _agentToolLastErrors;
|
|
441
|
+
private _agentToolPreTurnAssistantIds;
|
|
442
|
+
private _agentToolLiveSequences;
|
|
443
|
+
broadcast(
|
|
444
|
+
msg: string | ArrayBuffer | ArrayBufferView,
|
|
445
|
+
without?: string[]
|
|
446
|
+
): void;
|
|
405
447
|
/**
|
|
406
448
|
* Persist an arbitrary JSON-serializable configuration object for this
|
|
407
449
|
* agent instance. Stored in the Think-private `think_config` table —
|
|
@@ -446,6 +488,11 @@ declare class Think<
|
|
|
446
488
|
getTools(): ToolSet;
|
|
447
489
|
/** Maximum number of tool-call steps per turn. Override via property or per-turn via TurnConfig. */
|
|
448
490
|
maxSteps: number;
|
|
491
|
+
/**
|
|
492
|
+
* Whether reasoning chunks are sent to chat clients by default. Override
|
|
493
|
+
* per turn by returning `sendReasoning` from `beforeTurn`.
|
|
494
|
+
*/
|
|
495
|
+
sendReasoning: boolean;
|
|
449
496
|
/**
|
|
450
497
|
* Configure the session. Called once during `onStart`.
|
|
451
498
|
* Override to add context blocks, compaction, search, skills.
|
|
@@ -740,6 +787,32 @@ declare class Think<
|
|
|
740
787
|
getMessages(): UIMessage[];
|
|
741
788
|
/** Clear all messages from storage. */
|
|
742
789
|
clearMessages(): void;
|
|
790
|
+
private _ensureAgentToolChildRunTable;
|
|
791
|
+
private _readAgentToolChildRun;
|
|
792
|
+
private _inspectionFromChildRow;
|
|
793
|
+
protected formatAgentToolInput(input: unknown): UIMessage;
|
|
794
|
+
protected getAgentToolOutput(_runId: string): unknown;
|
|
795
|
+
startAgentToolRun(
|
|
796
|
+
input: unknown,
|
|
797
|
+
options: {
|
|
798
|
+
runId: string;
|
|
799
|
+
}
|
|
800
|
+
): Promise<AgentToolRunInspection>;
|
|
801
|
+
cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
|
|
802
|
+
inspectAgentToolRun(runId: string): Promise<AgentToolRunInspection | null>;
|
|
803
|
+
getAgentToolChunks(
|
|
804
|
+
runId: string,
|
|
805
|
+
options?: {
|
|
806
|
+
afterSequence?: number;
|
|
807
|
+
}
|
|
808
|
+
): Promise<AgentToolStoredChunk[]>;
|
|
809
|
+
tailAgentToolRun(
|
|
810
|
+
runId: string,
|
|
811
|
+
options?: {
|
|
812
|
+
afterSequence?: number;
|
|
813
|
+
}
|
|
814
|
+
): Promise<ReadableStream<AgentToolStoredChunk>>;
|
|
815
|
+
private _getAgentToolFinalText;
|
|
743
816
|
/**
|
|
744
817
|
* Inject messages and trigger a model turn — without a WebSocket request.
|
|
745
818
|
*
|
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 —
|
|
@@ -411,7 +437,7 @@ var Think = class Think extends Agent {
|
|
|
411
437
|
};
|
|
412
438
|
const system = await this.session.freezeSystemPrompt() || this.getSystemPrompt();
|
|
413
439
|
const messages = pruneMessages({
|
|
414
|
-
messages: await convertToModelMessages(truncateOlderMessages(this.session.getHistory())),
|
|
440
|
+
messages: await convertToModelMessages(truncateOlderMessages(this.session.getHistory()), { tools }),
|
|
415
441
|
toolCalls: "before-last-2-messages"
|
|
416
442
|
});
|
|
417
443
|
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.");
|
|
@@ -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
|
*
|
|
@@ -981,6 +1187,7 @@ var Think = class Think extends Agent {
|
|
|
981
1187
|
_setupProtocolHandlers() {
|
|
982
1188
|
const _onConnect = this.onConnect.bind(this);
|
|
983
1189
|
this.onConnect = async (connection, ctx) => {
|
|
1190
|
+
if (this._cf_requestTargetsSubAgent(ctx.request)) return _onConnect(connection, ctx);
|
|
984
1191
|
if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
|
|
985
1192
|
else connection.send(JSON.stringify({
|
|
986
1193
|
type: MSG_CHAT_MESSAGES,
|
|
@@ -998,6 +1205,7 @@ var Think = class Think extends Agent {
|
|
|
998
1205
|
};
|
|
999
1206
|
const _onMessage = this.onMessage.bind(this);
|
|
1000
1207
|
this.onMessage = async (connection, message) => {
|
|
1208
|
+
if (this._cf_connectionTargetsSubAgent(connection)) return _onMessage(connection, message);
|
|
1001
1209
|
if (typeof message === "string") {
|
|
1002
1210
|
const event = parseProtocolMessage(message);
|
|
1003
1211
|
if (event) {
|
|
@@ -1073,7 +1281,13 @@ var Think = class Think extends Agent {
|
|
|
1073
1281
|
if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === requestId) {
|
|
1074
1282
|
const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
|
|
1075
1283
|
if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
|
|
1076
|
-
}
|
|
1284
|
+
} else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, requestId)) connection.send(JSON.stringify({
|
|
1285
|
+
body: "",
|
|
1286
|
+
done: true,
|
|
1287
|
+
id: requestId,
|
|
1288
|
+
type: MSG_CHAT_RESPONSE,
|
|
1289
|
+
replay: true
|
|
1290
|
+
}));
|
|
1077
1291
|
}
|
|
1078
1292
|
async _handleChatRequest(connection, event) {
|
|
1079
1293
|
if (!event.init?.body) return;
|