@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.
@@ -0,0 +1,13 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __exportAll = (all, no_symbols) => {
4
+ let target = {};
5
+ for (var name in all) __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true
8
+ });
9
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
10
+ return target;
11
+ };
12
+ //#endregion
13
+ export { __exportAll as t };
package/dist/think.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { $n as MediaEvictionConfig, $t as RunTurnWait, An as TurnConfig, At as ChunkContext, Bn as defaultContextOverflowClassifier, Bt as MessageMetadataCallback, Cn as ThinkSubmissionInspection, Ct as ChatRecoveryConfig, D as DeliveryKind, Dn as ToolCallContext, Dt as ChatRecoveryProgressContext, En as ThinkWallClockSchedule, Et as ChatRecoveryOptions, Fn as TurnTrigger, Ft as ExtensionConfig, Gn as ChannelDefinition, Gt as PrepareStepResult, Hn as skills, Ht as PendingApproval, In as TypedToolCall, It as FiberContext, Jn as ChannelIngress, Jt as ResolvedChatRecoveryConfig, Kn as ChannelDeliveryPolicy, Kt as RejectExecutionOptions, Ln as TypedToolResult, Lt as FiberRecoveryContext, Mn as TurnInput, Mt as ContextOverflowConfig, Nn as TurnInputMessages, Nt as DeleteSubmissionsOptions, O as DeliveryTag, On as ToolCallDecision, Ot as ChatResponseResult, Pn as TurnResult, Pt as DeliverNoticeOptions, Qn as messengerChannel, Qt as RunTurnSubmit, Rn as WaitForSubmissionOptions, Rt as ListSubmissionsOptions, Sn as ThinkScheduledTasks, St as ChatOptions, Tn as ThinkTime, Tt as ChatRecoveryExhaustedContext, Un as ChannelCapabilities, Ut as PrepareStepContext, Vn as isAction, Vt as OnStartDegradation, Wn as ChannelContext, Wt as PrepareStepFunction, Xn as NormalizedChannelDefinition, Xt as RunTurnOptions, Yn as ChannelKind, Yt as RunTurnBase, Zn as ThinkChannels, Zt as RunTurnStream, _n as ThinkModel, _t as AddMessagesOptions, an as SkillWorkspaceSeedOptions, bn as ThinkScheduledTaskContext, bt as ChatErrorContext, cn as StepResult, ct as ActionApprovalPolicy, dn as StreamableResult, dt as ActionConfig, en as SaveMessagesOptions, er as CompactAfterOptions, fn as SubmitMessagesOptions, ft as ActionContext, gn as ThinkIntervalSchedule, gt as ActiveTurn, hn as Think, ht as ActionPermissionSpec, in as SkillSource, jn as TurnContext, jt as ChunkPart, kn as ToolCallResultContext, kt as ChatStartEvent, ln as StopCondition, lt as ActionAuthorizationContext, mn as TextStreamPart, mt as ActionKind, nn as SessionMessage, nr as SessionContextOptions, on as StepConfig, ot as Action, pn as SubmitMessagesResult, pt as ActionIdempotencyKey, qn as ChannelDeliverySurface, qt as ReplyAttachment, rn as SkillRunContext, rr as ThinkSession, sn as StepContext, st as ActionApprovalDescriptor, tn as SaveMessagesResult, tr as CompactionErrorHandler, un as StreamCallback, ut as ActionAuthorizationDecision, vn as ThinkModelId, vt as CancelSubmissionResult, wn as ThinkSubmissionStatus, wt as ChatRecoveryContext, xn as ThinkScheduledTaskSchedule, xt as ChatInterruptedInfo, yn as ThinkScheduledTask, yt as ChatErrorClassification, zn as action, zt as MessageConcurrency } from "./index-BFK9bpzz.js";
1
+ import { $n as MediaEvictionConfig, $t as RunTurnWait, An as ToolCallResultContext, At as ChunkContext, Bn as action, Bt as MessageMetadataCallback, Cn as ThinkScheduledTasks, Ct as ChatRecoveryConfig, D as DeliveryKind, Dn as ThinkWallClockSchedule, Dt as ChatRecoveryProgressContext, En as ThinkTime, Et as ChatRecoveryOptions, Fn as TurnResult, Ft as ExtensionConfig, Gn as ChannelDefinition, Gt as PrepareStepResult, Hn as isAction, Ht as PendingApproval, In as TurnTrigger, It as FiberContext, Jn as ChannelIngress, Jt as ResolvedChatRecoveryConfig, Kn as ChannelDeliveryPolicy, Kt as RejectExecutionOptions, Ln as TypedToolCall, Lt as FiberRecoveryContext, Mn as TurnContext, Mt as ContextOverflowConfig, Nn as TurnInput, Nt as DeleteSubmissionsOptions, O as DeliveryTag, On as ToolCallContext, Ot as ChatResponseResult, Pn as TurnInputMessages, Pt as DeliverNoticeOptions, Qn as messengerChannel, Qt as RunTurnSubmit, Rn as TypedToolResult, Rt as ListSubmissionsOptions, Sn as ThinkScheduledTaskSchedule, St as ChatOptions, Tn as ThinkSubmissionStatus, Tt as ChatRecoveryExhaustedContext, Un as ChannelCapabilities, Ut as PrepareStepContext, Vn as defaultContextOverflowClassifier, Vt as OnStartDegradation, Wn as ChannelContext, Wt as PrepareStepFunction, Xn as NormalizedChannelDefinition, Xt as RunTurnOptions, Yn as ChannelKind, Yt as RunTurnBase, Zn as ThinkChannels, Zt as RunTurnStream, _n as ThinkIntervalSchedule, _t as AddMessagesOptions, an as SkillRunContext, bn as ThinkScheduledTask, bt as ChatErrorContext, cn as StepContext, ct as ActionApprovalPolicy, dn as StreamCallback, dt as ActionConfig, en as SaveMessagesOptions, er as CompactAfterOptions, fn as StreamableResult, ft as ActionContext, gn as Think, gt as ActiveTurn, hn as TextStreamPart, ht as ActionPermissionSpec, in as SkillCatalog, ir as skills_d_exports, jn as TurnConfig, jt as ChunkPart, kn as ToolCallDecision, kt as ChatStartEvent, ln as StepResult, lt as ActionAuthorizationContext, mn as SubmitMessagesResult, mt as ActionKind, nn as SessionMessage, nr as SessionContextOptions, on as SkillSource, ot as Action, pn as SubmitMessagesOptions, pt as ActionIdempotencyKey, qn as ChannelDeliverySurface, qt as ReplyAttachment, rn as Skill, rr as ThinkSession, sn as StepConfig, st as ActionApprovalDescriptor, tn as SaveMessagesResult, tr as CompactionErrorHandler, un as StopCondition, ut as ActionAuthorizationDecision, vn as ThinkModel, vt as CancelSubmissionResult, wn as ThinkSubmissionInspection, wt as ChatRecoveryContext, xn as ThinkScheduledTaskContext, xt as ChatInterruptedInfo, yn as ThinkModelId, yt as ChatErrorClassification, zn as WaitForSubmissionOptions, zt as MessageConcurrency } from "./index-DIQ9oY1t.js";
2
2
  import { a as FetchResponseMode, i as FetchRedirectPolicy, l as ThinkWorkspace, n as FetchBindingTarget, o as FetchResult, r as FetchErrorCode, s as FetchToolEvent, t as CreateFetchToolsOptions, u as ThinkWorkspaceFilesystem } from "./fetch-CU2fC7O6.js";
