@cloudflare/think 0.3.0 → 0.4.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 +31 -9
- package/dist/{classPrivateFieldGet2-C7fYS0JL.js → classPrivateFieldGet2-Bvcn7kEw.js} +5 -5
- package/dist/extensions/index.js +2 -2
- package/dist/{manager-CR9ZdLiu.js → manager-DDC3Gb0V.js} +3 -3
- package/dist/{manager-CR9ZdLiu.js.map → manager-DDC3Gb0V.js.map} +1 -1
- package/dist/think.d.ts +155 -103
- package/dist/think.js +162 -113
- package/dist/think.js.map +1 -1
- package/dist/tools/browser.d.ts +1 -1
- package/dist/tools/browser.js +1 -1
- package/dist/tools/browser.js.map +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/workspace.d.ts +11 -2
- package/dist/tools/workspace.js +5 -1
- package/dist/tools/workspace.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ import { createWorkersAI } from "workers-ai-provider";
|
|
|
15
15
|
export class MyAgent extends Think<Env> {
|
|
16
16
|
getModel() {
|
|
17
17
|
return createWorkersAI({ binding: this.env.AI })(
|
|
18
|
-
"@cf/moonshotai/kimi-k2.
|
|
18
|
+
"@cf/moonshotai/kimi-k2.6"
|
|
19
19
|
);
|
|
20
20
|
}
|
|
21
21
|
|
|
@@ -82,6 +82,7 @@ Think owns the `streamText` call. Hooks fire on every turn regardless of entry p
|
|
|
82
82
|
| Hook | When it fires | Return |
|
|
83
83
|
| ------------------------ | ------------------------------------------- | ------------------------------ |
|
|
84
84
|
| `beforeTurn(ctx)` | Before `streamText` — see assembled context | `TurnConfig` overrides or void |
|
|
85
|
+
| `beforeStep(ctx)` | Before each model step | `StepConfig` overrides or void |
|
|
85
86
|
| `beforeToolCall(ctx)` | Before tool's `execute` runs | `ToolCallDecision` or void |
|
|
86
87
|
| `afterToolCall(ctx)` | After tool execution (success or failure) | void |
|
|
87
88
|
| `onStepFinish(ctx)` | After each step completes | void |
|
|
@@ -89,15 +90,20 @@ Think owns the `streamText` call. Hooks fire on every turn regardless of entry p
|
|
|
89
90
|
| `onChatResponse(result)` | After turn completes + message persisted | void |
|
|
90
91
|
| `onChatError(error)` | On error during a turn | error to propagate |
|
|
91
92
|
|
|
92
|
-
The
|
|
93
|
+
The AI SDK-derived contexts spread the SDK's own types at the top level — no information is dropped:
|
|
93
94
|
|
|
94
95
|
| Context | Backed by |
|
|
95
96
|
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
|
|
97
|
+
| `PrepareStepContext<TOOLS>` | `Parameters<PrepareStepFunction<TOOLS>>[0]` (`steps`, `stepNumber`, `model`, `messages`, `experimental_context`) |
|
|
96
98
|
| `ToolCallContext<TOOLS>` | `TypedToolCall<TOOLS>` + per-call extras from `OnToolCallStartEvent` (`stepNumber`, `messages`, `abortSignal`) |
|
|
97
99
|
| `ToolCallResultContext<TOOLS>` | `TypedToolCall<TOOLS>` + per-call extras (`durationMs`, `messages`, `stepNumber`) + discriminated `success`/`output`/`error` outcome |
|
|
98
100
|
| `StepContext<TOOLS>` | `StepResult<TOOLS>` (full step incl. `reasoning`, `sources`, `files`, `usage`, `providerMetadata`, `request`, `response`, `warnings`) |
|
|
99
101
|
| `ChunkContext<TOOLS>` | `Parameters<StreamTextOnChunkCallback<TOOLS>>[0]` (discriminated `TextStreamPart`) |
|
|
100
102
|
|
|
103
|
+
`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
|
+
|
|
105
|
+
`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.
|
|
106
|
+
|
|
101
107
|
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:
|
|
102
108
|
|
|
103
109
|
- `{ action: "allow", input? }` — run the original `execute`, optionally with a substituted `input`.
|
|
@@ -107,10 +113,24 @@ Per-tool hooks are wired so `beforeToolCall` fires _before_ `execute` (Think wra
|
|
|
107
113
|
Pass an explicit `TOOLS` generic when you want full input typing:
|
|
108
114
|
|
|
109
115
|
```ts
|
|
110
|
-
import type {
|
|
116
|
+
import type {
|
|
117
|
+
PrepareStepContext,
|
|
118
|
+
StepContext,
|
|
119
|
+
ToolCallContext,
|
|
120
|
+
ToolCallResultContext
|
|
121
|
+
} from "@cloudflare/think";
|
|
111
122
|
|
|
112
123
|
const tools = { search: tool({ inputSchema: z.object({ query: z.string() }), ... }) };
|
|
113
124
|
|
|
125
|
+
beforeStep(ctx: PrepareStepContext<typeof tools>) {
|
|
126
|
+
if (ctx.stepNumber === 0) {
|
|
127
|
+
return {
|
|
128
|
+
activeTools: ["search"],
|
|
129
|
+
toolChoice: { type: "tool", toolName: "search" }
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
114
134
|
beforeToolCall(ctx: ToolCallContext<typeof tools>) {
|
|
115
135
|
if (ctx.toolName === "search") {
|
|
116
136
|
ctx.input.query; // typed as string
|
|
@@ -143,7 +163,7 @@ onStepFinish(ctx: StepContext<typeof tools>) {
|
|
|
143
163
|
|
|
144
164
|
### Extension hook subscriptions
|
|
145
165
|
|
|
146
|
-
Extensions can subscribe to
|
|
166
|
+
Extensions can subscribe to `beforeTurn`, `beforeToolCall`, `afterToolCall`, `onStepFinish`, and `onChunk` via their manifest's `hooks` array. Think dispatches to extension-side handlers in load order with a JSON-safe snapshot of the event. `beforeStep` is available to subclasses only and is not dispatched to extensions.
|
|
147
167
|
|
|
148
168
|
```js
|
|
149
169
|
// extension source (loaded via getExtensions())
|
|
@@ -169,7 +189,7 @@ Extensions can subscribe to any of the five lifecycle hooks via their manifest's
|
|
|
169
189
|
});
|
|
170
190
|
```
|
|
171
191
|
|
|
172
|
-
The handler signature is `(snapshot, host) => void`, symmetric with tool `execute`. Errors from extension hooks are caught and logged; they do not abort the turn. Only `beforeTurn` honors return values — the other
|
|
192
|
+
The handler signature is `(snapshot, host) => void`, symmetric with tool `execute`. Errors from extension hooks are caught and logged; they do not abort the turn. Only `beforeTurn` honors return values — the other extension hooks are observation-only. See [docs/think/lifecycle-hooks.md](https://github.com/cloudflare/agents/blob/main/docs/think/lifecycle-hooks.md#extension-hook-subscriptions) for the full snapshot shapes.
|
|
173
193
|
|
|
174
194
|
#### beforeTurn example
|
|
175
195
|
|
|
@@ -284,24 +304,26 @@ await agent.chat("Summarize the project", relay, {
|
|
|
284
304
|
|
|
285
305
|
### Dynamic configuration
|
|
286
306
|
|
|
287
|
-
|
|
307
|
+
`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:
|
|
288
308
|
|
|
289
309
|
```ts
|
|
290
310
|
type MyConfig = { modelTier: "fast" | "capable"; systemPrompt: string };
|
|
291
311
|
|
|
292
|
-
export class MyAgent extends Think<Env
|
|
312
|
+
export class MyAgent extends Think<Env> {
|
|
293
313
|
getModel() {
|
|
294
|
-
const tier = this.getConfig()?.modelTier ?? "fast";
|
|
314
|
+
const tier = this.getConfig<MyConfig>()?.modelTier ?? "fast";
|
|
295
315
|
return createWorkersAI({ binding: this.env.AI })(MODEL_IDS[tier]);
|
|
296
316
|
}
|
|
297
317
|
}
|
|
298
318
|
```
|
|
299
319
|
|
|
320
|
+
For values you want broadcast to connected clients, use `state` / `setState` from `Agent` instead.
|
|
321
|
+
|
|
300
322
|
### Production features
|
|
301
323
|
|
|
302
324
|
- **WebSocket protocol** — wire-compatible with `useAgentChat` from `@cloudflare/ai-chat`
|
|
303
325
|
- **Built-in workspace** — every agent gets `this.workspace` with file tools auto-wired
|
|
304
|
-
- **Lifecycle hooks** — `beforeTurn`, `onStepFinish`, `onChunk`, `onChatResponse` fire on every turn
|
|
326
|
+
- **Lifecycle hooks** — `beforeTurn`, `beforeStep`, `onStepFinish`, `onChunk`, `onChatResponse` fire on every turn
|
|
305
327
|
- **Stream resumption** — page refresh replays buffered chunks via `ResumableStream`
|
|
306
328
|
- **Client tools** — accept tool schemas from clients, handle results and approvals
|
|
307
329
|
- **Auto-continuation** — debounce-based continuation after tool results
|
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
//#region \0@oxc-project+runtime@0.
|
|
1
|
+
//#region \0@oxc-project+runtime@0.127.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.127.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.127.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.127.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.127.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-DDC3Gb0V.js";
|
|
2
|
+
import { r as _assertClassBrand } from "../classPrivateFieldGet2-Bvcn7kEw.js";
|
|
3
3
|
import { WorkerEntrypoint } from "cloudflare:workers";
|
|
4
4
|
//#region src/extensions/host-bridge.ts
|
|
5
5
|
/**
|
|
@@ -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-Bvcn7kEw.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.127.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-DDC3Gb0V.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager-CR9ZdLiu.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,QAAQ,gBACT,CAAC;AAEF,OAAK,MAAM,aAAa,QAAQ,QAAQ,EAAE;AACxC,OAAA,uBAAA,aAAI,KAAgB,CAAC,IAAI,UAAU,SAAS,KAAK,CAAE;AACnD,SAAA,kBAAA,yBAAM,MAAA,cAAkB,CAAA,KAAA,MAAC,UAAU,UAAU,UAAU,OAAO;;;CAIlE,MAA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AC1C,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-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,QAAQ,gBACT,CAAC;AAEF,OAAK,MAAM,aAAa,QAAQ,QAAQ,EAAE;AACxC,OAAA,uBAAA,aAAI,KAAgB,CAAC,IAAI,UAAU,SAAS,KAAK,CAAE;AACnD,SAAA,kBAAA,yBAAM,MAAA,cAAkB,CAAA,KAAA,MAAC,UAAU,UAAU,UAAU,OAAO;;;CAIlE,MAAM,KACJ,UACA,QACwB;AACxB,MAAA,uBAAA,aAAI,KAAgB,CAAC,I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