@cloudflare/think 0.22.0 → 0.24.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 +79 -117
- package/dist/extensions/index.d.ts +4 -14
- package/dist/extensions/index.js +2 -15
- package/dist/extensions/index.js.map +1 -1
- package/dist/{index-BFK9bpzz.d.ts → index-DIQ9oY1t.d.ts} +208 -75
- package/dist/{manager-dOcdCX4u.d.ts → manager-CtXhU1fK.d.ts} +9 -2
- package/dist/{manager-BubfmA3q.js → manager-sfWIcYJT.js} +24 -4
- package/dist/manager-sfWIcYJT.js.map +1 -0
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
- package/dist/think.d.ts +2 -2
- package/dist/think.js +135 -88
- 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/execute.d.ts +2 -2
- package/dist/tools/execute.js +2 -2
- package/dist/tools/execute.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/workflows.d.ts +1 -1
- package/docs/getting-started.md +3 -3
- package/docs/index.md +100 -95
- package/docs/lifecycle-hooks.md +13 -13
- package/docs/multi-chat.md +8 -7
- package/docs/tools.md +12 -14
- package/docs/workflows.md +1 -1
- package/package.json +6 -6
- package/dist/manager-BubfmA3q.js.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
i as ExtensionManifest,
|
|
3
3
|
t as ExtensionManager
|
|
4
|
-
} from "./manager-
|
|
4
|
+
} from "./manager-CtXhU1fK.js";
|
|
5
5
|
import {
|
|
6
6
|
l as ThinkWorkspace,
|
|
7
7
|
t as CreateFetchToolsOptions
|
|
@@ -30,15 +30,65 @@ import {
|
|
|
30
30
|
UIMessage,
|
|
31
31
|
streamText
|
|
32
32
|
} from "ai";
|
|
33
|
-
import * as skills from "agents/skills";
|
|
34
33
|
import {
|
|
34
|
+
DEFAULT_WORKSPACE_SKILLS_ROOT,
|
|
35
|
+
InvalidSkill,
|
|
36
|
+
InvalidSkillResourcePathError,
|
|
37
|
+
ListedSkill,
|
|
38
|
+
LoadSkillCatalogOptions,
|
|
39
|
+
ParseSkillOptions,
|
|
40
|
+
R2SkillSourceOptions,
|
|
41
|
+
Skill,
|
|
42
|
+
Skill as Skill$1,
|
|
43
|
+
SkillCatalog,
|
|
44
|
+
SkillCatalog as SkillCatalog$1,
|
|
45
|
+
SkillCatalogEntry,
|
|
46
|
+
SkillCatalogResource,
|
|
47
|
+
SkillDiagnostic,
|
|
48
|
+
SkillListing,
|
|
49
|
+
SkillManifest,
|
|
50
|
+
SkillManifestEntry,
|
|
51
|
+
SkillManifestResource,
|
|
52
|
+
SkillName,
|
|
53
|
+
SkillParseError,
|
|
54
|
+
SkillParseErrorCode,
|
|
55
|
+
SkillParseResult,
|
|
56
|
+
SkillResource,
|
|
57
|
+
SkillResourceError,
|
|
58
|
+
SkillResourceInfo,
|
|
59
|
+
SkillResourceKind,
|
|
60
|
+
SkillResourceNotFoundError,
|
|
61
|
+
SkillResourcePath,
|
|
62
|
+
SkillResult,
|
|
35
63
|
SkillRunContext,
|
|
64
|
+
SkillRunContext as SkillRunContext$1,
|
|
65
|
+
SkillScriptContext,
|
|
66
|
+
SkillScriptFile,
|
|
67
|
+
SkillScriptRequest,
|
|
36
68
|
SkillScriptRunner,
|
|
69
|
+
SkillScriptRunner as SkillScriptRunner$1,
|
|
70
|
+
SkillScriptWorkspace,
|
|
37
71
|
SkillSource,
|
|
38
72
|
SkillSource as SkillSource$1,
|
|
39
|
-
|
|
40
|
-
|
|
73
|
+
SkillSource as SkillSource$2,
|
|
74
|
+
SkillSourceError,
|
|
75
|
+
SkillWorkspace,
|
|
76
|
+
UnknownSkillError,
|
|
77
|
+
WorkspaceSkillSourceOptions,
|
|
78
|
+
formatSkill,
|
|
79
|
+
formatSkillDiagnostic as formatSkillDiagnostic$1,
|
|
80
|
+
fromManifest,
|
|
81
|
+
isModelInvocable,
|
|
82
|
+
loadSkillCatalog as loadSkillCatalog$1,
|
|
83
|
+
manifest,
|
|
84
|
+
parseSkill,
|
|
85
|
+
parseSkillName,
|
|
86
|
+
parseSkillResourcePath,
|
|
87
|
+
r2,
|
|
88
|
+
renderSkillResource,
|
|
89
|
+
workspace
|
|
41
90
|
} from "agents/skills";
|
|
91
|
+
import { WorkerSkillScriptRunnerOptions, runner } from "agents/skills/runner";
|
|
42
92
|
import {
|
|
43
93
|
Agent,
|
|
44
94
|
AgentToolLifecycleResult,
|
|
@@ -118,6 +168,64 @@ import { ChatSdkStateAdapterOptions, ChatSdkStateAgent } from "agents/chat-sdk";
|
|
|
118
168
|
import { RpcTarget } from "cloudflare:workers";
|
|
119
169
|
import { Streams } from "agents/streams";
|
|
120
170
|
|
|
171
|
+
//#region src/skills.d.ts
|
|
172
|
+
declare namespace skills_d_exports {
|
|
173
|
+
export {
|
|
174
|
+
DEFAULT_WORKSPACE_SKILLS_ROOT,
|
|
175
|
+
InvalidSkill,
|
|
176
|
+
InvalidSkillResourcePathError,
|
|
177
|
+
ListedSkill,
|
|
178
|
+
LoadSkillCatalogOptions,
|
|
179
|
+
ParseSkillOptions,
|
|
180
|
+
R2SkillSourceOptions,
|
|
181
|
+
Skill$1 as Skill,
|
|
182
|
+
SkillCatalog$1 as SkillCatalog,
|
|
183
|
+
SkillCatalogEntry,
|
|
184
|
+
SkillCatalogResource,
|
|
185
|
+
SkillDiagnostic,
|
|
186
|
+
SkillListing,
|
|
187
|
+
SkillManifest,
|
|
188
|
+
SkillManifestEntry,
|
|
189
|
+
SkillManifestResource,
|
|
190
|
+
SkillName,
|
|
191
|
+
SkillParseError,
|
|
192
|
+
SkillParseErrorCode,
|
|
193
|
+
SkillParseResult,
|
|
194
|
+
SkillResource,
|
|
195
|
+
SkillResourceError,
|
|
196
|
+
SkillResourceInfo,
|
|
197
|
+
SkillResourceKind,
|
|
198
|
+
SkillResourceNotFoundError,
|
|
199
|
+
SkillResourcePath,
|
|
200
|
+
SkillResult,
|
|
201
|
+
SkillRunContext$1 as SkillRunContext,
|
|
202
|
+
SkillScriptContext,
|
|
203
|
+
SkillScriptFile,
|
|
204
|
+
SkillScriptRequest,
|
|
205
|
+
SkillScriptRunner$1 as SkillScriptRunner,
|
|
206
|
+
SkillScriptWorkspace,
|
|
207
|
+
SkillSource$2 as SkillSource,
|
|
208
|
+
SkillSourceError,
|
|
209
|
+
SkillWorkspace,
|
|
210
|
+
UnknownSkillError,
|
|
211
|
+
WorkerSkillScriptRunnerOptions,
|
|
212
|
+
WorkspaceSkillSourceOptions,
|
|
213
|
+
formatSkill,
|
|
214
|
+
formatSkillDiagnostic$1 as formatSkillDiagnostic,
|
|
215
|
+
fromManifest,
|
|
216
|
+
isModelInvocable,
|
|
217
|
+
loadSkillCatalog$1 as loadSkillCatalog,
|
|
218
|
+
manifest,
|
|
219
|
+
parseSkill,
|
|
220
|
+
parseSkillName,
|
|
221
|
+
parseSkillResourcePath,
|
|
222
|
+
r2,
|
|
223
|
+
renderSkillResource,
|
|
224
|
+
runner,
|
|
225
|
+
workspace
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
//#endregion
|
|
121
229
|
//#region src/session.d.ts
|
|
122
230
|
/** Options for a block declared through `withContext()` / `addContext()`. */
|
|
123
231
|
type SessionContextOptions = Omit<ContextConfig, "label">;
|
|
@@ -1005,7 +1113,7 @@ interface TurnInput {
|
|
|
1005
1113
|
* Contains everything Think assembled — the hook can inspect and override.
|
|
1006
1114
|
*/
|
|
1007
1115
|
interface TurnContext {
|
|
1008
|
-
/** Assembled system prompt (
|
|
1116
|
+
/** Assembled system prompt: an overridden `getSystemPrompt()`, then context blocks. */
|
|
1009
1117
|
system: string;
|
|
1010
1118
|
/**
|
|
1011
1119
|
* Assembled model messages (truncated, pruned). When a `whenChanged:
|
|
@@ -1630,15 +1738,8 @@ declare class Think<
|
|
|
1630
1738
|
storeMessages: boolean;
|
|
1631
1739
|
/** Store tool input/output on `execute_tool` spans. */
|
|
1632
1740
|
storeTools: boolean;
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
* and edit skills as files under `/workspace/.agents/skills`.
|
|
1636
|
-
* Existing edits are preserved. Off by default: skills load from their
|
|
1637
|
-
* sources and nothing is written to the Workspace, as before. Set `{}` to
|
|
1638
|
-
* project with the defaults.
|
|
1639
|
-
*/
|
|
1640
|
-
skillWorkspace: false | SkillWorkspaceSeedOptions;
|
|
1641
|
-
private _skillRegistry;
|
|
1741
|
+
private _skillSources;
|
|
1742
|
+
private _skillCatalog;
|
|
1642
1743
|
private _loggedSkillWarnings;
|
|
1643
1744
|
private _loggedProtocolWarnings;
|
|
1644
1745
|
/**
|
|
@@ -2267,7 +2368,7 @@ declare class Think<
|
|
|
2267
2368
|
* @example String (Workers AI)
|
|
2268
2369
|
* ```typescript
|
|
2269
2370
|
* getModel() {
|
|
2270
|
-
* return "@cf/
|
|
2371
|
+
* return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
|
|
2271
2372
|
* }
|
|
2272
2373
|
* ```
|
|
2273
2374
|
*
|
|
@@ -2330,11 +2431,21 @@ declare class Think<
|
|
|
2330
2431
|
*/
|
|
2331
2432
|
resolveModel(model?: ThinkModel): LanguageModel;
|
|
2332
2433
|
/**
|
|
2333
|
-
* Return the
|
|
2334
|
-
*
|
|
2335
|
-
* always
|
|
2434
|
+
* Return the instructions at the top of the system prompt.
|
|
2435
|
+
*
|
|
2436
|
+
* An override always comes first, followed by the context blocks from
|
|
2437
|
+
* `configureContext()`, skills, and extensions. Think's default text is
|
|
2438
|
+
* used only when the agent overrides nothing and has no context blocks.
|
|
2336
2439
|
*/
|
|
2337
2440
|
getSystemPrompt(): string;
|
|
2441
|
+
/**
|
|
2442
|
+
* The base system prompt for a turn: an overridden `getSystemPrompt()`,
|
|
2443
|
+
* then the frozen context blocks. Think's default `getSystemPrompt()` is
|
|
2444
|
+
* only a fallback for an agent with no context blocks.
|
|
2445
|
+
*
|
|
2446
|
+
* @internal Exposed to subclasses for tests.
|
|
2447
|
+
*/
|
|
2448
|
+
protected _buildBaseSystemPrompt(): Promise<string>;
|
|
2338
2449
|
/** Return the tools available to the assistant. */
|
|
2339
2450
|
getTools(): ToolSet;
|
|
2340
2451
|
/** Return action descriptors compiled into tools for the assistant. */
|
|
@@ -2751,36 +2862,40 @@ declare class Think<
|
|
|
2751
2862
|
/**
|
|
2752
2863
|
* Return Agent Skills sources for this Think agent.
|
|
2753
2864
|
*
|
|
2754
|
-
*
|
|
2865
|
+
* A skill is a directory with a `SKILL.md` file, as defined by
|
|
2866
|
+
* https://agentskills.io. Keep skills as files in the agent's Workspace
|
|
2867
|
+
* and they become available as soon as they are written:
|
|
2755
2868
|
*
|
|
2756
2869
|
* ```typescript
|
|
2757
|
-
*
|
|
2870
|
+
* getSkills() {
|
|
2871
|
+
* return [skills.workspace(this.workspace)]; // /workspace/.agents/skills
|
|
2872
|
+
* }
|
|
2758
2873
|
* ```
|
|
2759
2874
|
*
|
|
2760
|
-
*
|
|
2761
|
-
*
|
|
2875
|
+
* `skills.r2()` reads skills from an R2 bucket and `skills.manifest()`
|
|
2876
|
+
* defines them in code. Sources are applied in order; the first source to
|
|
2877
|
+
* provide a skill name wins, and later collisions are skipped with a
|
|
2878
|
+
* logged warning. Sources are listed again before every turn.
|
|
2762
2879
|
*/
|
|
2763
2880
|
getSkills(): SkillSource[] | Promise<SkillSource[]>;
|
|
2764
2881
|
private _initializeSkills;
|
|
2765
|
-
|
|
2882
|
+
/** Load the catalog from every source and log new diagnostics. */
|
|
2883
|
+
private _loadSkillCatalog;
|
|
2766
2884
|
/**
|
|
2767
|
-
* Log
|
|
2768
|
-
*
|
|
2769
|
-
* the same warning is not repeated on every turn.
|
|
2885
|
+
* Log a skills warning once per object lifetime, so a new problem after a
|
|
2886
|
+
* deploy still surfaces while the same warning is not repeated every turn.
|
|
2770
2887
|
*/
|
|
2771
|
-
private
|
|
2888
|
+
private _warnSkillsOnce;
|
|
2772
2889
|
/**
|
|
2773
2890
|
* Return an optional runner that enables the `run_skill_script` tool.
|
|
2774
2891
|
*
|
|
2892
|
+
* Prefer keeping skills in the Workspace and letting the agent run their
|
|
2893
|
+
* scripts with its shell tools.
|
|
2894
|
+
*
|
|
2775
2895
|
* @experimental Skill script execution is experimental and may change
|
|
2776
2896
|
* before stabilizing.
|
|
2777
2897
|
*/
|
|
2778
2898
|
getSkillScriptRunner(): SkillScriptRunner | null;
|
|
2779
|
-
/**
|
|
2780
|
-
* The persisted skills fingerprint, read from `think_config` once per
|
|
2781
|
-
* object lifetime; `null` once read and absent. Saves the per-turn probe.
|
|
2782
|
-
*/
|
|
2783
|
-
private _skillsFingerprint;
|
|
2784
2899
|
private _refreshSkillsIfChanged;
|
|
2785
2900
|
/**
|
|
2786
2901
|
* Return sandboxed extension configurations. Defines load order,
|
|
@@ -3929,8 +4044,9 @@ declare class Think<
|
|
|
3929
4044
|
* tab briefly renders the turn twice before collapsing. Mirrors the fix in
|
|
3930
4045
|
* `@cloudflare/ai-chat`. Continuations are skipped — they reuse the existing
|
|
3931
4046
|
* assistant message via the `continuation` frame flag, so the id must not
|
|
3932
|
-
* change mid-message.
|
|
3933
|
-
* stored chunk
|
|
4047
|
+
* change mid-message. Orphan recovery inherits a new turn's id from the
|
|
4048
|
+
* stored chunk; a continuation's id is recorded with its stream instead
|
|
4049
|
+
* (`_streamResult`).
|
|
3934
4050
|
*/
|
|
3935
4051
|
private _alignStreamStartId;
|
|
3936
4052
|
private _annotateActionApprovalChunk;
|
|
@@ -4933,6 +5049,7 @@ declare class Think<
|
|
|
4933
5049
|
options?: {
|
|
4934
5050
|
messageId?: string;
|
|
4935
5051
|
parentMessageId?: string;
|
|
5052
|
+
basePartCount?: number;
|
|
4936
5053
|
continuation?: boolean;
|
|
4937
5054
|
}
|
|
4938
5055
|
): string;
|
|
@@ -4971,6 +5088,21 @@ declare class Think<
|
|
|
4971
5088
|
* that does not record the parent.
|
|
4972
5089
|
*/
|
|
4973
5090
|
private _orphanParentId;
|
|
5091
|
+
/**
|
|
5092
|
+
* The assistant message a leaf-extending stream continues, and how many parts
|
|
5093
|
+
* it held when the stream started; undefined for a stream that produces a
|
|
5094
|
+
* message of its own. `_streamResult` records both when it starts the stream.
|
|
5095
|
+
*
|
|
5096
|
+
* Recovery keeps that many leading parts of the stored message, so it relies
|
|
5097
|
+
* on them staying put until the stream is recovered. That holds today: the
|
|
5098
|
+
* stream itself only adds parts after them, and once a stream is recovered
|
|
5099
|
+
* it is marked completed and reclaimed when the next stream starts, so a
|
|
5100
|
+
* later stream that extends the message again cannot be overwritten by a
|
|
5101
|
+
* replay.
|
|
5102
|
+
* (`_dropGenerationAfterResolvedPause` can trim an orphaned leaf; it only
|
|
5103
|
+
* drops text and reasoning written against a paused tool result.)
|
|
5104
|
+
*/
|
|
5105
|
+
private _orphanContinuedMessage;
|
|
4974
5106
|
private _persistOrphanedStream;
|
|
4975
5107
|
private _broadcastChat;
|
|
4976
5108
|
/**
|
|
@@ -5566,31 +5698,31 @@ export {
|
|
|
5566
5698
|
MediaEvictionConfig as $n,
|
|
5567
5699
|
RunTurnWait as $t,
|
|
5568
5700
|
ERROR_MESSENGER_RESPONSE as A,
|
|
5569
|
-
|
|
5701
|
+
ToolCallResultContext as An,
|
|
5570
5702
|
ChunkContext as At,
|
|
5571
5703
|
defaultDeliveryTag as B,
|
|
5572
|
-
|
|
5704
|
+
action as Bn,
|
|
5573
5705
|
MessageMetadataCallback as Bt,
|
|
5574
5706
|
toMessengerAuthor as C,
|
|
5575
|
-
|
|
5707
|
+
ThinkScheduledTasks as Cn,
|
|
5576
5708
|
ChatRecoveryConfig$1 as Ct,
|
|
5577
5709
|
DeliveryKind as D,
|
|
5578
|
-
|
|
5710
|
+
ThinkWallClockSchedule as Dn,
|
|
5579
5711
|
ChatRecoveryProgressContext as Dt,
|
|
5580
5712
|
DeliverMessengerReplyOptions as E,
|
|
5581
|
-
|
|
5713
|
+
ThinkTime as En,
|
|
5582
5714
|
ChatRecoveryOptions$1 as Et,
|
|
5583
5715
|
MessengerDeliveryTarget as F,
|
|
5584
|
-
|
|
5716
|
+
TurnResult as Fn,
|
|
5585
5717
|
ExtensionConfig as Ft,
|
|
5586
5718
|
parseMessengerReplySnapshot as G,
|
|
5587
5719
|
ChannelDefinition as Gn,
|
|
5588
5720
|
PrepareStepResult$1 as Gt,
|
|
5589
5721
|
messengerReplyFailureMode as H,
|
|
5590
|
-
|
|
5722
|
+
isAction as Hn,
|
|
5591
5723
|
PendingApproval as Ht,
|
|
5592
5724
|
MessengerReplySnapshot as I,
|
|
5593
|
-
|
|
5725
|
+
TurnTrigger as In,
|
|
5594
5726
|
FiberContext$1 as It,
|
|
5595
5727
|
MessengerAttachment as J,
|
|
5596
5728
|
ChannelIngress as Jn,
|
|
@@ -5599,37 +5731,37 @@ export {
|
|
|
5599
5731
|
ChannelDeliveryPolicy as Kn,
|
|
5600
5732
|
RejectExecutionOptions as Kt,
|
|
5601
5733
|
MessengerReplyStage as L,
|
|
5602
|
-
|
|
5734
|
+
TypedToolCall$1 as Ln,
|
|
5603
5735
|
FiberRecoveryContext$1 as Lt,
|
|
5604
5736
|
MESSENGER_REPLY_FIBER_NAME as M,
|
|
5605
|
-
|
|
5737
|
+
TurnContext as Mn,
|
|
5606
5738
|
ContextOverflowConfig as Mt,
|
|
5607
5739
|
MessengerDeliveryPolicy as N,
|
|
5608
|
-
|
|
5740
|
+
TurnInput as Nn,
|
|
5609
5741
|
DeleteSubmissionsOptions as Nt,
|
|
5610
5742
|
DeliveryTag as O,
|
|
5611
|
-
|
|
5743
|
+
ToolCallContext as On,
|
|
5612
5744
|
ChatResponseResult$1 as Ot,
|
|
5613
5745
|
MessengerDeliverySurface as P,
|
|
5614
|
-
|
|
5746
|
+
TurnInputMessages as Pn,
|
|
5615
5747
|
DeliverNoticeOptions as Pt,
|
|
5616
5748
|
MessengerEvent as Q,
|
|
5617
5749
|
messengerChannel as Qn,
|
|
5618
5750
|
RunTurnSubmit as Qt,
|
|
5619
5751
|
TextStreamCallback as R,
|
|
5620
|
-
|
|
5752
|
+
TypedToolResult as Rn,
|
|
5621
5753
|
ListSubmissionsOptions as Rt,
|
|
5622
5754
|
toMessengerAttachment as S,
|
|
5623
|
-
|
|
5755
|
+
ThinkScheduledTaskSchedule as Sn,
|
|
5624
5756
|
ChatOptions as St,
|
|
5625
5757
|
toMessengerThread as T,
|
|
5626
|
-
|
|
5758
|
+
ThinkSubmissionStatus as Tn,
|
|
5627
5759
|
ChatRecoveryExhaustedContext as Tt,
|
|
5628
5760
|
messengerReplyRecoveryMode as U,
|
|
5629
5761
|
ChannelCapabilities as Un,
|
|
5630
5762
|
PrepareStepContext as Ut,
|
|
5631
5763
|
deliverMessengerReply as V,
|
|
5632
|
-
|
|
5764
|
+
defaultContextOverflowClassifier as Vn,
|
|
5633
5765
|
OnStartDegradation as Vt,
|
|
5634
5766
|
messengerReplySnapshot as W,
|
|
5635
5767
|
ChannelContext as Wn,
|
|
@@ -5644,88 +5776,89 @@ export {
|
|
|
5644
5776
|
ThinkChannels as Zn,
|
|
5645
5777
|
RunTurnStream as Zt,
|
|
5646
5778
|
defaultChatSdkEvent as _,
|
|
5647
|
-
|
|
5779
|
+
ThinkIntervalSchedule as _n,
|
|
5648
5780
|
AddMessagesOptions as _t,
|
|
5649
5781
|
MessengerConversationMode as a,
|
|
5650
|
-
|
|
5782
|
+
SkillRunContext as an,
|
|
5651
5783
|
toMessengerUserMessage as at,
|
|
5652
5784
|
normalizeMessengers as b,
|
|
5653
|
-
|
|
5785
|
+
ThinkScheduledTask as bn,
|
|
5654
5786
|
ChatErrorContext as bt,
|
|
5655
5787
|
MessengerDefinition as c,
|
|
5656
|
-
|
|
5788
|
+
StepContext as cn,
|
|
5657
5789
|
ActionApprovalPolicy as ct,
|
|
5658
5790
|
MessengerThinkTarget as d,
|
|
5659
|
-
|
|
5791
|
+
StreamCallback as dn,
|
|
5660
5792
|
ActionConfig as dt,
|
|
5661
5793
|
SaveMessagesOptions$1 as en,
|
|
5662
5794
|
CompactAfterOptions as er,
|
|
5663
5795
|
MessengerMessage as et,
|
|
5664
5796
|
NormalizedMessengerDefinition as f,
|
|
5665
|
-
|
|
5797
|
+
StreamableResult as fn,
|
|
5666
5798
|
ActionContext as ft,
|
|
5667
5799
|
chatSdkMessenger as g,
|
|
5668
|
-
|
|
5800
|
+
Think as gn,
|
|
5669
5801
|
ActiveTurn as gt,
|
|
5670
5802
|
ThinkMessengers as h,
|
|
5671
|
-
|
|
5803
|
+
TextStreamPart$1 as hn,
|
|
5672
5804
|
ActionPermissionSpec as ht,
|
|
5673
5805
|
MessengerConcurrency as i,
|
|
5674
|
-
|
|
5806
|
+
SkillCatalog as in,
|
|
5807
|
+
skills_d_exports as ir,
|
|
5675
5808
|
serializableMessengerEvent as it,
|
|
5676
5809
|
INTERRUPTED_MESSENGER_RESPONSE as j,
|
|
5677
|
-
|
|
5810
|
+
TurnConfig as jn,
|
|
5678
5811
|
ChunkPart as jt,
|
|
5679
5812
|
EMPTY_MESSENGER_RESPONSE as k,
|
|
5680
|
-
|
|
5813
|
+
ToolCallDecision as kn,
|
|
5681
5814
|
ChatStartEvent as kt,
|
|
5682
5815
|
MessengerRespondTo as l,
|
|
5683
|
-
|
|
5816
|
+
StepResult as ln,
|
|
5684
5817
|
ActionAuthorizationContext as lt,
|
|
5685
5818
|
ThinkMessengerStateAgent as m,
|
|
5686
|
-
|
|
5819
|
+
SubmitMessagesResult as mn,
|
|
5687
5820
|
ActionKind as mt,
|
|
5688
5821
|
ChatSdkMessengerOptions as n,
|
|
5689
5822
|
SessionMessage$1 as nn,
|
|
5690
5823
|
SessionContextOptions as nr,
|
|
5691
5824
|
messengerContextFromEvent as nt,
|
|
5692
5825
|
MessengerConversationResolver as o,
|
|
5693
|
-
|
|
5826
|
+
SkillSource$1 as on,
|
|
5694
5827
|
Action as ot,
|
|
5695
5828
|
ThinkMessengerRuntime as p,
|
|
5696
|
-
|
|
5829
|
+
SubmitMessagesOptions as pn,
|
|
5697
5830
|
ActionIdempotencyKey as pt,
|
|
5698
5831
|
MessengerAction as q,
|
|
5699
5832
|
ChannelDeliverySurface as qn,
|
|
5700
5833
|
ReplyAttachment as qt,
|
|
5701
5834
|
DEFAULT_MESSENGER_CONCURRENCY as r,
|
|
5702
|
-
|
|
5835
|
+
Skill as rn,
|
|
5703
5836
|
ThinkSession as rr,
|
|
5704
5837
|
resolveChannelSpeakerLabel as rt,
|
|
5705
5838
|
MessengerConversationTarget as s,
|
|
5706
|
-
|
|
5839
|
+
StepConfig as sn,
|
|
5707
5840
|
ActionApprovalDescriptor as st,
|
|
5708
5841
|
ChatSdkMessengerEventInput as t,
|
|
5709
5842
|
SaveMessagesResult$1 as tn,
|
|
5710
5843
|
CompactionErrorHandler as tr,
|
|
5711
5844
|
MessengerThread as tt,
|
|
5712
5845
|
MessengerThinkHost as u,
|
|
5713
|
-
|
|
5846
|
+
StopCondition$1 as un,
|
|
5714
5847
|
ActionAuthorizationDecision as ut,
|
|
5715
5848
|
defaultConversationName as v,
|
|
5716
|
-
|
|
5849
|
+
ThinkModel as vn,
|
|
5717
5850
|
CancelSubmissionResult as vt,
|
|
5718
5851
|
toMessengerMessage as w,
|
|
5719
|
-
|
|
5852
|
+
ThinkSubmissionInspection as wn,
|
|
5720
5853
|
ChatRecoveryContext$1 as wt,
|
|
5721
5854
|
resolveSelfMention as x,
|
|
5722
|
-
|
|
5855
|
+
ThinkScheduledTaskContext as xn,
|
|
5723
5856
|
ChatInterruptedInfo as xt,
|
|
5724
5857
|
idempotencyKeyForEvent as y,
|
|
5725
|
-
|
|
5858
|
+
ThinkModelId as yn,
|
|
5726
5859
|
ChatErrorClassification as yt,
|
|
5727
5860
|
TextStreamCallbackOptions as z,
|
|
5728
|
-
|
|
5861
|
+
WaitForSubmissionOptions as zn,
|
|
5729
5862
|
MessageConcurrency$1 as zt
|
|
5730
5863
|
};
|
|
5731
|
-
//# sourceMappingURL=index-
|
|
5864
|
+
//# sourceMappingURL=index-DIQ9oY1t.d.ts.map
|
|
@@ -36,7 +36,6 @@ interface ExtensionManifest {
|
|
|
36
36
|
type:
|
|
37
37
|
| "readonly"
|
|
38
38
|
| "writable"
|
|
39
|
-
| "skill"
|
|
40
39
|
| "searchable" /** Maximum token budget for this block. */;
|
|
41
40
|
maxTokens?: number;
|
|
42
41
|
}>;
|
|
@@ -158,6 +157,14 @@ interface ExtensionManagerOptions {
|
|
|
158
157
|
permissions: ExtensionPermissions,
|
|
159
158
|
ownContextLabels: string[]
|
|
160
159
|
) => Fetcher;
|
|
160
|
+
/**
|
|
161
|
+
* Identifies the agent that `createHostBinding` binds to (for example
|
|
162
|
+
* `${className}:${ctx.id}`). It is part of the Dynamic Worker id of
|
|
163
|
+
* extensions that receive `env.host`, so a cached worker is never shared
|
|
164
|
+
* with another agent. Without it, such extensions get a fresh id per
|
|
165
|
+
* manager instance.
|
|
166
|
+
*/
|
|
167
|
+
workerIdScope?: string;
|
|
161
168
|
}
|
|
162
169
|
declare class ExtensionManager {
|
|
163
170
|
#private;
|
|
@@ -233,4 +240,4 @@ export {
|
|
|
233
240
|
ExtensionInfo as r,
|
|
234
241
|
ExtensionManager as t
|
|
235
242
|
};
|
|
236
|
-
//# sourceMappingURL=manager-
|
|
243
|
+
//# sourceMappingURL=manager-CtXhU1fK.d.ts.map
|
|
@@ -44,9 +44,15 @@ function sanitizeName(name) {
|
|
|
44
44
|
return name.replace(/[^a-zA-Z0-9]/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "");
|
|
45
45
|
}
|
|
46
46
|
const STORAGE_PREFIX = "ext:";
|
|
47
|
+
async function hashWorkerConfig(input) {
|
|
48
|
+
const data = new TextEncoder().encode(JSON.stringify(input));
|
|
49
|
+
const digest = await crypto.subtle.digest("SHA-256", data);
|
|
50
|
+
return Array.from(new Uint8Array(digest).slice(0, 16), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
51
|
+
}
|
|
47
52
|
var _loader = /* @__PURE__ */ new WeakMap();
|
|
48
53
|
var _storage = /* @__PURE__ */ new WeakMap();
|
|
49
54
|
var _createHostBinding = /* @__PURE__ */ new WeakMap();
|
|
55
|
+
var _workerIdScope = /* @__PURE__ */ new WeakMap();
|
|
50
56
|
var _extensions = /* @__PURE__ */ new WeakMap();
|
|
51
57
|
var _restored = /* @__PURE__ */ new WeakMap();
|
|
52
58
|
var _onUnload = /* @__PURE__ */ new WeakMap();
|
|
@@ -57,12 +63,14 @@ var ExtensionManager = class {
|
|
|
57
63
|
_classPrivateFieldInitSpec(this, _loader, void 0);
|
|
58
64
|
_classPrivateFieldInitSpec(this, _storage, void 0);
|
|
59
65
|
_classPrivateFieldInitSpec(this, _createHostBinding, void 0);
|
|
66
|
+
_classPrivateFieldInitSpec(this, _workerIdScope, void 0);
|
|
60
67
|
_classPrivateFieldInitSpec(this, _extensions, /* @__PURE__ */ new Map());
|
|
61
68
|
_classPrivateFieldInitSpec(this, _restored, false);
|
|
62
69
|
_classPrivateFieldInitSpec(this, _onUnload, null);
|
|
63
70
|
_classPrivateFieldSet2(_loader, this, options.loader);
|
|
64
71
|
_classPrivateFieldSet2(_storage, this, options.storage ?? null);
|
|
65
72
|
_classPrivateFieldSet2(_createHostBinding, this, options.createHostBinding ?? null);
|
|
73
|
+
_classPrivateFieldSet2(_workerIdScope, this, options.workerIdScope ?? crypto.randomUUID());
|
|
66
74
|
}
|
|
67
75
|
/**
|
|
68
76
|
* Load an extension from source code.
|
|
@@ -193,18 +201,30 @@ async function _loadInternal(manifest, source) {
|
|
|
193
201
|
const workerModule = wrapExtensionSource(source);
|
|
194
202
|
const permissions = manifest.permissions ?? {};
|
|
195
203
|
const workerEnv = {};
|
|
204
|
+
let ownLabels = [];
|
|
196
205
|
const needsHost = (permissions.workspace ?? "none") !== "none" || permissions.context?.read !== void 0 || permissions.context?.write !== void 0 || (permissions.messages ?? "none") !== "none" || permissions.session?.sendMessage || permissions.session?.metadata;
|
|
197
206
|
if (_classPrivateFieldGet2(_createHostBinding, this) && needsHost) {
|
|
198
207
|
const prefix = sanitizeName(manifest.name);
|
|
199
|
-
|
|
208
|
+
ownLabels = (manifest.context ?? []).map((c) => `${prefix}_${c.label}`);
|
|
200
209
|
workerEnv.host = _classPrivateFieldGet2(_createHostBinding, this).call(this, permissions, ownLabels);
|
|
201
210
|
}
|
|
202
|
-
const
|
|
211
|
+
const globalOutbound = permissions.network?.length ? void 0 : null;
|
|
212
|
+
const hash = await hashWorkerConfig({
|
|
213
|
+
workerModule,
|
|
214
|
+
globalOutbound: globalOutbound === null ? "null" : "inherit",
|
|
215
|
+
envBindings: Object.keys(workerEnv).sort(),
|
|
216
|
+
permissions,
|
|
217
|
+
...workerEnv.host ? {
|
|
218
|
+
hostScope: _classPrivateFieldGet2(_workerIdScope, this),
|
|
219
|
+
ownContextLabels: ownLabels
|
|
220
|
+
} : {}
|
|
221
|
+
});
|
|
222
|
+
const entrypoint = _classPrivateFieldGet2(_loader, this).get(`ext-${manifest.name}-${manifest.version}-${hash}`, () => ({
|
|
203
223
|
compatibilityDate: "2025-06-01",
|
|
204
224
|
compatibilityFlags: ["nodejs_compat"],
|
|
205
225
|
mainModule: "extension.js",
|
|
206
226
|
modules: { "extension.js": workerModule },
|
|
207
|
-
globalOutbound
|
|
227
|
+
globalOutbound,
|
|
208
228
|
...Object.keys(workerEnv).length > 0 ? { env: workerEnv } : {}
|
|
209
229
|
})).getEntrypoint();
|
|
210
230
|
const descriptorsJson = await entrypoint.describe();
|
|
@@ -310,4 +330,4 @@ export default class Extension extends WorkerEntrypoint {
|
|
|
310
330
|
//#endregion
|
|
311
331
|
export { sanitizeName as n, _classPrivateMethodInitSpec as r, ExtensionManager as t };
|
|
312
332
|
|
|
313
|
-
//# sourceMappingURL=manager-
|
|
333
|
+
//# sourceMappingURL=manager-sfWIcYJT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"manager-sfWIcYJT.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 * Identifies the agent that `createHostBinding` binds to (for example\n * `${className}:${ctx.id}`). It is part of the Dynamic Worker id of\n * extensions that receive `env.host`, so a cached worker is never shared\n * with another agent. Without it, such extensions get a fresh id per\n * manager instance.\n */\n workerIdScope?: string;\n}\n\nasync function hashWorkerConfig(input: unknown): Promise<string> {\n const data = new TextEncoder().encode(JSON.stringify(input));\n const digest = await crypto.subtle.digest(\"SHA-256\", data);\n return Array.from(new Uint8Array(digest).slice(0, 16), (b) =>\n b.toString(16).padStart(2, \"0\")\n ).join(\"\");\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 #workerIdScope: string;\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 this.#workerIdScope = options.workerIdScope ?? crypto.randomUUID();\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 let ownLabels: string[] = [];\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 ownLabels = (manifest.context ?? []).map((c) => `${prefix}_${c.label}`);\n workerEnv.host = this.#createHostBinding(permissions, ownLabels);\n }\n\n // Stable, content-derived id: Dynamic Workers are billed per distinct\n // id, so restarts must reuse the id while code/permissions are unchanged.\n // A cached worker keeps the env it was created with, so an id that\n // carries `env.host` must also cover the agent and the context labels\n // that binding was created for.\n const globalOutbound = permissions.network?.length ? undefined : null;\n const hash = await hashWorkerConfig({\n workerModule,\n globalOutbound: globalOutbound === null ? \"null\" : \"inherit\",\n envBindings: Object.keys(workerEnv).sort(),\n permissions,\n ...(workerEnv.host\n ? { hostScope: this.#workerIdScope, ownContextLabels: ownLabels }\n : {})\n });\n\n const worker = this.#loader.get(\n `ext-${manifest.name}-${manifest.version}-${hash}`,\n () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"extension.js\",\n modules: { \"extension.js\": workerModule },\n globalOutbound,\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,KAAK,CAAC,CAAC,WAAW,GAClC,MAAM,IAAI,MAAM,kCAAkC;CAEpD,OAAO,KACJ,QAAQ,iBAAiB,GAAG,CAAC,CAC7B,QAAQ,OAAO,GAAG,CAAC,CACnB,QAAQ,UAAU,EAAE;AACzB;AAsBA,MAAM,iBAAiB;AAyCvB,eAAe,iBAAiB,OAAiC;CAC/D,MAAM,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,UAAU,KAAK,CAAC;CAC3D,MAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,IAAI;CACzD,OAAO,MAAM,KAAK,IAAI,WAAW,MAAM,CAAC,CAAC,MAAM,GAAG,EAAE,IAAI,MACtD,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAChC,CAAC,CAAC,KAAK,EAAE;AACX;;;;;;;;;AAEA,IAAa,mBAAb,MAA8B;CAgB5B,YAA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,OAAO,MAAM,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,MAAM;EAC7C,gBAAgB,SAAS,WAAW,CAAC,EAAA,CAAG,KAAK,MAAM,GAAG,OAAO,GAAG,EAAE,OAAO;EACzE,aAAa,SAAS,eAAe,CAAC;CACxC;AACF;;;;;;;;AASA,SAAS,oBAAoB,QAAwB;CACnD,OAAO;;iBAEQ,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DxB"}
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
R as TextStreamCallback,
|
|
3
3
|
c as MessengerDefinition,
|
|
4
4
|
n as ChatSdkMessengerOptions
|
|
5
|
-
} from "../index-
|
|
5
|
+
} from "../index-DIQ9oY1t.js";
|
|
6
6
|
import { TelegramAdapterConfig } from "@chat-adapter/telegram";
|
|
7
7
|
|
|
8
8
|
//#region src/messengers/telegram.d.ts
|