3
- export { Action, ActionApprovalDescriptor, ActionApprovalPolicy, ActionAuthorizationContext, ActionAuthorizationDecision, ActionConfig, ActionContext, ActionIdempotencyKey, ActionKind, ActionPermissionSpec, ActiveTurn, AddMessagesOptions, CancelSubmissionResult, type ChannelCapabilities, type ChannelContext, type ChannelDefinition, type ChannelDeliveryPolicy, type ChannelDeliverySurface, type ChannelIngress, type ChannelKind, ChatErrorClassification, ChatErrorContext, ChatInterruptedInfo, ChatOptions, type ChatRecoveryConfig, type ChatRecoveryContext, type ChatRecoveryExhaustedContext, type ChatRecoveryOptions, type ChatRecoveryProgressContext, type ChatResponseResult, ChatStartEvent, ChunkContext, ChunkPart, type CompactAfterOptions, type CompactionErrorHandler, ContextOverflowConfig, type CreateFetchToolsOptions, DeleteSubmissionsOptions, DeliverNoticeOptions, type DeliveryKind, type DeliveryTag, ExtensionConfig, type FetchBindingTarget, type FetchErrorCode, type FetchRedirectPolicy, type FetchResponseMode, type FetchResult, type FetchToolEvent, type FiberContext, type FiberRecoveryContext, ListSubmissionsOptions, type MediaEvictionConfig, type MessageConcurrency, MessageMetadataCallback, type NormalizedChannelDefinition, OnStartDegradation, PendingApproval, PrepareStepContext, type PrepareStepFunction, type PrepareStepResult, RejectExecutionOptions, ReplyAttachment, type ResolvedChatRecoveryConfig, RunTurnBase, RunTurnOptions, RunTurnStream, RunTurnSubmit, RunTurnWait, type SaveMessagesOptions, type SaveMessagesResult, ThinkSession as Session, ThinkSession, type SessionContextOptions, type SessionMessage, type SkillRunContext, type SkillSource, type SkillWorkspaceSeedOptions, StepConfig, StepContext, type StepResult, type StopCondition, StreamCallback, StreamableResult, SubmitMessagesOptions, SubmitMessagesResult, type TextStreamPart, Think, type ThinkChannels, ThinkIntervalSchedule, ThinkModel, ThinkModelId, ThinkScheduledTask, ThinkScheduledTaskContext, ThinkScheduledTaskSchedule, ThinkScheduledTasks, ThinkSubmissionInspection, ThinkSubmissionStatus, ThinkTime, ThinkWallClockSchedule, type ThinkWorkspace, type ThinkWorkspaceFilesystem, ToolCallContext, ToolCallDecision, ToolCallResultContext, TurnConfig, TurnContext, TurnInput, TurnInputMessages, TurnResult, TurnTrigger, type TypedToolCall, type TypedToolResult, WaitForSubmissionOptions, action, defaultContextOverflowClassifier, isAction, messengerChannel, skills };
3
+ export { Action, ActionApprovalDescriptor, ActionApprovalPolicy, ActionAuthorizationContext, ActionAuthorizationDecision, ActionConfig, ActionContext, ActionIdempotencyKey, ActionKind, ActionPermissionSpec, ActiveTurn, AddMessagesOptions, CancelSubmissionResult, type ChannelCapabilities, type ChannelContext, type ChannelDefinition, type ChannelDeliveryPolicy, type ChannelDeliverySurface, type ChannelIngress, type ChannelKind, ChatErrorClassification, ChatErrorContext, ChatInterruptedInfo, ChatOptions, type ChatRecoveryConfig, type ChatRecoveryContext, type ChatRecoveryExhaustedContext, type ChatRecoveryOptions, type ChatRecoveryProgressContext, type ChatResponseResult, ChatStartEvent, ChunkContext, ChunkPart, type CompactAfterOptions, type CompactionErrorHandler, ContextOverflowConfig, type CreateFetchToolsOptions, DeleteSubmissionsOptions, DeliverNoticeOptions, type DeliveryKind, type DeliveryTag, ExtensionConfig, type FetchBindingTarget, type FetchErrorCode, type FetchRedirectPolicy, type FetchResponseMode, type FetchResult, type FetchToolEvent, type FiberContext, type FiberRecoveryContext, ListSubmissionsOptions, type MediaEvictionConfig, type MessageConcurrency, MessageMetadataCallback, type NormalizedChannelDefinition, OnStartDegradation, PendingApproval, PrepareStepContext, type PrepareStepFunction, type PrepareStepResult, RejectExecutionOptions, ReplyAttachment, type ResolvedChatRecoveryConfig, RunTurnBase, RunTurnOptions, RunTurnStream, RunTurnSubmit, RunTurnWait, type SaveMessagesOptions, type SaveMessagesResult, ThinkSession as Session, ThinkSession, type SessionContextOptions, type SessionMessage, type Skill, type SkillCatalog, type SkillRunContext, type SkillSource, StepConfig, StepContext, type StepResult, type StopCondition, StreamCallback, StreamableResult, SubmitMessagesOptions, SubmitMessagesResult, type TextStreamPart, Think, type ThinkChannels, ThinkIntervalSchedule, ThinkModel, ThinkModelId, ThinkScheduledTask, ThinkScheduledTaskContext, ThinkScheduledTaskSchedule, ThinkScheduledTasks, ThinkSubmissionInspection, ThinkSubmissionStatus, ThinkTime, ThinkWallClockSchedule, type ThinkWorkspace, type ThinkWorkspaceFilesystem, ToolCallContext, ToolCallDecision, ToolCallResultContext, TurnConfig, TurnContext, TurnInput, TurnInputMessages, TurnResult, TurnTrigger, type TypedToolCall, type TypedToolResult, WaitForSubmissionOptions, action, defaultContextOverflowClassifier, isAction, messengerChannel, skills_d_exports as skills };
package/dist/think.js CHANGED
@@ -1,5 +1,6 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
1
2
  import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-DwGJfC3w.js";
