@cloudflare/think 0.23.0 → 0.25.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 +30 -40
- package/dist/{chat-sdk-BEjKXjCm.js → chat-sdk-4Nu96eDX.js} +375 -256
- package/dist/chat-sdk-4Nu96eDX.js.map +1 -0
- package/dist/extensions/index.d.ts +30 -72
- package/dist/extensions/index.js +45 -47
- package/dist/extensions/index.js.map +1 -1
- package/dist/{fetch-DO3uQ9py.js → fetch-BbYxtlff.js} +10 -2
- package/dist/fetch-BbYxtlff.js.map +1 -0
- package/dist/manager-B3rcb_6p.js +493 -0
- package/dist/manager-B3rcb_6p.js.map +1 -0
- package/dist/manager-CWGumyKi.d.ts +3391 -0
- package/dist/messengers/index.d.ts +54 -66
- package/dist/messengers/index.js +2 -2
- package/dist/messengers/telegram.d.ts +4 -4
- package/dist/messengers/telegram.js +1 -1
- package/dist/think.d.ts +2 -2
- package/dist/think.js +8493 -10725
- 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/tools/fetch.js +1 -1
- package/dist/workflows.d.ts +5 -2
- package/docs/actions.md +12 -0
- package/docs/channels.md +10 -4
- package/docs/client-tools.md +57 -27
- package/docs/context.md +92 -0
- package/docs/getting-started.md +4 -4
- package/docs/index.md +112 -52
- package/docs/lifecycle-hooks.md +10 -21
- package/docs/multi-chat.md +6 -6
- package/docs/programmatic-submissions.md +28 -10
- package/docs/sub-agents.md +45 -51
- package/docs/tools.md +41 -15
- package/docs/workflows.md +5 -4
- package/package.json +15 -10
- package/dist/chat-sdk-BEjKXjCm.js.map +0 -1
- package/dist/fetch-DO3uQ9py.js.map +0 -1
- package/dist/hook-proxy-DY2sBNa0.js +0 -117
- package/dist/hook-proxy-DY2sBNa0.js.map +0 -1
- package/dist/index-DDnny6kt.d.ts +0 -5847
- package/dist/manager-BubfmA3q.js +0 -313
- package/dist/manager-BubfmA3q.js.map +0 -1
- package/dist/manager-rze95KCk.d.ts +0 -235
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat-sdk-4Nu96eDX.js","names":[],"sources":["../src/messengers/reply-task.ts","../src/messengers/events.ts","../src/messengers/delivery.ts","../src/messengers/chat-sdk.ts"],"sourcesContent":["/**\n * Messenger replies as deliveries. A webhook's reply is one delivery run:\n * its input is the event and thread, its first attempt answers live, and\n * an attempt after a reset answers again or apologizes, by how far the\n * reply got (the `stage` in its checkpoint).\n *\n * Durable: nothing of its own (the run and its checkpoint belong to Tasks).\n * In memory: the live reply, for as long as the webhook waits on it.\n */\n\nimport {\n isDurableObjectCodeUpdateReset,\n isDurableObjectMemoryLimitReset,\n isPlatformTransientError\n} from \"agents\";\nimport {\n registerDeliverySink,\n sendDelivery,\n type DeliverySink\n} from \"agents/internal\";\nimport { NonRetryableError, type TaskJson, type Tasks } from \"agents/tasks\";\nimport type { MessengerReplyStage } from \"./delivery\";\nimport type { MessengerEvent } from \"./events\";\n\nconst MESSENGER_REPLY_SINK = \"messenger-reply\";\n\n/** The checkpoint key of how far a reply got. */\nconst STAGE = \"stage\";\n\n/**\n * The checkpoint key of the reply's event and thread. In the checkpoint,\n * not the run's input: the run is kept once answered (a repeat is a\n * repeat), and its checkpoint, unlike its input, is cleared then, so the\n * message's text is not kept with it.\n */\nconst REPLY = \"reply\";\n\n/** A reply's own attempt takes as long as its answer: one day at most. */\nconst REPLY_ATTEMPT_TIMEOUT_MS = 24 * 60 * 60 * 1000;\n\n/** @internal */\nexport type MessengerReplyPayload = {\n /** The event, as JSON. */\n event: MessengerEvent;\n /** The Chat SDK thread, as JSON. */\n thread: unknown;\n};\n\n/** Records how far a reply got. @internal */\nexport type RecordReplyStage = (stage: \"streaming\" | \"completed\") => void;\n\n/** The reply the webhook that received its message waits on. @internal */\nexport type LiveMessengerReply = {\n payload: MessengerReplyPayload;\n answer(record: RecordReplyStage): Promise<void>;\n};\n\n/** What the messenger runtime gives the reply sink. @internal */\nexport type MessengerReplyRuntime = {\n recoverReply(\n payload: MessengerReplyPayload,\n stage: MessengerReplyStage,\n record: RecordReplyStage\n ): Promise<void>;\n /** After a recovered reply ended (or gave up), answer what queued behind it. */\n drainAfterRecovery(payload: MessengerReplyPayload): void;\n};\n\nconst isPlatformReset = (error: unknown) =>\n isPlatformTransientError(error) ||\n isDurableObjectMemoryLimitReset(error) ||\n isDurableObjectCodeUpdateReset(error);\n\n/**\n * Post the apology for a reply a reset cut off. A post the platform fails is\n * not sent again (it may have landed): the thread gets `errorText` once\n * instead, so it is not left without a word. A platform reset is thrown on,\n * for the retry. `spent` records that the apology was tried, before the\n * error text is posted: a reset while that is posted does not send the\n * apology a second time.\n *\n * @internal\n */\nexport async function postApology(\n thread: { post(message: string): Promise<unknown> },\n apology: string,\n errorText: string,\n spent: () => void | Promise<void>\n): Promise<void> {\n try {\n await thread.post(apology);\n } catch (error) {\n if (isPlatformReset(error)) throw error;\n console.error(\"[Think] Messenger apology was not posted\", error);\n await spent();\n try {\n await thread.post(errorText);\n } catch (failure) {\n if (isPlatformReset(failure)) throw failure;\n console.error(\"[Think] Messenger failure notice failed\", failure);\n }\n }\n}\n\n/**\n * Answer again or apologize for a reply a reset cut off at `stage`, then\n * answer what queued behind it. A failure `retried` says is tried again\n * (the queue waits for it); any other ends the reply, so it is never\n * answered twice.\n *\n * @internal\n */\nexport async function recoverMessengerReply(\n messengers: MessengerReplyRuntime,\n payload: MessengerReplyPayload,\n stage: MessengerReplyStage,\n record: RecordReplyStage,\n retried: (error: unknown) => boolean = isPlatformReset\n): Promise<void> {\n try {\n await messengers.recoverReply(payload, stage, record);\n } catch (error) {\n if (retried(error)) throw error;\n messengers.drainAfterRecovery(payload);\n throw new NonRetryableError(\n error instanceof Error ? error.message : String(error)\n );\n }\n messengers.drainAfterRecovery(payload);\n}\n\n/**\n * Where reply deliveries go: the first attempt answers live, a later one\n * recovers by the stage the reply reached.\n *\n * @internal\n */\nexport function messengerReplySink(\n runtime: () => MessengerReplyRuntime | undefined\n): DeliverySink<Record<string, never>> {\n return {\n attemptTimeoutMs: REPLY_ATTEMPT_TIMEOUT_MS,\n async deliver(_input, attempt) {\n const messengers = runtime();\n if (!messengers) throw new Error(\"Messenger runtime is unavailable\");\n const record: RecordReplyStage = (stage) =>\n attempt.checkpoint.set(STAGE, stage);\n const live = attempt.local as LiveMessengerReply | undefined;\n if (live) {\n await live.answer(record);\n return;\n }\n const payload = attempt.checkpoint.get<MessengerReplyPayload & TaskJson>(\n REPLY\n );\n // Nothing to recover: the reset came before the reply was kept.\n if (!payload) return;\n await recoverMessengerReply(\n messengers,\n payload,\n attempt.checkpoint.get<MessengerReplyStage>(STAGE) ?? \"accepted\",\n record\n );\n },\n onGiveUp(error, _input, progress) {\n console.error(\"[Think] A messenger reply was given up\", error);\n // Nothing else will answer what queued behind it.\n const payload = progress.get<MessengerReplyPayload & TaskJson>(REPLY);\n if (payload) runtime()?.drainAfterRecovery(payload);\n }\n };\n}\n\n/**\n * Register the sink each reply runs on (`sendMessengerReply`), without the\n * runs think@0.24.0 left.\n *\n * @internal\n */\nexport function registerMessengerReplySink(\n tasks: Tasks,\n runtime: () => MessengerReplyRuntime | undefined\n): void {\n registerDeliverySink(\n tasks,\n MESSENGER_REPLY_SINK,\n messengerReplySink(runtime)\n );\n}\n\n/**\n * Accept one reply and answer it here and now. A repeated webhook (same\n * id) joins the reply, or finds it answered.\n *\n * @internal\n */\nexport function sendMessengerReply(\n tasks: Tasks,\n id: string,\n live: LiveMessengerReply\n): Promise<void> {\n return sendDelivery(tasks, MESSENGER_REPLY_SINK, id, {}, undefined, {\n local: live,\n // Written with the run's row: a reset before the first attempt runs\n // still finds what to answer.\n progress: { [REPLY]: live.payload as unknown as TaskJson },\n // Kept once answered: a repeated webhook or button callback after the\n // reply ended is a repeat, not a new request.\n retain: true\n });\n}\n\n/**\n * The definition think@0.24.0 ran replies on.\n *\n * @internal\n */\nexport const RELEASED_REPLY_DEFINITION = \"__cf_internal_messenger_reply\";\n\n/**\n * A released reply snapshot, as think@0.24.0 kept it.\n *\n * @internal\n */\nexport function releasedSnapshot(\n value: unknown\n):\n | { stage: MessengerReplyStage; event: MessengerEvent; thread: unknown }\n | undefined {\n if (value === null || typeof value !== \"object\") return undefined;\n const candidate = value as {\n type?: unknown;\n stage?: unknown;\n event?: MessengerEvent;\n thread?: unknown;\n };\n if (\n candidate.type !== \"think:messenger-reply\" ||\n (candidate.stage !== \"accepted\" &&\n candidate.stage !== \"streaming\" &&\n candidate.stage !== \"completed\") ||\n candidate.event === undefined\n ) {\n return undefined;\n }\n return {\n stage: candidate.stage,\n event: candidate.event,\n thread: candidate.thread\n };\n}\n","import type { UIMessage } from \"ai\";\n\nexport type MessengerEventKind =\n | \"direct-message\"\n | \"mention\"\n | \"subscribed-message\"\n | \"action\"\n | \"delivery-event\";\n\nexport interface MessengerAuthor {\n fullName?: string;\n isBot?: boolean | \"unknown\";\n isMe?: boolean;\n userId: string;\n userName?: string;\n}\n\nexport interface MessengerAttachment {\n data?: ArrayBuffer;\n fetch?: () => Promise<ArrayBuffer>;\n /**\n * Platform-specific metadata needed to re-fetch the attachment after the\n * event has been serialized (e.g. across a sub-agent Durable Object hop).\n * Adapters store identifiers here — Telegram `fileId`, WhatsApp `mediaId`,\n * etc. — that survive serialization even when `fetch`, `data`, and `raw`\n * cannot, so a downstream agent can reconstruct the download closure.\n */\n fetchMetadata?: Record<string, string>;\n id?: string;\n mediaType?: string;\n name?: string;\n raw?: unknown;\n size?: number;\n text?: string;\n url?: string;\n}\n\nexport interface MessengerThread {\n channelId?: string;\n channelName?: string;\n id: string;\n isDirectMessage: boolean;\n providerThreadId: string;\n title?: string;\n}\n\nexport interface MessengerMessage {\n attachments: MessengerAttachment[];\n author: MessengerAuthor;\n createdAt?: Date;\n id: string;\n isMention?: boolean;\n providerMessageId: string;\n raw?: unknown;\n text: string;\n}\n\nexport interface MessengerAction {\n actionId: string;\n messageId?: string;\n raw?: unknown;\n user?: MessengerAuthor;\n value?: string;\n}\n\nexport interface MessengerCapabilities {\n canEditMessages?: boolean;\n canStream?: boolean;\n maxMessageLength?: number;\n supportsActions?: boolean;\n supportsAttachments?: boolean;\n supportsEphemeral?: boolean;\n}\n\nexport interface MessengerContext {\n action?: MessengerAction;\n author?: MessengerAuthor;\n capabilities: MessengerCapabilities;\n kind: MessengerEventKind;\n message?: MessengerMessage;\n messengerId: string;\n provider: string;\n /**\n * Earlier messages folded into this event, oldest first. A quick run of\n * messages in one thread is answered once, for its newest message (the Chat\n * SDK `burst` concurrency strategy); the rest arrive here. They are part of\n * this turn's input: the model-facing user message renders them before\n * `message`, and their attachments are listed with its own.\n */\n skipped?: MessengerMessage[];\n thread: MessengerThread;\n}\n\nexport interface MessengerEvent extends MessengerContext {\n raw?: unknown;\n}\n\n/**\n * The context persisted on a messenger turn's user message. Built from the\n * serializable form of the event, so raw platform payloads and attachment\n * bytes are never stored and a live turn matches its recovered replay.\n */\nexport function messengerContextFromEvent(\n event: MessengerEvent\n): MessengerContext {\n const serializable = serializableMessengerEvent(event);\n return {\n action: serializable.action,\n author: serializable.message?.author ?? serializable.action?.user,\n capabilities: serializable.capabilities,\n kind: serializable.kind,\n message: serializable.message,\n messengerId: serializable.messengerId,\n provider: serializable.provider,\n skipped: serializable.skipped,\n thread: serializable.thread\n };\n}\n\nexport function serializableMessengerEvent(\n event: MessengerEvent\n): MessengerEvent {\n return {\n capabilities: { ...event.capabilities },\n kind: event.kind,\n messengerId: event.messengerId,\n provider: event.provider,\n thread: { ...event.thread },\n action: event.action\n ? {\n actionId: event.action.actionId,\n messageId: event.action.messageId,\n user: event.action.user ? { ...event.action.user } : undefined,\n value: event.action.value\n }\n : undefined,\n message: event.message\n ? serializableMessengerMessage(event.message)\n : undefined,\n skipped: event.skipped?.map(serializableMessengerMessage)\n };\n}\n\nfunction serializableMessengerMessage(\n message: MessengerMessage\n): MessengerMessage {\n return {\n attachments: message.attachments.map((attachment) => ({\n fetchMetadata: attachment.fetchMetadata\n ? { ...attachment.fetchMetadata }\n : undefined,\n id: attachment.id,\n mediaType: attachment.mediaType,\n name: attachment.name,\n size: attachment.size,\n text: attachment.text,\n url: attachment.url\n })),\n author: { ...message.author },\n createdAt: message.createdAt,\n id: message.id,\n isMention: message.isMention,\n providerMessageId: message.providerMessageId,\n text: message.text\n };\n}\n\n/**\n * Customizes how channel (non-DM) speaker names are prefixed onto model-facing\n * text. By default, speaker labels use `fullName || userName || userId`.\n * Direct messages never get a speaker prefix, regardless of this setting.\n * Return `null`/empty to suppress the prefix for that author.\n */\nexport type ChannelSpeakerLabel = (\n author: MessengerAuthor\n) => string | null | undefined;\n\nexport function resolveChannelSpeakerLabel(\n author: MessengerAuthor | undefined,\n channelSpeakerLabel?: ChannelSpeakerLabel\n): string | undefined {\n if (!author) {\n return undefined;\n }\n\n if (channelSpeakerLabel) {\n const label = channelSpeakerLabel(author);\n return label ? label : undefined;\n }\n\n return author.fullName || author.userName || author.userId || undefined;\n}\n\nexport function toMessengerUserMessage(\n event: MessengerEvent,\n channelSpeakerLabel?: ChannelSpeakerLabel\n): UIMessage {\n const message = event.message;\n if (event.action) {\n const user = event.action.user;\n const displayName = event.thread.isDirectMessage\n ? undefined\n : resolveChannelSpeakerLabel(user, channelSpeakerLabel);\n const details = [\n `Action selected: ${event.action.actionId}`,\n event.action.value ? `Value: ${event.action.value}` : undefined,\n event.action.messageId\n ? `Source message: ${event.action.messageId}`\n : undefined\n ].filter(Boolean);\n const text = displayName\n ? `${displayName}: ${details.join(\"\\n\")}`\n : details.join(\"\\n\");\n\n return {\n id: [\n event.messengerId,\n \"action\",\n event.thread.id,\n event.action.messageId,\n event.action.actionId\n ]\n .filter(Boolean)\n .join(\":\"),\n role: \"user\",\n parts: [{ type: \"text\", text }],\n metadata: {\n messenger: messengerContextFromEvent(event)\n }\n } as UIMessage;\n }\n\n if (!message) {\n throw new Error(`Messenger event ${event.kind} does not contain a message`);\n }\n\n const messages = [...(event.skipped ?? []), message];\n const runs = speakerRuns(messages).map((run) => ({\n author: run[0].author,\n text: run\n .map((entry) => entry.text.trim())\n .filter(Boolean)\n .join(\"\\n\")\n }));\n const content = runs\n .filter((run) => runs.length === 1 || run.text)\n .map((run) => {\n const displayName = event.thread.isDirectMessage\n ? undefined\n : resolveChannelSpeakerLabel(run.author, channelSpeakerLabel);\n return displayName ? `${displayName}: ${run.text}` : run.text;\n })\n .join(\"\\n\");\n const attachmentText = describeAttachments(\n messages.flatMap((entry) => entry.attachments)\n );\n const fullText = [content, attachmentText].filter(Boolean).join(\"\\n\\n\");\n\n return {\n id: `${event.messengerId}:${message.id}`,\n role: \"user\",\n parts: [{ type: \"text\", text: fullText }],\n metadata: {\n messenger: messengerContextFromEvent(event)\n }\n } as UIMessage;\n}\n\n/** Consecutive messages from the same author, in order. */\nfunction speakerRuns(messages: MessengerMessage[]): MessengerMessage[][] {\n const runs: MessengerMessage[][] = [];\n for (const message of messages) {\n const run = runs.at(-1);\n if (run && run[0].author.userId === message.author.userId) {\n run.push(message);\n } else {\n runs.push([message]);\n }\n }\n return runs;\n}\n\nfunction describeAttachments(attachments: MessengerAttachment[]): string {\n if (attachments.length === 0) {\n return \"\";\n }\n\n const lines = attachments.map((attachment, index) => {\n const label = attachment.name || attachment.id || `attachment ${index + 1}`;\n const details = [\n attachment.mediaType,\n attachment.size === undefined ? undefined : `${attachment.size} bytes`,\n attachment.url\n ].filter(Boolean);\n return `- ${label}${details.length ? ` (${details.join(\", \")})` : \"\"}`;\n });\n\n return [\"Attachments:\", ...lines].join(\"\\n\");\n}\n","import { RpcTarget } from \"cloudflare:workers\";\nimport { TextSegmentJoiner } from \"agents/chat\";\nimport type { UIMessage } from \"ai\";\nimport type {\n ChatInterruptedInfo,\n ChatStartEvent,\n StreamCallback\n} from \"../think\";\nimport type { MessengerEvent, MessengerMessage } from \"./events\";\nimport { toMessengerUserMessage } from \"./events\";\n\nexport const EMPTY_MESSENGER_RESPONSE =\n \"I couldn't produce a text response. Please try again.\";\nexport const ERROR_MESSENGER_RESPONSE =\n \"Sorry, I couldn't answer that right now. Please try again.\";\nexport const INTERRUPTED_MESSENGER_RESPONSE =\n \"Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.\";\n\ntype Wake = () => void;\n\nexport interface TextStreamCallbackOptions {\n /**\n * Streamed as the reply when a turn completes without text, so surfaces that\n * wait for the first chunk before posting never post an empty message.\n */\n emptyText?: string;\n onVisibleStart?: () => Promise<void> | void;\n visibleSoftLimit?: number;\n}\n\nexport class TextStreamCallback extends RpcTarget implements StreamCallback {\n private readonly emptyText?: string;\n private readonly onVisibleStart?: () => Promise<void> | void;\n private readonly textSegmentJoiner = new TextSegmentJoiner();\n private readonly visibleChunks: string[] = [];\n private readonly wakeups: Wake[] = [];\n private readonly visibleSoftLimit?: number;\n private chatRequestId?: string;\n private closed = false;\n private interrupted = false;\n private recoveredReplyDelivered = false;\n private error?: Error;\n private text = \"\";\n private visibleClosed = false;\n private visibleLimitReachedValue = false;\n private visibleStarted = false;\n private visibleTextValue = \"\";\n\n constructor(options: TextStreamCallbackOptions = {}) {\n super();\n this.emptyText = options.emptyText;\n this.onVisibleStart = options.onVisibleStart;\n this.visibleSoftLimit = options.visibleSoftLimit;\n }\n\n onStart(event: ChatStartEvent): void {\n this.chatRequestId = event.requestId;\n }\n\n onEvent(json: string): void {\n const chunk = streamChunkFromJson(json);\n if (!chunk) return;\n\n let pushedText = false;\n for (const event of this.textSegmentJoiner.pushChunk(chunk)) {\n if (event.type !== \"text\") continue;\n this.text += event.text;\n this.pushVisibleText(event.text);\n pushedText = true;\n }\n if (pushedText) this.wake();\n }\n\n onDone(): void {\n this.complete();\n }\n\n onError(error: string): void {\n this.fail(new Error(error));\n }\n\n onInterrupted(info?: ChatInterruptedInfo): void {\n // The attempt was interrupted and a continuation (not this callback) owns\n // the real answer. Mark interrupted and stop the visible stream WITHOUT\n // failing it, so delivery does not treat the partial as the final reply\n // (#1644).\n this.interrupted = true;\n this.recoveredReplyDelivered = info?.deliversRecoveredReply === true;\n this.close();\n }\n\n wasInterrupted(): boolean {\n return this.interrupted;\n }\n\n /** Whether the target posts the recovered reply to the thread itself. */\n targetDeliversRecoveredReply(): boolean {\n return this.recoveredReplyDelivered;\n }\n\n /** Ends a completed turn, streaming `emptyText` if it produced no text. */\n complete(): void {\n if (!this.closed && this.emptyText !== undefined && !this.hasText()) {\n this.visibleChunks.push(this.emptyText);\n }\n this.close();\n }\n\n close(): void {\n this.closed = true;\n this.visibleClosed = true;\n this.wake();\n }\n\n fail(error: unknown): void {\n this.error = error instanceof Error ? error : new Error(String(error));\n this.closed = true;\n this.visibleClosed = true;\n this.wake();\n }\n\n hasText(): boolean {\n return this.text.trim().length > 0;\n }\n\n /**\n * Resolves `true` once there is visible text to post, or `false` when the\n * stream ends without any, so a caller can avoid posting an empty reply.\n */\n async hasVisibleOutput(): Promise<boolean> {\n while (true) {\n if (this.visibleChunks.length > 0) return true;\n if (this.error || this.closed || this.visibleClosed) return false;\n await new Promise<void>((resolve) => {\n this.wakeups.push(resolve);\n });\n }\n }\n\n remainingText(): string {\n return this.text.slice(this.visibleTextValue.length);\n }\n\n requestId(): string | undefined {\n return this.chatRequestId;\n }\n\n textSoFar(): string {\n return this.text;\n }\n\n visibleLimitReached(): boolean {\n return this.visibleLimitReachedValue;\n }\n\n visibleText(): string {\n return this.visibleTextValue;\n }\n\n async *stream(): AsyncIterable<string> {\n while (true) {\n const next = this.visibleChunks.shift();\n if (next !== undefined) {\n await this.markVisibleStarted();\n yield next;\n continue;\n }\n\n if (this.error) {\n throw this.error;\n }\n\n if (this.closed || this.visibleClosed) {\n return;\n }\n\n await new Promise<void>((resolve) => {\n this.wakeups.push(resolve);\n });\n }\n }\n\n private pushVisibleText(text: string): void {\n if (this.visibleClosed) {\n return;\n }\n\n if (this.visibleSoftLimit === undefined) {\n this.visibleChunks.push(text);\n this.visibleTextValue += text;\n return;\n }\n\n const remaining = this.visibleSoftLimit - this.visibleTextValue.length;\n if (remaining <= 0) {\n this.visibleClosed = true;\n this.visibleLimitReachedValue = true;\n return;\n }\n\n const visible = text.slice(0, remaining);\n if (visible) {\n this.visibleChunks.push(visible);\n this.visibleTextValue += visible;\n }\n\n if (\n visible.length < text.length ||\n this.visibleTextValue.length >= this.visibleSoftLimit\n ) {\n this.visibleClosed = true;\n this.visibleLimitReachedValue = true;\n }\n }\n\n private wake(): void {\n for (const wake of this.wakeups.splice(0)) {\n wake();\n }\n }\n\n private async markVisibleStarted(): Promise<void> {\n if (this.visibleStarted) {\n return;\n }\n this.visibleStarted = true;\n await this.onVisibleStart?.();\n }\n}\n\nfunction streamChunkFromJson(\n json: string\n): { delta?: unknown; type?: unknown } | null {\n try {\n const chunk: unknown = JSON.parse(json);\n return typeof chunk === \"object\" && chunk !== null\n ? (chunk as { delta?: unknown; type?: unknown })\n : null;\n } catch {\n return null;\n }\n}\n\nexport type MessengerReplyStage = \"accepted\" | \"streaming\" | \"completed\";\n\n/**\n * Explicit delivery lifecycle kind, orthogonal to {@link MessengerReplyStage}.\n * Lets surfaces (voice/CLI especially) tell a final answer from an interim\n * progress note from a deterministic notice from a control command, rather than\n * inferring from text shape.\n */\nexport type DeliveryKind = \"final\" | \"interim\" | \"notice\" | \"command\";\n\n/**\n * A messenger event kept as JSON (a reply's delivery input) holds its\n * messages' `createdAt` as strings: give them back as `Date`s.\n *\n * @internal\n */\nexport function reviveMessengerEvent(event: MessengerEvent): MessengerEvent {\n const revive = (message: MessengerMessage): MessengerMessage =>\n typeof message.createdAt === \"string\"\n ? { ...message, createdAt: new Date(message.createdAt) }\n : message;\n return {\n ...event,\n ...(event.message && { message: revive(event.message) }),\n ...(event.skipped && { skipped: event.skipped.map(revive) })\n };\n}\n\n/** What a reply cut off at `stage` does on its next attempt. */\nexport function messengerReplyRecoveryMode(\n stage: MessengerReplyStage\n): \"answer\" | \"apologize\" | null {\n if (stage === \"accepted\") {\n return \"answer\";\n }\n if (stage === \"streaming\") {\n return \"apologize\";\n }\n return null;\n}\n\nexport function messengerReplyFailureMode(\n hasStreamedText: boolean,\n completedModelTurn = false,\n expectedDeliveryCompletion = false\n): \"apologize\" | \"error\" | null {\n if (expectedDeliveryCompletion) {\n return null;\n }\n\n if (completedModelTurn) {\n return \"error\";\n }\n\n return hasStreamedText ? \"apologize\" : \"error\";\n}\n\nexport interface MessengerDeliveryTarget {\n cancelChat(\n requestId: string,\n reason?: string\n ): boolean | void | Promise<boolean | void>;\n chat(\n userMessage: string | UIMessage,\n callback: StreamCallback\n ): Promise<void>;\n chatWithMessengerContext?(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n context: MessengerEvent\n ): Promise<void>;\n /**\n * Bind the live delivery surface for the duration of the model turn so the\n * target can reach it from `deliverNotice` while a messenger turn is active.\n * Returns a restore function (save/restore, so nested turns are safe).\n */\n bindActiveDeliverySurface?(surface: MessengerDeliverySurface): () => void;\n}\n\nexport interface MessengerDeliverySurface {\n post(\n message: string | { markdown: string } | AsyncIterable<string>\n ): Promise<unknown>;\n startTyping?(status?: string): Promise<void>;\n}\n\nexport interface MessengerDeliveryPolicy {\n emptyResponseText?: string;\n errorResponseText?: string;\n interruptedResponseText?: string;\n isExpectedDeliveryCompletion?(\n error: unknown,\n callback: TextStreamCallback\n ): boolean;\n splitText?(text: string): string[];\n /**\n * How often, in milliseconds, the typing indicator is re-sent until the\n * reply's first text is posted. Platforms expire the indicator after a few\n * seconds. `0` sends it once.\n * @default 4000\n */\n typingRefreshMs?: number;\n visibleSoftLimit?: number;\n}\n\nconst DEFAULT_TYPING_REFRESH_MS = 4_000;\n/** Longest the reply waits on a typing request an adapter never settles. */\nconst TYPING_SETTLE_TIMEOUT_MS = 1_000;\n\nasync function settleTyping(pending: Promise<void> | undefined) {\n if (!pending) return;\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n pending,\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, TYPING_SETTLE_TIMEOUT_MS);\n })\n ]);\n clearTimeout(timer);\n}\n\nexport interface DeliverMessengerReplyOptions {\n event: MessengerEvent;\n /**\n * Records how far the reply got, for the attempt after a reset:\n * `\"streaming\"` once text is visible, `\"completed\"` once nothing more\n * should be posted for it.\n */\n onStage?: (stage: \"streaming\" | \"completed\") => Promise<void> | void;\n policy?: MessengerDeliveryPolicy;\n /** The event in its JSON form, handed to `chatWithMessengerContext`. */\n snapshotEvent?: MessengerEvent;\n surface: MessengerDeliverySurface;\n target: MessengerDeliveryTarget;\n userMessage?: UIMessage;\n}\n\nexport async function deliverMessengerReply(\n options: DeliverMessengerReplyOptions\n): Promise<void> {\n const emptyResponseText =\n options.policy?.emptyResponseText ?? EMPTY_MESSENGER_RESPONSE;\n const errorResponseText =\n options.policy?.errorResponseText ?? ERROR_MESSENGER_RESPONSE;\n const interruptedResponseText =\n options.policy?.interruptedResponseText ?? INTERRUPTED_MESSENGER_RESPONSE;\n let completedModelTurn = false;\n const snapshotEvent = options.snapshotEvent ?? options.event;\n const onStage = options.onStage ?? (() => undefined);\n\n const callback = new TextStreamCallback({\n emptyText: emptyResponseText,\n onVisibleStart: async () => {\n await onStage(\"streaming\");\n },\n visibleSoftLimit: options.policy?.visibleSoftLimit\n });\n\n // The typing indicator is cosmetic: a failure to show it must not stop the\n // turn. It is re-sent until the reply's first text is posted, one request\n // at a time so a slow one cannot land after the post and re-show it.\n let typingInFlight: Promise<void> | undefined;\n let typingStopped = false;\n const sendTyping = (): Promise<void> => {\n if (typingStopped) return Promise.resolve();\n typingInFlight ??= (async () => {\n try {\n await options.surface.startTyping?.(\"Thinking...\");\n } catch (error) {\n console.warn(\"[Think] Messenger typing indicator failed\", error);\n } finally {\n typingInFlight = undefined;\n }\n })();\n return typingInFlight;\n };\n const typingRefreshMs =\n options.policy?.typingRefreshMs ?? DEFAULT_TYPING_REFRESH_MS;\n let typingTimer: ReturnType<typeof setInterval> | undefined;\n const stopTyping = () => {\n typingStopped = true;\n clearInterval(typingTimer);\n typingTimer = undefined;\n };\n\n // Posting waits for the first visible text: a stream that ends without any\n // (an interrupted turn, a failure) would otherwise post a blank message\n // ahead of the apology on adapters without native streaming.\n const post = callback\n .hasVisibleOutput()\n .then(async (visible) => {\n stopTyping();\n await settleTyping(typingInFlight);\n return visible ? options.surface.post(callback.stream()) : undefined;\n })\n .catch(async (error: unknown) => {\n if (options.policy?.isExpectedDeliveryCompletion?.(error, callback)) {\n return;\n }\n\n const requestId = callback.requestId();\n if (requestId) {\n await Promise.resolve(\n options.target.cancelChat(requestId, toError(error).message)\n ).catch(() => undefined);\n }\n callback.fail(error);\n throw error;\n });\n\n try {\n if (options.surface.startTyping && typingRefreshMs > 0) {\n typingTimer = setInterval(() => void sendTyping(), typingRefreshMs);\n }\n await settleTyping(sendTyping());\n const userMessage =\n options.userMessage ?? toMessengerUserMessage(options.event);\n const restoreSurface = options.target.bindActiveDeliverySurface?.(\n options.surface\n );\n try {\n if (options.target.chatWithMessengerContext) {\n await options.target.chatWithMessengerContext(\n userMessage,\n callback,\n snapshotEvent\n );\n } else {\n await options.target.chat(userMessage, callback);\n }\n } finally {\n restoreSurface?.();\n }\n if (callback.wasInterrupted()) {\n // The model turn was interrupted and routed into bounded recovery; the\n // recovered answer is produced later by a scheduled continuation. Do NOT\n // mark the turn complete or finalize the truncated partial as the reply\n // (#1644). When the target posts the recovered answer (or the apology,\n // if recovery gives up) itself, stay quiet (#2106); otherwise surface\n // the interrupted apology so the user knows to retry.\n callback.close();\n const streamRejected = await post.then(\n () => false,\n () => true\n );\n // Checkpoint before the post: a reset after it must not let recovery\n // (which apologizes for a reply cut off while streaming) post a second apology.\n await onStage(\"completed\");\n if (callback.targetDeliversRecoveredReply()) {\n // The target subtracts every streamed character from the recovered\n // reply, including any past `visibleSoftLimit` or in a rejected\n // stream post, so post that text now.\n for (const chunk of options.policy?.splitText?.(\n streamRejected ? callback.textSoFar() : callback.remainingText()\n ) ?? []) {\n await options.surface.post(chunk).catch(() => undefined);\n }\n return;\n }\n await options.surface\n .post(interruptedResponseText)\n .catch(() => undefined);\n return;\n }\n completedModelTurn = true;\n callback.complete();\n await post;\n for (const chunk of options.policy?.splitText?.(callback.remainingText()) ??\n []) {\n await options.surface.post(chunk);\n }\n await onStage(\"completed\");\n } catch (error) {\n callback.fail(error);\n await post.catch(() => undefined);\n const failureMode = messengerReplyFailureMode(\n callback.hasText(),\n completedModelTurn,\n options.policy?.isExpectedDeliveryCompletion?.(error, callback)\n );\n\n if (failureMode === null) {\n await onStage(\"completed\");\n return;\n }\n\n await onStage(\"completed\");\n if (failureMode === \"apologize\") {\n await options.surface\n .post(interruptedResponseText)\n .catch(() => undefined);\n return;\n }\n\n await options.surface\n .post({\n markdown: errorResponseText\n })\n .catch(() => undefined);\n } finally {\n stopTyping();\n }\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n","import type { UIMessage } from \"ai\";\nimport type {\n Adapter,\n ActionEvent as ChatActionEvent,\n Attachment as ChatAttachment,\n Author as ChatAuthor,\n ChatConfig,\n ConcurrencyConfig,\n ConcurrencyStrategy,\n Lock as ChatLock,\n Message as ChatMessage,\n SerializedThread,\n Thread as ChatThread\n} from \"chat\";\nimport { Chat, Message, ThreadImpl } from \"chat\";\nimport type {\n Agent,\n FiberContext,\n FiberRecoveryResult,\n StartFiberOptions,\n SubAgentClass,\n SubAgentStub\n} from \"agents\";\nimport { createChatSdkState, defaultKeyShard } from \"agents/chat-sdk\";\nimport type { ChatSdkStateAdapterOptions } from \"agents/chat-sdk\";\nimport { ChatSdkStateAgent } from \"agents/chat-sdk\";\nimport type { StreamCallback } from \"../think\";\nimport {\n postApology,\n type LiveMessengerReply,\n type MessengerReplyPayload,\n type RecordReplyStage\n} from \"./reply-task\";\nimport type {\n MessengerAttachment,\n MessengerAction,\n MessengerAuthor,\n MessengerCapabilities,\n MessengerEvent,\n MessengerEventKind,\n MessengerMessage,\n MessengerThread\n} from \"./events\";\nimport {\n serializableMessengerEvent,\n toMessengerUserMessage,\n type ChannelSpeakerLabel\n} from \"./events\";\nimport {\n deliverMessengerReply,\n EMPTY_MESSENGER_RESPONSE,\n ERROR_MESSENGER_RESPONSE,\n INTERRUPTED_MESSENGER_RESPONSE,\n messengerReplyRecoveryMode,\n reviveMessengerEvent,\n type MessengerReplyStage,\n type MessengerDeliveryPolicy,\n type MessengerDeliverySurface,\n type MessengerDeliveryTarget\n} from \"./delivery\";\n\nexport class ThinkMessengerStateAgent extends ChatSdkStateAgent {}\n\n/**\n * Adapters without native streaming would otherwise post `\"...\"` and edit it,\n * and platforms such as Slack keep that first text as the notification\n * preview. Delivery already shows a typing indicator before the reply starts.\n */\nconst FALLBACK_STREAMING_PLACEHOLDER_TEXT = null;\n\n/** The posts that deliver a recovered messenger reply, in order. @internal */\nexport function recoveredReplyPosts(\n definition: { delivery?: MessengerDeliveryPolicy },\n input: {\n outcome: \"completed\" | \"interrupted\";\n text?: string;\n partialPosted?: boolean;\n notice?: true;\n }\n): Array<string | { markdown: string }> {\n if (input.notice) {\n return [definition.delivery?.errorResponseText ?? ERROR_MESSENGER_RESPONSE];\n }\n if (input.outcome === \"interrupted\") {\n return [\n definition.delivery?.interruptedResponseText ??\n INTERRUPTED_MESSENGER_RESPONSE\n ];\n }\n const text = input.text?.trim() ? input.text : \"\";\n if (!text) {\n return input.partialPosted\n ? []\n : [definition.delivery?.emptyResponseText ?? EMPTY_MESSENGER_RESPONSE];\n }\n return (definition.delivery?.splitText?.(text) ?? [text]).map((chunk) => ({\n markdown: chunk\n }));\n}\n\nexport type MessengerRespondTo =\n | \"action\"\n | \"direct-message\"\n | \"mention\"\n | \"subscribed-thread\";\n\nexport type MessengerConversationMode = \"self\" | \"thread\";\n\nexport type MessengerConversationTarget =\n | { target: \"self\" }\n | {\n agentClass?: SubAgentClass<Agent & MessengerThinkTarget>;\n name: string;\n target: \"subagent\";\n };\n\nexport type MessengerConversationResolver = (\n event: MessengerEvent\n) => MessengerConversationTarget | Promise<MessengerConversationTarget>;\n\nexport interface MessengerDefinition {\n adapter: Adapter;\n adapterName: string;\n capabilities?: MessengerCapabilities;\n /**\n * Customizes how non-DM channel messages are labelled for the model.\n *\n * Channel (group) messages use `fullName || userName || userId` by default and\n * are rendered as `SpeakerName: text` so the model can attribute multi-user\n * traffic. Direct messages never get a prefix.\n */\n channelSpeakerLabel?: ChannelSpeakerLabel;\n conversation?: MessengerConversationMode | MessengerConversationResolver;\n delivery?: MessengerDeliveryPolicy;\n keyShard?: ChatSdkStateAdapterOptions[\"keyShard\"];\n path?: string;\n provider: string;\n respondTo?: readonly MessengerRespondTo[];\n shardKey?: ChatSdkStateAdapterOptions[\"shardKey\"];\n subscribeOnMention?: boolean;\n toEvent?: (\n input: ChatSdkMessengerEventInput\n ) => MessengerEvent | Promise<MessengerEvent>;\n userName: string;\n verifyWebhook?:\n | false\n | ((request: Request) => boolean | Response | Promise<boolean | Response>);\n}\n\nexport type ThinkMessengers = Record<string, MessengerDefinition>;\n\n/** The Chat SDK `concurrency` setting for a Think agent's messengers. */\nexport type MessengerConcurrency = ConcurrencyStrategy | ConcurrencyConfig;\n\n/**\n * How long a message queued behind a running reply stays answerable. The\n * Chat SDK default (90 seconds) drops follow-ups sent early in a long turn,\n * so Think applies this unless `queueEntryTtlMs` is set explicitly.\n */\nconst MESSENGER_QUEUE_ENTRY_TTL_MS = 30 * 60 * 1000;\n\nexport const DEFAULT_MESSENGER_CONCURRENCY: MessengerConcurrency = {\n debounceMs: 600,\n queueEntryTtlMs: MESSENGER_QUEUE_ENTRY_TTL_MS,\n strategy: \"burst\"\n};\n\n/** The Chat SDK's thread lock TTL (`DEFAULT_LOCK_TTL_MS`). */\nconst CHAT_SDK_LOCK_TTL_MS = 30_000;\n\n/**\n * Private `Chat` methods the post-recovery drain reuses so a stranded queue\n * is dispatched exactly as the SDK would (lock scope, expiry, `skipped`).\n * Feature-checked at runtime: a `chat` release without them skips the drain.\n */\ninterface ChatSdkQueueInternals {\n getLockKey(adapter: Adapter, threadId: string): Promise<string>;\n drainQueue(\n lock: ChatLock,\n adapter: Adapter,\n threadId: string,\n lockKey: string\n ): Promise<void>;\n}\n\n/**\n * Answer the messages queued on `threadId` behind a reply whose isolate\n * died: once the dead holder's lock expires, take the lock and hand the\n * queue to the SDK's own drain. A live holder drains the queue itself,\n * which ends the wait.\n *\n * @internal\n */\nexport async function drainStrandedQueue(\n chat: Chat<Record<string, Adapter>>,\n definition: NormalizedMessengerDefinition,\n threadId: string\n): Promise<void> {\n const internals = chat as unknown as Partial<ChatSdkQueueInternals>;\n if (\n typeof internals.getLockKey !== \"function\" ||\n typeof internals.drainQueue !== \"function\"\n ) {\n return;\n }\n await chat.initialize();\n const state = chat.getState();\n const lockKey = await internals.getLockKey.call(\n chat,\n definition.adapter,\n threadId\n );\n const deadline = Date.now() + CHAT_SDK_LOCK_TTL_MS + 5_000;\n while ((await state.queueDepth(lockKey)) > 0) {\n const lock = await state.acquireLock(lockKey, CHAT_SDK_LOCK_TTL_MS);\n if (lock) {\n try {\n await internals.drainQueue.call(\n chat,\n lock,\n definition.adapter,\n threadId,\n lockKey\n );\n } finally {\n await state.releaseLock(lock);\n }\n return;\n }\n if (Date.now() >= deadline) return;\n await new Promise((resolve) => setTimeout(resolve, 1_000));\n }\n}\n\n/** Fill in Think's queue-entry TTL where the setting leaves it unset. */\nexport function withMessengerQueueTtl(\n concurrency: MessengerConcurrency\n): MessengerConcurrency {\n if (typeof concurrency === \"string\") {\n return {\n queueEntryTtlMs: MESSENGER_QUEUE_ENTRY_TTL_MS,\n strategy: concurrency\n };\n }\n return {\n ...concurrency,\n queueEntryTtlMs: concurrency.queueEntryTtlMs ?? MESSENGER_QUEUE_ENTRY_TTL_MS\n };\n}\n\nexport interface NormalizedMessengerDefinition extends MessengerDefinition {\n id: string;\n path: string;\n respondTo: readonly MessengerRespondTo[];\n subscribeOnMention: boolean;\n verifyWebhook:\n | false\n | ((request: Request) => boolean | Response | Promise<boolean | Response>);\n}\n\nexport interface ChatSdkMessengerOptions extends Omit<\n MessengerDefinition,\n \"adapterName\"\n> {\n adapterName?: string;\n}\n\nexport interface ChatSdkMessengerEventInput {\n action?: ChatActionEvent;\n eventKind: MessengerEventKind;\n message?: ChatMessage;\n raw?: unknown;\n /**\n * Earlier messages the Chat SDK's concurrency strategy folded into this one,\n * oldest first (`MessageContext.skipped`). The runtime's `burst` strategy\n * answers only the newest message of a quick run and reports the rest here.\n * {@link defaultChatSdkEvent} carries them on the event's `skipped` so they\n * reach the model; a custom `toEvent` that ignores them drops them.\n */\n skipped?: readonly ChatMessage[];\n thread: ChatThread;\n}\n\nexport interface MessengerThinkTarget {\n cancelChat(\n requestId: string,\n reason?: string\n ): boolean | void | Promise<boolean | void>;\n chat(\n userMessage: string | UIMessage,\n callback: StreamCallback\n ): Promise<void>;\n chatWithMessengerContext?(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n context: MessengerEvent\n ): Promise<void>;\n}\n\nexport interface MessengerThinkHost extends MessengerThinkTarget {\n constructor: { name: string };\n name: string;\n parentPath: ReadonlyArray<{ className: string; name: string }>;\n startFiber(\n name: string,\n fn: (ctx: FiberContext) => Promise<void>,\n options?: StartFiberOptions\n ): Promise<MessengerFiberStartResult>;\n resolveFiber(id: string, result: FiberRecoveryResult): Promise<boolean>;\n /**\n * Durably accept one messenger reply as a delivery and answer it inline\n * while this isolate lives. The same id joins a reply still running.\n */\n _sendMessengerReply(id: string, live: LiveMessengerReply): Promise<void>;\n subAgent<T extends Agent>(\n agentClass: SubAgentClass<T>,\n name: string\n ): Promise<SubAgentStub<T>>;\n /** Keep the host alive while background messenger work runs. */\n keepAliveWhile?<T>(fn: () => Promise<T>): Promise<T>;\n}\n\ninterface MessengerFiberStartResult {\n accepted: boolean;\n fiberId: string;\n snapshot?: unknown;\n status: string;\n}\n\nexport function chatSdkMessenger(\n options: ChatSdkMessengerOptions\n): MessengerDefinition {\n return {\n ...options,\n adapterName: options.adapterName ?? options.provider\n };\n}\n\nexport class ThinkMessengerRuntime {\n private chat?: Chat<Record<string, Adapter>>;\n private readonly definitionsById = new Map<\n string,\n NormalizedMessengerDefinition\n >();\n private readonly definitions: NormalizedMessengerDefinition[];\n\n private readonly concurrency: MessengerConcurrency;\n\n constructor(\n definitions: ThinkMessengers,\n private readonly host: MessengerThinkHost,\n options?: { concurrency?: MessengerConcurrency }\n ) {\n this.concurrency = withMessengerQueueTtl(\n options?.concurrency ?? DEFAULT_MESSENGER_CONCURRENCY\n );\n this.definitions = normalizeMessengers(definitions);\n for (const definition of this.definitions) {\n this.definitionsById.set(definition.id, definition);\n }\n }\n\n get size(): number {\n return this.definitions.length;\n }\n\n initialize(): void {\n if (this.host.parentPath.length > 0) {\n return;\n }\n\n this.chat = this.createChat();\n }\n\n async handleRequest(request: Request): Promise<Response | undefined> {\n if (this.host.parentPath.length > 0) {\n return undefined;\n }\n\n const url = new URL(request.url);\n const definition = this.definitions.find(\n (candidate) => candidate.path === url.pathname\n );\n if (!definition) {\n return undefined;\n }\n\n if (request.method !== \"POST\") {\n return new Response(\"Method not allowed\", { status: 405 });\n }\n\n if (definition.verifyWebhook !== false) {\n const verification = await definition.verifyWebhook(\n request.clone() as Request\n );\n if (verification instanceof Response) {\n return verification;\n }\n if (verification === false) {\n return new Response(\"Unauthorized\", { status: 401 });\n }\n }\n\n const chat = this.chat ?? this.createChat();\n this.chat = chat;\n return chat.webhooks[definition.adapterName](request);\n }\n\n /**\n * Answer again, or apologize, for a reply a reset cut off at `stage`.\n *\n * @internal\n */\n async recoverReply(\n payload: MessengerReplyPayload,\n stage: MessengerReplyStage,\n record: RecordReplyStage\n ): Promise<void> {\n const event = reviveMessengerEvent(payload.event);\n const definition = this.definitionsById.get(event.messengerId);\n if (!definition) {\n throw new Error(\n `No messenger definition found for recovered messenger ${event.messengerId}`\n );\n }\n const thread = this.reviveThread(definition, payload.thread);\n const mode = messengerReplyRecoveryMode(stage);\n if (mode === \"answer\") {\n await this.answer(definition, event, thread, record, event);\n return;\n }\n if (mode === \"apologize\") {\n await postApology(\n thread,\n definition.delivery?.interruptedResponseText ??\n INTERRUPTED_MESSENGER_RESPONSE,\n definition.delivery?.errorResponseText ?? ERROR_MESSENGER_RESPONSE,\n () => record(\"completed\")\n );\n record(\"completed\");\n }\n }\n\n /**\n * After a recovered reply ended or gave up, answer the messages queued\n * behind it.\n *\n * @internal\n */\n drainAfterRecovery(payload: MessengerReplyPayload): void {\n const definition = this.definitionsById.get(payload.event.messengerId);\n if (!definition) return;\n const thread = this.reviveThread(definition, payload.thread);\n this.drainQueuedMessagesInBackground(definition, thread.id);\n }\n\n /**\n * Messages queued behind a reply are drained only by the Chat SDK handler\n * holding the thread lock. When the isolate running that reply dies, the\n * queue is stranded until another message arrives, so recovery drains it:\n * once the dead holder's lock expires, take the lock and hand the queue to\n * the SDK's own drain. A live holder drains the queue itself, which ends\n * the wait.\n */\n private drainQueuedMessagesInBackground(\n definition: NormalizedMessengerDefinition,\n threadId: string\n ): void {\n const drain = () => this.drainQueuedMessages(definition, threadId);\n const running = this.host.keepAliveWhile?.(drain) ?? drain();\n void running.catch((error: unknown) => {\n console.error(\n `[Think] Failed to drain messages queued on ${threadId} after recovery`,\n error\n );\n });\n }\n\n private async drainQueuedMessages(\n definition: NormalizedMessengerDefinition,\n threadId: string\n ): Promise<void> {\n await drainStrandedQueue(\n (this.chat ??= this.createChat()),\n definition,\n threadId\n );\n }\n\n private createChat(): Chat<Record<string, Adapter>> {\n return createMessengerChat({\n definitions: this.definitions,\n concurrency: this.concurrency,\n parent: this.host,\n onEvent: (definition, event, thread) =>\n this.enqueueReply(definition, event, thread)\n });\n }\n\n private async enqueueReply(\n definition: NormalizedMessengerDefinition,\n event: MessengerEvent,\n thread: ChatThread\n ): Promise<void> {\n const snapshotEvent = serializableMessengerEvent(event);\n // Durable acceptance plus inline execution, as one delivery. A\n // duplicate webhook joins a reply still running; a reply a reset cut\n // off is answered again or apologized for on wake, by its stage.\n await this.host._sendMessengerReply(idempotencyKeyForEvent(event), {\n payload: { event: snapshotEvent, thread: thread.toJSON() },\n answer: (record) =>\n this.answer(definition, event, thread, record, snapshotEvent)\n });\n }\n\n private async answer(\n definition: NormalizedMessengerDefinition,\n event: MessengerEvent,\n thread: ChatThread,\n record?: RecordReplyStage,\n snapshotEvent = serializableMessengerEvent(event)\n ): Promise<void> {\n const target = await this.resolveTarget(definition, event);\n await deliverMessengerReply({\n event,\n ...(record && { onStage: record }),\n policy: definition.delivery,\n snapshotEvent,\n surface: thread satisfies MessengerDeliverySurface,\n target,\n userMessage: toMessengerUserMessage(event, definition.channelSpeakerLabel)\n });\n }\n\n /**\n * Resolve a live delivery surface for an out-of-turn notice (e.g. a scheduled\n * task or webhook handler calling `deliverNotice`). Uses `chat.thread(id)` —\n * the chat SDK's supported \"post from outside a webhook\" primitive, which\n * returns a postable {@link ChatThread} and infers the adapter from the\n * thread-id prefix, so it works for every chat-sdk adapter with no per-adapter\n * wiring. Returns `undefined` when the channel is unregistered or no `threadId`\n * was supplied so the caller can fail fast.\n */\n async resolveDeliverySurface(\n channelId: string,\n threadId?: string\n ): Promise<MessengerDeliverySurface | undefined> {\n const definition = this.definitionsById.get(channelId);\n if (!definition || !threadId) {\n return undefined;\n }\n const chat = (this.chat ??= this.createChat());\n // Out of a turn (no webhook yet) the Chat may not have connected its\n // state, which a post records to.\n await chat.initialize();\n return chat.thread(threadId) satisfies MessengerDeliverySurface;\n }\n\n /**\n * Post what chat recovery produced for an interrupted messenger turn: the\n * text the thread has not seen yet, or the interrupted apology when\n * recovery gave up. The reply may span several posts; this posts only post\n * number `chunk` (skipped when out of range) and returns how many there\n * are, so the caller can checkpoint between posts.\n */\n async deliverRecoveredReply(input: {\n messengerId: string;\n threadId: string;\n outcome: \"completed\" | \"interrupted\";\n text?: string;\n partialPosted?: boolean;\n chunk: number;\n notice?: true;\n }): Promise<{ chunks: number }> {\n const definition = this.definitionsById.get(input.messengerId);\n const surface = await this.resolveDeliverySurface(\n input.messengerId,\n input.threadId\n );\n if (!definition || !surface) {\n throw new Error(\n `No messenger delivery surface for ${input.messengerId} thread ${input.threadId}`\n );\n }\n const posts = recoveredReplyPosts(definition, input);\n const post = posts[input.chunk];\n if (post !== undefined) await surface.post(post);\n return { chunks: posts.length };\n }\n\n private async resolveTarget(\n definition: NormalizedMessengerDefinition,\n event: MessengerEvent\n ): Promise<MessengerDeliveryTarget> {\n const conversation = definition.conversation ?? \"thread\";\n const target =\n typeof conversation === \"function\"\n ? await conversation(event)\n : conversation === \"self\"\n ? { target: \"self\" as const }\n : {\n name: defaultConversationName(event),\n target: \"subagent\" as const\n };\n\n if (target.target === \"self\") {\n return this.host;\n }\n\n const agentClass =\n target.agentClass ??\n (this.host.constructor as unknown as SubAgentClass<\n Agent & MessengerThinkTarget\n >);\n const stub = (await this.host.subAgent(\n agentClass,\n target.name\n )) as unknown as Required<MessengerThinkTarget>;\n // A live thread cannot cross the sub-agent RPC boundary, so the stub's\n // `bindActiveDeliverySurface` must not be offered to delivery.\n return {\n cancelChat: (requestId, reason) => stub.cancelChat(requestId, reason),\n chat: (userMessage, callback) => stub.chat(userMessage, callback),\n chatWithMessengerContext: (userMessage, callback, context) =>\n stub.chatWithMessengerContext(userMessage, callback, context)\n };\n }\n\n /**\n * `ThreadImpl.fromJSON` (what `chat.reviver()` calls) builds the thread\n * without the Chat's streaming config, so a recovered reply would fall back to\n * the `\"...\"` placeholder. Rebuild it from the same fields with that config.\n */\n private reviveThread(\n definition: NormalizedMessengerDefinition,\n value: unknown\n ): ChatThread {\n return reviveMessengerThread(\n (this.chat ??= this.createChat()),\n definition,\n value\n );\n }\n}\n\n/**\n * The Chat SDK `Chat` a Think's messengers take their webhooks through: its\n * state on Think's state sub-agents (subscriptions, thread locks, queued\n * messages), its concurrency, and the handlers that turn what each\n * messenger answers (`respondTo`) into a {@link MessengerEvent} for\n * `onEvent`. A handler holds the thread's lock until `onEvent` resolves.\n *\n * @internal\n */\nexport function createMessengerChat(options: {\n definitions: NormalizedMessengerDefinition[];\n concurrency: MessengerConcurrency;\n parent: unknown;\n onEvent(\n definition: NormalizedMessengerDefinition,\n event: MessengerEvent,\n thread: ChatThread\n ): Promise<void>;\n}): Chat<Record<string, Adapter>> {\n const { definitions } = options;\n const lookup = messengerLookup(definitions);\n const adapters = Object.fromEntries(\n definitions.map((definition) => [\n definition.adapterName,\n definition.adapter\n ])\n ) as Record<string, Adapter>;\n const chat = new Chat({\n adapters,\n concurrency: options.concurrency,\n fallbackStreamingPlaceholderText: FALLBACK_STREAMING_PLACEHOLDER_TEXT,\n state: createChatSdkState({\n agent: ThinkMessengerStateAgent,\n keyShard: (key) => lookup.shardStateKey(key),\n // The Chat SDK never extends its 30 second thread lock while a\n // handler runs; a Think turn often takes longer.\n lockHeartbeat: true,\n parent: options.parent as ChatSdkStateAdapterOptions[\"parent\"],\n shardKey: (threadId) => lookup.shardThread(threadId)\n }),\n userName: definitions[0]?.userName ?? \"think\"\n } satisfies ChatConfig<Record<string, Adapter>>);\n\n chat.onDirectMessage(async (thread, message, _channel, context) => {\n const definition = lookup.forThread(thread);\n if (!definition) return;\n if (definition.respondTo.includes(\"direct-message\")) {\n await options.onEvent(\n definition,\n await messengerEvent(definition, {\n eventKind: \"direct-message\",\n message,\n skipped: context?.skipped,\n thread\n }),\n thread\n );\n }\n });\n\n chat.onNewMention(async (thread, message, context) => {\n const definition = lookup.forThread(thread);\n if (!definition) return;\n if (definition.subscribeOnMention) {\n await thread.subscribe();\n }\n if (definition.respondTo.includes(\"mention\")) {\n await options.onEvent(\n definition,\n await messengerEvent(definition, {\n eventKind: \"mention\",\n message,\n skipped: context?.skipped,\n thread\n }),\n thread\n );\n }\n });\n\n // A burst is routed on its newest message only. When an earlier message\n // in an unsubscribed thread mentioned the bot, answer the burst as that\n // mention instead of letting it fall through unanswered.\n chat.onNewMessage(/[\\s\\S]*/, async (thread, message, context) => {\n const definition = lookup.forThread(thread);\n if (!definition || !definition.respondTo.includes(\"mention\")) return;\n if (!context?.skipped.some((skipped) => mentionsBot(definition, skipped)))\n return;\n if (definition.subscribeOnMention) {\n await thread.subscribe();\n }\n await options.onEvent(\n definition,\n await messengerEvent(definition, {\n eventKind: \"mention\",\n message,\n skipped: context.skipped,\n thread\n }),\n thread\n );\n });\n\n chat.onSubscribedMessage(async (thread, message, context) => {\n const definition = lookup.forThread(thread);\n if (!definition) return;\n const mentioned =\n message.isMention ||\n (context?.skipped.some((skipped) => mentionsBot(definition, skipped)) ??\n false);\n if (\n definition.respondTo.includes(\"subscribed-thread\") ||\n (mentioned && definition.respondTo.includes(\"mention\"))\n ) {\n await options.onEvent(\n definition,\n await messengerEvent(definition, {\n eventKind: mentioned ? \"mention\" : \"subscribed-message\",\n message,\n skipped: context?.skipped,\n thread\n }),\n thread\n );\n }\n });\n\n chat.onAction(async (event) => {\n if (!event.thread) return;\n const thread = event.thread as ChatThread;\n const definition = lookup.forThread(thread);\n if (!definition) return;\n if (definition.respondTo.includes(\"action\")) {\n await options.onEvent(\n definition,\n await messengerEvent(definition, {\n action: event,\n eventKind: \"action\",\n raw: event.raw,\n thread\n }),\n thread\n );\n }\n });\n\n return chat.registerSingleton();\n}\n\n/** Which messenger a thread or a state key belongs to. */\nfunction messengerLookup(definitions: NormalizedMessengerDefinition[]) {\n const byAdapterName = new Map(\n definitions.map((definition) => [definition.adapterName, definition])\n );\n const hasUniqueProvider = (provider: string): boolean =>\n definitions.filter((definition) => definition.provider === provider)\n .length === 1;\n const forThreadId = (\n threadId: string | undefined\n ): NormalizedMessengerDefinition | undefined => {\n if (!threadId) return undefined;\n if (definitions.length === 1) return definitions[0];\n return definitions.find(\n (definition) =>\n threadId === definition.id ||\n threadId.startsWith(`${definition.id}:`) ||\n (hasUniqueProvider(definition.provider) &&\n (threadId === definition.provider ||\n threadId.startsWith(`${definition.provider}:`))) ||\n threadId === definition.adapterName ||\n threadId.startsWith(`${definition.adapterName}:`)\n );\n };\n const shardThread = (threadId: string): string =>\n forThreadId(threadId)?.shardKey?.(threadId) ||\n threadId.split(\":\").slice(0, 2).join(\":\") ||\n \"default\";\n return {\n forThread: (thread: ChatThread) =>\n byAdapterName.get(thread.toJSON().adapterName) ??\n forThreadId(thread.id) ??\n forThreadId(thread.channelId),\n shardThread,\n shardStateKey(key: string): string | undefined {\n for (const definition of definitions) {\n const shard = definition.keyShard?.(key);\n if (shard) return shard;\n }\n return defaultKeyShard(key, shardThread);\n }\n };\n}\n\nasync function messengerEvent(\n definition: NormalizedMessengerDefinition,\n input: ChatSdkMessengerEventInput\n): Promise<MessengerEvent> {\n return (\n (await definition.toEvent?.(input)) ??\n defaultChatSdkEvent(definition, input)\n );\n}\n\nexport function normalizeMessengers(\n messengers: ThinkMessengers\n): NormalizedMessengerDefinition[] {\n const ids = new Set<string>();\n const adapterNames = new Set<string>();\n const paths = new Set<string>();\n const normalized: NormalizedMessengerDefinition[] = [];\n\n for (const [id, definition] of Object.entries(messengers)) {\n if (ids.has(id)) {\n throw new Error(`Duplicate messenger id: ${id}`);\n }\n ids.add(id);\n\n const path = definition.path ?? `/messengers/${id}/webhook`;\n validatePath(path, id);\n if (definition.verifyWebhook === undefined) {\n throw new Error(\n `Messenger ${id} requires verifyWebhook, or verifyWebhook: false to opt out explicitly`\n );\n }\n const verifyWebhook = definition.verifyWebhook;\n if (adapterNames.has(definition.adapterName)) {\n throw new Error(\n `Duplicate messenger adapter name: ${definition.adapterName}`\n );\n }\n adapterNames.add(definition.adapterName);\n if (paths.has(path)) {\n throw new Error(`Duplicate messenger path: ${path}`);\n }\n paths.add(path);\n\n normalized.push({\n ...definition,\n id,\n path,\n respondTo: definition.respondTo ?? [\"direct-message\", \"mention\"],\n subscribeOnMention: definition.subscribeOnMention ?? true,\n verifyWebhook\n });\n }\n\n return normalized;\n}\n\n/**\n * `ThreadImpl.fromJSON` (what `chat.reviver()` calls) builds the thread\n * without the Chat's streaming config, so a recovered reply would fall back to\n * the `\"...\"` placeholder, and `chat.thread(id)` has no current message to\n * stream against. Rebuild a reply's thread from its JSON with that config.\n *\n * @internal\n */\nexport function reviveMessengerThread(\n chat: Chat<Record<string, Adapter>>,\n definition: NormalizedMessengerDefinition,\n value: unknown\n): ChatThread {\n if (value === undefined) {\n throw new Error(\"Messenger recovery snapshot is missing chat object data\");\n }\n const json = JSON.parse(JSON.stringify(value)) as SerializedThread;\n // Bound explicitly: a lazy thread resolves its adapter from the\n // module-global Chat singleton on first use, which another runtime in\n // this isolate can replace while recovery awaits.\n return new ThreadImpl({\n adapter: definition.adapter,\n stateAdapter: chat.getState(),\n channelId: json.channelId,\n channelVisibility: json.channelVisibility,\n currentMessage: json.currentMessage\n ? Message.fromJSON(json.currentMessage)\n : undefined,\n fallbackStreamingPlaceholderText: FALLBACK_STREAMING_PLACEHOLDER_TEXT,\n id: json.id,\n isDM: json.isDM\n });\n}\n\nexport function defaultConversationName(event: MessengerEvent): string {\n return `messenger:${event.messengerId}:${stableNamePart(event.thread.id)}`;\n}\n\nexport function idempotencyKeyForEvent(event: MessengerEvent): string {\n return [\n \"messenger\",\n event.messengerId,\n \"message\",\n event.thread.id,\n idempotencyEventPart(event)\n ].join(\":\");\n}\n\nfunction idempotencyEventPart(event: MessengerEvent): string {\n if (event.message) {\n return event.message.id;\n }\n\n if (event.action) {\n return [\n \"action\",\n stableNamePart(event.action.messageId ?? \"unknown-message\"),\n stableNamePart(event.action.actionId),\n stableNamePart(event.action.user?.userId ?? \"unknown-user\"),\n stableNamePart(event.action.value ?? \"no-value\")\n ].join(\":\");\n }\n\n return event.kind;\n}\n\nexport function defaultChatSdkEvent(\n definition: NormalizedMessengerDefinition,\n input: ChatSdkMessengerEventInput\n): MessengerEvent {\n const convert = (chatMessage: ChatMessage): MessengerMessage => {\n const message = toMessengerMessage(chatMessage);\n message.text = resolveSelfMention(\n message.text,\n definition.adapter.botUserId,\n definition.userName\n );\n return message;\n };\n const skipped = input.skipped?.length\n ? input.skipped.map(convert)\n : undefined;\n return {\n capabilities: definition.capabilities ?? {},\n action: input.action && toMessengerAction(input.action),\n kind: input.eventKind,\n message: input.message && convert(input.message),\n messengerId: definition.id,\n provider: definition.provider,\n raw: input.raw ?? input.message?.raw,\n ...(skipped && { skipped }),\n thread: toMessengerThread(input.thread)\n };\n}\n\n/**\n * Rewrite the bot's own unresolved self-mention to `@<userName>`.\n *\n * Adapters resolve every user's `<@id>` mention to a readable `@DisplayName`\n * except the bot's own, which is deliberately left as a raw id token so mention\n * detection can still find it. That raw id is therefore the only unresolved\n * mention that can survive in the text, so once it has served its purpose we\n * replace it with the bot's configured handle before the model sees it —\n * reconstructing the readable `@handle` the sender originally typed. Handles\n * both the angle-bracket form (`<@U123>` / `<@!U123>`, Slack/Discord) and the\n * bare `@U123` form some adapters normalize to. No-op when the adapter does not\n * expose a `botUserId`.\n */\nexport function resolveSelfMention(\n text: string,\n botUserId: string | undefined,\n userName: string\n): string {\n if (!botUserId) {\n return text;\n }\n const id = escapeRegExp(botUserId);\n const replacement = `@${userName}`;\n return text\n .replace(new RegExp(`<@!?${id}>`, \"g\"), replacement)\n .replace(new RegExp(`@${id}\\\\b`, \"g\"), replacement);\n}\n\n/**\n * Whether a message mentions the bot. The Chat SDK only runs its own mention\n * detection on the message it dispatches, so messages a burst folded into\n * `skipped` carry `isMention` only when their adapter set it. This mirrors the\n * SDK's check (`@userName`, `@botUserId`, `<@botUserId>`) for them.\n */\nexport function mentionsBot(\n definition: Pick<NormalizedMessengerDefinition, \"adapter\" | \"userName\">,\n message: Pick<ChatMessage, \"isMention\" | \"text\">\n): boolean {\n if (message.isMention) return true;\n const userName = definition.adapter.userName || definition.userName;\n const patterns = [new RegExp(`@${escapeRegExp(userName)}\\\\b`, \"i\")];\n const botUserId = definition.adapter.botUserId;\n if (botUserId) {\n const id = escapeRegExp(botUserId);\n patterns.push(new RegExp(`@${id}\\\\b`, \"i\"), new RegExp(`<@!?${id}>`, \"i\"));\n }\n return patterns.some((pattern) => pattern.test(message.text));\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction toMessengerAction(action: ChatActionEvent): MessengerAction {\n return {\n actionId: action.actionId,\n messageId: action.messageId,\n raw: action.raw,\n user: toMessengerAuthor(action.user),\n value: action.value\n };\n}\n\nexport function toMessengerThread(thread: ChatThread): MessengerThread {\n return {\n channelId: thread.channelId,\n channelName: thread.channel.name ?? undefined,\n id: thread.id,\n isDirectMessage: thread.isDM,\n providerThreadId: thread.id\n };\n}\n\nexport function toMessengerMessage(message: ChatMessage): MessengerMessage {\n return {\n attachments: message.attachments.map(toMessengerAttachment),\n author: toMessengerAuthor(message.author),\n createdAt: message.metadata.dateSent,\n id: message.id,\n isMention: message.isMention,\n providerMessageId: message.id,\n raw: message.raw,\n text: message.text\n };\n}\n\nexport function toMessengerAuthor(author: ChatAuthor): MessengerAuthor {\n return {\n fullName: author.fullName || undefined,\n isBot: author.isBot,\n isMe: author.isMe,\n userId: author.userId,\n userName: author.userName || undefined\n };\n}\n\nexport function toMessengerAttachment(\n attachment: ChatAttachment\n): MessengerAttachment {\n const fetchMetadata = attachment.fetchMetadata;\n const inline: unknown = attachment.data;\n const data =\n inline instanceof ArrayBuffer || ArrayBuffer.isView(inline)\n ? attachmentBytes(inline)\n : undefined;\n const blob = inline instanceof Blob ? inline : undefined;\n return {\n data,\n fetch: attachment.fetchData\n ? async () => {\n const fetched = await attachment.fetchData?.();\n return fetched ? attachmentBytes(fetched) : new ArrayBuffer(0);\n }\n : data\n ? () => Promise.resolve(data)\n : blob\n ? () => blob.arrayBuffer()\n : undefined,\n fetchMetadata: fetchMetadata ? { ...fetchMetadata } : undefined,\n id: identifierFromFetchMetadata(fetchMetadata),\n mediaType: attachment.mimeType,\n name: attachment.name,\n raw: attachment,\n size: attachment.size,\n url: attachment.url\n };\n}\n\n/**\n * `chat` adapters resolve `fetchData` to a `Buffer` or, from `chat@4.41`\n * (inside this package's `^4.31.0` range), a plain `ArrayBuffer`. A `Buffer` is\n * a view that may share a pooled or `SharedArrayBuffer` backing store with\n * unrelated bytes, so only its own range is copied out; a view spanning its\n * whole `ArrayBuffer` hands that buffer over as is.\n */\nfunction attachmentBytes(data: ArrayBuffer | ArrayBufferView): ArrayBuffer {\n if (data instanceof ArrayBuffer) {\n return data;\n }\n if (\n data.buffer instanceof ArrayBuffer &&\n data.byteOffset === 0 &&\n data.byteLength === data.buffer.byteLength\n ) {\n return data.buffer;\n }\n const copy = new Uint8Array(data.byteLength);\n copy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));\n return copy.buffer;\n}\n\nconst FETCH_METADATA_ID_KEYS = [\"id\", \"fileId\", \"mediaId\", \"fileUniqueId\"];\n\n/**\n * Best-effort top-level id for an attachment whose adapter only records its\n * identifier in `fetchMetadata` (e.g. Telegram `fileId`). This keeps id-based\n * consumers working without per-adapter knowledge, while the full\n * `fetchMetadata` is preserved verbatim for precise re-fetching.\n */\nfunction identifierFromFetchMetadata(\n fetchMetadata: Record<string, string> | undefined\n): string | undefined {\n if (!fetchMetadata) {\n return undefined;\n }\n for (const key of FETCH_METADATA_ID_KEYS) {\n const value = fetchMetadata[key];\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n }\n return undefined;\n}\n\nfunction stableNamePart(value: string): string {\n const safe = value.replace(/[^a-zA-Z0-9:_-]/g, \"_\");\n if (safe.length <= 80) {\n return safe;\n }\n return `${safe.slice(0, 48)}_${hashString(value)}`;\n}\n\nfunction hashString(value: string): string {\n let hash = 5381;\n for (let index = 0; index < value.length; index += 1) {\n hash = (hash * 33) ^ value.charCodeAt(index);\n }\n return (hash >>> 0).toString(36);\n}\n\nfunction validatePath(path: string, id: string): void {\n if (!path.startsWith(\"/\")) {\n throw new Error(`Messenger ${id} path must start with \"/\"`);\n }\n if (path.includes(\"?\") || path.includes(\"#\")) {\n throw new Error(`Messenger ${id} path must not include query or hash`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAw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AAC;CACtE,OAAO,KAAK;AACd;AAEA,MAAM,yBAAyB;CAAC;CAAM;CAAU;CAAW;AAAc;;;;;;;AAQzE,SAAS,4BACP,eACoB;CACpB,IAAI,CAAC,eACH;CAEF,KAAK,MAAM,OAAO,wBAAwB;EACxC,MAAM,QAAQ,cAAc;EAC5B,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,GAC9C,OAAO;CAEX;AAEF;AAEA,SAAS,eAAe,OAAuB;CAC7C,MAAM,OAAO,MAAM,QAAQ,oBAAoB,GAAG;CAClD,IAAI,KAAK,UAAU,IACjB,OAAO;CAET,OAAO,GAAG,KAAK,MAAM,GAAG,EAAE,EAAE,GAAG,WAAW,KAAK;AACjD;AAEA,SAAS,WAAW,OAAuB;CACzC,IAAI,OAAO;CACX,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,GACjD,OAAQ,OAAO,KAAM,MAAM,WAAW,KAAK;CAE7C,QAAQ,SAAS,EAAA,CAAG,SAAS,EAAE;AACjC;AAEA,SAAS,aAAa,MAAc,IAAkB;CACpD,IAAI,CAAC,KAAK,WAAW,GAAG,GACtB,MAAM,IAAI,MAAM,aAAa,GAAG,0BAA0B;CAE5D,IAAI,KAAK,SAAS,GAAG,KAAK,KAAK,SAAS,GAAG,GACzC,MAAM,IAAI,MAAM,aAAa,GAAG,qCAAqC;AAEzE"}
|
|
@@ -1,17 +1,29 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
Dn as ThinkHostMessage,
|
|
3
|
+
En as ThinkHostFileEntry,
|
|
4
|
+
ar as ExtensionManifest,
|
|
5
|
+
ir as ExtensionInfo,
|
|
4
6
|
n as ExtensionManagerOptions,
|
|
5
|
-
|
|
6
|
-
|
|
7
|
+
or as ExtensionPermissions,
|
|
8
|
+
sr as ExtensionToolDescriptor,
|
|
7
9
|
t as ExtensionManager
|
|
8
|
-
} from "../manager-
|
|
10
|
+
} from "../manager-CWGumyKi.js";
|
|
9
11
|
import { WorkerEntrypoint } from "cloudflare:workers";
|
|
10
12
|
|
|
11
13
|
//#region src/extensions/host-bridge.d.ts
|
|
12
14
|
type HostBridgeLoopbackProps = {
|
|
13
15
|
agentClassName: string;
|
|
14
16
|
agentId: string;
|
|
17
|
+
/**
|
|
18
|
+
* @internal For an agent that is a sub-agent (a facet): its path from
|
|
19
|
+
* the root, root first. A facet has no namespace of its own, so calls go
|
|
20
|
+
* through the root.
|
|
21
|
+
*/
|
|
22
|
+
agentPath?: readonly {
|
|
23
|
+
className: string;
|
|
24
|
+
name: string;
|
|
25
|
+
}[] /** @internal The root's jurisdiction, with `agentPath`. */;
|
|
26
|
+
rootJurisdiction?: DurableObjectJurisdiction;
|
|
15
27
|
permissions: ExtensionPermissions /** Namespaced context labels this extension declared (for "own" write validation). */;
|
|
16
28
|
ownContextLabels?: string[];
|
|
17
29
|
};
|
|
@@ -25,88 +37,34 @@ declare class HostBridgeLoopback extends WorkerEntrypoint<
|
|
|
25
37
|
readFile(path: string): Promise<string | null>;
|
|
26
38
|
writeFile(path: string, content: string): Promise<void>;
|
|
27
39
|
deleteFile(path: string): Promise<boolean>;
|
|
28
|
-
listFiles(dir: string): Promise<
|
|
29
|
-
Array<{
|
|
30
|
-
name: string;
|
|
31
|
-
type: string;
|
|
32
|
-
size: number;
|
|
33
|
-
path: string;
|
|
34
|
-
}>
|
|
35
|
-
>;
|
|
40
|
+
listFiles(dir: string): Promise<ThinkHostFileEntry[]>;
|
|
36
41
|
getContext(label: string): Promise<string | null>;
|
|
37
42
|
setContext(label: string, content: string): Promise<void>;
|
|
38
|
-
getMessages(limit?: number): Promise<
|
|
39
|
-
Array<{
|
|
40
|
-
id: string;
|
|
41
|
-
role: string;
|
|
42
|
-
content: string;
|
|
43
|
-
}>
|
|
44
|
-
>;
|
|
43
|
+
getMessages(limit?: number): Promise<ThinkHostMessage[]>;
|
|
45
44
|
sendMessage(content: string): Promise<void>;
|
|
45
|
+
/**
|
|
46
|
+
* The extension Worker's outbound network, when its manifest lists
|
|
47
|
+
* `network` hosts: every `fetch()` it makes arrives here. A request to a
|
|
48
|
+
* host the list does not match, or to a private or local address, is
|
|
49
|
+
* refused with `403`. Redirects are not followed here, so each hop comes
|
|
50
|
+
* back through this check.
|
|
51
|
+
*
|
|
52
|
+
* @internal The runtime calls it for the extension Worker; not for apps.
|
|
53
|
+
*/
|
|
54
|
+
fetch(request: Request): Promise<Response>;
|
|
46
55
|
getSessionInfo(): Promise<{
|
|
47
56
|
messageCount: number;
|
|
48
57
|
}>;
|
|
49
58
|
}
|
|
50
59
|
//#endregion
|
|
51
|
-
//#region src/extensions/bridge-provider.d.ts
|
|
52
|
-
/**
|
|
53
|
-
* Bridge providers that adapt extension Worker RPC into Session's
|
|
54
|
-
* ContextProvider / WritableContextProvider interfaces.
|
|
55
|
-
*
|
|
56
|
-
* When an extension declares context blocks in its manifest, Think creates
|
|
57
|
-
* a bridge provider for each block. The bridge delegates `get()` and
|
|
58
|
-
* `set()` to the extension Worker's entrypoint via RPC.
|
|
59
|
-
*
|
|
60
|
-
* This allows extensions to contribute context blocks to the Session's
|
|
61
|
-
* system prompt without Session knowing about the extension system.
|
|
62
|
-
*/
|
|
63
|
-
interface ExtensionContextEntrypoint {
|
|
64
|
-
contextGet(label: string): Promise<string | null>;
|
|
65
|
-
contextSet?(
|
|
66
|
-
label: string,
|
|
67
|
-
key: string,
|
|
68
|
-
content: string,
|
|
69
|
-
description?: string
|
|
70
|
-
): Promise<void>;
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* A readonly context provider backed by an extension Worker.
|
|
74
|
-
* Delegates `get()` to the extension's `contextGet` RPC method.
|
|
75
|
-
*/
|
|
76
|
-
declare class ExtensionContextBridge {
|
|
77
|
-
protected _label: string;
|
|
78
|
-
protected _entrypoint: ExtensionContextEntrypoint;
|
|
79
|
-
constructor(label: string, entrypoint: ExtensionContextEntrypoint);
|
|
80
|
-
init(_label: string): void;
|
|
81
|
-
get(): Promise<string | null>;
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* A writable context provider backed by an extension Worker.
|
|
85
|
-
* Delegates `get()` and `set()` to the extension's RPC methods.
|
|
86
|
-
*/
|
|
87
|
-
declare class ExtensionWritableBridge extends ExtensionContextBridge {
|
|
88
|
-
set(content: string): Promise<void>;
|
|
89
|
-
}
|
|
90
|
-
/**
|
|
91
|
-
* Create the appropriate bridge provider based on the context block type.
|
|
92
|
-
*/
|
|
93
|
-
declare function createBridgeProvider(
|
|
94
|
-
label: string,
|
|
95
|
-
type: "readonly" | "writable" | "searchable",
|
|
96
|
-
entrypoint: ExtensionContextEntrypoint
|
|
97
|
-
): ExtensionContextBridge;
|
|
98
|
-
//#endregion
|
|
99
60
|
export {
|
|
100
|
-
ExtensionContextBridge,
|
|
101
61
|
type ExtensionInfo,
|
|
102
62
|
ExtensionManager,
|
|
103
63
|
type ExtensionManagerOptions,
|
|
104
64
|
type ExtensionManifest,
|
|
105
65
|
type ExtensionPermissions,
|
|
106
66
|
type ExtensionToolDescriptor,
|
|
107
|
-
ExtensionWritableBridge,
|
|
108
67
|
HostBridgeLoopback,
|
|
109
|
-
type HostBridgeLoopbackProps
|
|
110
|
-
createBridgeProvider
|
|
68
|
+
type HostBridgeLoopbackProps
|
|
111
69
|
};
|
|
112
70
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/extensions/index.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { r as _assertClassBrand } from "../classPrivateFieldSet2-DwGJfC3w.js";
|
|
2
|
-
import {
|
|
2
|
+
import { l as _classPrivateMethodInitSpec, t as ExtensionManager } from "../manager-B3rcb_6p.js";
|
|
3
|
+
import { getAgentByName } from "agents";
|
|
4
|
+
import { validateUrl } from "agents/internal";
|
|
3
5
|
import { WorkerEntrypoint } from "cloudflare:workers";
|
|
4
6
|
//#region src/extensions/host-bridge.ts
|
|
5
7
|
/**
|
|
@@ -8,7 +10,7 @@ import { WorkerEntrypoint } from "cloudflare:workers";
|
|
|
8
10
|
*
|
|
9
11
|
* This is a loopback: the extension worker's `env.host` binding points here,
|
|
10
12
|
* and each method call resolves the parent agent via `ctx.exports`, then
|
|
11
|
-
*
|
|
13
|
+
* calls the agent's `_cfHostBridge` with the operation name.
|
|
12
14
|
*
|
|
13
15
|
* Props carry serializable identifiers (agent class name, agent ID, and
|
|
14
16
|
* permissions) so the binding survives across requests and hibernation.
|
|
@@ -29,45 +31,72 @@ var HostBridgeLoopback = class extends WorkerEntrypoint {
|
|
|
29
31
|
this._permissions = this.ctx.props.permissions;
|
|
30
32
|
}
|
|
31
33
|
_getAgent() {
|
|
32
|
-
const { agentClassName, agentId } = this.ctx.props;
|
|
33
|
-
const
|
|
34
|
+
const { agentClassName, agentId, agentPath, rootJurisdiction } = this.ctx.props;
|
|
35
|
+
const exports = this.ctx.exports;
|
|
36
|
+
const [root] = agentPath ?? [];
|
|
37
|
+
if (agentPath && root && agentPath.length > 1) {
|
|
38
|
+
const rootStub = getAgentByName(exports[root.className], root.name, rootJurisdiction ? { jurisdiction: rootJurisdiction } : void 0);
|
|
39
|
+
return { _cfHostBridge: async (operation, args) => (await rootStub)._cf_invokeSubAgentPath(agentPath, "_cfHostBridge", [operation, args]) };
|
|
40
|
+
}
|
|
41
|
+
const ns = exports[agentClassName];
|
|
34
42
|
return ns.get(ns.idFromString(agentId));
|
|
35
43
|
}
|
|
36
44
|
async readFile(path) {
|
|
37
45
|
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireWorkspace).call(this, "read");
|
|
38
|
-
return this
|
|
46
|
+
return _assertClassBrand(_HostBridgeLoopback_brand, this, _call).call(this, "readFile", path);
|
|
39
47
|
}
|
|
40
48
|
async writeFile(path, content) {
|
|
41
49
|
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireWorkspace).call(this, "read-write");
|
|
42
|
-
return this
|
|
50
|
+
return _assertClassBrand(_HostBridgeLoopback_brand, this, _call).call(this, "writeFile", path, content);
|
|
43
51
|
}
|
|
44
52
|
async deleteFile(path) {
|
|
45
53
|
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireWorkspace).call(this, "read-write");
|
|
46
|
-
return this
|
|
54
|
+
return _assertClassBrand(_HostBridgeLoopback_brand, this, _call).call(this, "deleteFile", path);
|
|
47
55
|
}
|
|
48
56
|
async listFiles(dir) {
|
|
49
57
|
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireWorkspace).call(this, "read");
|
|
50
|
-
return this
|
|
58
|
+
return _assertClassBrand(_HostBridgeLoopback_brand, this, _call).call(this, "listFiles", dir);
|
|
51
59
|
}
|
|
52
60
|
async getContext(label) {
|
|
53
61
|
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireContextRead).call(this, label);
|
|
54
|
-
return this
|
|
62
|
+
return _assertClassBrand(_HostBridgeLoopback_brand, this, _call).call(this, "getContext", label);
|
|
55
63
|
}
|
|
56
64
|
async setContext(label, content) {
|
|
57
65
|
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireContextWrite).call(this, label);
|
|
58
|
-
return this
|
|
66
|
+
return _assertClassBrand(_HostBridgeLoopback_brand, this, _call).call(this, "setContext", label, content);
|
|
59
67
|
}
|
|
60
68
|
async getMessages(limit) {
|
|
61
69
|
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireMessages).call(this);
|
|
62
|
-
return this
|
|
70
|
+
return _assertClassBrand(_HostBridgeLoopback_brand, this, _call).call(this, "getMessages", limit);
|
|
63
71
|
}
|
|
64
72
|
async sendMessage(content) {
|
|
65
73
|
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireSendMessage).call(this);
|
|
66
|
-
return this
|
|
74
|
+
return _assertClassBrand(_HostBridgeLoopback_brand, this, _call).call(this, "sendMessage", content);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* The extension Worker's outbound network, when its manifest lists
|
|
78
|
+
* `network` hosts: every `fetch()` it makes arrives here. A request to a
|
|
79
|
+
* host the list does not match, or to a private or local address, is
|
|
80
|
+
* refused with `403`. Redirects are not followed here, so each hop comes
|
|
81
|
+
* back through this check.
|
|
82
|
+
*
|
|
83
|
+
* @internal The runtime calls it for the extension Worker; not for apps.
|
|
84
|
+
*/
|
|
85
|
+
async fetch(request) {
|
|
86
|
+
const hosts = this._permissions.network ?? [];
|
|
87
|
+
const checked = hosts.length === 0 ? {
|
|
88
|
+
ok: false,
|
|
89
|
+
message: "no network permission declared"
|
|
90
|
+
} : validateUrl(request.url, {
|
|
91
|
+
allowedHosts: hosts,
|
|
92
|
+
maxUrlLength: Number.POSITIVE_INFINITY
|
|
93
|
+
});
|
|
94
|
+
if (!checked.ok) return new Response(`Extension error: ${checked.message}`, { status: 403 });
|
|
95
|
+
return fetch(new Request(request, { redirect: "manual" }));
|
|
67
96
|
}
|
|
68
97
|
async getSessionInfo() {
|
|
69
98
|
_assertClassBrand(_HostBridgeLoopback_brand, this, _requireSessionMetadata).call(this);
|
|
70
|
-
return this
|
|
99
|
+
return _assertClassBrand(_HostBridgeLoopback_brand, this, _call).call(this, "getSessionInfo");
|
|
71
100
|
}
|
|
72
101
|
};
|
|
73
102
|
function _requireWorkspace(level) {
|
|
@@ -96,41 +125,10 @@ function _requireSendMessage() {
|
|
|
96
125
|
function _requireSessionMetadata() {
|
|
97
126
|
if (!this._permissions.session?.metadata) throw new Error("Extension error: no session.metadata permission declared");
|
|
98
127
|
}
|
|
99
|
-
|
|
100
|
-
|
|
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
|
-
* Create the appropriate bridge provider based on the context block type.
|
|
126
|
-
*/
|
|
127
|
-
function createBridgeProvider(label, type, entrypoint) {
|
|
128
|
-
switch (type) {
|
|
129
|
-
case "writable": return new ExtensionWritableBridge(label, entrypoint);
|
|
130
|
-
default: return new ExtensionContextBridge(label, entrypoint);
|
|
131
|
-
}
|
|
128
|
+
function _call(operation, ...args) {
|
|
129
|
+
return this._getAgent()._cfHostBridge(operation, args);
|
|
132
130
|
}
|
|
133
131
|
//#endregion
|
|
134
|
-
export {
|
|
132
|
+
export { ExtensionManager, HostBridgeLoopback };
|
|
135
133
|
|
|
136
134
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/extensions/host-bridge.ts","../../src/extensions/bridge-provider.ts"],"sourcesContent":["/**\n * HostBridgeLoopback — a WorkerEntrypoint that provides controlled workspace\n * access to extension Workers loaded via WorkerLoader.\n *\n * This is a loopback: the extension worker's `env.host` binding points here,\n * and each method call resolves the parent agent via `ctx.exports`, then\n * delegates to the agent's workspace proxy methods (`_hostReadFile`, etc.).\n *\n * Props carry serializable identifiers (agent class name, agent ID, and\n * permissions) so the binding survives across requests and hibernation.\n *\n * Users must re-export this class from their worker entry point:\n *\n * ```typescript\n * export { HostBridgeLoopback } from \"@cloudflare/think/extensions\";\n * ```\n *\n * @experimental The API surface may change before stabilizing.\n */\n\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport type { ExtensionPermissions } from \"./types\";\n\nexport type HostBridgeLoopbackProps = {\n agentClassName: string;\n agentId: string;\n permissions: ExtensionPermissions;\n /** Namespaced context labels this extension declared (for \"own\" write validation). */\n ownContextLabels?: string[];\n};\n\nexport class HostBridgeLoopback extends WorkerEntrypoint<\n Record<string, unknown>,\n HostBridgeLoopbackProps\n> {\n private _permissions = this.ctx.props.permissions;\n\n private _getAgent() {\n const { agentClassName, agentId } = this.ctx.props;\n // @ts-expect-error — experimental: ctx.exports on WorkerEntrypoint\n const ns = this.ctx.exports[agentClassName] as DurableObjectNamespace;\n return ns.get(ns.idFromString(agentId));\n }\n\n // ── Permission checks ──────────────────────────────────────────\n\n #requireWorkspace(level: \"read\" | \"read-write\"): void {\n const ws = this._permissions.workspace ?? \"none\";\n if (ws === \"none\") {\n throw new Error(\"Extension error: no workspace permission declared\");\n }\n if (level === \"read-write\" && ws !== \"read-write\") {\n throw new Error(\n \"Extension error: workspace write permission required, but only read granted\"\n );\n }\n }\n\n #requireContextRead(label: string): void {\n const ctx = this._permissions.context;\n if (!ctx?.read) {\n throw new Error(\"Extension error: no context read permission declared\");\n }\n if (ctx.read !== \"all\" && !ctx.read.includes(label)) {\n throw new Error(\n `Extension error: no read permission for context label \"${label}\"`\n );\n }\n }\n\n #requireContextWrite(label: string): void {\n const ctx = this._permissions.context;\n if (!ctx?.write) {\n throw new Error(\"Extension error: no context write permission declared\");\n }\n if (ctx.write === \"own\") {\n const owned = this.ctx.props.ownContextLabels ?? [];\n if (!owned.includes(label)) {\n throw new Error(\n `Extension error: label \"${label}\" is not owned by this extension`\n );\n }\n } else if (!ctx.write.includes(label)) {\n throw new Error(\n `Extension error: no write permission for context label \"${label}\"`\n );\n }\n }\n\n #requireMessages(): void {\n if (this._permissions.messages !== \"read\") {\n throw new Error(\"Extension error: no messages read permission declared\");\n }\n }\n\n #requireSendMessage(): void {\n if (!this._permissions.session?.sendMessage) {\n throw new Error(\n \"Extension error: no session.sendMessage permission declared\"\n );\n }\n }\n\n #requireSessionMetadata(): void {\n if (!this._permissions.session?.metadata) {\n throw new Error(\n \"Extension error: no session.metadata permission declared\"\n );\n }\n }\n\n // ── Workspace (existing) ───────────────────────────────────────\n\n async readFile(path: string): Promise<string | null> {\n this.#requireWorkspace(\"read\");\n return (\n this._getAgent() as unknown as {\n _hostReadFile(path: string): Promise<string | null>;\n }\n )._hostReadFile(path);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n this.#requireWorkspace(\"read-write\");\n return (\n this._getAgent() as unknown as {\n _hostWriteFile(path: string, content: string): Promise<void>;\n }\n )._hostWriteFile(path, content);\n }\n\n async deleteFile(path: string): Promise<boolean> {\n this.#requireWorkspace(\"read-write\");\n return (\n this._getAgent() as unknown as {\n _hostDeleteFile(path: string): Promise<boolean>;\n }\n )._hostDeleteFile(path);\n }\n\n async listFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n > {\n this.#requireWorkspace(\"read\");\n return (\n this._getAgent() as unknown as {\n _hostListFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n >;\n }\n )._hostListFiles(dir);\n }\n\n // ── Context blocks (new) ───────────────────────────────────────\n\n async getContext(label: string): Promise<string | null> {\n this.#requireContextRead(label);\n return (\n this._getAgent() as unknown as {\n _hostGetContext(label: string): Promise<string | null>;\n }\n )._hostGetContext(label);\n }\n\n async setContext(label: string, content: string): Promise<void> {\n this.#requireContextWrite(label);\n return (\n this._getAgent() as unknown as {\n _hostSetContext(label: string, content: string): Promise<void>;\n }\n )._hostSetContext(label, content);\n }\n\n // ── Messages (new) ────────────────────────────────────────────\n\n async getMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>> {\n this.#requireMessages();\n return (\n this._getAgent() as unknown as {\n _hostGetMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>>;\n }\n )._hostGetMessages(limit);\n }\n\n async sendMessage(content: string): Promise<void> {\n this.#requireSendMessage();\n return (\n this._getAgent() as unknown as {\n _hostSendMessage(content: string): Promise<void>;\n }\n )._hostSendMessage(content);\n }\n\n // ── Session metadata (new) ────────────────────────────────────\n\n async getSessionInfo(): Promise<{ messageCount: number }> {\n this.#requireSessionMetadata();\n return (\n this._getAgent() as unknown as {\n _hostGetSessionInfo(): Promise<{ messageCount: number }>;\n }\n )._hostGetSessionInfo();\n }\n}\n","/**\n * Bridge providers that adapt extension Worker RPC into Session's\n * ContextProvider / 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()` and\n * `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 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 * Create the appropriate bridge provider based on the context block type.\n */\nexport function createBridgeProvider(\n label: string,\n type: \"readonly\" | \"writable\" | \"searchable\",\n entrypoint: ExtensionContextEntrypoint\n) {\n switch (type) {\n case \"writable\":\n return new ExtensionWritableBridge(label, entrypoint);\n case \"readonly\":\n case \"searchable\":\n default:\n return new ExtensionContextBridge(label, entrypoint);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,qBAAb,cAAwC,iBAGtC;;;;EACA,KAAQ,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AgC;CAC9B,IAAI,CAAC,KAAK,aAAa,SAAS,UAC9B,MAAM,IAAI,MACR,0DACF;AAEJ;;;;;;;ACnFF,IAAa,yBAAb,MAAoC;CAIlC,YAAY,OAAe,YAAwC;EACjE,KAAK,SAAS;EACd,KAAK,cAAc;CACrB;CAEA,KAAK,QAAsB,CAAC;CAE5B,MAAM,MAA8B;EAClC,OAAO,KAAK,YAAY,WAAW,KAAK,MAAM;CAChD;AACF;;;;;AAMA,IAAa,0BAAb,cAA6C,uBAAuB;CAClE,MAAM,IAAI,SAAgC;EACxC,MAAM,KAAK,YAAY,aAAa,KAAK,QAAQ,IAAI,OAAO;CAC9D;AACF;;;;AAKA,SAAgB,qBACd,OACA,MACA,YACA;CACA,QAAQ,MAAR;EACE,KAAK,YACH,OAAO,IAAI,wBAAwB,OAAO,UAAU;EAGtD,SACE,OAAO,IAAI,uBAAuB,OAAO,UAAU;CACvD;AACF"}
|
|
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 * calls the agent's `_cfHostBridge` with the operation name.\n *\n * Props carry serializable identifiers (agent class name, agent ID, and\n * permissions) so the binding survives across requests and hibernation.\n *\n * Users must re-export this class from their worker entry point:\n *\n * ```typescript\n * export { HostBridgeLoopback } from \"@cloudflare/think/extensions\";\n * ```\n *\n * @experimental The API surface may change before stabilizing.\n */\n\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport { getAgentByName, type Agent } from \"agents\";\nimport { validateUrl } from \"agents/internal\";\nimport type {\n ThinkHostApi,\n ThinkHostFileEntry,\n ThinkHostMessage,\n ThinkHostOperation\n} from \"./host-api\";\nimport type { ExtensionPermissions } from \"./types\";\n\n/** The agent side of the loopback: the Think agent's host entry point. */\ntype ThinkHostBridgeAgent = {\n _cfHostBridge<K extends ThinkHostOperation>(\n operation: K,\n args: Parameters<ThinkHostApi[K]>\n ): Promise<Awaited<ReturnType<ThinkHostApi[K]>>>;\n};\n\nexport type HostBridgeLoopbackProps = {\n agentClassName: string;\n agentId: string;\n /**\n * @internal For an agent that is a sub-agent (a facet): its path from\n * the root, root first. A facet has no namespace of its own, so calls go\n * through the root.\n */\n agentPath?: readonly { className: string; name: string }[];\n /** @internal The root's jurisdiction, with `agentPath`. */\n rootJurisdiction?: DurableObjectJurisdiction;\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(): ThinkHostBridgeAgent {\n const { agentClassName, agentId, agentPath, rootJurisdiction } =\n this.ctx.props;\n // Experimental: ctx.exports on WorkerEntrypoint.\n const exports = (\n this.ctx as unknown as {\n exports: Record<string, DurableObjectNamespace>;\n }\n ).exports;\n const [root] = agentPath ?? [];\n if (agentPath && root && agentPath.length > 1) {\n // As `parentAgent()` reaches a facet parent: the root by name, in\n // its jurisdiction, then down the path.\n const rootStub = getAgentByName(\n exports[root.className] as unknown as DurableObjectNamespace<Agent>,\n root.name,\n rootJurisdiction ? { jurisdiction: rootJurisdiction } : undefined\n ) as unknown as Promise<{\n _cf_invokeSubAgentPath(\n path: readonly { className: string; name: string }[],\n method: string,\n args: unknown[]\n ): Promise<unknown>;\n }>;\n return {\n _cfHostBridge: async (operation, args) =>\n (await rootStub)._cf_invokeSubAgentPath(agentPath, \"_cfHostBridge\", [\n operation,\n args\n ]) as never\n };\n }\n const ns = exports[agentClassName];\n return ns.get(ns.idFromString(agentId)) as unknown as ThinkHostBridgeAgent;\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 #call<K extends ThinkHostOperation>(\n operation: K,\n ...args: Parameters<ThinkHostApi[K]>\n ): Promise<Awaited<ReturnType<ThinkHostApi[K]>>> {\n return this._getAgent()._cfHostBridge(operation, args);\n }\n\n // ── Workspace ──────────────────────────────────────────────────\n\n async readFile(path: string): Promise<string | null> {\n this.#requireWorkspace(\"read\");\n return this.#call(\"readFile\", path);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n this.#requireWorkspace(\"read-write\");\n return this.#call(\"writeFile\", path, content);\n }\n\n async deleteFile(path: string): Promise<boolean> {\n this.#requireWorkspace(\"read-write\");\n return this.#call(\"deleteFile\", path);\n }\n\n async listFiles(dir: string): Promise<ThinkHostFileEntry[]> {\n this.#requireWorkspace(\"read\");\n return this.#call(\"listFiles\", dir);\n }\n\n // ── Context blocks ─────────────────────────────────────────────\n\n async getContext(label: string): Promise<string | null> {\n this.#requireContextRead(label);\n return this.#call(\"getContext\", label);\n }\n\n async setContext(label: string, content: string): Promise<void> {\n this.#requireContextWrite(label);\n return this.#call(\"setContext\", label, content);\n }\n\n // ── Messages ───────────────────────────────────────────────────\n\n async getMessages(limit?: number): Promise<ThinkHostMessage[]> {\n this.#requireMessages();\n return this.#call(\"getMessages\", limit);\n }\n\n async sendMessage(content: string): Promise<void> {\n this.#requireSendMessage();\n return this.#call(\"sendMessage\", content);\n }\n\n // ── Network ────────────────────────────────────────────────────\n\n /**\n * The extension Worker's outbound network, when its manifest lists\n * `network` hosts: every `fetch()` it makes arrives here. A request to a\n * host the list does not match, or to a private or local address, is\n * refused with `403`. Redirects are not followed here, so each hop comes\n * back through this check.\n *\n * @internal The runtime calls it for the extension Worker; not for apps.\n */\n async fetch(request: Request): Promise<Response> {\n const hosts = this._permissions.network ?? [];\n const checked =\n hosts.length === 0\n ? { ok: false as const, message: \"no network permission declared\" }\n : validateUrl(request.url, {\n allowedHosts: hosts,\n maxUrlLength: Number.POSITIVE_INFINITY\n });\n if (!checked.ok) {\n return new Response(`Extension error: ${checked.message}`, {\n status: 403\n });\n }\n return fetch(new Request(request, { redirect: \"manual\" }));\n }\n\n // ── Session metadata ───────────────────────────────────────────\n\n async getSessionInfo(): Promise<{ messageCount: number }> {\n this.#requireSessionMetadata();\n return this.#call(\"getSessionInfo\");\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,IAAa,qBAAb,cAAwC,iBAGtC;;;;EACA,KAAQ,eAAe,KAAK,IAAI,MAAM;;CAEtC,YAA0C;EACxC,MAAM,EAAE,gBAAgB,SAAS,WAAW,qBAC1C,KAAK,IAAI;EAEX,MAAM,UACJ,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B,OAAO,cACnC,MAAM,IAAI,MACR,6EACF;AAEJ;AAEA,SAAA,oBAAoB,OAAqB;CACvC,MAAM,MAAM,KAAK,aAAa;CAC9B,IAAI,CAAC,KAAK,MACR,MAAM,IAAI,MAAM,sDAAsD;CAExE,IAAI,IAAI,SAAS,SAAS,CAAC,IAAI,KAAK,SAAS,KAAK,GAChD,MAAM,IAAI,MACR,0DAA0D,MAAM,EAClE;AAEJ;AAEA,SAAA,qBAAqB,OAAqB;CACxC,MAAM,MAAM,KAAK,aAAa;CAC9B,IAAI,CAAC,KAAK,OACR,MAAM,IAAI,MAAM,uDAAuD;CAEzE,IAAI,IAAI,UAAU;MAEZ,EADU,KAAK,IAAI,MAAM,oBAAoB,CAAC,EAAA,CACvC,SAAS,KAAK,GACvB,MAAM,IAAI,MACR,2BAA2B,MAAM,iCACnC;CAAA,OAEG,IAAI,CAAC,IAAI,MAAM,SAAS,KAAK,GAClC,MAAM,IAAI,MACR,2DAA2D,MAAM,EACnE;AAEJ;AAEA,SAAA,mBAAyB;CACvB,IAAI,KAAK,aAAa,aAAa,QACjC,MAAM,IAAI,MAAM,uDAAuD;AAE3E;AAEA,SAAA,sBAA4B;CAC1B,IAAI,CAAC,KAAK,aAAa,SAAS,aAC9B,MAAM,IAAI,MACR,6DACF;AAEJ;AAEA,SAAA,0BAAgC;CAC9B,IAAI,CAAC,KAAK,aAAa,SAAS,UAC9B,MAAM,IAAI,MACR,0DACF;AAEJ;AAEA,SAAA,MACE,WACA,GAAG,MAC4C;CAC/C,OAAO,KAAK,UAAU,CAAC,CAAC,cAAc,WAAW,IAAI;AACvD"}
|
|
@@ -127,6 +127,14 @@ function parentDirectory(path) {
|
|
|
127
127
|
function joinPath(directory, name) {
|
|
128
128
|
return directory.endsWith("/") ? `${directory}${name}` : `${directory}/${name}`;
|
|
129
129
|
}
|
|
130
|
+
/**
|
|
131
|
+
* Whether a workspace is a Computer `Workspace` this agent owns, as opposed
|
|
132
|
+
* to a client for one another Durable Object owns. Checked by shape so a
|
|
133
|
+
* second copy of `@cloudflare/computer` in the bundle still matches.
|
|
134
|
+
*/
|
|
135
|
+
function isLocalWorkspace(workspace) {
|
|
136
|
+
return "ready" in workspace && typeof workspace.ready === "function" && "stub" in workspace && typeof workspace.stub === "function";
|
|
137
|
+
}
|
|
130
138
|
//#endregion
|
|
131
139
|
//#region src/tools/fetch.ts
|
|
132
140
|
const DEFAULT_MAX_BYTES = 1e6;
|
|
@@ -722,6 +730,6 @@ function toModelOutput(output) {
|
|
|
722
730
|
};
|
|
723
731
|
}
|
|
724
732
|
//#endregion
|
|
725
|
-
export { WorkspaceFiles as n,
|
|
733
|
+
export { resolveWorkspacePath as i, WorkspaceFiles as n, isLocalWorkspace as r, createFetchTools as t };
|
|
726
734
|
|
|
727
|
-
//# sourceMappingURL=fetch-
|
|
735
|
+
//# sourceMappingURL=fetch-BbYxtlff.js.map
|