@cloudflare/think 0.5.2 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -2
- package/dist/{classPrivateFieldGet2-Bvcn7kEw.js → classPrivateFieldGet2-CCiYk1x3.js} +5 -5
- package/dist/extensions/index.js +2 -2
- package/dist/extensions/index.js.map +1 -1
- package/dist/hook-proxy-5248W-ea.js.map +1 -1
- package/dist/{manager-DDC3Gb0V.js → manager-BypfrNX0.js} +3 -3
- package/dist/{manager-DDC3Gb0V.js.map → manager-BypfrNX0.js.map} +1 -1
- package/dist/think.d.ts +126 -4
- package/dist/think.js +848 -100
- package/dist/think.js.map +1 -1
- package/dist/tools/browser.js.map +1 -1
- package/dist/tools/execute.js.map +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/extensions.js.map +1 -1
- package/dist/tools/sandbox.js.map +1 -1
- package/dist/tools/workspace.js +42 -12
- package/dist/tools/workspace.js.map +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -113,10 +113,11 @@ export class MyAgent extends Think<Env> {
|
|
|
113
113
|
| `configureSession()` | identity | Add context blocks, compaction, search, skills |
|
|
114
114
|
| `getExtensions()` | `[]` | Sandboxed extension declarations (load order) |
|
|
115
115
|
| `extensionLoader` | `undefined` | `WorkerLoader` binding — enables extensions |
|
|
116
|
+
| `chatRecovery` | `true` | Wrap turns in `runFiber` for durable execution |
|
|
116
117
|
|
|
117
118
|
### Lifecycle hooks
|
|
118
119
|
|
|
119
|
-
Think owns the `streamText` call. Hooks fire on every turn regardless of entry path (WebSocket, `chat()`, `saveMessages`, auto-continuation).
|
|
120
|
+
Think owns the `streamText` call. Hooks fire on every turn regardless of entry path (WebSocket, `chat()`, `saveMessages()`, durable `submitMessages()` execution, `continueLastTurn()`, auto-continuation).
|
|
120
121
|
|
|
121
122
|
| Hook | When it fires | Return |
|
|
122
123
|
| ------------------------ | ------------------------------------------- | ------------------------------ |
|
|
@@ -143,6 +144,8 @@ The AI SDK-derived contexts spread the SDK's own types at the top level — no i
|
|
|
143
144
|
|
|
144
145
|
`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
|
|
|
147
|
+
`TurnConfig` also accepts stable AI SDK `streamText` call settings such as `maxOutputTokens`, `temperature`, `stopSequences`, `seed`, `maxRetries`, `timeout`, and `headers`. Use them to tune model behavior per turn, for example disabling retries or adding a chunk timeout during recovery flows.
|
|
148
|
+
|
|
146
149
|
`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.
|
|
147
150
|
|
|
148
151
|
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:
|
|
@@ -259,6 +262,17 @@ interface TurnConfig {
|
|
|
259
262
|
toolChoice?: ToolChoice; // force a specific tool
|
|
260
263
|
maxSteps?: number; // override maxSteps for this turn
|
|
261
264
|
sendReasoning?: boolean; // send reasoning chunks for this turn
|
|
265
|
+
maxOutputTokens?: number;
|
|
266
|
+
temperature?: number;
|
|
267
|
+
topP?: number;
|
|
268
|
+
topK?: number;
|
|
269
|
+
presencePenalty?: number;
|
|
270
|
+
frequencyPenalty?: number;
|
|
271
|
+
stopSequences?: string[];
|
|
272
|
+
seed?: number;
|
|
273
|
+
maxRetries?: number;
|
|
274
|
+
timeout?: TimeoutConfiguration;
|
|
275
|
+
headers?: Record<string, string | undefined>;
|
|
262
276
|
providerOptions?: Record<string, unknown>;
|
|
263
277
|
experimental_telemetry?: TelemetrySettings;
|
|
264
278
|
}
|
|
@@ -327,6 +341,22 @@ export class MyAgent extends Think<Env> {
|
|
|
327
341
|
}
|
|
328
342
|
```
|
|
329
343
|
|
|
344
|
+
### Choosing a turn API
|
|
345
|
+
|
|
346
|
+
Use browser chat through `useAgentChat` when a user drives the conversation. Use
|
|
347
|
+
`saveMessages()` when server code controls the trigger and can wait for the
|
|
348
|
+
model response. Use `submitMessages()` when a caller needs fast durable
|
|
349
|
+
acceptance, idempotent retries, cancellation, and later status inspection.
|
|
350
|
+
|
|
351
|
+
Use `subAgent(...).chat()` for direct streaming RPC to a specific child when
|
|
352
|
+
your code owns forwarding and replay policy. Use `agentTool()` or
|
|
353
|
+
`runAgentTool()` when a parent agent delegates work to a retained child and you
|
|
354
|
+
want event replay, abort bridging, and UI drill-in.
|
|
355
|
+
|
|
356
|
+
See [Choosing a turn API](../../docs/think/index.md#choosing-a-turn-api) and
|
|
357
|
+
[Programmatic Submissions](../../docs/think/programmatic-submissions.md) for the
|
|
358
|
+
full API comparison.
|
|
359
|
+
|
|
330
360
|
### Sub-agent streaming via RPC
|
|
331
361
|
|
|
332
362
|
When used as a sub-agent (via `this.subAgent()`), the `chat()` method runs a full turn and streams events via a callback:
|
|
@@ -340,11 +370,13 @@ interface StreamCallback {
|
|
|
340
370
|
|
|
341
371
|
const agent = await this.subAgent(MyAgent, "thread-1");
|
|
342
372
|
await agent.chat("Summarize the project", relay, {
|
|
343
|
-
tools: extraTools,
|
|
344
373
|
signal: abortController.signal
|
|
345
374
|
});
|
|
346
375
|
```
|
|
347
376
|
|
|
377
|
+
Tools belong to the child agent; define them with `getTools()` or use
|
|
378
|
+
`agentTool()` / `runAgentTool()` for parent-child orchestration.
|
|
379
|
+
|
|
348
380
|
### Dynamic configuration
|
|
349
381
|
|
|
350
382
|
`configure()` and `getConfig()` persist a JSON-serializable config blob in SQLite — useful for private server-side settings that should survive hibernation and restarts. Pass the config shape as a method generic for typed call sites:
|
|
@@ -369,6 +401,7 @@ For values you want broadcast to connected clients, use `state` / `setState` fro
|
|
|
369
401
|
- **Lifecycle hooks** — `beforeTurn`, `beforeStep`, `onStepFinish`, `onChunk`, `onChatResponse` fire on every turn
|
|
370
402
|
- **Stream resumption** — page refresh replays buffered chunks via `ResumableStream`
|
|
371
403
|
- **Client tools** — accept tool schemas from clients, handle results and approvals
|
|
404
|
+
- **Durable submissions** — accept webhook/RPC-triggered turns with idempotent retry and status inspection
|
|
372
405
|
- **Auto-continuation** — debounce-based continuation after tool results
|
|
373
406
|
- **MCP integration** — MCP tools auto-merged, wait for connections before inference
|
|
374
407
|
- **Abort/cancel** — pass an `AbortSignal` or send a cancel message
|
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
//#region \0@oxc-project+runtime@0.
|
|
1
|
+
//#region \0@oxc-project+runtime@0.129.0/helpers/checkPrivateRedeclaration.js
|
|
2
2
|
function _checkPrivateRedeclaration(e, t) {
|
|
3
3
|
if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
|
|
4
4
|
}
|
|
5
5
|
//#endregion
|
|
6
|
-
//#region \0@oxc-project+runtime@0.
|
|
6
|
+
//#region \0@oxc-project+runtime@0.129.0/helpers/classPrivateFieldInitSpec.js
|
|
7
7
|
function _classPrivateFieldInitSpec(e, t, a) {
|
|
8
8
|
_checkPrivateRedeclaration(e, t), t.set(e, a);
|
|
9
9
|
}
|
|
10
10
|
//#endregion
|
|
11
|
-
//#region \0@oxc-project+runtime@0.
|
|
11
|
+
//#region \0@oxc-project+runtime@0.129.0/helpers/assertClassBrand.js
|
|
12
12
|
function _assertClassBrand(e, t, n) {
|
|
13
13
|
if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
|
|
14
14
|
throw new TypeError("Private element is not present on this object");
|
|
15
15
|
}
|
|
16
16
|
//#endregion
|
|
17
|
-
//#region \0@oxc-project+runtime@0.
|
|
17
|
+
//#region \0@oxc-project+runtime@0.129.0/helpers/classPrivateFieldSet2.js
|
|
18
18
|
function _classPrivateFieldSet2(s, a, r) {
|
|
19
19
|
return s.set(_assertClassBrand(s, a), r), r;
|
|
20
20
|
}
|
|
21
21
|
//#endregion
|
|
22
|
-
//#region \0@oxc-project+runtime@0.
|
|
22
|
+
//#region \0@oxc-project+runtime@0.129.0/helpers/classPrivateFieldGet2.js
|
|
23
23
|
function _classPrivateFieldGet2(s, a) {
|
|
24
24
|
return s.get(_assertClassBrand(s, a));
|
|
25
25
|
}
|
package/dist/extensions/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { i as _classPrivateMethodInitSpec, t as ExtensionManager } from "../manager-
|
|
2
|
-
import { r as _assertClassBrand } from "../classPrivateFieldGet2-
|
|
1
|
+
import { i as _classPrivateMethodInitSpec, t as ExtensionManager } from "../manager-BypfrNX0.js";
|
|
2
|
+
import { r as _assertClassBrand } from "../classPrivateFieldGet2-CCiYk1x3.js";
|
|
3
3
|
import { WorkerEntrypoint } from "cloudflare:workers";
|
|
4
4
|
//#region src/extensions/host-bridge.ts
|
|
5
5
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/extensions/host-bridge.ts","../../src/extensions/bridge-provider.ts"],"sourcesContent":["/**\n * HostBridgeLoopback — a WorkerEntrypoint that provides controlled workspace\n * access to extension Workers loaded via WorkerLoader.\n *\n * This is a loopback: the extension worker's `env.host` binding points here,\n * and each method call resolves the parent agent via `ctx.exports`, then\n * delegates to the agent's workspace proxy methods (`_hostReadFile`, etc.).\n *\n * Props carry serializable identifiers (agent class name, agent ID, and\n * permissions) so the binding survives across requests and hibernation.\n *\n * Users must re-export this class from their worker entry point:\n *\n * ```typescript\n * export { HostBridgeLoopback } from \"@cloudflare/think/extensions\";\n * ```\n *\n * @experimental The API surface may change before stabilizing.\n */\n\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport type { ExtensionPermissions } from \"./types\";\n\nexport type HostBridgeLoopbackProps = {\n agentClassName: string;\n agentId: string;\n permissions: ExtensionPermissions;\n /** Namespaced context labels this extension declared (for \"own\" write validation). */\n ownContextLabels?: string[];\n};\n\nexport class HostBridgeLoopback extends WorkerEntrypoint<\n Record<string, unknown>,\n HostBridgeLoopbackProps\n> {\n private _permissions = this.ctx.props.permissions;\n\n private _getAgent() {\n const { agentClassName, agentId } = this.ctx.props;\n // @ts-expect-error — experimental: ctx.exports on WorkerEntrypoint\n const ns = this.ctx.exports[agentClassName] as DurableObjectNamespace;\n return ns.get(ns.idFromString(agentId));\n }\n\n // ── Permission checks ──────────────────────────────────────────\n\n #requireWorkspace(level: \"read\" | \"read-write\"): void {\n const ws = this._permissions.workspace ?? \"none\";\n if (ws === \"none\") {\n throw new Error(\"Extension error: no workspace permission declared\");\n }\n if (level === \"read-write\" && ws !== \"read-write\") {\n throw new Error(\n \"Extension error: workspace write permission required, but only read granted\"\n );\n }\n }\n\n #requireContextRead(label: string): void {\n const ctx = this._permissions.context;\n if (!ctx?.read) {\n throw new Error(\"Extension error: no context read permission declared\");\n }\n if (ctx.read !== \"all\" && !ctx.read.includes(label)) {\n throw new Error(\n `Extension error: no read permission for context label \"${label}\"`\n );\n }\n }\n\n #requireContextWrite(label: string): void {\n const ctx = this._permissions.context;\n if (!ctx?.write) {\n throw new Error(\"Extension error: no context write permission declared\");\n }\n if (ctx.write === \"own\") {\n const owned = this.ctx.props.ownContextLabels ?? [];\n if (!owned.includes(label)) {\n throw new Error(\n `Extension error: label \"${label}\" is not owned by this extension`\n );\n }\n } else if (!ctx.write.includes(label)) {\n throw new Error(\n `Extension error: no write permission for context label \"${label}\"`\n );\n }\n }\n\n #requireMessages(): void {\n if (this._permissions.messages !== \"read\") {\n throw new Error(\"Extension error: no messages read permission declared\");\n }\n }\n\n #requireSendMessage(): void {\n if (!this._permissions.session?.sendMessage) {\n throw new Error(\n \"Extension error: no session.sendMessage permission declared\"\n );\n }\n }\n\n #requireSessionMetadata(): void {\n if (!this._permissions.session?.metadata) {\n throw new Error(\n \"Extension error: no session.metadata permission declared\"\n );\n }\n }\n\n // ── Workspace (existing) ───────────────────────────────────────\n\n async readFile(path: string): Promise<string | null> {\n this.#requireWorkspace(\"read\");\n return (\n this._getAgent() as unknown as {\n _hostReadFile(path: string): Promise<string | null>;\n }\n )._hostReadFile(path);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n this.#requireWorkspace(\"read-write\");\n return (\n this._getAgent() as unknown as {\n _hostWriteFile(path: string, content: string): Promise<void>;\n }\n )._hostWriteFile(path, content);\n }\n\n async deleteFile(path: string): Promise<boolean> {\n this.#requireWorkspace(\"read-write\");\n return (\n this._getAgent() as unknown as {\n _hostDeleteFile(path: string): Promise<boolean>;\n }\n )._hostDeleteFile(path);\n }\n\n async listFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n > {\n this.#requireWorkspace(\"read\");\n return (\n this._getAgent() as unknown as {\n _hostListFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n >;\n }\n )._hostListFiles(dir);\n }\n\n // ── Context blocks (new) ───────────────────────────────────────\n\n async getContext(label: string): Promise<string | null> {\n this.#requireContextRead(label);\n return (\n this._getAgent() as unknown as {\n _hostGetContext(label: string): Promise<string | null>;\n }\n )._hostGetContext(label);\n }\n\n async setContext(label: string, content: string): Promise<void> {\n this.#requireContextWrite(label);\n return (\n this._getAgent() as unknown as {\n _hostSetContext(label: string, content: string): Promise<void>;\n }\n )._hostSetContext(label, content);\n }\n\n // ── Messages (new) ────────────────────────────────────────────\n\n async getMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>> {\n this.#requireMessages();\n return (\n this._getAgent() as unknown as {\n _hostGetMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>>;\n }\n )._hostGetMessages(limit);\n }\n\n async sendMessage(content: string): Promise<void> {\n this.#requireSendMessage();\n return (\n this._getAgent() as unknown as {\n _hostSendMessage(content: string): Promise<void>;\n }\n )._hostSendMessage(content);\n }\n\n // ── Session metadata (new) ────────────────────────────────────\n\n async getSessionInfo(): Promise<{ messageCount: number }> {\n this.#requireSessionMetadata();\n return (\n this._getAgent() as unknown as {\n _hostGetSessionInfo(): Promise<{ messageCount: number }>;\n }\n )._hostGetSessionInfo();\n }\n}\n","/**\n * Bridge providers that adapt extension Worker RPC into Session's\n * ContextProvider / SkillProvider / WritableContextProvider interfaces.\n *\n * When an extension declares context blocks in its manifest, Think creates\n * a bridge provider for each block. The bridge delegates `get()`, `load()`,\n * and `set()` to the extension Worker's entrypoint via RPC.\n *\n * This allows extensions to contribute context blocks to the Session's\n * system prompt without Session knowing about the extension system.\n */\n\ninterface ExtensionContextEntrypoint {\n contextGet(label: string): Promise<string | null>;\n contextLoad?(label: string, key: string): Promise<string | null>;\n contextSet?(\n label: string,\n key: string,\n content: string,\n description?: string\n ): Promise<void>;\n}\n\n/**\n * A readonly context provider backed by an extension Worker.\n * Delegates `get()` to the extension's `contextGet` RPC method.\n */\nexport class ExtensionContextBridge {\n protected _label: string;\n protected _entrypoint: ExtensionContextEntrypoint;\n\n constructor(label: string, entrypoint: ExtensionContextEntrypoint) {\n this._label = label;\n this._entrypoint = entrypoint;\n }\n\n init(_label: string): void {}\n\n async get(): Promise<string | null> {\n return this._entrypoint.contextGet(this._label);\n }\n}\n\n/**\n * A writable context provider backed by an extension Worker.\n * Delegates `get()` and `set()` to the extension's RPC methods.\n */\nexport class ExtensionWritableBridge extends ExtensionContextBridge {\n async set(content: string): Promise<void> {\n await this._entrypoint.contextSet?.(this._label, \"\", content);\n }\n}\n\n/**\n * A skill provider backed by an extension Worker.\n * Delegates `get()`, `load()`, and optionally `set()` to the extension's RPC methods.\n */\nexport class ExtensionSkillBridge extends ExtensionContextBridge {\n async load(key: string): Promise<string | null> {\n return (await this._entrypoint.contextLoad?.(this._label, key)) ?? null;\n }\n\n async set(key: string, content: string, description?: string): Promise<void> {\n await this._entrypoint.contextSet?.(this._label, key, content, description);\n }\n}\n\n/**\n * Create the appropriate bridge provider based on the context block type.\n */\nexport function createBridgeProvider(\n label: string,\n type: \"readonly\" | \"writable\" | \"skill\" | \"searchable\",\n entrypoint: ExtensionContextEntrypoint\n) {\n switch (type) {\n case \"skill\":\n return new ExtensionSkillBridge(label, entrypoint);\n case \"writable\":\n return new ExtensionWritableBridge(label, entrypoint);\n case \"readonly\":\n case \"searchable\":\n default:\n return new ExtensionContextBridge(label, entrypoint);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,qBAAb,cAAwC,iBAGtC;;;;AACA,OAAQ,eAAe,KAAK,IAAI,MAAM;;CAEtC,YAAoB;EAClB,MAAM,EAAE,gBAAgB,YAAY,KAAK,IAAI;EAE7C,MAAM,KAAK,KAAK,IAAI,QAAQ;AAC5B,SAAO,GAAG,IAAI,GAAG,aAAa,QAAQ,CAAC;;CAwEzC,MAAM,SAAS,MAAsC;AACnD,oBAAA,2BAAA,MAAA,kBAAsB,CAAA,KAAA,MAAC,OAAO;AAC9B,SACE,KAAK,WAAW,CAGhB,cAAc,KAAK;;CAGvB,MAAM,UAAU,MAAc,SAAgC;AAC5D,oBAAA,2BAAA,MAAA,kBAAsB,CAAA,KAAA,MAAC,aAAa;AACpC,SACE,KAAK,WAAW,CAGhB,eAAe,MAAM,QAAQ;;CAGjC,MAAM,WAAW,MAAgC;AAC/C,oBAAA,2BAAA,MAAA,kBAAsB,CAAA,KAAA,MAAC,aAAa;AACpC,SACE,KAAK,WAAW,CAGhB,gBAAgB,KAAK;;CAGzB,MAAM,UACJ,KAGA;AACA,oBAAA,2BAAA,MAAA,kBAAsB,CAAA,KAAA,MAAC,OAAO;AAC9B,SACE,KAAK,WAAW,CAOhB,eAAe,IAAI;;CAKvB,MAAM,WAAW,OAAuC;AACtD,oBAAA,2BAAA,MAAA,oBAAwB,CAAA,KAAA,MAAC,MAAM;AAC/B,SACE,KAAK,WAAW,CA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IAAI,MACR,2DAA2D,MAAM,GAClE;;AAIL,SAAA,mBAAyB;AACvB,KAAI,KAAK,aAAa,aAAa,OACjC,OAAM,IAAI,MAAM,wDAAwD;;AAI5E,SAAA,sBAA4B;AAC1B,KAAI,CAAC,KAAK,aAAa,SAAS,YAC9B,OAAM,IAAI,MACR,8DACD;;AAIL,SAAA,0BAAgC;AAC9B,KAAI,CAAC,KAAK,aAAa,SAAS,SAC9B,OAAM,IAAI,MACR,2DACD;;;;;;;;AChFP,IAAa,yBAAb,MAAoC;CAIlC,YAAY,OAAe,YAAwC;AACjE,OAAK,SAAS;AACd,OAAK,cAAc;;CAGrB,KAAK,QAAsB;CAE3B,MAAM,MAA8B;AAClC,SAAO,KAAK,YAAY,WAAW,KAAK,OAAO;;;;;;;AAQnD,IAAa,0BAAb,cAA6C,uBAAuB;CAClE,MAAM,IAAI,SAAgC;AACxC,QAAM,KAAK,YAAY,aAAa,KAAK,QAAQ,IAAI,QAAQ;;;;;;;AAQjE,IAAa,uBAAb,cAA0C,uBAAuB;CAC/D,MAAM,KAAK,KAAqC;AAC9C,SAAQ,MAAM,KAAK,YAAY,cAAc,KAAK,QAAQ,IAAI,IAAK;;CAGrE,MAAM,IAAI,KAAa,SAAiB,aAAqC;AAC3E,QAAM,KAAK,YAAY,aAAa,KAAK,QAAQ,KAAK,SAAS,YAAY;;;;;;AAO/E,SAAgB,qBACd,OACA,MACA,YACA;AACA,SAAQ,MAAR;EACE,KAAK,QACH,QAAO,IAAI,qBAAqB,OAAO,WAAW;EACpD,KAAK,WACH,QAAO,IAAI,wBAAwB,OAAO,WAAW;EAGvD,QACE,QAAO,IAAI,uBAAuB,OAAO,WAAW"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/extensions/host-bridge.ts","../../src/extensions/bridge-provider.ts"],"sourcesContent":["/**\n * HostBridgeLoopback — a WorkerEntrypoint that provides controlled workspace\n * access to extension Workers loaded via WorkerLoader.\n *\n * This is a loopback: the extension worker's `env.host` binding points here,\n * and each method call resolves the parent agent via `ctx.exports`, then\n * delegates to the agent's workspace proxy methods (`_hostReadFile`, etc.).\n *\n * Props carry serializable identifiers (agent class name, agent ID, and\n * permissions) so the binding survives across requests and hibernation.\n *\n * Users must re-export this class from their worker entry point:\n *\n * ```typescript\n * export { HostBridgeLoopback } from \"@cloudflare/think/extensions\";\n * ```\n *\n * @experimental The API surface may change before stabilizing.\n */\n\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport type { ExtensionPermissions } from \"./types\";\n\nexport type HostBridgeLoopbackProps = {\n agentClassName: string;\n agentId: string;\n permissions: ExtensionPermissions;\n /** Namespaced context labels this extension declared (for \"own\" write validation). */\n ownContextLabels?: string[];\n};\n\nexport class HostBridgeLoopback extends WorkerEntrypoint<\n Record<string, unknown>,\n HostBridgeLoopbackProps\n> {\n private _permissions = this.ctx.props.permissions;\n\n private _getAgent() {\n const { agentClassName, agentId } = this.ctx.props;\n // @ts-expect-error — experimental: ctx.exports on WorkerEntrypoint\n const ns = this.ctx.exports[agentClassName] as DurableObjectNamespace;\n return ns.get(ns.idFromString(agentId));\n }\n\n // ── Permission checks ──────────────────────────────────────────\n\n #requireWorkspace(level: \"read\" | \"read-write\"): void {\n const ws = this._permissions.workspace ?? \"none\";\n if (ws === \"none\") {\n throw new Error(\"Extension error: no workspace permission declared\");\n }\n if (level === \"read-write\" && ws !== \"read-write\") {\n throw new Error(\n \"Extension error: workspace write permission required, but only read granted\"\n );\n }\n }\n\n #requireContextRead(label: string): void {\n const ctx = this._permissions.context;\n if (!ctx?.read) {\n throw new Error(\"Extension error: no context read permission declared\");\n }\n if (ctx.read !== \"all\" && !ctx.read.includes(label)) {\n throw new Error(\n `Extension error: no read permission for context label \"${label}\"`\n );\n }\n }\n\n #requireContextWrite(label: string): void {\n const ctx = this._permissions.context;\n if (!ctx?.write) {\n throw new Error(\"Extension error: no context write permission declared\");\n }\n if (ctx.write === \"own\") {\n const owned = this.ctx.props.ownContextLabels ?? [];\n if (!owned.includes(label)) {\n throw new Error(\n `Extension error: label \"${label}\" is not owned by this extension`\n );\n }\n } else if (!ctx.write.includes(label)) {\n throw new Error(\n `Extension error: no write permission for context label \"${label}\"`\n );\n }\n }\n\n #requireMessages(): void {\n if (this._permissions.messages !== \"read\") {\n throw new Error(\"Extension error: no messages read permission declared\");\n }\n }\n\n #requireSendMessage(): void {\n if (!this._permissions.session?.sendMessage) {\n throw new Error(\n \"Extension error: no session.sendMessage permission declared\"\n );\n }\n }\n\n #requireSessionMetadata(): void {\n if (!this._permissions.session?.metadata) {\n throw new Error(\n \"Extension error: no session.metadata permission declared\"\n );\n }\n }\n\n // ── Workspace (existing) ───────────────────────────────────────\n\n async readFile(path: string): Promise<string | null> {\n this.#requireWorkspace(\"read\");\n return (\n this._getAgent() as unknown as {\n _hostReadFile(path: string): Promise<string | null>;\n }\n )._hostReadFile(path);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n this.#requireWorkspace(\"read-write\");\n return (\n this._getAgent() as unknown as {\n _hostWriteFile(path: string, content: string): Promise<void>;\n }\n )._hostWriteFile(path, content);\n }\n\n async deleteFile(path: string): Promise<boolean> {\n this.#requireWorkspace(\"read-write\");\n return (\n this._getAgent() as unknown as {\n _hostDeleteFile(path: string): Promise<boolean>;\n }\n )._hostDeleteFile(path);\n }\n\n async listFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n > {\n this.#requireWorkspace(\"read\");\n return (\n this._getAgent() as unknown as {\n _hostListFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n >;\n }\n )._hostListFiles(dir);\n }\n\n // ── Context blocks (new) ───────────────────────────────────────\n\n async getContext(label: string): Promise<string | null> {\n this.#requireContextRead(label);\n return (\n this._getAgent() as unknown as {\n _hostGetContext(label: string): Promise<string | null>;\n }\n )._hostGetContext(label);\n }\n\n async setContext(label: string, content: string): Promise<void> {\n this.#requireContextWrite(label);\n return (\n this._getAgent() as unknown as {\n _hostSetContext(label: string, content: string): Promise<void>;\n }\n )._hostSetContext(label, content);\n }\n\n // ── Messages (new) ────────────────────────────────────────────\n\n async getMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>> {\n this.#requireMessages();\n return (\n this._getAgent() as unknown as {\n _hostGetMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>>;\n }\n )._hostGetMessages(limit);\n }\n\n async sendMessage(content: string): Promise<void> {\n this.#requireSendMessage();\n return (\n this._getAgent() as unknown as {\n _hostSendMessage(content: string): Promise<void>;\n }\n )._hostSendMessage(content);\n }\n\n // ── Session metadata (new) ────────────────────────────────────\n\n async getSessionInfo(): Promise<{ messageCount: number }> {\n this.#requireSessionMetadata();\n return (\n this._getAgent() as unknown as {\n _hostGetSessionInfo(): Promise<{ messageCount: number }>;\n }\n )._hostGetSessionInfo();\n }\n}\n","/**\n * Bridge providers that adapt extension Worker RPC into Session's\n * ContextProvider / SkillProvider / WritableContextProvider interfaces.\n *\n * When an extension declares context blocks in its manifest, Think creates\n * a bridge provider for each block. The bridge delegates `get()`, `load()`,\n * and `set()` to the extension Worker's entrypoint via RPC.\n *\n * This allows extensions to contribute context blocks to the Session's\n * system prompt without Session knowing about the extension system.\n */\n\ninterface ExtensionContextEntrypoint {\n contextGet(label: string): Promise<string | null>;\n contextLoad?(label: string, key: string): Promise<string | null>;\n contextSet?(\n label: string,\n key: string,\n content: string,\n description?: string\n ): Promise<void>;\n}\n\n/**\n * A readonly context provider backed by an extension Worker.\n * Delegates `get()` to the extension's `contextGet` RPC method.\n */\nexport class ExtensionContextBridge {\n protected _label: string;\n protected _entrypoint: ExtensionContextEntrypoint;\n\n constructor(label: string, entrypoint: ExtensionContextEntrypoint) {\n this._label = label;\n this._entrypoint = entrypoint;\n }\n\n init(_label: string): void {}\n\n async get(): Promise<string | null> {\n return this._entrypoint.contextGet(this._label);\n }\n}\n\n/**\n * A writable context provider backed by an extension Worker.\n * Delegates `get()` and `set()` to the extension's RPC methods.\n */\nexport class ExtensionWritableBridge extends ExtensionContextBridge {\n async set(content: string): Promise<void> {\n await this._entrypoint.contextSet?.(this._label, \"\", content);\n }\n}\n\n/**\n * A skill provider backed by an extension Worker.\n * Delegates `get()`, `load()`, and optionally `set()` to the extension's RPC methods.\n */\nexport class ExtensionSkillBridge extends ExtensionContextBridge {\n async load(key: string): Promise<string | null> {\n return (await this._entrypoint.contextLoad?.(this._label, key)) ?? null;\n }\n\n async set(key: string, content: string, description?: string): Promise<void> {\n await this._entrypoint.contextSet?.(this._label, key, content, description);\n }\n}\n\n/**\n * Create the appropriate bridge provider based on the context block type.\n */\nexport function createBridgeProvider(\n label: string,\n type: \"readonly\" | \"writable\" | \"skill\" | \"searchable\",\n entrypoint: ExtensionContextEntrypoint\n) {\n switch (type) {\n case \"skill\":\n return new ExtensionSkillBridge(label, entrypoint);\n case \"writable\":\n return new ExtensionWritableBridge(label, entrypoint);\n case \"readonly\":\n case \"searchable\":\n default:\n return new ExtensionContextBridge(label, entrypoint);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,qBAAb,cAAwC,iBAGtC;;;;EACA,KAAQ,eAAe,KAAK,IAAI,MAAM;;CAEtC,YAAoB;EAClB,MAAM,EAAE,gBAAgB,YAAY,KAAK,IAAI;EAE7C,MAAM,KAAK,KAAK,IAAI,QAAQ;EAC5B,OAAO,GAAG,IAAI,GAAG,aAAa,QAAQ,CAAC;;CAwEzC,MAAM,SAAS,MAAsC;EACnD,kBAAA,2BAAA,MAAA,kBAAA,CAAA,KAAA,MAAuB,OAAO;EAC9B,OACE,KAAK,WAAW,CAGhB,cAAc,KAAK;;CAGvB,MAAM,UAAU,MAAc,SAAgC;EAC5D,kBAAA,2BAAA,MAAA,kBAAA,CAAA,KAAA,MAAuB,aAAa;EACpC,OACE,KAAK,WAAW,CAGhB,eAAe,MAAM,QAAQ;;CAGjC,MAAM,WAAW,MAAgC;EAC/C,kBAAA,2BAAA,MAAA,kBAAA,C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,IAAI,qBAAqB,OAAO,WAAW;EACpD,KAAK,YACH,OAAO,IAAI,wBAAwB,OAAO,WAAW;EAGvD,SACE,OAAO,IAAI,uBAAuB,OAAO,WAAW"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hook-proxy-5248W-ea.js","names":[],"sources":["../src/extensions/hook-proxy.ts"],"sourcesContent":["/**\n * Serializable snapshots for passing context to sandboxed extension\n * Workers during hook dispatch.\n *\n * Extension Workers can't receive AI SDK or Think objects directly (they\n * contain functions, AbortSignals, class instances, etc.). These snapshots\n * are plain JSON-safe data objects that survive Workers RPC serialization.\n */\n\nimport type { TurnContext, TurnConfig } from \"../think\";\n\n/**\n * Best-effort JSON-safe normalization. Strips functions, AbortSignals,\n * symbols, and replaces `Error` instances with `{ name, message, stack }`.\n * Falls back to `String(value)` for anything that won't round-trip.\n */\nfunction jsonSafe(value: unknown, depth = 0): unknown {\n if (depth > 6) return undefined;\n if (value === null || value === undefined) return value;\n const t = typeof value;\n if (t === \"string\" || t === \"number\" || t === \"boolean\") return value;\n if (t === \"bigint\") return String(value);\n if (t === \"function\" || t === \"symbol\") return undefined;\n if (value instanceof Error) {\n return { name: value.name, message: value.message, stack: value.stack };\n }\n if (Array.isArray(value)) return value.map((v) => jsonSafe(v, depth + 1));\n if (t === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n // Skip non-cloneable hosts like AbortSignal which carry event listeners.\n if (v instanceof AbortSignal) continue;\n const safe = jsonSafe(v, depth + 1);\n if (safe !== undefined) out[k] = safe;\n }\n return out;\n }\n try {\n return String(value);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Serializable snapshot of TurnContext.\n * Passed to extension Workers during beforeTurn hook dispatch.\n * Plain data — no methods, no functions, no classes.\n */\nexport interface TurnContextSnapshot {\n system: string;\n toolNames: string[];\n messageCount: number;\n continuation: boolean;\n body?: Record<string, unknown>;\n modelId: string;\n}\n\n/**\n * Create a serializable snapshot from a TurnContext.\n */\nexport function createTurnContextSnapshot(\n ctx: TurnContext\n): TurnContextSnapshot {\n return {\n system: ctx.system,\n toolNames: Object.keys(ctx.tools),\n messageCount: ctx.messages.length,\n continuation: ctx.continuation,\n body: ctx.body,\n modelId:\n ((ctx.model as Record<string, unknown>).modelId as string) ?? \"unknown\"\n };\n}\n\n/**\n * Parse a hook result from the extension Worker's JSON response.\n * Returns a TurnConfig or null if the extension skipped/errored.\n */\nexport function parseHookResult(\n json: string\n): { config: TurnConfig } | { skipped: true } | { error: string } {\n try {\n const parsed = JSON.parse(json) as Record<string, unknown>;\n if (parsed.skipped) return { skipped: true };\n if (parsed.error) return { error: parsed.error as string };\n return { config: (parsed.result ?? {}) as TurnConfig };\n } catch {\n return { error: \"Failed to parse hook result\" };\n }\n}\n\n// ── Per-tool / per-step / per-chunk snapshots ─────────────────────────\n// These are observation-only snapshots — extensions cannot return data\n// that influences the turn (block/substitute/cancel etc.). Keep the\n// payloads small; extensions that need richer state should subscribe\n// to `beforeTurn` (which gives them the full TurnContextSnapshot) and\n// stash references there.\n\n/** Snapshot for the `beforeToolCall` hook. */\nexport interface ToolCallStartSnapshot {\n toolName: string;\n toolCallId: string;\n input: unknown;\n stepNumber: number | undefined;\n dynamic?: boolean;\n}\n\n/** Snapshot for the `afterToolCall` hook. */\nexport interface ToolCallFinishSnapshot {\n toolName: string;\n toolCallId: string;\n input: unknown;\n stepNumber: number | undefined;\n durationMs: number;\n success: boolean;\n output?: unknown;\n /** Normalized error: `{ name, message, stack }` for Error instances, otherwise `String(error)`. */\n error?: unknown;\n dynamic?: boolean;\n}\n\n/** Snapshot for the `onStepFinish` hook. */\nexport interface StepFinishSnapshot {\n stepNumber: number;\n finishReason: string;\n text: string;\n reasoningText: string | undefined;\n toolCallCount: number;\n toolResultCount: number;\n usage:\n | {\n inputTokens: number | undefined;\n outputTokens: number | undefined;\n totalTokens: number | undefined;\n reasoningTokens: number | undefined;\n cachedInputTokens: number | undefined;\n }\n | undefined;\n /** Provider-specific metadata (e.g. Anthropic cache accounting). */\n providerMetadata: Record<string, unknown> | undefined;\n}\n\n/** Snapshot for the `onChunk` hook. High-frequency — keep minimal. */\nexport interface ChunkSnapshot {\n type: string;\n text?: string;\n toolName?: string;\n toolCallId?: string;\n}\n\nexport function createToolCallStartSnapshot(event: {\n toolCall: {\n toolName: string;\n toolCallId: string;\n input?: unknown;\n dynamic?: boolean;\n };\n stepNumber: number | undefined;\n}): ToolCallStartSnapshot {\n return {\n toolName: event.toolCall.toolName,\n toolCallId: event.toolCall.toolCallId,\n input: jsonSafe(event.toolCall.input),\n stepNumber: event.stepNumber,\n ...(event.toolCall.dynamic !== undefined\n ? { dynamic: event.toolCall.dynamic }\n : {})\n };\n}\n\nexport function createToolCallFinishSnapshot(event: {\n toolCall: {\n toolName: string;\n toolCallId: string;\n input?: unknown;\n dynamic?: boolean;\n };\n stepNumber: number | undefined;\n durationMs: number;\n success: boolean;\n output?: unknown;\n error?: unknown;\n}): ToolCallFinishSnapshot {\n return {\n toolName: event.toolCall.toolName,\n toolCallId: event.toolCall.toolCallId,\n input: jsonSafe(event.toolCall.input),\n stepNumber: event.stepNumber,\n durationMs: event.durationMs,\n success: event.success,\n ...(event.success\n ? { output: jsonSafe(event.output) }\n : { error: jsonSafe(event.error) }),\n ...(event.toolCall.dynamic !== undefined\n ? { dynamic: event.toolCall.dynamic }\n : {})\n };\n}\n\nexport function createStepFinishSnapshot(event: {\n stepNumber: number;\n finishReason: string;\n text: string;\n reasoningText: string | undefined;\n toolCalls: ReadonlyArray<unknown>;\n toolResults: ReadonlyArray<unknown>;\n usage?: {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n reasoningTokens?: number;\n cachedInputTokens?: number;\n };\n providerMetadata?: Record<string, unknown>;\n}): StepFinishSnapshot {\n return {\n stepNumber: event.stepNumber,\n finishReason: event.finishReason,\n text: event.text,\n reasoningText: event.reasoningText,\n toolCallCount: event.toolCalls.length,\n toolResultCount: event.toolResults.length,\n usage: event.usage\n ? {\n inputTokens: event.usage.inputTokens,\n outputTokens: event.usage.outputTokens,\n totalTokens: event.usage.totalTokens,\n reasoningTokens: event.usage.reasoningTokens,\n cachedInputTokens: event.usage.cachedInputTokens\n }\n : undefined,\n providerMetadata: event.providerMetadata as\n | Record<string, unknown>\n | undefined\n };\n}\n\nexport function createChunkSnapshot(event: {\n chunk: { type: string; [key: string]: unknown };\n}): ChunkSnapshot {\n const c = event.chunk;\n const snapshot: ChunkSnapshot = { type: c.type };\n // text-delta / reasoning-delta carry `text`\n if (typeof c.text === \"string\") snapshot.text = c.text;\n // tool-related chunks carry tool identifiers\n if (typeof c.toolName === \"string\") snapshot.toolName = c.toolName;\n if (typeof c.toolCallId === \"string\") snapshot.toolCallId = c.toolCallId;\n return snapshot;\n}\n"],"mappings":";;;;;;AAgBA,SAAS,SAAS,OAAgB,QAAQ,GAAY;AACpD,KAAI,QAAQ,EAAG,QAAO,KAAA;AACtB,KAAI,UAAU,QAAQ,UAAU,KAAA,EAAW,QAAO;CAClD,MAAM,IAAI,OAAO;AACjB,KAAI,MAAM,YAAY,MAAM,YAAY,MAAM,UAAW,QAAO;AAChE,KAAI,MAAM,SAAU,QAAO,OAAO,MAAM;AACxC,KAAI,MAAM,cAAc,MAAM,SAAU,QAAO,KAAA;AAC/C,KAAI,iBAAiB,MACnB,QAAO;EAAE,MAAM,MAAM;EAAM,SAAS,MAAM;EAAS,OAAO,MAAM;EAAO;AAEzE,KAAI,MAAM,QAAQ,MAAM,CAAE,QAAO,MAAM,KAAK,MAAM,SAAS,GAAG,QAAQ,EAAE,CAAC;AACzE,KAAI,MAAM,UAAU;EAClB,MAAM,MAA+B,EAAE;AACvC,OAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,MAAiC,EAAE;AAErE,OAAI,aAAa,YAAa;GAC9B,MAAM,OAAO,SAAS,GAAG,QAAQ,EAAE;AACnC,OAAI,SAAS,KAAA,EAAW,KAAI,KAAK;;AAEnC,SAAO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AAM;EACrB,eAAe,MAAM,UAAU;EAC/B,iBAAiB,MAAM,YAAY;EACnC,OAAO,MAAM,QACT;GACE,aAAa,MAAM,MAAM;GACzB,cAAc,MAAM,MAAM;GAC1B,aAAa,MAAM,MAAM;GACzB,iBAAiB,MAAM,MAAM;GAC7B,mBAAmB,MAAM,MAAM;GAChC,GACD,KAAA;EACJ,kBAAkB,MAAM;EAGzB;;AAGH,SAAgB,oBAAoB,OAElB;CAChB,MAAM,IAAI,MAAM;CAChB,MAAM,WAA0B,EAAE,MAAM,EAAE,MAAM;AAEhD,KAAI,OAAO,EAAE,SAAS,SAAU,UAAS,OAAO,EAAE;AAElD,KAAI,OAAO,EAAE,aAAa,SAAU,UAAS,WAAW,EAAE;AAC1D,KAAI,OAAO,EAAE,eAAe,SAAU,UAAS,aAAa,EAAE;AAC9D,QAAO"}
|
|
1
|
+
{"version":3,"file":"hook-proxy-5248W-ea.js","names":[],"sources":["../src/extensions/hook-proxy.ts"],"sourcesContent":["/**\n * Serializable snapshots for passing context to sandboxed extension\n * Workers during hook dispatch.\n *\n * Extension Workers can't receive AI SDK or Think objects directly (they\n * contain functions, AbortSignals, class instances, etc.). These snapshots\n * are plain JSON-safe data objects that survive Workers RPC serialization.\n */\n\nimport type { TurnContext, TurnConfig } from \"../think\";\n\n/**\n * Best-effort JSON-safe normalization. Strips functions, AbortSignals,\n * symbols, and replaces `Error` instances with `{ name, message, stack }`.\n * Falls back to `String(value)` for anything that won't round-trip.\n */\nfunction jsonSafe(value: unknown, depth = 0): unknown {\n if (depth > 6) return undefined;\n if (value === null || value === undefined) return value;\n const t = typeof value;\n if (t === \"string\" || t === \"number\" || t === \"boolean\") return value;\n if (t === \"bigint\") return String(value);\n if (t === \"function\" || t === \"symbol\") return undefined;\n if (value instanceof Error) {\n return { name: value.name, message: value.message, stack: value.stack };\n }\n if (Array.isArray(value)) return value.map((v) => jsonSafe(v, depth + 1));\n if (t === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n // Skip non-cloneable hosts like AbortSignal which carry event listeners.\n if (v instanceof AbortSignal) continue;\n const safe = jsonSafe(v, depth + 1);\n if (safe !== undefined) out[k] = safe;\n }\n return out;\n }\n try {\n return String(value);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Serializable snapshot of TurnContext.\n * Passed to extension Workers during beforeTurn hook dispatch.\n * Plain data — no methods, no functions, no classes.\n */\nexport interface TurnContextSnapshot {\n system: string;\n toolNames: string[];\n messageCount: number;\n continuation: boolean;\n body?: Record<string, unknown>;\n modelId: string;\n}\n\n/**\n * Create a serializable snapshot from a TurnContext.\n */\nexport function createTurnContextSnapshot(\n ctx: TurnContext\n): TurnContextSnapshot {\n return {\n system: ctx.system,\n toolNames: Object.keys(ctx.tools),\n messageCount: ctx.messages.length,\n continuation: ctx.continuation,\n body: ctx.body,\n modelId:\n ((ctx.model as Record<string, unknown>).modelId as string) ?? \"unknown\"\n };\n}\n\n/**\n * Parse a hook result from the extension Worker's JSON response.\n * Returns a TurnConfig or null if the extension skipped/errored.\n */\nexport function parseHookResult(\n json: string\n): { config: TurnConfig } | { skipped: true } | { error: string } {\n try {\n const parsed = JSON.parse(json) as Record<string, unknown>;\n if (parsed.skipped) return { skipped: true };\n if (parsed.error) return { error: parsed.error as string };\n return { config: (parsed.result ?? {}) as TurnConfig };\n } catch {\n return { error: \"Failed to parse hook result\" };\n }\n}\n\n// ── Per-tool / per-step / per-chunk snapshots ─────────────────────────\n// These are observation-only snapshots — extensions cannot return data\n// that influences the turn (block/substitute/cancel etc.). Keep the\n// payloads small; extensions that need richer state should subscribe\n// to `beforeTurn` (which gives them the full TurnContextSnapshot) and\n// stash references there.\n\n/** Snapshot for the `beforeToolCall` hook. */\nexport interface ToolCallStartSnapshot {\n toolName: string;\n toolCallId: string;\n input: unknown;\n stepNumber: number | undefined;\n dynamic?: boolean;\n}\n\n/** Snapshot for the `afterToolCall` hook. */\nexport interface ToolCallFinishSnapshot {\n toolName: string;\n toolCallId: string;\n input: unknown;\n stepNumber: number | undefined;\n durationMs: number;\n success: boolean;\n output?: unknown;\n /** Normalized error: `{ name, message, stack }` for Error instances, otherwise `String(error)`. */\n error?: unknown;\n dynamic?: boolean;\n}\n\n/** Snapshot for the `onStepFinish` hook. */\nexport interface StepFinishSnapshot {\n stepNumber: number;\n finishReason: string;\n text: string;\n reasoningText: string | undefined;\n toolCallCount: number;\n toolResultCount: number;\n usage:\n | {\n inputTokens: number | undefined;\n outputTokens: number | undefined;\n totalTokens: number | undefined;\n reasoningTokens: number | undefined;\n cachedInputTokens: number | undefined;\n }\n | undefined;\n /** Provider-specific metadata (e.g. Anthropic cache accounting). */\n providerMetadata: Record<string, unknown> | undefined;\n}\n\n/** Snapshot for the `onChunk` hook. High-frequency — keep minimal. */\nexport interface ChunkSnapshot {\n type: string;\n text?: string;\n toolName?: string;\n toolCallId?: string;\n}\n\nexport function createToolCallStartSnapshot(event: {\n toolCall: {\n toolName: string;\n toolCallId: string;\n input?: unknown;\n dynamic?: boolean;\n };\n stepNumber: number | undefined;\n}): ToolCallStartSnapshot {\n return {\n toolName: event.toolCall.toolName,\n toolCallId: event.toolCall.toolCallId,\n input: jsonSafe(event.toolCall.input),\n stepNumber: event.stepNumber,\n ...(event.toolCall.dynamic !== undefined\n ? { dynamic: event.toolCall.dynamic }\n : {})\n };\n}\n\nexport function createToolCallFinishSnapshot(event: {\n toolCall: {\n toolName: string;\n toolCallId: string;\n input?: unknown;\n dynamic?: boolean;\n };\n stepNumber: number | undefined;\n durationMs: number;\n success: boolean;\n output?: unknown;\n error?: unknown;\n}): ToolCallFinishSnapshot {\n return {\n toolName: event.toolCall.toolName,\n toolCallId: event.toolCall.toolCallId,\n input: jsonSafe(event.toolCall.input),\n stepNumber: event.stepNumber,\n durationMs: event.durationMs,\n success: event.success,\n ...(event.success\n ? { output: jsonSafe(event.output) }\n : { error: jsonSafe(event.error) }),\n ...(event.toolCall.dynamic !== undefined\n ? { dynamic: event.toolCall.dynamic }\n : {})\n };\n}\n\nexport function createStepFinishSnapshot(event: {\n stepNumber: number;\n finishReason: string;\n text: string;\n reasoningText: string | undefined;\n toolCalls: ReadonlyArray<unknown>;\n toolResults: ReadonlyArray<unknown>;\n usage?: {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n reasoningTokens?: number;\n cachedInputTokens?: number;\n };\n providerMetadata?: Record<string, unknown>;\n}): StepFinishSnapshot {\n return {\n stepNumber: event.stepNumber,\n finishReason: event.finishReason,\n text: event.text,\n reasoningText: event.reasoningText,\n toolCallCount: event.toolCalls.length,\n toolResultCount: event.toolResults.length,\n usage: event.usage\n ? {\n inputTokens: event.usage.inputTokens,\n outputTokens: event.usage.outputTokens,\n totalTokens: event.usage.totalTokens,\n reasoningTokens: event.usage.reasoningTokens,\n cachedInputTokens: event.usage.cachedInputTokens\n }\n : undefined,\n providerMetadata: event.providerMetadata as\n | Record<string, unknown>\n | undefined\n };\n}\n\nexport function createChunkSnapshot(event: {\n chunk: { type: string; [key: string]: unknown };\n}): ChunkSnapshot {\n const c = event.chunk;\n const snapshot: ChunkSnapshot = { type: c.type };\n // text-delta / reasoning-delta carry `text`\n if (typeof c.text === \"string\") snapshot.text = c.text;\n // tool-related chunks carry tool identifiers\n if (typeof c.toolName === \"string\") snapshot.toolName = c.toolName;\n if (typeof c.toolCallId === \"string\") snapshot.toolCallId = c.toolCallId;\n return snapshot;\n}\n"],"mappings":";;;;;;AAgBA,SAAS,SAAS,OAAgB,QAAQ,GAAY;CACpD,IAAI,QAAQ,GAAG,OAAO,KAAA;CACtB,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAClD,MAAM,IAAI,OAAO;CACjB,IAAI,MAAM,YAAY,MAAM,YAAY,MAAM,WAAW,OAAO;CAChE,IAAI,MAAM,UAAU,OAAO,OAAO,MAAM;CACxC,IAAI,MAAM,cAAc,MAAM,UAAU,OAAO,KAAA;CAC/C,IAAI,iBAAiB,OACnB,OAAO;EAAE,MA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AAO,SAAS,MAAM,SAAS,MAAM;EACrC,YAAY,MAAM;EAClB,YAAY,MAAM;EAClB,SAAS,MAAM;EACf,GAAI,MAAM,UACN,EAAE,QAAQ,SAAS,MAAM,OAAO,EAAE,GAClC,EAAE,OAAO,SAAS,MAAM,MAAM,EAAE;EACpC,GAAI,MAAM,SAAS,YAAY,KAAA,IAC3B,EAAE,SAAS,MAAM,SAAS,SAAS,GACnC,EAAE;EACP;;AAGH,SAAgB,yBAAyB,OAelB;CACrB,OAAO;EACL,YAAY,MAAM;EAClB,cAAc,MAAM;EACpB,MAAM,MAAM;EACZ,eAAe,MAAM;EACrB,eAAe,MAAM,UAAU;EAC/B,iBAAiB,MAAM,YAAY;EACnC,OAAO,MAAM,QACT;GACE,aAAa,MAAM,MAAM;GACzB,cAAc,MAAM,MAAM;GAC1B,aAAa,MAAM,MAAM;GACzB,iBAAiB,MAAM,MAAM;GAC7B,mBAAmB,MAAM,MAAM;GAChC,GACD,KAAA;EACJ,kBAAkB,MAAM;EAGzB;;AAGH,SAAgB,oBAAoB,OAElB;CAChB,MAAM,IAAI,MAAM;CAChB,MAAM,WAA0B,EAAE,MAAM,EAAE,MAAM;CAEhD,IAAI,OAAO,EAAE,SAAS,UAAU,SAAS,OAAO,EAAE;CAElD,IAAI,OAAO,EAAE,aAAa,UAAU,SAAS,WAAW,EAAE;CAC1D,IAAI,OAAO,EAAE,eAAe,UAAU,SAAS,aAAa,EAAE;CAC9D,OAAO"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as _checkPrivateRedeclaration, i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, r as _assertClassBrand, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-
|
|
1
|
+
import { a as _checkPrivateRedeclaration, i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, r as _assertClassBrand, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-CCiYk1x3.js";
|
|
2
2
|
import { jsonSchema, tool } from "ai";
|
|
3
3
|
//#region \0rolldown/runtime.js
|
|
4
4
|
var __defProp = Object.defineProperty;
|
|
@@ -12,7 +12,7 @@ var __exportAll = (all, no_symbols) => {
|
|
|
12
12
|
return target;
|
|
13
13
|
};
|
|
14
14
|
//#endregion
|
|
15
|
-
//#region \0@oxc-project+runtime@0.
|
|
15
|
+
//#region \0@oxc-project+runtime@0.129.0/helpers/classPrivateMethodInitSpec.js
|
|
16
16
|
function _classPrivateMethodInitSpec(e, a) {
|
|
17
17
|
_checkPrivateRedeclaration(e, a), a.add(e);
|
|
18
18
|
}
|
|
@@ -326,4 +326,4 @@ export default class Extension extends WorkerEntrypoint {
|
|
|
326
326
|
//#endregion
|
|
327
327
|
export { _classPrivateMethodInitSpec as i, manager_exports as n, sanitizeName as r, ExtensionManager as t };
|
|
328
328
|
|
|
329
|
-
//# sourceMappingURL=manager-
|
|
329
|
+
//# sourceMappingURL=manager-BypfrNX0.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager-DDC3Gb0V.js","names":[],"sources":["../src/extensions/manager.ts"],"sourcesContent":["/**\n * ExtensionManager — loads, manages, and exposes tools from extension Workers.\n *\n * Extensions are sandboxed Workers created via WorkerLoader. Each extension\n * declares tools (with JSON Schema inputs) and permissions. The manager:\n *\n * 1. Wraps extension source in a Worker module with describe/execute RPC\n * 2. Loads it via WorkerLoader with permission-gated bindings\n * 3. Discovers tools via describe() RPC call\n * 4. Exposes them as AI SDK tools via getTools()\n *\n * Extension source format — a JS object expression defining tools:\n *\n * ```js\n * ({\n * greet: {\n * description: \"Greet someone\",\n * parameters: { name: { type: \"string\" } },\n * required: [\"name\"],\n * execute: async (args, host) => `Hello, ${args.name}!`\n * }\n * })\n * ```\n *\n * The `host` parameter in execute is provided via `env.host` — a loopback\n * binding that resolves the parent agent and delegates workspace operations\n * (gated by permissions). See HostBridgeLoopback.\n */\n\nimport { tool, jsonSchema } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport type {\n ExtensionManifest,\n ExtensionPermissions,\n ExtensionInfo,\n ExtensionToolDescriptor\n} from \"./types\";\n\n/**\n * Sanitize a name for use as a tool name prefix.\n * Replaces any non-alphanumeric characters with underscores and\n * collapses consecutive underscores.\n */\nexport function sanitizeName(name: string): string {\n if (!name || name.trim().length === 0) {\n throw new Error(\"Extension name must not be empty\");\n }\n return name\n .replace(/[^a-zA-Z0-9]/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_|_$/g, \"\");\n}\n\ninterface ExtensionEntrypoint {\n describe(): Promise<string>;\n manifest(): Promise<string>;\n execute(toolName: string, argsJson: string): Promise<string>;\n hook(name: string, ctxProxy: unknown): Promise<string>;\n}\n\ninterface LoadedExtension {\n manifest: ExtensionManifest;\n tools: ExtensionToolDescriptor[];\n hooks: string[];\n entrypoint: ExtensionEntrypoint;\n}\n\n/** Shape persisted to DO storage for each extension. */\ninterface PersistedExtension {\n manifest: ExtensionManifest;\n source: string;\n}\n\nconst STORAGE_PREFIX = \"ext:\";\n\nexport interface ExtensionManagerOptions {\n /** WorkerLoader binding for creating sandboxed extension Workers. */\n loader: WorkerLoader;\n /**\n * Durable Object storage for persisting extensions across hibernation.\n * If provided, loaded extensions survive DO restarts. Call `restore()`\n * on each turn to rebuild in-memory state from storage.\n */\n storage?: DurableObjectStorage;\n /**\n * Factory that creates a loopback Fetcher for workspace access, given\n * an extension's declared permissions. The returned binding is injected\n * into the extension worker's `env.host`.\n *\n * If not provided, extensions receive no host binding (workspace tools\n * will get `null` for the host parameter).\n *\n * Typically wired up using HostBridgeLoopback via `ctx.exports`:\n * ```typescript\n * createHostBinding: (permissions, ownContextLabels) =>\n * ctx.exports.HostBridgeLoopback({\n * props: { agentClassName: \"ChatSession\", agentId: ctx.id.toString(), permissions, ownContextLabels }\n * })\n * ```\n */\n createHostBinding?: (\n permissions: ExtensionPermissions,\n ownContextLabels: string[]\n ) => Fetcher;\n}\n\nexport class ExtensionManager {\n #loader: WorkerLoader;\n #storage: DurableObjectStorage | null;\n #createHostBinding:\n | ((\n permissions: ExtensionPermissions,\n ownContextLabels: string[]\n ) => Fetcher)\n | null;\n #extensions = new Map<string, LoadedExtension>();\n #restored = false;\n #onUnload:\n | ((name: string, contextLabels: string[]) => void | Promise<void>)\n | null = null;\n\n constructor(options: ExtensionManagerOptions) {\n this.#loader = options.loader;\n this.#storage = options.storage ?? null;\n this.#createHostBinding = options.createHostBinding ?? null;\n }\n\n /**\n * Load an extension from source code.\n *\n * The source is a JS object expression defining tools. Each tool has\n * `description`, `parameters` (JSON Schema properties), optional\n * `required` array, and an `execute` async function.\n *\n * @returns Summary of the loaded extension including discovered tools.\n */\n /**\n * Restore extensions from DO storage after hibernation.\n *\n * Idempotent — skips extensions already in memory. Call this at the\n * start of each chat turn (e.g. in onChatMessage before getTools).\n */\n async restore(): Promise<void> {\n if (this.#restored || !this.#storage) return;\n this.#restored = true;\n\n const entries = await this.#storage.list<PersistedExtension>({\n prefix: STORAGE_PREFIX\n });\n\n for (const persisted of entries.values()) {\n if (this.#extensions.has(persisted.manifest.name)) continue;\n await this.#loadInternal(persisted.manifest, persisted.source);\n }\n }\n\n async load(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n if (this.#extensions.has(manifest.name)) {\n throw new Error(\n `Extension \"${manifest.name}\" is already loaded. Unload it first.`\n );\n }\n\n const info = await this.#loadInternal(manifest, source);\n\n // Persist to storage so it survives hibernation\n if (this.#storage) {\n await this.#storage.put<PersistedExtension>(\n `${STORAGE_PREFIX}${manifest.name}`,\n { manifest, source }\n );\n }\n\n return info;\n }\n\n async #loadInternal(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n const workerModule = wrapExtensionSource(source);\n const permissions = manifest.permissions ?? {};\n\n // Build env bindings for the dynamic worker. Inject a loopback\n // Fetcher as env.host when the extension declares ANY permission\n // that requires host access (workspace, context, messages, session).\n const workerEnv: Record<string, Fetcher> = {};\n const needsHost =\n (permissions.workspace ?? \"none\") !== \"none\" ||\n permissions.context?.read !== undefined ||\n permissions.context?.write !== undefined ||\n (permissions.messages ?? \"none\") !== \"none\" ||\n permissions.session?.sendMessage ||\n permissions.session?.metadata;\n if (this.#createHostBinding && needsHost) {\n const prefix = sanitizeName(manifest.name);\n const ownLabels = (manifest.context ?? []).map(\n (c) => `${prefix}_${c.label}`\n );\n workerEnv.host = this.#createHostBinding(permissions, ownLabels);\n }\n\n const worker = this.#loader.get(\n `ext-${manifest.name}-${manifest.version}-${Date.now()}`,\n () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"extension.js\",\n modules: { \"extension.js\": workerModule },\n globalOutbound: permissions.network?.length ? undefined : null,\n ...(Object.keys(workerEnv).length > 0 ? { env: workerEnv } : {})\n })\n );\n\n const entrypoint = worker.getEntrypoint() as unknown as ExtensionEntrypoint;\n\n // Discover tools and hooks via RPC\n const descriptorsJson = await entrypoint.describe();\n const tools = JSON.parse(descriptorsJson) as ExtensionToolDescriptor[];\n\n let hooks: string[] = [];\n try {\n const manifestJson = await entrypoint.manifest();\n const runtimeManifest = JSON.parse(manifestJson) as {\n hooks?: string[];\n };\n hooks = runtimeManifest.hooks ?? [];\n } catch {\n // Legacy extensions may not have manifest() — treat as no hooks\n }\n\n this.#extensions.set(manifest.name, {\n manifest,\n tools,\n hooks,\n entrypoint\n });\n\n return toExtensionInfo(manifest, tools);\n }\n\n /**\n * Unload an extension, removing its tools from the agent.\n * If an onUnload callback is registered, it fires with the\n * extension's namespaced context labels so the caller can\n * remove context blocks from the Session.\n */\n async unload(name: string): Promise<boolean> {\n const ext = this.#extensions.get(name);\n if (!ext) return false;\n\n const removed = this.#extensions.delete(name);\n if (removed && this.#storage) {\n await this.#storage.delete(`${STORAGE_PREFIX}${name}`);\n }\n\n if (removed && this.#onUnload) {\n const prefix = sanitizeName(name);\n const contextLabels = (ext.manifest.context ?? []).map(\n (c) => `${prefix}_${c.label}`\n );\n await this.#onUnload(name, contextLabels);\n }\n\n return removed;\n }\n\n /**\n * Register a callback invoked when an extension is unloaded.\n * Think uses this to remove the extension's context blocks from Session.\n */\n onUnload(\n cb: (name: string, contextLabels: string[]) => void | Promise<void>\n ): void {\n this.#onUnload = cb;\n }\n\n /**\n * Get the namespaced context labels for all loaded extensions\n * that declare context blocks in their manifests.\n */\n getContextLabels(): Array<{ extName: string; label: string }> {\n const result: Array<{ extName: string; label: string }> = [];\n for (const ext of this.#extensions.values()) {\n if (!ext.manifest.context) continue;\n const prefix = sanitizeName(ext.manifest.name);\n for (const ctx of ext.manifest.context) {\n result.push({\n extName: ext.manifest.name,\n label: `${prefix}_${ctx.label}`\n });\n }\n }\n return result;\n }\n\n /**\n * Get extension manifest by name.\n */\n getManifest(name: string): ExtensionManifest | null {\n return this.#extensions.get(name)?.manifest ?? null;\n }\n\n /**\n * Get extensions that subscribe to a specific hook, in load order.\n */\n getHookSubscribers(\n hookName: string\n ): Array<{ name: string; entrypoint: ExtensionEntrypoint }> {\n const result: Array<{ name: string; entrypoint: ExtensionEntrypoint }> = [];\n for (const ext of this.#extensions.values()) {\n if (ext.hooks.includes(hookName)) {\n result.push({ name: ext.manifest.name, entrypoint: ext.entrypoint });\n }\n }\n return result;\n }\n\n /**\n * List all loaded extensions.\n */\n list(): ExtensionInfo[] {\n return [...this.#extensions.values()].map((ext) =>\n toExtensionInfo(ext.manifest, ext.tools)\n );\n }\n\n /**\n * Get AI SDK tools from all loaded extensions.\n *\n * Tool names are prefixed with the sanitized extension name to avoid\n * collisions: e.g. extension \"github\" with tool \"create_pr\" → \"github_create_pr\".\n */\n getTools(): ToolSet {\n const tools: ToolSet = {};\n\n for (const ext of this.#extensions.values()) {\n const prefix = sanitizeName(ext.manifest.name);\n\n for (const descriptor of ext.tools) {\n const toolName = `${prefix}_${descriptor.name}`;\n\n tools[toolName] = tool({\n description: `[${ext.manifest.name}] ${descriptor.description}`,\n inputSchema: jsonSchema(\n descriptor.inputSchema as Record<string, unknown>\n ),\n execute: async (args: Record<string, unknown>) => {\n if (!this.#extensions.has(ext.manifest.name)) {\n throw new Error(\n `Extension \"${ext.manifest.name}\" has been unloaded. Tool \"${toolName}\" is no longer available.`\n );\n }\n const resultJson = await ext.entrypoint.execute(\n descriptor.name,\n JSON.stringify(args)\n );\n const parsed = JSON.parse(resultJson) as {\n result?: unknown;\n error?: string;\n };\n if (parsed.error) throw new Error(parsed.error);\n return parsed.result;\n }\n });\n }\n }\n\n return tools;\n }\n}\n\nfunction toExtensionInfo(\n manifest: ExtensionManifest,\n tools: ExtensionToolDescriptor[]\n): ExtensionInfo {\n const prefix = sanitizeName(manifest.name);\n return {\n name: manifest.name,\n version: manifest.version,\n description: manifest.description,\n tools: tools.map((t) => `${prefix}_${t.name}`),\n contextLabels: (manifest.context ?? []).map((c) => `${prefix}_${c.label}`),\n permissions: manifest.permissions ?? {}\n };\n}\n\n/**\n * Wrap an extension source in a Worker module that exposes\n * describe(), execute(), manifest(), and hook RPC methods.\n *\n * Source format: `({ tools: {...}, hooks: {...} })`\n * Both `tools` and `hooks` are optional.\n */\nfunction wrapExtensionSource(source: string): string {\n return `import { WorkerEntrypoint } from \"cloudflare:workers\";\n\nconst __ext = (${source});\nif (__ext && typeof __ext === \"object\" && !(\"tools\" in __ext) && !(\"hooks\" in __ext)) {\n throw new Error(\n \"Invalid extension source format. Expected { tools: {...}, hooks: {...} } \" +\n \"but got a flat object. Wrap your tools in a 'tools' key.\"\n );\n}\nconst __tools = __ext.tools || {};\nconst __hooks = __ext.hooks || {};\n\nexport default class Extension extends WorkerEntrypoint {\n describe() {\n const descriptors = [];\n for (const [name, def] of Object.entries(__tools)) {\n descriptors.push({\n name,\n description: def.description || name,\n inputSchema: {\n type: \"object\",\n properties: def.parameters || {},\n required: def.required || []\n }\n });\n }\n return JSON.stringify(descriptors);\n }\n\n manifest() {\n return JSON.stringify({\n hooks: Object.keys(__hooks)\n });\n }\n\n async execute(toolName, argsJson) {\n const def = __tools[toolName];\n if (!def || !def.execute) {\n return JSON.stringify({ error: \"Unknown tool: \" + toolName });\n }\n try {\n const args = JSON.parse(argsJson);\n const result = await def.execute(args, this.env.host ?? null);\n return JSON.stringify({ result });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n\n async hook(name, ctxSnapshot) {\n const fn = __hooks[name];\n if (!fn) return JSON.stringify({ skipped: true });\n try {\n // Hook handlers receive (ctxSnapshot, host) — symmetric with tool\n // executes. \\`host\\` is null when the extension was loaded without\n // host-requiring permissions or when the worker entry point doesn't\n // re-export HostBridgeLoopback.\n const result = await fn(ctxSnapshot, this.env.host ?? null);\n return JSON.stringify({ result: result ?? {} });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n}\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,aAAa,MAAsB;AACjD,KAAI,CAAC,QAAQ,KAAK,MAAM,CAAC,WAAW,EAClC,OAAM,IAAI,MAAM,mCAAmC;AAErD,QAAO,KACJ,QAAQ,iBAAiB,IAAI,CAC7B,QAAQ,OAAO,IAAI,CACnB,QAAQ,UAAU,GAAG;;AAuB1B,MAAM,iBAAiB;;;;;;;;AAiCvB,IAAa,mBAAb,MAA8B;CAe5B,YAAY,SAAkC;;mDAdxB;oDACgB;8DAM7B;gEACK,IAAI,KAA8B,CAAC;8CACrC,MAAM;8CAGP,KAAK;AAGd,yBAAA,SAAA,MAAe,QAAQ,OAAM;AAC7B,yBAAA,UAAA,MAAgB,QAAQ,WAAW,KAAI;AACvC,yBAAA,oBAAA,MAA0B,QAAQ,qBAAqB,KAAI;;;;;;;;;;;;;;;;;CAkB7D,MAAM,UAAyB;AAC7B,MAAA,uBAAA,WAAI,KAAc,IAAI,CAAA,uBAAA,UAAC,KAAa,CAAE;AACtC,yBAAA,WAAA,MAAiB,KAAI;EAErB,MAAM,UAAU,MAAA,uBAAA,UAAM,KAAa,CAAC,KAAyB,EAC3D,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B,KAAK,MAAM,aAGZ,CAAC,SAAS,EAAE;SAC7B;AAIR,wBAAA,aAAA,KAAgB,CAAC,IAAI,SAAS,MAAM;EAClC;EACA;EACA;EACA;EACD,CAAC;AAEF,QAAO,gBAAgB,UAAU,MAAM;;AAsI3C,SAAS,gBACP,UACA,OACe;CACf,MAAM,SAAS,aAAa,SAAS,KAAK;AAC1C,QAAO;EACL,MAAM,SAAS;EACf,SAAS,SAAS;EAClB,aAAa,SAAS;EACtB,OAAO,MAAM,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,OAAO;EAC9C,gBAAgB,SAAS,WAAW,EAAE,EAAE,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,QAAQ;EAC1E,aAAa,SAAS,eAAe,EAAE;EACxC;;;;;;;;;AAUH,SAAS,oBAAoB,QAAwB;AACnD,QAAO;;iBAEQ,OAAO"}
|
|
1
|
+
{"version":3,"file":"manager-BypfrNX0.js","names":[],"sources":["../src/extensions/manager.ts"],"sourcesContent":["/**\n * ExtensionManager — loads, manages, and exposes tools from extension Workers.\n *\n * Extensions are sandboxed Workers created via WorkerLoader. Each extension\n * declares tools (with JSON Schema inputs) and permissions. The manager:\n *\n * 1. Wraps extension source in a Worker module with describe/execute RPC\n * 2. Loads it via WorkerLoader with permission-gated bindings\n * 3. Discovers tools via describe() RPC call\n * 4. Exposes them as AI SDK tools via getTools()\n *\n * Extension source format — a JS object expression defining tools:\n *\n * ```js\n * ({\n * greet: {\n * description: \"Greet someone\",\n * parameters: { name: { type: \"string\" } },\n * required: [\"name\"],\n * execute: async (args, host) => `Hello, ${args.name}!`\n * }\n * })\n * ```\n *\n * The `host` parameter in execute is provided via `env.host` — a loopback\n * binding that resolves the parent agent and delegates workspace operations\n * (gated by permissions). See HostBridgeLoopback.\n */\n\nimport { tool, jsonSchema } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport type {\n ExtensionManifest,\n ExtensionPermissions,\n ExtensionInfo,\n ExtensionToolDescriptor\n} from \"./types\";\n\n/**\n * Sanitize a name for use as a tool name prefix.\n * Replaces any non-alphanumeric characters with underscores and\n * collapses consecutive underscores.\n */\nexport function sanitizeName(name: string): string {\n if (!name || name.trim().length === 0) {\n throw new Error(\"Extension name must not be empty\");\n }\n return name\n .replace(/[^a-zA-Z0-9]/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_|_$/g, \"\");\n}\n\ninterface ExtensionEntrypoint {\n describe(): Promise<string>;\n manifest(): Promise<string>;\n execute(toolName: string, argsJson: string): Promise<string>;\n hook(name: string, ctxProxy: unknown): Promise<string>;\n}\n\ninterface LoadedExtension {\n manifest: ExtensionManifest;\n tools: ExtensionToolDescriptor[];\n hooks: string[];\n entrypoint: ExtensionEntrypoint;\n}\n\n/** Shape persisted to DO storage for each extension. */\ninterface PersistedExtension {\n manifest: ExtensionManifest;\n source: string;\n}\n\nconst STORAGE_PREFIX = \"ext:\";\n\nexport interface ExtensionManagerOptions {\n /** WorkerLoader binding for creating sandboxed extension Workers. */\n loader: WorkerLoader;\n /**\n * Durable Object storage for persisting extensions across hibernation.\n * If provided, loaded extensions survive DO restarts. Call `restore()`\n * on each turn to rebuild in-memory state from storage.\n */\n storage?: DurableObjectStorage;\n /**\n * Factory that creates a loopback Fetcher for workspace access, given\n * an extension's declared permissions. The returned binding is injected\n * into the extension worker's `env.host`.\n *\n * If not provided, extensions receive no host binding (workspace tools\n * will get `null` for the host parameter).\n *\n * Typically wired up using HostBridgeLoopback via `ctx.exports`:\n * ```typescript\n * createHostBinding: (permissions, ownContextLabels) =>\n * ctx.exports.HostBridgeLoopback({\n * props: { agentClassName: \"ChatSession\", agentId: ctx.id.toString(), permissions, ownContextLabels }\n * })\n * ```\n */\n createHostBinding?: (\n permissions: ExtensionPermissions,\n ownContextLabels: string[]\n ) => Fetcher;\n}\n\nexport class ExtensionManager {\n #loader: WorkerLoader;\n #storage: DurableObjectStorage | null;\n #createHostBinding:\n | ((\n permissions: ExtensionPermissions,\n ownContextLabels: string[]\n ) => Fetcher)\n | null;\n #extensions = new Map<string, LoadedExtension>();\n #restored = false;\n #onUnload:\n | ((name: string, contextLabels: string[]) => void | Promise<void>)\n | null = null;\n\n constructor(options: ExtensionManagerOptions) {\n this.#loader = options.loader;\n this.#storage = options.storage ?? null;\n this.#createHostBinding = options.createHostBinding ?? null;\n }\n\n /**\n * Load an extension from source code.\n *\n * The source is a JS object expression defining tools. Each tool has\n * `description`, `parameters` (JSON Schema properties), optional\n * `required` array, and an `execute` async function.\n *\n * @returns Summary of the loaded extension including discovered tools.\n */\n /**\n * Restore extensions from DO storage after hibernation.\n *\n * Idempotent — skips extensions already in memory. Call this at the\n * start of each chat turn (e.g. in onChatMessage before getTools).\n */\n async restore(): Promise<void> {\n if (this.#restored || !this.#storage) return;\n this.#restored = true;\n\n const entries = await this.#storage.list<PersistedExtension>({\n prefix: STORAGE_PREFIX\n });\n\n for (const persisted of entries.values()) {\n if (this.#extensions.has(persisted.manifest.name)) continue;\n await this.#loadInternal(persisted.manifest, persisted.source);\n }\n }\n\n async load(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n if (this.#extensions.has(manifest.name)) {\n throw new Error(\n `Extension \"${manifest.name}\" is already loaded. Unload it first.`\n );\n }\n\n const info = await this.#loadInternal(manifest, source);\n\n // Persist to storage so it survives hibernation\n if (this.#storage) {\n await this.#storage.put<PersistedExtension>(\n `${STORAGE_PREFIX}${manifest.name}`,\n { manifest, source }\n );\n }\n\n return info;\n }\n\n async #loadInternal(\n manifest: ExtensionManifest,\n source: string\n ): Promise<ExtensionInfo> {\n const workerModule = wrapExtensionSource(source);\n const permissions = manifest.permissions ?? {};\n\n // Build env bindings for the dynamic worker. Inject a loopback\n // Fetcher as env.host when the extension declares ANY permission\n // that requires host access (workspace, context, messages, session).\n const workerEnv: Record<string, Fetcher> = {};\n const needsHost =\n (permissions.workspace ?? \"none\") !== \"none\" ||\n permissions.context?.read !== undefined ||\n permissions.context?.write !== undefined ||\n (permissions.messages ?? \"none\") !== \"none\" ||\n permissions.session?.sendMessage ||\n permissions.session?.metadata;\n if (this.#createHostBinding && needsHost) {\n const prefix = sanitizeName(manifest.name);\n const ownLabels = (manifest.context ?? []).map(\n (c) => `${prefix}_${c.label}`\n );\n workerEnv.host = this.#createHostBinding(permissions, ownLabels);\n }\n\n const worker = this.#loader.get(\n `ext-${manifest.name}-${manifest.version}-${Date.now()}`,\n () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"extension.js\",\n modules: { \"extension.js\": workerModule },\n globalOutbound: permissions.network?.length ? undefined : null,\n ...(Object.keys(workerEnv).length > 0 ? { env: workerEnv } : {})\n })\n );\n\n const entrypoint = worker.getEntrypoint() as unknown as ExtensionEntrypoint;\n\n // Discover tools and hooks via RPC\n const descriptorsJson = await entrypoint.describe();\n const tools = JSON.parse(descriptorsJson) as ExtensionToolDescriptor[];\n\n let hooks: string[] = [];\n try {\n const manifestJson = await entrypoint.manifest();\n const runtimeManifest = JSON.parse(manifestJson) as {\n hooks?: string[];\n };\n hooks = runtimeManifest.hooks ?? [];\n } catch {\n // Legacy extensions may not have manifest() — treat as no hooks\n }\n\n this.#extensions.set(manifest.name, {\n manifest,\n tools,\n hooks,\n entrypoint\n });\n\n return toExtensionInfo(manifest, tools);\n }\n\n /**\n * Unload an extension, removing its tools from the agent.\n * If an onUnload callback is registered, it fires with the\n * extension's namespaced context labels so the caller can\n * remove context blocks from the Session.\n */\n async unload(name: string): Promise<boolean> {\n const ext = this.#extensions.get(name);\n if (!ext) return false;\n\n const removed = this.#extensions.delete(name);\n if (removed && this.#storage) {\n await this.#storage.delete(`${STORAGE_PREFIX}${name}`);\n }\n\n if (removed && this.#onUnload) {\n const prefix = sanitizeName(name);\n const contextLabels = (ext.manifest.context ?? []).map(\n (c) => `${prefix}_${c.label}`\n );\n await this.#onUnload(name, contextLabels);\n }\n\n return removed;\n }\n\n /**\n * Register a callback invoked when an extension is unloaded.\n * Think uses this to remove the extension's context blocks from Session.\n */\n onUnload(\n cb: (name: string, contextLabels: string[]) => void | Promise<void>\n ): void {\n this.#onUnload = cb;\n }\n\n /**\n * Get the namespaced context labels for all loaded extensions\n * that declare context blocks in their manifests.\n */\n getContextLabels(): Array<{ extName: string; label: string }> {\n const result: Array<{ extName: string; label: string }> = [];\n for (const ext of this.#extensions.values()) {\n if (!ext.manifest.context) continue;\n const prefix = sanitizeName(ext.manifest.name);\n for (const ctx of ext.manifest.context) {\n result.push({\n extName: ext.manifest.name,\n label: `${prefix}_${ctx.label}`\n });\n }\n }\n return result;\n }\n\n /**\n * Get extension manifest by name.\n */\n getManifest(name: string): ExtensionManifest | null {\n return this.#extensions.get(name)?.manifest ?? null;\n }\n\n /**\n * Get extensions that subscribe to a specific hook, in load order.\n */\n getHookSubscribers(\n hookName: string\n ): Array<{ name: string; entrypoint: ExtensionEntrypoint }> {\n const result: Array<{ name: string; entrypoint: ExtensionEntrypoint }> = [];\n for (const ext of this.#extensions.values()) {\n if (ext.hooks.includes(hookName)) {\n result.push({ name: ext.manifest.name, entrypoint: ext.entrypoint });\n }\n }\n return result;\n }\n\n /**\n * List all loaded extensions.\n */\n list(): ExtensionInfo[] {\n return [...this.#extensions.values()].map((ext) =>\n toExtensionInfo(ext.manifest, ext.tools)\n );\n }\n\n /**\n * Get AI SDK tools from all loaded extensions.\n *\n * Tool names are prefixed with the sanitized extension name to avoid\n * collisions: e.g. extension \"github\" with tool \"create_pr\" → \"github_create_pr\".\n */\n getTools(): ToolSet {\n const tools: ToolSet = {};\n\n for (const ext of this.#extensions.values()) {\n const prefix = sanitizeName(ext.manifest.name);\n\n for (const descriptor of ext.tools) {\n const toolName = `${prefix}_${descriptor.name}`;\n\n tools[toolName] = tool({\n description: `[${ext.manifest.name}] ${descriptor.description}`,\n inputSchema: jsonSchema(\n descriptor.inputSchema as Record<string, unknown>\n ),\n execute: async (args: Record<string, unknown>) => {\n if (!this.#extensions.has(ext.manifest.name)) {\n throw new Error(\n `Extension \"${ext.manifest.name}\" has been unloaded. Tool \"${toolName}\" is no longer available.`\n );\n }\n const resultJson = await ext.entrypoint.execute(\n descriptor.name,\n JSON.stringify(args)\n );\n const parsed = JSON.parse(resultJson) as {\n result?: unknown;\n error?: string;\n };\n if (parsed.error) throw new Error(parsed.error);\n return parsed.result;\n }\n });\n }\n }\n\n return tools;\n }\n}\n\nfunction toExtensionInfo(\n manifest: ExtensionManifest,\n tools: ExtensionToolDescriptor[]\n): ExtensionInfo {\n const prefix = sanitizeName(manifest.name);\n return {\n name: manifest.name,\n version: manifest.version,\n description: manifest.description,\n tools: tools.map((t) => `${prefix}_${t.name}`),\n contextLabels: (manifest.context ?? []).map((c) => `${prefix}_${c.label}`),\n permissions: manifest.permissions ?? {}\n };\n}\n\n/**\n * Wrap an extension source in a Worker module that exposes\n * describe(), execute(), manifest(), and hook RPC methods.\n *\n * Source format: `({ tools: {...}, hooks: {...} })`\n * Both `tools` and `hooks` are optional.\n */\nfunction wrapExtensionSource(source: string): string {\n return `import { WorkerEntrypoint } from \"cloudflare:workers\";\n\nconst __ext = (${source});\nif (__ext && typeof __ext === \"object\" && !(\"tools\" in __ext) && !(\"hooks\" in __ext)) {\n throw new Error(\n \"Invalid extension source format. Expected { tools: {...}, hooks: {...} } \" +\n \"but got a flat object. Wrap your tools in a 'tools' key.\"\n );\n}\nconst __tools = __ext.tools || {};\nconst __hooks = __ext.hooks || {};\n\nexport default class Extension extends WorkerEntrypoint {\n describe() {\n const descriptors = [];\n for (const [name, def] of Object.entries(__tools)) {\n descriptors.push({\n name,\n description: def.description || name,\n inputSchema: {\n type: \"object\",\n properties: def.parameters || {},\n required: def.required || []\n }\n });\n }\n return JSON.stringify(descriptors);\n }\n\n manifest() {\n return JSON.stringify({\n hooks: Object.keys(__hooks)\n });\n }\n\n async execute(toolName, argsJson) {\n const def = __tools[toolName];\n if (!def || !def.execute) {\n return JSON.stringify({ error: \"Unknown tool: \" + toolName });\n }\n try {\n const args = JSON.parse(argsJson);\n const result = await def.execute(args, this.env.host ?? null);\n return JSON.stringify({ result });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n\n async hook(name, ctxSnapshot) {\n const fn = __hooks[name];\n if (!fn) return JSON.stringify({ skipped: true });\n try {\n // Hook handlers receive (ctxSnapshot, host) — symmetric with tool\n // executes. \\`host\\` is null when the extension was loaded without\n // host-requiring permissions or when the worker entry point doesn't\n // re-export HostBridgeLoopback.\n const result = await fn(ctxSnapshot, this.env.host ?? null);\n return JSON.stringify({ result: result ?? {} });\n } catch (err) {\n return JSON.stringify({ error: err.message || String(err) });\n }\n }\n}\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,aAAa,MAAsB;CACjD,IAAI,CAAC,QAAQ,KAAK,MAAM,CAAC,WAAW,GAClC,MAAM,IAAI,MAAM,mCAAmC;CAErD,OAAO,KACJ,QAAQ,iBAAiB,IAAI,CAC7B,QAAQ,OAAO,IAAI,CACnB,QAAQ,UAAU,GAAG;;AAuB1B,MAAM,iBAAiB;;;;;;;;AAiCvB,IAAa,mBAAb,MAA8B;CAe5B,YAAY,SAAkC;;;;;gEANhC,IAAI,KAA8B,CAAA;8CACpC,MAAA;8CAGD,KAAA;EAGT,uBAAA,SAAA,MAAe,QAAQ,OAAA;EACvB,uBAAA,UAAA,MAAgB,QAAQ,WAAW,KAAA;EACnC,uBAAA,oBAAA,MAA0B,QAAQ,qBAAqB,KAAA;;;;;;;;;;;;;;;;;CAkBzD,MAAM,UAAyB;EAC7B,IAAA,uBAAA,WAAI,KAAA,IAAkB,CAAA,uBAAA,UAAC,KAAA,EAAe;EACtC,uBAAA,WAAA,MAAiB,KAAA;EAEjB,MAAM,UAAU,MAAA,uBAAA,UAAM,KAAA,CAAc,KAAyB,EAC3D,QAAQ,gBACT,CAAC;EAEF,KAAK,MAAM,aAAa,QAAQ,QAAQ,EAAE;GACxC,IAAA,uB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IAAI,SAAS,MAAM;EAClC;EACA;EACA;EACA;EACD,CAAC;CAEF,OAAO,gBAAgB,UAAU,MAAM;;AAsI3C,SAAS,gBACP,UACA,OACe;CACf,MAAM,SAAS,aAAa,SAAS,KAAK;CAC1C,OAAO;EACL,MAAM,SAAS;EACf,SAAS,SAAS;EAClB,aAAa,SAAS;EACtB,OAAO,MAAM,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,OAAO;EAC9C,gBAAgB,SAAS,WAAW,EAAE,EAAE,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,QAAQ;EAC1E,aAAa,SAAS,eAAe,EAAE;EACxC;;;;;;;;;AAUH,SAAS,oBAAoB,QAAwB;CACnD,OAAO;;iBAEQ,OAAO"}
|
package/dist/think.d.ts
CHANGED
|
@@ -75,7 +75,6 @@ interface StreamableResult {
|
|
|
75
75
|
*/
|
|
76
76
|
interface ChatOptions {
|
|
77
77
|
signal?: AbortSignal;
|
|
78
|
-
tools?: ToolSet;
|
|
79
78
|
}
|
|
80
79
|
type AgentToolChildRunStatus =
|
|
81
80
|
| "starting"
|
|
@@ -98,6 +97,41 @@ type AgentToolStoredChunk = {
|
|
|
98
97
|
sequence: number;
|
|
99
98
|
body: string;
|
|
100
99
|
};
|
|
100
|
+
type ThinkSubmissionStatus =
|
|
101
|
+
| "pending"
|
|
102
|
+
| "running"
|
|
103
|
+
| "completed"
|
|
104
|
+
| "aborted"
|
|
105
|
+
| "skipped"
|
|
106
|
+
| "error";
|
|
107
|
+
type SubmitMessagesOptions = {
|
|
108
|
+
submissionId?: string;
|
|
109
|
+
idempotencyKey?: string;
|
|
110
|
+
metadata?: Record<string, unknown>;
|
|
111
|
+
};
|
|
112
|
+
type ThinkSubmissionInspection = {
|
|
113
|
+
submissionId: string;
|
|
114
|
+
idempotencyKey?: string;
|
|
115
|
+
requestId?: string;
|
|
116
|
+
status: ThinkSubmissionStatus;
|
|
117
|
+
error?: string;
|
|
118
|
+
metadata?: Record<string, unknown>;
|
|
119
|
+
createdAt: number;
|
|
120
|
+
startedAt?: number;
|
|
121
|
+
completedAt?: number;
|
|
122
|
+
};
|
|
123
|
+
type SubmitMessagesResult = ThinkSubmissionInspection & {
|
|
124
|
+
accepted: boolean;
|
|
125
|
+
};
|
|
126
|
+
type ListSubmissionsOptions = {
|
|
127
|
+
status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
|
|
128
|
+
limit?: number;
|
|
129
|
+
};
|
|
130
|
+
type DeleteSubmissionsOptions = {
|
|
131
|
+
status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
|
|
132
|
+
completedBefore?: Date;
|
|
133
|
+
limit?: number;
|
|
134
|
+
};
|
|
101
135
|
/**
|
|
102
136
|
* A chat turn request. Built automatically by each entry path
|
|
103
137
|
* (WebSocket, chat(), saveMessages, auto-continuation) and passed
|
|
@@ -105,8 +139,6 @@ type AgentToolStoredChunk = {
|
|
|
105
139
|
*/
|
|
106
140
|
interface TurnInput {
|
|
107
141
|
signal?: AbortSignal;
|
|
108
|
-
/** Extra tools from the caller (e.g. chat() options) — highest merge priority. */
|
|
109
|
-
callerTools?: ToolSet;
|
|
110
142
|
/** Client-provided tool schemas for dynamic tool registration. */
|
|
111
143
|
clientTools?: ClientToolSchema[];
|
|
112
144
|
/** Custom body fields from the client request. */
|
|
@@ -156,6 +188,28 @@ interface TurnConfig {
|
|
|
156
188
|
* for this turn. Defaults to the instance-level `sendReasoning` setting.
|
|
157
189
|
*/
|
|
158
190
|
sendReasoning?: boolean;
|
|
191
|
+
/** Maximum number of tokens to generate for this turn. */
|
|
192
|
+
maxOutputTokens?: Parameters<typeof streamText>[0]["maxOutputTokens"];
|
|
193
|
+
/** Temperature setting for this turn. */
|
|
194
|
+
temperature?: Parameters<typeof streamText>[0]["temperature"];
|
|
195
|
+
/** Nucleus sampling setting for this turn. */
|
|
196
|
+
topP?: Parameters<typeof streamText>[0]["topP"];
|
|
197
|
+
/** Top-K sampling setting for this turn. */
|
|
198
|
+
topK?: Parameters<typeof streamText>[0]["topK"];
|
|
199
|
+
/** Presence penalty setting for this turn. */
|
|
200
|
+
presencePenalty?: Parameters<typeof streamText>[0]["presencePenalty"];
|
|
201
|
+
/** Frequency penalty setting for this turn. */
|
|
202
|
+
frequencyPenalty?: Parameters<typeof streamText>[0]["frequencyPenalty"];
|
|
203
|
+
/** Stop sequences for this turn. */
|
|
204
|
+
stopSequences?: Parameters<typeof streamText>[0]["stopSequences"];
|
|
205
|
+
/** Seed for deterministic sampling when supported by the model. */
|
|
206
|
+
seed?: Parameters<typeof streamText>[0]["seed"];
|
|
207
|
+
/** Maximum number of retries for this turn. Set to 0 to disable retries. */
|
|
208
|
+
maxRetries?: Parameters<typeof streamText>[0]["maxRetries"];
|
|
209
|
+
/** Timeout configuration for this turn. */
|
|
210
|
+
timeout?: Parameters<typeof streamText>[0]["timeout"];
|
|
211
|
+
/** Additional HTTP headers for provider requests on this turn. */
|
|
212
|
+
headers?: Parameters<typeof streamText>[0]["headers"];
|
|
159
213
|
/** Provider-specific options (AI SDK providerOptions). */
|
|
160
214
|
providerOptions?: Record<string, unknown>;
|
|
161
215
|
/** Optional AI SDK telemetry configuration for this turn. */
|
|
@@ -440,6 +494,11 @@ declare class Think<
|
|
|
440
494
|
private _agentToolLastErrors;
|
|
441
495
|
private _agentToolPreTurnAssistantIds;
|
|
442
496
|
private _agentToolLiveSequences;
|
|
497
|
+
private _submissionTableEnsured;
|
|
498
|
+
private _drainingSubmissions;
|
|
499
|
+
private _submissionAbortControllers;
|
|
500
|
+
private _programmaticStreamErrors;
|
|
501
|
+
protected static submissionRecoveryStaleMs: number;
|
|
443
502
|
broadcast(
|
|
444
503
|
msg: string | ArrayBuffer | ArrayBufferView,
|
|
445
504
|
without?: string[]
|
|
@@ -788,10 +847,12 @@ declare class Think<
|
|
|
788
847
|
/** Clear all messages from storage. */
|
|
789
848
|
clearMessages(): void;
|
|
790
849
|
private _ensureAgentToolChildRunTable;
|
|
850
|
+
private _addAgentToolChildRunColumnIfMissing;
|
|
791
851
|
private _readAgentToolChildRun;
|
|
792
852
|
private _inspectionFromChildRow;
|
|
793
853
|
protected formatAgentToolInput(input: unknown): UIMessage;
|
|
794
854
|
protected getAgentToolOutput(_runId: string): unknown;
|
|
855
|
+
protected getAgentToolSummary(runId: string, output: unknown): string;
|
|
795
856
|
startAgentToolRun(
|
|
796
857
|
input: unknown,
|
|
797
858
|
options: {
|
|
@@ -812,7 +873,52 @@ declare class Think<
|
|
|
812
873
|
afterSequence?: number;
|
|
813
874
|
}
|
|
814
875
|
): Promise<ReadableStream<AgentToolStoredChunk>>;
|
|
876
|
+
private static _stringifyAgentToolOutput;
|
|
877
|
+
private static _parseAgentToolOutput;
|
|
815
878
|
private _getAgentToolFinalText;
|
|
879
|
+
private _ensureSubmissionTable;
|
|
880
|
+
private _readSubmission;
|
|
881
|
+
private _readSubmissionByIdempotencyKey;
|
|
882
|
+
private _normalizeStatusFilter;
|
|
883
|
+
private _listSubmissionRows;
|
|
884
|
+
private _listSubmissionRowsByStatus;
|
|
885
|
+
private _inspectionFromSubmissionRow;
|
|
886
|
+
private _parseJsonObject;
|
|
887
|
+
private _parseSubmissionMessages;
|
|
888
|
+
private _serializeSubmissionMessages;
|
|
889
|
+
private _serializeMetadata;
|
|
890
|
+
private _emitSubmissionStatus;
|
|
891
|
+
protected onSubmissionStatus(
|
|
892
|
+
_submission: ThinkSubmissionInspection
|
|
893
|
+
): void | Promise<void>;
|
|
894
|
+
inspectSubmission(
|
|
895
|
+
submissionId: string
|
|
896
|
+
): Promise<ThinkSubmissionInspection | null>;
|
|
897
|
+
listSubmissions(
|
|
898
|
+
options?: ListSubmissionsOptions
|
|
899
|
+
): Promise<ThinkSubmissionInspection[]>;
|
|
900
|
+
deleteSubmission(submissionId: string): Promise<boolean>;
|
|
901
|
+
deleteSubmissions(options?: DeleteSubmissionsOptions): Promise<number>;
|
|
902
|
+
private _listTerminalSubmissionRowsForDelete;
|
|
903
|
+
private _isTerminalSubmissionStatus;
|
|
904
|
+
cancelSubmission(submissionId: string, reason?: unknown): Promise<void>;
|
|
905
|
+
submitMessages(
|
|
906
|
+
messages: UIMessage[],
|
|
907
|
+
options?: SubmitMessagesOptions
|
|
908
|
+
): Promise<SubmitMessagesResult>;
|
|
909
|
+
private _scheduleSubmissionDrain;
|
|
910
|
+
private _startSubmissionDrain;
|
|
911
|
+
_drainThinkSubmissions(): Promise<void>;
|
|
912
|
+
private _drainSubmissions;
|
|
913
|
+
private _runSubmission;
|
|
914
|
+
private _getSubmissionFinalStatus;
|
|
915
|
+
private _markPendingSubmissionsSkipped;
|
|
916
|
+
private _emitSkippedSubmissions;
|
|
917
|
+
private _recoverSubmissionsOnStart;
|
|
918
|
+
private _getSubmissionMessagesAppliedState;
|
|
919
|
+
private _hasRecoverableChatTurn;
|
|
920
|
+
private _hasFreshRecoverableSubmissionEvidence;
|
|
921
|
+
private _hasScheduledRecoveredContinuation;
|
|
816
922
|
/**
|
|
817
923
|
* Inject messages and trigger a model turn — without a WebSocket request.
|
|
818
924
|
*
|
|
@@ -862,6 +968,7 @@ declare class Think<
|
|
|
862
968
|
| ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),
|
|
863
969
|
options?: SaveMessagesOptions$1
|
|
864
970
|
): Promise<SaveMessagesResult$1>;
|
|
971
|
+
private _runProgrammaticMessagesTurn;
|
|
865
972
|
/**
|
|
866
973
|
* Run a new LLM call following the last assistant message.
|
|
867
974
|
*
|
|
@@ -934,6 +1041,8 @@ declare class Think<
|
|
|
934
1041
|
*/
|
|
935
1042
|
protected abortAllRequests(): void;
|
|
936
1043
|
private _handleClear;
|
|
1044
|
+
private _streamResultToRpcCallback;
|
|
1045
|
+
private _shouldFlushRpcStreamChunk;
|
|
937
1046
|
private _streamResult;
|
|
938
1047
|
private _persistAssistantMessage;
|
|
939
1048
|
/**
|
|
@@ -957,10 +1066,17 @@ declare class Think<
|
|
|
957
1066
|
protected _handleInternalFiberRecovery(
|
|
958
1067
|
ctx: FiberRecoveryContext$1
|
|
959
1068
|
): Promise<boolean>;
|
|
1069
|
+
private _hasRunningSubmission;
|
|
1070
|
+
private _readRunningSubmissionByRequestId;
|
|
1071
|
+
private _markRecoveredSubmissionInterrupted;
|
|
1072
|
+
private _completeRecoveredSubmission;
|
|
960
1073
|
protected onChatRecovery(
|
|
961
1074
|
_ctx: ChatRecoveryContext$1
|
|
962
1075
|
): Promise<ChatRecoveryOptions$1>;
|
|
963
|
-
_chatRecoveryContinue(data?: {
|
|
1076
|
+
_chatRecoveryContinue(data?: {
|
|
1077
|
+
targetAssistantId?: string;
|
|
1078
|
+
recoveredRequestId?: string;
|
|
1079
|
+
}): Promise<void>;
|
|
964
1080
|
private _getPartialStreamText;
|
|
965
1081
|
private _getSubmitConcurrencyDecision;
|
|
966
1082
|
private _completeSkippedRequest;
|
|
@@ -983,9 +1099,11 @@ export {
|
|
|
983
1099
|
type ChatResponseResult,
|
|
984
1100
|
ChunkContext,
|
|
985
1101
|
ChunkPart,
|
|
1102
|
+
DeleteSubmissionsOptions,
|
|
986
1103
|
ExtensionConfig,
|
|
987
1104
|
type FiberContext,
|
|
988
1105
|
type FiberRecoveryContext,
|
|
1106
|
+
ListSubmissionsOptions,
|
|
989
1107
|
type MessageConcurrency,
|
|
990
1108
|
PrepareStepContext,
|
|
991
1109
|
type PrepareStepFunction,
|
|
@@ -998,8 +1116,12 @@ export {
|
|
|
998
1116
|
type StepResult,
|
|
999
1117
|
StreamCallback,
|
|
1000
1118
|
StreamableResult,
|
|
1119
|
+
SubmitMessagesOptions,
|
|
1120
|
+
SubmitMessagesResult,
|
|
1001
1121
|
type TextStreamPart,
|
|
1002
1122
|
Think,
|
|
1123
|
+
ThinkSubmissionInspection,
|
|
1124
|
+
ThinkSubmissionStatus,
|
|
1003
1125
|
ToolCallContext,
|
|
1004
1126
|
ToolCallDecision,
|
|
1005
1127
|
ToolCallResultContext,
|