2
- import { n as sanitizeName, r as _classPrivateMethodInitSpec, t as ExtensionManager } from "./manager-BubfmA3q.js";
3
+ import { n as sanitizeName, r as _classPrivateMethodInitSpec, t as ExtensionManager } from "./manager-sfWIcYJT.js";
3
4
  import { n as WorkspaceFiles, r as resolveWorkspacePath, t as createFetchTools } from "./fetch-DO3uQ9py.js";
4
5
  import { truncatePausedExecutionOutput } from "./tools/execute.js";
5
6
  import { _ as MESSENGER_REPLY_FIBER_NAME, n as ThinkMessengerRuntime, t as DEFAULT_MESSENGER_CONCURRENCY } from "./chat-sdk-BEjKXjCm.js";
@@ -11,14 +12,38 @@ import { wrapAISDK } from "agents/observability/ai";
11
12
  import { createWorkersAI } from "workers-ai-provider";
12
13
  import { anthropic } from "workers-ai-provider/anthropic";
13
14
  import { openai } from "workers-ai-provider/openai";
14
- import * as skills from "agents/skills";
15
- import { SkillRegistry } from "agents/skills";
15
+ import { DEFAULT_WORKSPACE_SKILLS_ROOT, InvalidSkillResourcePathError, SkillParseError, SkillResourceNotFoundError, SkillSourceError, UnknownSkillError, formatSkill, formatSkillDiagnostic, formatSkillDiagnostic as formatSkillDiagnostic$1, fromManifest, isModelInvocable, loadSkillCatalog, loadSkillCatalog as loadSkillCatalog$1, manifest, parseSkill, parseSkillName, parseSkillResourcePath, r2, renderSkillResource, workspace } from "agents/skills";
16
+ import { runner } from "agents/skills/runner";
17
+ import { createSkillTools } from "agents/skills/tools/ai-sdk";
16
18
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, __DO_NOT_USE_WILL_BREAK__withInvocationScope, callable, getCurrentAgent, isDurableObjectCodeUpdateReset, isDurableObjectMemoryLimitReset, isPlatformTransientError } from "agents";
17
19
  import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, CHAT_MESSAGE_TYPES, CHAT_RECOVERY_INCIDENT_KEY_PREFIX, CHAT_RECOVERY_PROGRESS_KEY, CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, CHAT_RECOVERY_TASK_NAME, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, MAX_BOUND_PARAMS, PreStreamTurns, ResumableStream, ResumeHandshake, StreamAccumulator, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyToolUpdate, awaitWithDeadline, buildChatRecoveringFrame, buildInClauseStrings, chatRecoveryBackoffSeconds, chatRecoveryTaskRunOptions, classifyAgentToolChildRecovery, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createChatRecoveryTaskDefinition, createChatStreams, createChatTurnTaskDefinition, createToolsFromClientSchemas, crossMessageToolResultUpdate, dispatchChatRecoveryToHandoff, drainInteractionApplies, enforceRowSizeLimit, hasIncompleteToolBatch, interceptAgentToolBroadcast, isDurableObjectResetError, isLateToolInputChunk, isPositionlessAgentToolChunk, iterateWithStallWatchdog, lateToolInputForwardChunks, listActiveChatRecoveryIncidents, normalizeToolInput, originMessageIds, parseProtocolMessage, partAwaitsClientInteraction, pausedExecutionUpdate, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, retryAfterSeconds, runChatRecoveryExhaustion, sanitizeMessage, setChatRecovering, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, toolPartHasSettledResult, toolResultUpdate, truncateOlderMessages, truncateOlderToolResults, unwrapChatFiberSnapshot, withOriginMessageIds, wrapChatFiberSnapshot } from "agents/chat";
