@cloudflare/think 0.1.2 → 0.2.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 +134 -31
- package/dist/{classPrivateFieldSet2-D-GfNNJe.js → classPrivateFieldGet2-DZKvdPZj.js} +6 -6
- package/dist/extensions/index.d.ts +20 -10
- package/dist/extensions/index.js +96 -8
- package/dist/extensions/index.js.map +1 -1
- package/dist/hook-proxy-f_DqtJ9u.js +32 -0
- package/dist/hook-proxy-f_DqtJ9u.js.map +1 -0
- package/dist/index-BsB4GUsL.d.ts +109 -0
- package/dist/{index-CAMRySsy.d.ts → manager-DCbSiSWT.d.ts} +106 -41
- package/dist/{manager-UjPxAz2E.js → manager-dtoAI3A6.js} +115 -8
- package/dist/manager-dtoAI3A6.js.map +1 -0
- package/dist/think.d.ts +518 -82
- package/dist/think.js +1019 -352
- package/dist/think.js.map +1 -1
- package/dist/tools/execute.d.ts +1 -1
- package/dist/tools/extensions.d.ts +3 -3
- package/dist/tools/extensions.js +3 -3
- package/dist/tools/extensions.js.map +1 -1
- package/package.json +6 -9
- package/dist/manager-UjPxAz2E.js.map +0 -1
package/README.md
CHANGED
|
@@ -25,51 +25,156 @@ export class MyAgent extends Think<Env> {
|
|
|
25
25
|
}
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
-
That's it. Think handles the WebSocket chat protocol, message persistence, the agentic loop, message sanitization, stream resumption,
|
|
28
|
+
That's it. Think handles the WebSocket chat protocol, message persistence, the agentic loop, message sanitization, stream resumption, client tool support, and workspace file tools. Connect from the browser with `useAgentChat` from `@cloudflare/ai-chat`.
|
|
29
|
+
|
|
30
|
+
## Built-in workspace
|
|
31
|
+
|
|
32
|
+
Every Think agent gets `this.workspace` — a virtual filesystem backed by the DO's SQLite storage. Workspace tools (`read`, `write`, `edit`, `list`, `find`, `grep`, `delete`) are automatically available to the model.
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
export class MyAgent extends Think<Env> {
|
|
36
|
+
getModel() { ... }
|
|
37
|
+
// this.workspace is ready to use — no setup needed
|
|
38
|
+
// workspace tools are auto-merged into every chat turn
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Override to add R2 spillover for large files:
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
export class MyAgent extends Think<Env> {
|
|
46
|
+
override workspace = new Workspace({
|
|
47
|
+
sql: this.ctx.storage.sql,
|
|
48
|
+
r2: this.env.R2,
|
|
49
|
+
name: () => this.name
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
```
|
|
29
53
|
|
|
30
54
|
## Exports
|
|
31
55
|
|
|
32
56
|
| Export | Description |
|
|
33
57
|
| ------------------------------------ | ------------------------------------------------------------- |
|
|
34
|
-
| `@cloudflare/think` | `Think` —
|
|
35
|
-
| `@cloudflare/think/tools/workspace` | `createWorkspaceTools()` —
|
|
58
|
+
| `@cloudflare/think` | `Think`, `Session`, `Workspace` — main class + re-exports |
|
|
59
|
+
| `@cloudflare/think/tools/workspace` | `createWorkspaceTools()` — for custom storage backends |
|
|
36
60
|
| `@cloudflare/think/tools/execute` | `createExecuteTool()` — sandboxed code execution via codemode |
|
|
37
61
|
| `@cloudflare/think/tools/extensions` | `createExtensionTools()` — LLM-driven extension loading |
|
|
38
62
|
| `@cloudflare/think/extensions` | `ExtensionManager`, `HostBridgeLoopback` — extension runtime |
|
|
39
63
|
|
|
40
64
|
## Think
|
|
41
65
|
|
|
42
|
-
###
|
|
66
|
+
### Configuration
|
|
43
67
|
|
|
44
|
-
| Method
|
|
45
|
-
|
|
|
46
|
-
| `getModel()`
|
|
47
|
-
| `getSystemPrompt()`
|
|
48
|
-
| `getTools()`
|
|
49
|
-
| `
|
|
50
|
-
| `
|
|
51
|
-
| `
|
|
52
|
-
| `
|
|
68
|
+
| Method / Property | Default | Description |
|
|
69
|
+
| -------------------- | -------------------------------- | ----------------------------------------------- |
|
|
70
|
+
| `getModel()` | throws | Return the `LanguageModel` to use |
|
|
71
|
+
| `getSystemPrompt()` | `"You are a helpful assistant."` | System prompt (fallback when no context blocks) |
|
|
72
|
+
| `getTools()` | `{}` | AI SDK `ToolSet` for the agentic loop |
|
|
73
|
+
| `maxSteps` | `10` | Max tool-call rounds per turn (property) |
|
|
74
|
+
| `configureSession()` | identity | Add context blocks, compaction, search, skills |
|
|
75
|
+
| `getExtensions()` | `[]` | Sandboxed extension declarations (load order) |
|
|
76
|
+
| `extensionLoader` | `undefined` | `WorkerLoader` binding — enables extensions |
|
|
53
77
|
|
|
54
|
-
###
|
|
78
|
+
### Lifecycle hooks
|
|
79
|
+
|
|
80
|
+
Think owns the `streamText` call. Hooks fire on every turn regardless of entry path (WebSocket, `chat()`, `saveMessages`, auto-continuation).
|
|
55
81
|
|
|
56
|
-
|
|
82
|
+
| Hook | When it fires | Return |
|
|
83
|
+
| ------------------------ | ------------------------------------------- | ------------------------------ |
|
|
84
|
+
| `beforeTurn(ctx)` | Before `streamText` — see assembled context | `TurnConfig` overrides or void |
|
|
85
|
+
| `beforeToolCall(ctx)` | When model calls a tool (observation only) | `ToolCallDecision` or void |
|
|
86
|
+
| `afterToolCall(ctx)` | After tool execution | void |
|
|
87
|
+
| `onStepFinish(ctx)` | After each step completes | void |
|
|
88
|
+
| `onChunk(ctx)` | Per streaming chunk (high-frequency) | void |
|
|
89
|
+
| `onChatResponse(result)` | After turn completes + message persisted | void |
|
|
90
|
+
| `onChatError(error)` | On error during a turn | error to propagate |
|
|
91
|
+
|
|
92
|
+
#### beforeTurn example
|
|
57
93
|
|
|
58
94
|
```ts
|
|
59
|
-
|
|
60
|
-
{
|
|
95
|
+
export class MyAgent extends Think<Env> {
|
|
96
|
+
getModel() { ... }
|
|
97
|
+
|
|
98
|
+
// Switch to a cheaper model for continuation turns
|
|
99
|
+
beforeTurn(ctx: TurnContext) {
|
|
100
|
+
if (ctx.continuation) {
|
|
101
|
+
return { model: this.cheapModel };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
```
|
|
61
106
|
|
|
62
|
-
|
|
63
|
-
|
|
107
|
+
#### TurnConfig — what you can override per-turn
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
interface TurnConfig {
|
|
111
|
+
model?: LanguageModel; // override model
|
|
112
|
+
system?: string; // override system prompt
|
|
113
|
+
messages?: ModelMessage[]; // override assembled messages
|
|
114
|
+
tools?: ToolSet; // extra tools to merge (additive)
|
|
115
|
+
activeTools?: string[]; // limit which tools the model can call
|
|
116
|
+
toolChoice?: ToolChoice; // force a specific tool
|
|
117
|
+
maxSteps?: number; // override maxSteps for this turn
|
|
118
|
+
providerOptions?: Record<string, unknown>;
|
|
119
|
+
}
|
|
64
120
|
```
|
|
65
121
|
|
|
66
|
-
|
|
122
|
+
### Client tools
|
|
123
|
+
|
|
124
|
+
Think supports client-defined tools that execute in the browser. The client sends tool schemas in the chat request body, and Think merges them with server tools automatically.
|
|
125
|
+
|
|
126
|
+
When the LLM calls a client tool, the tool call chunk is sent to the client. The client executes it and sends back `CF_AGENT_TOOL_RESULT`. Think applies the result, persists the updated message, broadcasts `CF_AGENT_MESSAGE_UPDATED`, and optionally auto-continues the conversation.
|
|
67
127
|
|
|
68
128
|
Tool approval flows are also supported via `CF_AGENT_TOOL_APPROVAL`.
|
|
69
129
|
|
|
130
|
+
### Session and context blocks
|
|
131
|
+
|
|
132
|
+
Think uses Session for conversation storage. Override `configureSession` to add persistent memory, skills, compaction, and search:
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
export class MyAgent extends Think<Env> {
|
|
136
|
+
getModel() { ... }
|
|
137
|
+
|
|
138
|
+
configureSession(session: Session) {
|
|
139
|
+
return session
|
|
140
|
+
.withContext("memory", { description: "Learned facts", maxTokens: 2000 })
|
|
141
|
+
.withCachedPrompt();
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
#### Dynamic context blocks
|
|
147
|
+
|
|
148
|
+
Context blocks can also be added at runtime (e.g., by extensions):
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
await session.addContext("notes", { description: "User notes" });
|
|
152
|
+
await session.refreshSystemPrompt(); // rebuild the prompt
|
|
153
|
+
|
|
154
|
+
session.removeContext("notes");
|
|
155
|
+
await session.refreshSystemPrompt();
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
#### Skills
|
|
159
|
+
|
|
160
|
+
Skills support load/unload for explicit context management:
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
import { R2SkillProvider } from "agents/experimental/memory/session";
|
|
164
|
+
|
|
165
|
+
configureSession(session: Session) {
|
|
166
|
+
return session
|
|
167
|
+
.withContext("skills", {
|
|
168
|
+
provider: new R2SkillProvider(this.env.SKILLS_BUCKET, { prefix: "skills/" })
|
|
169
|
+
})
|
|
170
|
+
.withCachedPrompt();
|
|
171
|
+
}
|
|
172
|
+
// Model gets load_context and unload_context tools automatically
|
|
173
|
+
```
|
|
174
|
+
|
|
70
175
|
### MCP integration
|
|
71
176
|
|
|
72
|
-
Think inherits MCP client support from the Agent base class. Set `waitForMcpConnections` to ensure MCP
|
|
177
|
+
Think inherits MCP client support from the Agent base class. MCP tools are automatically merged into every turn. Set `waitForMcpConnections` to ensure MCP servers are connected before the inference loop runs:
|
|
73
178
|
|
|
74
179
|
```ts
|
|
75
180
|
export class MyAgent extends Think<Env> {
|
|
@@ -113,31 +218,30 @@ export class MyAgent extends Think<Env, MyConfig> {
|
|
|
113
218
|
### Production features
|
|
114
219
|
|
|
115
220
|
- **WebSocket protocol** — wire-compatible with `useAgentChat` from `@cloudflare/ai-chat`
|
|
221
|
+
- **Built-in workspace** — every agent gets `this.workspace` with file tools auto-wired
|
|
222
|
+
- **Lifecycle hooks** — `beforeTurn`, `onStepFinish`, `onChunk`, `onChatResponse` fire on every turn
|
|
116
223
|
- **Stream resumption** — page refresh replays buffered chunks via `ResumableStream`
|
|
117
224
|
- **Client tools** — accept tool schemas from clients, handle results and approvals
|
|
118
225
|
- **Auto-continuation** — debounce-based continuation after tool results
|
|
119
|
-
- **MCP integration** — wait for
|
|
226
|
+
- **MCP integration** — MCP tools auto-merged, wait for connections before inference
|
|
120
227
|
- **Abort/cancel** — pass an `AbortSignal` or send a cancel message
|
|
121
228
|
- **Multi-tab broadcast** — all connected clients see the stream (resume-aware exclusions)
|
|
122
229
|
- **Partial persistence** — on error, the partial assistant message is saved
|
|
123
230
|
- **Message sanitization** — strips ephemeral provider metadata before storage
|
|
124
231
|
- **Row size enforcement** — compacts tool outputs exceeding 1.8MB
|
|
125
|
-
- **Incremental persistence** — skips SQL writes for unchanged messages
|
|
126
|
-
- **Storage bounds** — set `maxPersistedMessages` to cap stored history
|
|
127
|
-
- **Messages on connect** — newly connected clients receive the current message list immediately
|
|
128
232
|
|
|
129
233
|
## Workspace tools
|
|
130
234
|
|
|
131
|
-
File operation tools
|
|
235
|
+
File operation tools are built into Think and available to the model on every turn. For custom storage backends, the individual tool factories are also exported:
|
|
132
236
|
|
|
133
237
|
```ts
|
|
134
238
|
import { createWorkspaceTools } from "@cloudflare/think/tools/workspace";
|
|
135
239
|
|
|
136
|
-
|
|
137
|
-
|
|
240
|
+
// Use with a custom ReadOperations/WriteOperations implementation
|
|
241
|
+
const tools = createWorkspaceTools(myCustomStorage);
|
|
138
242
|
```
|
|
139
243
|
|
|
140
|
-
Each tool is an AI SDK `tool()` with Zod schemas. The underlying operations are abstracted behind interfaces (`ReadOperations`, `WriteOperations`, etc.) so you can create tools backed by
|
|
244
|
+
Each tool is an AI SDK `tool()` with Zod schemas. The underlying operations are abstracted behind interfaces (`ReadOperations`, `WriteOperations`, etc.) so you can create tools backed by any storage.
|
|
141
245
|
|
|
142
246
|
## Code execution tool
|
|
143
247
|
|
|
@@ -148,7 +252,6 @@ import { createExecuteTool } from "@cloudflare/think/tools/execute";
|
|
|
148
252
|
|
|
149
253
|
getTools() {
|
|
150
254
|
return {
|
|
151
|
-
...createWorkspaceTools(this.workspace),
|
|
152
255
|
execute: createExecuteTool({ tools: wsTools, loader: this.env.LOADER })
|
|
153
256
|
};
|
|
154
257
|
}
|
|
@@ -181,5 +284,5 @@ getTools() {
|
|
|
181
284
|
| `agents` | yes | Cloudflare Agents SDK |
|
|
182
285
|
| `ai` | yes | Vercel AI SDK v6 |
|
|
183
286
|
| `zod` | yes | Schema validation (v3.25+ or v4) |
|
|
287
|
+
| `@cloudflare/shell` | yes | Workspace filesystem |
|
|
184
288
|
| `@cloudflare/codemode` | optional | For `createExecuteTool` |
|
|
185
|
-
| `@cloudflare/shell` | optional | For workspace tools |
|
|
@@ -14,14 +14,14 @@ function _assertClassBrand(e, 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.122.0/helpers/classPrivateFieldGet2.js
|
|
18
|
-
function _classPrivateFieldGet2(s, a) {
|
|
19
|
-
return s.get(_assertClassBrand(s, a));
|
|
20
|
-
}
|
|
21
|
-
//#endregion
|
|
22
17
|
//#region \0@oxc-project+runtime@0.122.0/helpers/classPrivateFieldSet2.js
|
|
23
18
|
function _classPrivateFieldSet2(s, a, r) {
|
|
24
19
|
return s.set(_assertClassBrand(s, a), r), r;
|
|
25
20
|
}
|
|
26
21
|
//#endregion
|
|
27
|
-
|
|
22
|
+
//#region \0@oxc-project+runtime@0.122.0/helpers/classPrivateFieldGet2.js
|
|
23
|
+
function _classPrivateFieldGet2(s, a) {
|
|
24
|
+
return s.get(_assertClassBrand(s, a));
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
export { _checkPrivateRedeclaration as a, _classPrivateFieldInitSpec as i, _classPrivateFieldSet2 as n, _assertClassBrand as r, _classPrivateFieldGet2 as t };
|
|
@@ -1,20 +1,30 @@
|
|
|
1
1
|
import {
|
|
2
|
-
a as
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
2
|
+
a as ExtensionPermissions,
|
|
3
|
+
i as ExtensionManifest,
|
|
4
|
+
n as ExtensionManagerOptions,
|
|
5
|
+
o as ExtensionToolDescriptor,
|
|
6
|
+
r as ExtensionInfo,
|
|
7
|
+
t as ExtensionManager
|
|
8
|
+
} from "../manager-DCbSiSWT.js";
|
|
9
|
+
import {
|
|
10
|
+
a as HostBridgeLoopback,
|
|
11
|
+
i as createBridgeProvider,
|
|
12
|
+
n as ExtensionSkillBridge,
|
|
13
|
+
o as HostBridgeLoopbackProps,
|
|
14
|
+
r as ExtensionWritableBridge,
|
|
15
|
+
t as ExtensionContextBridge
|
|
16
|
+
} from "../index-BsB4GUsL.js";
|
|
11
17
|
export {
|
|
18
|
+
ExtensionContextBridge,
|
|
12
19
|
ExtensionInfo,
|
|
13
20
|
ExtensionManager,
|
|
14
21
|
ExtensionManagerOptions,
|
|
15
22
|
ExtensionManifest,
|
|
16
23
|
ExtensionPermissions,
|
|
24
|
+
ExtensionSkillBridge,
|
|
17
25
|
ExtensionToolDescriptor,
|
|
26
|
+
ExtensionWritableBridge,
|
|
18
27
|
HostBridgeLoopback,
|
|
19
|
-
HostBridgeLoopbackProps
|
|
28
|
+
HostBridgeLoopbackProps,
|
|
29
|
+
createBridgeProvider
|
|
20
30
|
};
|
package/dist/extensions/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { r as
|
|
1
|
+
import { i as _classPrivateMethodInitSpec, t as ExtensionManager } from "../manager-dtoAI3A6.js";
|
|
2
|
+
import { r as _assertClassBrand } from "../classPrivateFieldGet2-DZKvdPZj.js";
|
|
3
3
|
import { WorkerEntrypoint } from "cloudflare:workers";
|
|
4
4
|
//#region src/extensions/host-bridge.ts
|
|
5
5
|
/**
|
|
@@ -34,28 +34,116 @@ var HostBridgeLoopback = class extends WorkerEntrypoint {
|
|
|
34
34
|
return ns.get(ns.idFromString(agentId));
|
|
35
35
|
}
|
|
36
36
|
async readFile(path) {
|
|
37
|
-
_assertClassBrand(_HostBridgeLoopback_brand, this,
|
|
37
|
+
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireWorkspace).call(this, "read");
|
|
38
38
|
return this._getAgent()._hostReadFile(path);
|
|
39
39
|
}
|
|
40
40
|
async writeFile(path, content) {
|
|
41
|
-
_assertClassBrand(_HostBridgeLoopback_brand, this,
|
|
41
|
+
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireWorkspace).call(this, "read-write");
|
|
42
42
|
return this._getAgent()._hostWriteFile(path, content);
|
|
43
43
|
}
|
|
44
44
|
async deleteFile(path) {
|
|
45
|
-
_assertClassBrand(_HostBridgeLoopback_brand, this,
|
|
45
|
+
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireWorkspace).call(this, "read-write");
|
|
46
46
|
return this._getAgent()._hostDeleteFile(path);
|
|
47
47
|
}
|
|
48
48
|
async listFiles(dir) {
|
|
49
|
-
_assertClassBrand(_HostBridgeLoopback_brand, this,
|
|
49
|
+
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireWorkspace).call(this, "read");
|
|
50
50
|
return this._getAgent()._hostListFiles(dir);
|
|
51
51
|
}
|
|
52
|
+
async getContext(label) {
|
|
53
|
+
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireContextRead).call(this, label);
|
|
54
|
+
return this._getAgent()._hostGetContext(label);
|
|
55
|
+
}
|
|
56
|
+
async setContext(label, content) {
|
|
57
|
+
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireContextWrite).call(this, label);
|
|
58
|
+
return this._getAgent()._hostSetContext(label, content);
|
|
59
|
+
}
|
|
60
|
+
async getMessages(limit) {
|
|
61
|
+
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireMessages).call(this);
|
|
62
|
+
return this._getAgent()._hostGetMessages(limit);
|
|
63
|
+
}
|
|
64
|
+
async sendMessage(content) {
|
|
65
|
+
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireSendMessage).call(this);
|
|
66
|
+
return this._getAgent()._hostSendMessage(content);
|
|
67
|
+
}
|
|
68
|
+
async getSessionInfo() {
|
|
69
|
+
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireSessionMetadata).call(this);
|
|
70
|
+
return this._getAgent()._hostGetSessionInfo();
|
|
71
|
+
}
|
|
52
72
|
};
|
|
53
|
-
function
|
|
73
|
+
function _requireWorkspace(level) {
|
|
54
74
|
const ws = this._permissions.workspace ?? "none";
|
|
55
75
|
if (ws === "none") throw new Error("Extension error: no workspace permission declared");
|
|
56
76
|
if (level === "read-write" && ws !== "read-write") throw new Error("Extension error: workspace write permission required, but only read granted");
|
|
57
77
|
}
|
|
78
|
+
function _requireContextRead(label) {
|
|
79
|
+
const ctx = this._permissions.context;
|
|
80
|
+
if (!ctx?.read) throw new Error("Extension error: no context read permission declared");
|
|
81
|
+
if (ctx.read !== "all" && !ctx.read.includes(label)) throw new Error(`Extension error: no read permission for context label "${label}"`);
|
|
82
|
+
}
|
|
83
|
+
function _requireContextWrite(label) {
|
|
84
|
+
const ctx = this._permissions.context;
|
|
85
|
+
if (!ctx?.write) throw new Error("Extension error: no context write permission declared");
|
|
86
|
+
if (ctx.write === "own") {
|
|
87
|
+
if (!(this.ctx.props.ownContextLabels ?? []).includes(label)) throw new Error(`Extension error: label "${label}" is not owned by this extension`);
|
|
88
|
+
} else if (!ctx.write.includes(label)) throw new Error(`Extension error: no write permission for context label "${label}"`);
|
|
89
|
+
}
|
|
90
|
+
function _requireMessages() {
|
|
91
|
+
if (this._permissions.messages !== "read") throw new Error("Extension error: no messages read permission declared");
|
|
92
|
+
}
|
|
93
|
+
function _requireSendMessage() {
|
|
94
|
+
if (!this._permissions.session?.sendMessage) throw new Error("Extension error: no session.sendMessage permission declared");
|
|
95
|
+
}
|
|
96
|
+
function _requireSessionMetadata() {
|
|
97
|
+
if (!this._permissions.session?.metadata) throw new Error("Extension error: no session.metadata permission declared");
|
|
98
|
+
}
|
|
99
|
+
//#endregion
|
|
100
|
+
//#region src/extensions/bridge-provider.ts
|
|
101
|
+
/**
|
|
102
|
+
* A readonly context provider backed by an extension Worker.
|
|
103
|
+
* Delegates `get()` to the extension's `contextGet` RPC method.
|
|
104
|
+
*/
|
|
105
|
+
var ExtensionContextBridge = class {
|
|
106
|
+
constructor(label, entrypoint) {
|
|
107
|
+
this._label = label;
|
|
108
|
+
this._entrypoint = entrypoint;
|
|
109
|
+
}
|
|
110
|
+
init(_label) {}
|
|
111
|
+
async get() {
|
|
112
|
+
return this._entrypoint.contextGet(this._label);
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
/**
|
|
116
|
+
* A writable context provider backed by an extension Worker.
|
|
117
|
+
* Delegates `get()` and `set()` to the extension's RPC methods.
|
|
118
|
+
*/
|
|
119
|
+
var ExtensionWritableBridge = class extends ExtensionContextBridge {
|
|
120
|
+
async set(content) {
|
|
121
|
+
await this._entrypoint.contextSet?.(this._label, "", content);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
/**
|
|
125
|
+
* A skill provider backed by an extension Worker.
|
|
126
|
+
* Delegates `get()`, `load()`, and optionally `set()` to the extension's RPC methods.
|
|
127
|
+
*/
|
|
128
|
+
var ExtensionSkillBridge = class extends ExtensionContextBridge {
|
|
129
|
+
async load(key) {
|
|
130
|
+
return await this._entrypoint.contextLoad?.(this._label, key) ?? null;
|
|
131
|
+
}
|
|
132
|
+
async set(key, content, description) {
|
|
133
|
+
await this._entrypoint.contextSet?.(this._label, key, content, description);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
/**
|
|
137
|
+
* Create the appropriate bridge provider based on the context block type.
|
|
138
|
+
*/
|
|
139
|
+
function createBridgeProvider(label, type, entrypoint) {
|
|
140
|
+
switch (type) {
|
|
141
|
+
case "skill": return new ExtensionSkillBridge(label, entrypoint);
|
|
142
|
+
case "writable": return new ExtensionWritableBridge(label, entrypoint);
|
|
143
|
+
default: return new ExtensionContextBridge(label, entrypoint);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
58
146
|
//#endregion
|
|
59
|
-
export { ExtensionManager, HostBridgeLoopback };
|
|
147
|
+
export { ExtensionContextBridge, ExtensionManager, ExtensionSkillBridge, ExtensionWritableBridge, HostBridgeLoopback, createBridgeProvider };
|
|
60
148
|
|
|
61
149
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/extensions/host-bridge.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 Requires the `\"experimental\"` compatibility flag.\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};\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 #requirePermission(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 async readFile(path: string): Promise<string | null> {\n this.#requirePermission(\"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.#requirePermission(\"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.#requirePermission(\"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.#requirePermission(\"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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA6BA,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;;CAezC,MAAM,SAAS,MAAsC;AACnD,oBAAA,2BAAA,MAAA,mBAAuB,CAAA,KAAA,MAAC,OAAO;AAC/B,SACE,KAAK,WAAW,CAGhB,cAAc,KAAK;;CAGvB,MAAM,UAAU,MAAc,SAAgC;AAC5D,oBAAA,2BAAA,MAAA,mBAAuB,CAAA,KAAA,MAAC,aAAa;AACrC,SACE,KAAK,WAAW,CAGhB,eAAe,MAAM,QAAQ;;CAGjC,MAAM,WAAW,MAAgC;AAC/C,oBAAA,2BAAA,MAAA,mBAAuB,CAAA,KAAA,MAAC,aAAa;AACrC,SACE,KAAK,WAAW,CAGhB,gBAAgB,KAAK;;CAGzB,MAAM,UACJ,KAGA;AACA,oBAAA,2BAAA,MAAA,mBAAuB,CAAA,KAAA,MAAC,OAAO;AAC/B,SACE,KAAK,WAAW,CAOhB,eAAe,IAAI;;;AArDvB,SAAA,mBAAmB,OAAoC;CACrD,MAAM,KAAK,KAAK,aAAa,aAAa;AAC1C,KAAI,OAAO,OACT,OAAM,IAAI,MAAM,oDAAoD;AAEtE,KAAI,UAAU,gBAAgB,OAAO,aACnC,OAAM,IAAI,MACR,8EACD"}
|
|
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 Requires the `\"experimental\"` compatibility flag.\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":"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"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
//#region src/extensions/hook-proxy.ts
|
|
2
|
+
/**
|
|
3
|
+
* Create a serializable snapshot from a TurnContext.
|
|
4
|
+
*/
|
|
5
|
+
function createTurnContextSnapshot(ctx) {
|
|
6
|
+
return {
|
|
7
|
+
system: ctx.system,
|
|
8
|
+
toolNames: Object.keys(ctx.tools),
|
|
9
|
+
messageCount: ctx.messages.length,
|
|
10
|
+
continuation: ctx.continuation,
|
|
11
|
+
body: ctx.body,
|
|
12
|
+
modelId: ctx.model.modelId ?? "unknown"
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Parse a hook result from the extension Worker's JSON response.
|
|
17
|
+
* Returns a TurnConfig or null if the extension skipped/errored.
|
|
18
|
+
*/
|
|
19
|
+
function parseHookResult(json) {
|
|
20
|
+
try {
|
|
21
|
+
const parsed = JSON.parse(json);
|
|
22
|
+
if (parsed.skipped) return { skipped: true };
|
|
23
|
+
if (parsed.error) return { error: parsed.error };
|
|
24
|
+
return { config: parsed.result ?? {} };
|
|
25
|
+
} catch {
|
|
26
|
+
return { error: "Failed to parse hook result" };
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
//#endregion
|
|
30
|
+
export { createTurnContextSnapshot, parseHookResult };
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=hook-proxy-f_DqtJ9u.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hook-proxy-f_DqtJ9u.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 TurnContext directly (it contains\n * functions like ToolSet). These snapshots are plain data objects\n * that survive Workers RPC serialization (structured clone).\n */\n\nimport type { TurnContext, TurnConfig } from \"../think\";\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"],"mappings":";;;;AA4BA,SAAgB,0BACd,KACqB;AACrB,QAAO;EACL,QAAQ,IAAI;EACZ,WAAW,OAAO,KAAK,IAAI,MAAM;EACjC,cAAc,IAAI,SAAS;EAC3B,cAAc,IAAI;EAClB,MAAM,IAAI;EACV,SACI,IAAI,MAAkC,WAAsB;EACjE;;;;;;AAOH,SAAgB,gBACd,MACgE;AAChE,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,KAAK;AAC/B,MAAI,OAAO,QAAS,QAAO,EAAE,SAAS,MAAM;AAC5C,MAAI,OAAO,MAAO,QAAO,EAAE,OAAO,OAAO,OAAiB;AAC1D,SAAO,EAAE,QAAS,OAAO,UAAU,EAAE,EAAiB;SAChD;AACN,SAAO,EAAE,OAAO,+BAA+B"}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { a as ExtensionPermissions } from "./manager-DCbSiSWT.js";
|
|
2
|
+
import { WorkerEntrypoint } from "cloudflare:workers";
|
|
3
|
+
|
|
4
|
+
//#region src/extensions/host-bridge.d.ts
|
|
5
|
+
type HostBridgeLoopbackProps = {
|
|
6
|
+
agentClassName: string;
|
|
7
|
+
agentId: string;
|
|
8
|
+
permissions: ExtensionPermissions /** Namespaced context labels this extension declared (for "own" write validation). */;
|
|
9
|
+
ownContextLabels?: string[];
|
|
10
|
+
};
|
|
11
|
+
declare class HostBridgeLoopback extends WorkerEntrypoint<
|
|
12
|
+
Record<string, unknown>,
|
|
13
|
+
HostBridgeLoopbackProps
|
|
14
|
+
> {
|
|
15
|
+
#private;
|
|
16
|
+
private _permissions;
|
|
17
|
+
private _getAgent;
|
|
18
|
+
readFile(path: string): Promise<string | null>;
|
|
19
|
+
writeFile(path: string, content: string): Promise<void>;
|
|
20
|
+
deleteFile(path: string): Promise<boolean>;
|
|
21
|
+
listFiles(dir: string): Promise<
|
|
22
|
+
Array<{
|
|
23
|
+
name: string;
|
|
24
|
+
type: string;
|
|
25
|
+
size: number;
|
|
26
|
+
path: string;
|
|
27
|
+
}>
|
|
28
|
+
>;
|
|
29
|
+
getContext(label: string): Promise<string | null>;
|
|
30
|
+
setContext(label: string, content: string): Promise<void>;
|
|
31
|
+
getMessages(limit?: number): Promise<
|
|
32
|
+
Array<{
|
|
33
|
+
id: string;
|
|
34
|
+
role: string;
|
|
35
|
+
content: string;
|
|
36
|
+
}>
|
|
37
|
+
>;
|
|
38
|
+
sendMessage(content: string): Promise<void>;
|
|
39
|
+
getSessionInfo(): Promise<{
|
|
40
|
+
messageCount: number;
|
|
41
|
+
}>;
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
//#region src/extensions/bridge-provider.d.ts
|
|
45
|
+
/**
|
|
46
|
+
* Bridge providers that adapt extension Worker RPC into Session's
|
|
47
|
+
* ContextProvider / SkillProvider / WritableContextProvider interfaces.
|
|
48
|
+
*
|
|
49
|
+
* When an extension declares context blocks in its manifest, Think creates
|
|
50
|
+
* a bridge provider for each block. The bridge delegates `get()`, `load()`,
|
|
51
|
+
* and `set()` to the extension Worker's entrypoint via RPC.
|
|
52
|
+
*
|
|
53
|
+
* This allows extensions to contribute context blocks to the Session's
|
|
54
|
+
* system prompt without Session knowing about the extension system.
|
|
55
|
+
*/
|
|
56
|
+
interface ExtensionContextEntrypoint {
|
|
57
|
+
contextGet(label: string): Promise<string | null>;
|
|
58
|
+
contextLoad?(label: string, key: string): Promise<string | null>;
|
|
59
|
+
contextSet?(
|
|
60
|
+
label: string,
|
|
61
|
+
key: string,
|
|
62
|
+
content: string,
|
|
63
|
+
description?: string
|
|
64
|
+
): Promise<void>;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* A readonly context provider backed by an extension Worker.
|
|
68
|
+
* Delegates `get()` to the extension's `contextGet` RPC method.
|
|
69
|
+
*/
|
|
70
|
+
declare class ExtensionContextBridge {
|
|
71
|
+
protected _label: string;
|
|
72
|
+
protected _entrypoint: ExtensionContextEntrypoint;
|
|
73
|
+
constructor(label: string, entrypoint: ExtensionContextEntrypoint);
|
|
74
|
+
init(_label: string): void;
|
|
75
|
+
get(): Promise<string | null>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* A writable context provider backed by an extension Worker.
|
|
79
|
+
* Delegates `get()` and `set()` to the extension's RPC methods.
|
|
80
|
+
*/
|
|
81
|
+
declare class ExtensionWritableBridge extends ExtensionContextBridge {
|
|
82
|
+
set(content: string): Promise<void>;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* A skill provider backed by an extension Worker.
|
|
86
|
+
* Delegates `get()`, `load()`, and optionally `set()` to the extension's RPC methods.
|
|
87
|
+
*/
|
|
88
|
+
declare class ExtensionSkillBridge extends ExtensionContextBridge {
|
|
89
|
+
load(key: string): Promise<string | null>;
|
|
90
|
+
set(key: string, content: string, description?: string): Promise<void>;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Create the appropriate bridge provider based on the context block type.
|
|
94
|
+
*/
|
|
95
|
+
declare function createBridgeProvider(
|
|
96
|
+
label: string,
|
|
97
|
+
type: "readonly" | "writable" | "skill" | "searchable",
|
|
98
|
+
entrypoint: ExtensionContextEntrypoint
|
|
99
|
+
): ExtensionContextBridge;
|
|
100
|
+
//#endregion
|
|
101
|
+
export {
|
|
102
|
+
HostBridgeLoopback as a,
|
|
103
|
+
createBridgeProvider as i,
|
|
104
|
+
ExtensionSkillBridge as n,
|
|
105
|
+
HostBridgeLoopbackProps as o,
|
|
106
|
+
ExtensionWritableBridge as r,
|
|
107
|
+
ExtensionContextBridge as t
|
|
108
|
+
};
|
|
109
|
+
//# sourceMappingURL=index-BsB4GUsL.d.ts.map
|