18
20
  import { Sessions, isCompactionMessage } from "agents/sessions";
19
21
  import { AgentContextProvider, ContextBlocks } from "agents/context";
20
22
  import { Workspace } from "@cloudflare/computer";
21
23
  import { createAITools } from "@cloudflare/computer/tools/ai-sdk";
24
+ //#region src/skills.ts
25
+ var skills_exports = /* @__PURE__ */ __exportAll({
26
+ DEFAULT_WORKSPACE_SKILLS_ROOT: () => DEFAULT_WORKSPACE_SKILLS_ROOT,
27
+ InvalidSkillResourcePathError: () => InvalidSkillResourcePathError,
28
+ SkillParseError: () => SkillParseError,
29
+ SkillResourceNotFoundError: () => SkillResourceNotFoundError,
30
+ SkillSourceError: () => SkillSourceError,
31
+ UnknownSkillError: () => UnknownSkillError,
32
+ formatSkill: () => formatSkill,
33
+ formatSkillDiagnostic: () => formatSkillDiagnostic$1,
34
+ fromManifest: () => fromManifest,
35
+ isModelInvocable: () => isModelInvocable,
36
+ loadSkillCatalog: () => loadSkillCatalog$1,
37
+ manifest: () => manifest,
38
+ parseSkill: () => parseSkill,
39
+ parseSkillName: () => parseSkillName,
40
+ parseSkillResourcePath: () => parseSkillResourcePath,
41
+ r2: () => r2,
42
+ renderSkillResource: () => renderSkillResource,
43
+ runner: () => runner,
44
+ workspace: () => workspace
45
+ });
46
+ //#endregion
22
47
  //#region src/session.ts
23
48
  var _handle = /* @__PURE__ */ new WeakMap();
24
49
  var _context = /* @__PURE__ */ new WeakMap();
@@ -505,7 +530,7 @@ function resolveChannels(configured, messengers) {
505
530
  * Configuration overrides:
506
531
  * - getModel() — return a model id string (resolved via the
507
532
  * built-in workers-ai-provider) or a LanguageModel
508
- * - getSystemPrompt() — return the legacy fallback system prompt
533
+ * - getSystemPrompt() — instructions at the top of the system prompt
509
534
  * - getTools() — return the ToolSet for the agentic loop
510
535
  * - maxSteps — max tool-call rounds per turn (default: 10)
511
536
  * - configureSession() — compaction and search policy
@@ -545,7 +570,7 @@ function resolveChannels(configured, messengers) {
545
570
  * // A string is resolved via the built-in workers-ai-provider off env.AI.
546
571
  * // Use a "@cf/..." id for Workers AI, or a "provider/model" slug like
547
572
  * // "openai/gpt-5.5" to route through AI Gateway.
548
- * return "@cf/moonshotai/kimi-k2.7-code";
573
+ * return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
549
574
  * }
550
575
  *
551
576
  * getSystemPrompt() {
@@ -765,6 +790,8 @@ function keepResolvedPauses(incoming, serverMessages) {
765
790
  function isLocalWorkspace(workspace) {
766
791
  return "ready" in workspace && typeof workspace.ready === "function" && "stub" in workspace && typeof workspace.stub === "function";
767
792
  }
793
+ /** Context block label for the skills catalog. */
794
+ const SKILLS_CONTEXT_LABEL = "think_skills";
768
795
  const ACTION_PENDING_SWEEP_INTERVAL_MS = 3600 * 1e3;
769
796
  const ACTION_PENDING_LAST_SWEPT_KEY = "cf_think_action_pending_approvals:last_swept_at";
770
797
  /** Prefix for durable-pause action execution ids (vs codemode execution ids). */
@@ -1560,8 +1587,8 @@ var Think = class Think extends Agent {
1560
1587
  this.waitForMcpConnections = false;
1561
1588
  this.storeMessages = false;
1562
1589
  this.storeTools = false;
1563
- this.skillWorkspace = false;
1564
- this._skillRegistry = null;
1590
+ this._skillSources = [];
1591
+ this._skillCatalog = null;
1565
1592
  this._loggedSkillWarnings = /* @__PURE__ */ new Set();
1566
1593
  this._loggedProtocolWarnings = /* @__PURE__ */ new Set();
1567
1594
  this.messageConcurrency = "queue";
@@ -2392,7 +2419,7 @@ var Think = class Think extends Agent {
2392
2419
  * @example String (Workers AI)
2393
2420
  * ```typescript
2394
2421
  * getModel() {
2395
- * return "@cf/moonshotai/kimi-k2.7-code";
2422
+ * return "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
2396
2423
  * }
2397
2424
  * ```
2398
2425
  *
@@ -2412,7 +2439,7 @@ var Think = class Think extends Agent {
2412
2439
  * ```
2413
2440
  */
2414
2441
  getModel() {
2415
- throw new Error("Override getModel() to return a model id string (e.g. \"@cf/moonshotai/kimi-k2.7-code\" or \"openai/gpt-5.5\") or a LanguageModel.");
2442
+ throw new Error("Override getModel() to return a model id string (e.g. \"@cf/deepseek-ai/deepseek-v4.1-flash-1017\" or \"openai/gpt-5.5\") or a LanguageModel.");
2416
2443
  }
2417
2444
  /**
2418
2445
  * Return the Workers AI binding used by the built-in default provider when
@@ -2453,7 +2480,7 @@ var Think = class Think extends Agent {
2453
2480
  if (typeof model !== "string") return model;
2454
2481
  const isWorkersAI = isWorkersAIModelId(model);
2455
2482
  const slash = model.indexOf("/");
2456
- if (!isWorkersAI && (model.startsWith("@") || slash <= 0 || slash === model.length - 1)) throw new Error(`Invalid model id ${JSON.stringify(model)}. Use a Workers AI id (e.g. "@cf/moonshotai/kimi-k2.7-code") or a "<provider>/<model>" AI Gateway slug (e.g. "openai/gpt-5.5"), or return a LanguageModel.`);
2483
+ if (!isWorkersAI && (model.startsWith("@") || slash <= 0 || slash === model.length - 1)) throw new Error(`Invalid model id ${JSON.stringify(model)}. Use a Workers AI id (e.g. "@cf/deepseek-ai/deepseek-v4.1-flash-1017") or a "<provider>/<model>" AI Gateway slug (e.g. "openai/gpt-5.5"), or return a LanguageModel.`);
2457
2484
  const gateway = this.getGateway(model);
2458
2485
  if (gateway !== null && typeof gateway === "object" && typeof gateway.then === "function") throw new Error(`getGateway() returned a Promise for model "${model}". It must return GatewayOptions (or undefined) synchronously; resolve any async lookup in beforeTurn and return the model from there instead.`);
2459
2486
  this._defaultProvider ??= createWorkersAI({
@@ -2466,9 +2493,11 @@ var Think = class Think extends Agent {
2466
2493
  }) : this._defaultProvider(model, gateway && { gateway });
2467
2494
  }
2468
2495
  /**
2469
- * Return the fallback system prompt for the assistant.
2470
- * Ignored when context blocks are configured. Use `configureContext()` for
2471
- * always-on instructions that should coexist with context blocks or skills.
2496
+ * Return the instructions at the top of the system prompt.
2497
+ *
2498
+ * An override always comes first, followed by the context blocks from
2499
+ * `configureContext()`, skills, and extensions. Think's default text is
2500
+ * used only when the agent overrides nothing and has no context blocks.
2472
2501
  */
2473
2502
  getSystemPrompt() {
2474
2503
  return [
@@ -2479,6 +2508,18 @@ var Think = class Think extends Agent {
2479
2508
  "Be direct and useful in your final response: summarize the outcome, mention important files or commands, and call out real blockers or risks."
2480
2509
  ].join("\n\n");
2481
2510
  }
2511
+ /**
2512
+ * The base system prompt for a turn: an overridden `getSystemPrompt()`,
2513
+ * then the frozen context blocks. Think's default `getSystemPrompt()` is
2514
+ * only a fallback for an agent with no context blocks.
2515
+ *
2516
+ * @internal Exposed to subclasses for tests.
2517
+ */
2518
+ async _buildBaseSystemPrompt() {
2519
+ const blocks = await this.context.freezeSystemPrompt();
2520
+ if (!isMethodOverridden(this, "getSystemPrompt")) return blocks || this.getSystemPrompt();
2521
+ return [this.getSystemPrompt(), blocks].filter((part) => part.trim().length > 0).join("\n\n");
2522
+ }
2482
2523
  /** Return the tools available to the assistant. */
2483
2524
  getTools() {
2484
2525
  return {};
@@ -3083,14 +3124,20 @@ var Think = class Think extends Agent {
3083
3124
  /**
3084
3125
  * Return Agent Skills sources for this Think agent.
3085
3126
  *
3086
- * Bundled skills are typically imported with the Agents Vite plugin:
3127
+ * A skill is a directory with a `SKILL.md` file, as defined by
3128
+ * https://agentskills.io. Keep skills as files in the agent's Workspace
3129
+ * and they become available as soon as they are written:
3087
3130
  *
3088
3131
  * ```typescript
3089
- * import productSkills from "agents:skills"; // -> ./skills next to this file
3132
+ * getSkills() {
3133
+ * return [skills.workspace(this.workspace)]; // /workspace/.agents/skills
3134
+ * }
3090
3135
  * ```
3091
3136
  *
3092
- * Sources are applied in order; the first source to register a skill name
3093
- * wins, and later collisions are skipped with a logged warning.
3137
+ * `skills.r2()` reads skills from an R2 bucket and `skills.manifest()`
3138
+ * defines them in code. Sources are applied in order; the first source to
3139
+ * provide a skill name wins, and later collisions are skipped with a
3140
+ * logged warning. Sources are listed again before every turn.
3094
3141
  */
3095
3142
  getSkills() {
3096
3143
  return [];
@@ -3099,67 +3146,40 @@ var Think = class Think extends Agent {
3099
3146
  try {
3100
3147
  const sources = await this.getSkills();
3101
3148
  if (sources.length === 0) return;
3102
- if (isMethodOverridden(this, "getSystemPrompt")) {
3103
- const warning = "getSystemPrompt() is only used as a fallback when no context blocks are configured. getSkills() registers a skills context block, so move always-on instructions into configureContext() instead.";
3104
- if (!this._loggedSkillWarnings.has(warning)) {
3105
- this._loggedSkillWarnings.add(warning);
3106
- console.warn(`[think] ${warning}`);
3107
- }
3108
- }
3109
- const registry = new SkillRegistry(sources, this.getSkillScriptRunner());
3110
- await registry.load();
3111
- this._logSkillWarnings(registry);
3112
- this._skillRegistry = registry;
3113
- await this._configureSkillWorkspace(registry);
3149
+ this._skillSources = sources;
3150
+ await this._loadSkillCatalog();
3114
3151
  await this.context.addBlock({
3115
- label: registry.contextLabel,
3152
+ label: SKILLS_CONTEXT_LABEL,
3116
3153
  description: "Think skills: available skill catalog",
3117
- provider: { get: () => registry.systemPrompt() }
3154
+ whenChanged: "remind",
3155
+ provider: { get: async () => this._skillCatalog?.prompt() ?? "No skills are available." }
3118
3156
  });
3119
- if ((this._skillsFingerprint ??= this._configGet("skillsFingerprint") ?? null) !== registry.fingerprint) {
3120
- await this.context.refreshSystemPrompt();
3121
- this._configSet("skillsFingerprint", registry.fingerprint);
3122
- this._skillsFingerprint = registry.fingerprint;
3123
- }
3124
3157
  } catch (error) {
3125
3158
  console.warn(`[think] Failed to initialize skills; continuing without them: ${error instanceof Error ? error.message : String(error)}`);
3126
3159
  }
3127
3160
  }
3128
- async _configureSkillWorkspace(registry) {
3129
- if (this.skillWorkspace === false) return;
3130
- const workspace = this.workspace;
3131
- try {
3132
- const key = "skillsWorkspaceFingerprint";
3133
- if (this._configGet(key) === registry.fingerprint) {
3134
- await registry.useWorkspace(workspace, this.skillWorkspace);
3135
- return;
3136
- }
3137
- const seeded = await registry.seedWorkspace(workspace, this.skillWorkspace);
3138
- for (const warning of seeded.warnings) {
3139
- if (this._loggedSkillWarnings.has(warning)) continue;
3140
- this._loggedSkillWarnings.add(warning);
3141
- console.warn(`[think] ${warning}`);
3142
- }
3143
- if (seeded.skipped === 0) this._configSet(key, registry.fingerprint);
3144
- } catch (error) {
3145
- console.warn(`[think] Failed to seed skills into the workspace; source-backed skill tools remain available: ${error instanceof Error ? error.message : String(error)}`);
3146
- }
3161
+ /** Load the catalog from every source and log new diagnostics. */
3162
+ async _loadSkillCatalog() {
3163
+ const catalog = await loadSkillCatalog(this._skillSources, { previous: this._skillCatalog ?? void 0 });
3164
+ for (const diagnostic of catalog.diagnostics) this._warnSkillsOnce(formatSkillDiagnostic(diagnostic));
3165
+ this._skillCatalog = catalog;
3166
+ return catalog;
3147
3167
  }
3148
3168
  /**
3149
- * Log registry diagnostics (duplicate names, sources that failed to list),
3150
- * deduped by message so a new collision after a deploy still surfaces while
3151
- * the same warning is not repeated on every turn.
3169
+ * Log a skills warning once per object lifetime, so a new problem after a
3170
+ * deploy still surfaces while the same warning is not repeated every turn.
3152
3171
  */
3153
- _logSkillWarnings(registry) {
3154
- for (const warning of registry.warnings) {
3155
- if (this._loggedSkillWarnings.has(warning)) continue;
3156
- this._loggedSkillWarnings.add(warning);
3157
- console.warn(`[think] ${warning}`);
3158
- }
3172
+ _warnSkillsOnce(warning) {
3173
+ if (this._loggedSkillWarnings.has(warning)) return;
3174
+ this._loggedSkillWarnings.add(warning);
3175
+ console.warn(`[think] ${warning}`);
3159
3176
  }
3160
3177
  /**
3161
3178
  * Return an optional runner that enables the `run_skill_script` tool.
3162
3179
  *
3180
+ * Prefer keeping skills in the Workspace and letting the agent run their
3181
+ * scripts with its shell tools.
3182
+ *
3163
3183
  * @experimental Skill script execution is experimental and may change
3164
3184
  * before stabilizing.
3165
3185
  */
@@ -3167,16 +3187,9 @@ var Think = class Think extends Agent {
3167
3187
  return null;
3168
3188
  }
3169
3189
  async _refreshSkillsIfChanged() {
3170
- if (!this._skillRegistry) return;
3190
+ if (!this._skillCatalog) return;
3171
3191
  try {
3172
- await this._skillRegistry.refresh();
3173
- this._logSkillWarnings(this._skillRegistry);
3174
- await this._configureSkillWorkspace(this._skillRegistry);
3175
- if ((this._skillsFingerprint ??= this._configGet("skillsFingerprint") ?? null) !== this._skillRegistry.fingerprint) {
3176
- await this.context.refreshSystemPrompt();
3177
- this._configSet("skillsFingerprint", this._skillRegistry.fingerprint);
3178
- this._skillsFingerprint = this._skillRegistry.fingerprint;
3179
- }
3192
+ await this._loadSkillCatalog();
3180
3193
  } catch (error) {
3181
3194
  console.warn(`[think] Failed to refresh skills; using last known catalog: ${error instanceof Error ? error.message : String(error)}`);
3182
3195
  }
@@ -3545,12 +3558,15 @@ var Think = class Think extends Agent {
3545
3558
  this.extensionManager = new ExtensionManager({
3546
3559
  loader: this.extensionLoader,
3547
3560
  storage: this.ctx.storage,
3548
- ...hasBridge ? { createHostBinding: (permissions, ownContextLabels) => ctxExports.HostBridgeLoopback({ props: {
3549
- agentClassName,
3550
- agentId,
3551
- permissions,
3552
- ownContextLabels
3553
- } }) } : {}
3561
+ ...hasBridge ? {
3562
+ workerIdScope: `${agentClassName}:${agentId}`,
3563
+ createHostBinding: (permissions, ownContextLabels) => ctxExports.HostBridgeLoopback({ props: {
3564
+ agentClassName,
3565
+ agentId,
3566
+ permissions,
3567
+ ownContextLabels
3568
+ } })
3569
+ } : {}
3554
3570
  });
3555
3571
  const configs = this.getExtensions();
3556
3572
  for (const config of configs) await this.extensionManager.load(config.manifest, config.source);
@@ -3787,7 +3803,7 @@ var Think = class Think extends Agent {
3787
3803
  const extensionTools = this.extensionManager?.getTools() ?? {};
3788
3804
  await this._refreshSkillsIfChanged();
3789
3805
  const contextTools = await this.context.tools();
3790
- const skillTools = this._skillRegistry?.tools() ?? {};
3806
+ const skillTools = this._skillCatalog ? createSkillTools(this._skillCatalog, { scriptRunner: this.getSkillScriptRunner() }) : {};
3791
3807
  const clientToolSet = createToolsFromClientSchemas(input.clientTools, input.clientToolExecutor ? { execute: input.clientToolExecutor } : void 0);
3792
3808
  let tools = {
3793
3809
  ...workspaceTools,
@@ -3804,7 +3820,7 @@ var Think = class Think extends Agent {
3804
3820
  const channelDefinition = channelContext ? this._channels?.get(channelContext.channelId) : void 0;
3805
3821
  if (channelDefinition?.tools) tools = channelDefinition.tools(tools);
3806
3822
  const channelInstructions = channelDefinition?.instructions && channelContext ? typeof channelDefinition.instructions === "function" ? await channelDefinition.instructions(channelContext) : channelDefinition.instructions : void 0;
3807
- const rawBaseSystem = await this.context.freezeSystemPrompt() || this.getSystemPrompt();
3823
+ const rawBaseSystem = await this._buildBaseSystemPrompt();
3808
3824
  const baseSystem = channelInstructions ? `${channelInstructions}\n\n${rawBaseSystem}` : rawBaseSystem;
3809
3825
  const system = this._systemPromptForTurn(baseSystem, tools);
3810
3826
  this._turnContextReminder = await this.context.reminder();
@@ -7988,8 +8004,9 @@ var Think = class Think extends Agent {
7988
8004
  * tab briefly renders the turn twice before collapsing. Mirrors the fix in
7989
8005
  * `@cloudflare/ai-chat`. Continuations are skipped — they reuse the existing
7990
8006
  * assistant message via the `continuation` frame flag, so the id must not
7991
- * change mid-message. The orphan-recovery path inherits the id from the
7992
- * stored chunk, so it needs no separate stamping.
8007
+ * change mid-message. Orphan recovery inherits a new turn's id from the
8008
+ * stored chunk; a continuation's id is recorded with its stream instead
8009
+ * (`_streamResult`).
7993
8010
  */
7994
8011
  _alignStreamStartId(chunk, action, accumulator, continuation) {
7995
8012
  if (action?.type === "start" && action.messageId == null && !continuation) chunk.messageId = accumulator.messageId;
@@ -8404,19 +8421,22 @@ var Think = class Think extends Agent {
8404
8421
  const clearGen = this._turnQueue.generation;
8405
8422
  const continuation = options?.continuation ?? false;
8406
8423
  const parentId = options?.parentId;
8424
+ const leaf = this.messages.at(-1);
8425
+ const continuationAssistant = continuation && options?.extendLeafAssistant && leaf?.role === "assistant" ? leaf : void 0;
8426
+ const assistantId = continuationAssistant?.id ?? crypto.randomUUID();
8407
8427
  const streamId = this._startResumableStream(requestId, {
8408
8428
  continuation,
8429
+ ...continuation && { messageId: assistantId },
8430
+ ...continuationAssistant !== void 0 && { basePartCount: continuationAssistant.parts.length },
8409
8431
  ...parentId !== void 0 && { parentMessageId: parentId }
8410
8432
  });
8411
8433
  if (this._continuation.pending?.requestId === requestId) {
8412
8434
  this._continuation.activatePending();
8413
8435
  this._continuation.flushAwaitingConnections((c) => this._notifyStreamResuming(c));
8414
8436
  }
8415
- const leaf = this.messages.at(-1);
8416
- const continuationAssistant = continuation && options?.extendLeafAssistant && leaf?.role === "assistant" ? leaf : void 0;
8417
8437
  const leafMetadata = continuationAssistant?.metadata;
8418
8438
  const accumulator = new StreamAccumulator({
8419
- messageId: continuationAssistant?.id ?? crypto.randomUUID(),
8439
+ messageId: assistantId,
8420
8440
  continuation: continuationAssistant !== void 0,
8421
8441
  existingParts: continuationAssistant?.parts.map(settleInterruptedPart),
8422
8442
  existingMetadata: leafMetadata !== null && typeof leafMetadata === "object" ? leafMetadata : void 0
@@ -11220,6 +11240,28 @@ var Think = class Think extends Agent {
11220
11240
  _orphanParentId(streamId) {
11221
11241
  return this._resumableStream.getStreamParentMessageId?.(streamId) ?? void 0;
11222
11242
  }
11243
+ /**
11244
+ * The assistant message a leaf-extending stream continues, and how many parts
11245
+ * it held when the stream started; undefined for a stream that produces a
11246
+ * message of its own. `_streamResult` records both when it starts the stream.
11247
+ *
11248
+ * Recovery keeps that many leading parts of the stored message, so it relies
11249
+ * on them staying put until the stream is recovered. That holds today: the
11250
+ * stream itself only adds parts after them, and once a stream is recovered
11251
+ * it is marked completed and reclaimed when the next stream starts, so a
11252
+ * later stream that extends the message again cannot be overwritten by a
11253
+ * replay.
11254
+ * (`_dropGenerationAfterResolvedPause` can trim an orphaned leaf; it only
11255
+ * drops text and reasoning written against a paused tool result.)
11256
+ */
11257
+ _orphanContinuedMessage(streamId) {
11258
+ const messageId = this._resumableStream.getStreamMessageId(streamId);
11259
+ const basePartCount = this._resumableStream.getStreamBasePartCount(streamId);
11260
+ return messageId !== null && basePartCount !== null ? {
11261
+ messageId,
11262
+ basePartCount
11263
+ } : void 0;
11264
+ }
11223
11265
  async _persistOrphanedStream(streamId) {
11224
11266
  this._resumableStream.flushBuffer();
11225
11267
  const chunks = this._resumableStream.getStreamChunks(streamId);
@@ -11227,12 +11269,17 @@ var Think = class Think extends Agent {
11227
11269
  let persistedId;
11228
11270
  const store = this._orphanStore();
11229
11271
  const parentId = this._orphanParentId(streamId);
11272
+ const continued = this._orphanContinuedMessage(streamId);
11230
11273
  if (!await persistReconstructedOrphan(chunks, {
11231
11274
  store: parentId === void 0 ? store : {
11232
11275
  ...store,
11233
11276
  appendMessage: (message) => store.appendMessage(message, parentId)
11234
11277
  },
11235
- fallbackId: crypto.randomUUID(),
11278
+ ...continued && { continues: {
11279
+ ...continued,
11280
+ settleBasePart: settleInterruptedPart
11281
+ } },
11282
+ fallbackId: this._resumableStream.getStreamMessageId(streamId) ?? crypto.randomUUID(),
11236
11283
  prepare: (message) => {
11237
11284
  const prepared = this._strippedForPersist(message);
11238
11285
  persistedId = prepared?.id;
@@ -11286,6 +11333,6 @@ for (const method of [
11286
11333
  Think.prototype.rejectExecution
11287
11334
  ]) callable()(method, void 0);
11288
11335
  //#endregion
11289
- export { ThinkSession as Session, ThinkSession, Think, action, defaultContextOverflowClassifier, isAction, messengerChannel, skills };
11336
+ export { ThinkSession as Session, ThinkSession, Think, action, defaultContextOverflowClassifier, isAction, messengerChannel, skills_exports as skills };
11290
11337
 
11291
11338
  //# sourceMappingURL=think.js.map