agents 0.24.0 → 0.26.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/dist/{agent-routing-B2XLNMxq.d.ts → agent-routing-0DR0Tk2v.d.ts} +205 -132
- package/dist/agent-routing.d.ts +1 -1
- package/dist/agent-routing.js.map +1 -1
- package/dist/agent-tool-types.d.ts +28 -22
- package/dist/agent-tool-types.js +23 -1
- package/dist/agent-tool-types.js.map +1 -1
- package/dist/{agent-tools-y7zLfw4Q.js → agent-tools-CdJC-8Dc.js} +72 -9
- package/dist/agent-tools-CdJC-8Dc.js.map +1 -0
- package/dist/{agent-tools-Dj5Mzlw7.d.ts → agent-tools-YrATZJu2.d.ts} +34 -20
- package/dist/agent-tools.d.ts +20 -18
- package/dist/agent-tools.js.map +1 -1
- package/dist/ai-fm7xx1BK.js +312 -0
- package/dist/ai-fm7xx1BK.js.map +1 -0
- package/dist/base64-redaction-C1Uu29t5.js +59 -0
- package/dist/base64-redaction-C1Uu29t5.js.map +1 -0
- package/dist/browser/ai-sdk.d.ts +90 -0
- package/dist/browser/ai-sdk.js +51 -0
- package/dist/browser/ai-sdk.js.map +1 -0
- package/dist/browser/ai.d.ts +4 -4
- package/dist/browser/ai.js +1 -347
- package/dist/browser/index.d.ts +81 -79
- package/dist/browser/index.js +361 -2
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/tanstack-ai.d.ts +96 -1
- package/dist/browser/tanstack-ai.js +62 -2
- package/dist/browser/tanstack-ai.js.map +1 -1
- package/dist/browser-DE3d-RLk.d.ts +275 -0
- package/dist/browser-tool-CQ10e6Kj.js +480 -0
- package/dist/browser-tool-CQ10e6Kj.js.map +1 -0
- package/dist/browser-tool-DuNdlwZ9.d.ts +73 -0
- package/dist/capability-B4WbF81e.js.map +1 -1
- package/dist/{capability-runner-BUBa6Ake.d.ts → capability-runner-DBAnGr6L.d.ts} +7 -2
- package/dist/chat/index.d.ts +340 -234
- package/dist/chat/index.js +592 -66
- package/dist/chat/index.js.map +1 -1
- package/dist/chat/react.d.ts +42 -2
- package/dist/chat/react.js +191 -35
- package/dist/chat/react.js.map +1 -1
- package/dist/chat/transport.d.ts +1 -1
- package/dist/chat/transport.js +1 -1
- package/dist/chat-sdk/index.d.ts +17 -3
- package/dist/chat-sdk/index.js +28 -2
- package/dist/chat-sdk/index.js.map +1 -1
- package/dist/{client-C9DAjZIY.js → client-4OlMIJx-.js} +102 -29
- package/dist/client-4OlMIJx-.js.map +1 -0
- package/dist/{client-BxdkCuVy.d.ts → client-je3koD9Z.d.ts} +45 -10
- package/dist/client.d.ts +7 -5
- package/dist/client.js +2 -2
- package/dist/{connector-CptFKzRh.js → connector-58XDGvc3.js} +251 -120
- package/dist/connector-58XDGvc3.js.map +1 -0
- package/dist/{connector-CkQD4MK3.d.ts → connector-Cl-VqPmA.d.ts} +244 -146
- package/dist/context/index.d.ts +29 -0
- package/dist/context/index.js +64 -17
- package/dist/context/index.js.map +1 -1
- package/dist/current-agent-DhoDkSnH.js.map +1 -1
- package/dist/{current-agent-C4w86kcN.d.ts → current-agent-vAk_5JMt.d.ts} +4 -4
- package/dist/{durable-object-lifecycle-ei7M7lqB.d.ts → durable-object-lifecycle-HhgOMWq9.d.ts} +15 -7
- package/dist/harness/pi/index.d.ts +344 -0
- package/dist/harness/pi/index.js +873 -0
- package/dist/harness/pi/index.js.map +1 -0
- package/dist/images-iiTDSyRu.js +1631 -0
- package/dist/images-iiTDSyRu.js.map +1 -0
- package/dist/{index-Dlgtd3Mj.d.ts → index-BreL0YrQ.d.ts} +2 -2
- package/dist/index-kbSUIer3.d.ts +343 -0
- package/dist/index.d.ts +46 -44
- package/dist/index.js +1 -1
- package/dist/internal_context.d.ts +1 -1
- package/dist/lifecycle/index.d.ts +3 -3
- package/dist/lifecycle/index.js +1 -1
- package/dist/{lifecycle-Mm_jQh7r.js → lifecycle-CFu6OV03.js} +39 -10
- package/dist/{lifecycle-Mm_jQh7r.js.map → lifecycle-CFu6OV03.js.map} +1 -1
- package/dist/mcp/client/index.d.ts +20 -20
- package/dist/mcp/client/x402.js +21 -19
- package/dist/mcp/client/x402.js.map +1 -1
- package/dist/mcp/index.d.ts +35 -35
- package/dist/mcp/index.js +1 -1
- package/dist/{message-builder-BymO4N_D.js → message-builder-DAl9AhHH.js} +89 -4
- package/dist/message-builder-DAl9AhHH.js.map +1 -0
- package/dist/models/ai-sdk/index.d.ts +353 -0
- package/dist/models/ai-sdk/index.js +2443 -0
- package/dist/models/ai-sdk/index.js.map +1 -0
- package/dist/models/pi-ai/index.d.ts +313 -0
- package/dist/models/pi-ai/index.js +1795 -0
- package/dist/models/pi-ai/index.js.map +1 -0
- package/dist/observability/ai/index.js +20 -4
- package/dist/observability/ai/index.js.map +1 -1
- package/dist/{protocol-B0nh6KNf.js → protocol-kHsr-f0X.js} +26 -12
- package/dist/{protocol-B0nh6KNf.js.map → protocol-kHsr-f0X.js.map} +1 -1
- package/dist/queue/index.d.ts +3 -3
- package/dist/queue/index.js +1 -1
- package/dist/{queue-BC9F5cUo.js → queue-BB-zfIYF.js} +2 -2
- package/dist/{queue-BC9F5cUo.js.map → queue-BB-zfIYF.js.map} +1 -1
- package/dist/react.d.ts +6 -6
- package/dist/react.js +160 -64
- package/dist/react.js.map +1 -1
- package/dist/{retries-D9B2UCq3.d.ts → retries-CV6AkXmQ.d.ts} +18 -9
- package/dist/retries.d.ts +11 -9
- package/dist/retries.js +11 -1
- package/dist/retries.js.map +1 -1
- package/dist/routing/index.d.ts +2 -2
- package/dist/routing/index.js +1 -1
- package/dist/{scheduler-D_KHqxBa.js → scheduler-DZ3xQfeK.js} +2 -2
- package/dist/{scheduler-D_KHqxBa.js.map → scheduler-DZ3xQfeK.js.map} +1 -1
- package/dist/{scheduler-BGq6M5Kd.d.ts → scheduler-RdACNXDP.d.ts} +3 -3
- package/dist/schedules/index.d.ts +1 -1
- package/dist/schedules/index.js +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/sessions/index.d.ts +70 -3
- package/dist/sessions/index.js +276 -67
- package/dist/sessions/index.js.map +1 -1
- package/dist/skills/index.d.ts +29 -314
- package/dist/socket-address.d.ts +16 -0
- package/dist/socket-address.js +19 -0
- package/dist/socket-address.js.map +1 -0
- package/dist/{src-BNU3ZiJM.js → src-BZeu-SCD.js} +423 -115
- package/dist/src-BZeu-SCD.js.map +1 -0
- package/dist/state/index.d.ts +1 -1
- package/dist/state/index.js +1 -1
- package/dist/streams/index.d.ts +1 -1
- package/dist/streams/index.js +1 -1
- package/dist/{streams-BcE8JP2X.d.ts → streams-Cmkj9QfW.d.ts} +4 -2
- package/dist/{streams-CCPRV6dt.js → streams-DW-UCOUc.js} +9 -2
- package/dist/streams-DW-UCOUc.js.map +1 -0
- package/dist/sub-routing.d.ts +12 -12
- package/dist/tasks/index.d.ts +1 -1
- package/dist/tasks/index.js +1 -1
- package/dist/{tasks-D4nLqVSI.js → tasks-68DESxf0.js} +2 -2
- package/dist/{tasks-D4nLqVSI.js.map → tasks-68DESxf0.js.map} +1 -1
- package/dist/{tasks-V2lCT8ZV.d.ts → tasks-9YxYtByh.d.ts} +2 -2
- package/dist/transport-PfFnt-Ld.d.ts +525 -0
- package/dist/{types-DCD6BNZH.d.ts → types-BA4anrjI.d.ts} +2 -2
- package/dist/voice/index.d.ts +2 -2
- package/dist/websockets/index.d.ts +23 -6
- package/dist/websockets/index.js +1 -1
- package/dist/{websockets-D7IzWbZb.js → websockets-Ci-LZFHH.js} +45 -20
- package/dist/{websockets-D7IzWbZb.js.map → websockets-Ci-LZFHH.js.map} +1 -1
- package/dist/wire-types-CnMt6_HR.js.map +1 -1
- package/dist/wire-types-CrjKvDyi.d.ts +300 -0
- package/dist/workflow-types.d.ts +25 -25
- package/dist/workflows.d.ts +21 -21
- package/dist/workflows.js +1 -1
- package/dist/{ws-chat-transport-UNRIS2xl.d.ts → ws-chat-transport-BbT1A5Lc.d.ts} +51 -2
- package/dist/{ws-chat-transport-rWwta645.js → ws-chat-transport-cqMKq3IY.js} +143 -16
- package/dist/ws-chat-transport-cqMKq3IY.js.map +1 -0
- package/docs/agent-tools.md +29 -4
- package/docs/browse-the-web.md +87 -5
- package/docs/chat-agents.md +124 -16
- package/docs/context.md +27 -0
- package/docs/durable-execution.md +2 -0
- package/docs/harnesses/pi.md +173 -0
- package/docs/human-in-the-loop.md +4 -0
- package/docs/index.md +3 -0
- package/docs/lifecycle.md +20 -4
- package/docs/models-pi-ai.md +325 -0
- package/docs/models.md +504 -0
- package/docs/resumable-streaming.md +2 -0
- package/docs/routing.md +13 -13
- package/docs/sessions.md +36 -1
- package/docs/state.md +1 -0
- package/docs/sub-agents.md +9 -0
- package/package.json +40 -2
- package/dist/agent-tools-y7zLfw4Q.js.map +0 -1
- package/dist/browser/ai.js.map +0 -1
- package/dist/client-C9DAjZIY.js.map +0 -1
- package/dist/client-tools-aIBO0Fk7.d.ts +0 -53
- package/dist/connector-CptFKzRh.js.map +0 -1
- package/dist/message-builder-BymO4N_D.js.map +0 -1
- package/dist/src-BNU3ZiJM.js.map +0 -1
- package/dist/streams-CCPRV6dt.js.map +0 -1
- package/dist/ws-chat-transport-rWwta645.js.map +0 -1
|
@@ -2,9 +2,9 @@ import { camelCaseToKebabCase } from "./utils.js";
|
|
|
2
2
|
import "./types.js";
|
|
3
3
|
import { a as isCapnWebTransportUpgrade, n as CAPNWEB_TRANSPORT_SEND } from "./transport-protocol-BxyngQ_R.js";
|
|
4
4
|
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, r as _assertClassBrand, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-DZBYAB34.js";
|
|
5
|
-
import { t as LifecycleCapability } from "./capability-B4WbF81e.js";
|
|
6
5
|
import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-qMjJ6sHQ.js";
|
|
7
|
-
import "./
|
|
6
|
+
import { t as LifecycleCapability } from "./capability-B4WbF81e.js";
|
|
7
|
+
import "./lifecycle-CFu6OV03.js";
|
|
8
8
|
import { newWebSocketRpcSession } from "capnweb";
|
|
9
9
|
import { RpcTarget as RpcTarget$1 } from "cloudflare:workers";
|
|
10
10
|
import { nanoid } from "nanoid";
|
|
@@ -703,15 +703,41 @@ var WebSockets = class extends LifecycleCapability {
|
|
|
703
703
|
return _get_connectionManager.call(_assertClassBrand(_WebSockets_brand, this)).getConnection(id);
|
|
704
704
|
}
|
|
705
705
|
/**
|
|
706
|
-
* Send the identity frame,
|
|
707
|
-
*
|
|
708
|
-
*
|
|
709
|
-
*
|
|
706
|
+
* Send the connect sequence: the identity frame, then the current state
|
|
707
|
+
* when one is stored. The identity carries `stateFollows` in that case,
|
|
708
|
+
* so clients resolve `ready` only once the state has landed. Nothing is
|
|
709
|
+
* sent to a no-protocol connection. Identity defaults as for
|
|
710
|
+
* `sendIdentity()`.
|
|
710
711
|
*/
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
712
|
+
sendConnectFrames(connection, identity = _assertClassBrand(_WebSockets_brand, this, _defaultIdentity).call(this)) {
|
|
713
|
+
if (!isConnectionProtocolEnabled(connection)) return;
|
|
714
|
+
_classPrivateFieldGet2(_connecting, this).add(connection);
|
|
715
|
+
try {
|
|
716
|
+
const current = _classPrivateFieldGet2(_state, this)?.get();
|
|
717
|
+
const stateFrame = current === void 0 ? void 0 : JSON.stringify({
|
|
718
|
+
type: "cf_agent_state",
|
|
719
|
+
state: current
|
|
720
|
+
});
|
|
721
|
+
_assertClassBrand(_WebSockets_brand, this, _sendFrame).call(this, connection, {
|
|
722
|
+
type: "cf_agent_identity",
|
|
723
|
+
name: identity.name,
|
|
724
|
+
agent: identity.agent,
|
|
725
|
+
...stateFrame !== void 0 && { stateFollows: true }
|
|
726
|
+
});
|
|
727
|
+
if (stateFrame !== void 0) _assertClassBrand(_WebSockets_brand, this, _send).call(this, connection, stateFrame);
|
|
728
|
+
} finally {
|
|
729
|
+
_classPrivateFieldGet2(_connecting, this).delete(connection);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
/**
|
|
733
|
+
* Send the identity frame alone, unless the connection is no-protocol.
|
|
734
|
+
* Clients resolve `ready` on it, so a host that also pushes state on
|
|
735
|
+
* connect should use `sendConnectFrames()`. The defaults are the Durable
|
|
736
|
+
* Object's routed name and host class; a host whose public identity
|
|
737
|
+
* differs — an `Agent` facet, whose routed name is an internal encoding
|
|
738
|
+
* of its logical name — passes its own.
|
|
739
|
+
*/
|
|
740
|
+
sendIdentity(connection, identity = _assertClassBrand(_WebSockets_brand, this, _defaultIdentity).call(this)) {
|
|
715
741
|
if (!isConnectionProtocolEnabled(connection)) return;
|
|
716
742
|
_assertClassBrand(_WebSockets_brand, this, _sendFrame).call(this, connection, {
|
|
717
743
|
type: "cf_agent_identity",
|
|
@@ -808,15 +834,8 @@ function _get_connectionManager() {
|
|
|
808
834
|
async function _connect(connection, ctx) {
|
|
809
835
|
ensureConnectionWrapped(connection);
|
|
810
836
|
if (_classPrivateFieldGet2(_readonly, this)?.call(this, connection, ctx)) setConnectionReadonly(connection, true);
|
|
811
|
-
if (_classPrivateFieldGet2(_protocol, this) !== false) if (typeof _classPrivateFieldGet2(_protocol, this) === "function" ? _classPrivateFieldGet2(_protocol, this).call(this, connection, ctx) : true)
|
|
812
|
-
|
|
813
|
-
try {
|
|
814
|
-
this.sendIdentity(connection);
|
|
815
|
-
this.sendState(connection);
|
|
816
|
-
} finally {
|
|
817
|
-
_classPrivateFieldGet2(_connecting, this).delete(connection);
|
|
818
|
-
}
|
|
819
|
-
} else setConnectionProtocolEnabled(connection, false);
|
|
837
|
+
if (_classPrivateFieldGet2(_protocol, this) !== false) if (typeof _classPrivateFieldGet2(_protocol, this) === "function" ? _classPrivateFieldGet2(_protocol, this).call(this, connection, ctx) : true) this.sendConnectFrames(connection);
|
|
838
|
+
else setConnectionProtocolEnabled(connection, false);
|
|
820
839
|
await this.lifecycle.runInHostContext(() => _classPrivateFieldGet2(_handlers, this)?.onConnect?.(connection, ctx), {
|
|
821
840
|
connection,
|
|
822
841
|
request: ctx.request
|
|
@@ -881,6 +900,12 @@ async function _acceptCapnWebSession(request) {
|
|
|
881
900
|
});
|
|
882
901
|
return response;
|
|
883
902
|
}
|
|
903
|
+
function _defaultIdentity() {
|
|
904
|
+
return {
|
|
905
|
+
name: this.lifecycle.name,
|
|
906
|
+
agent: camelCaseToKebabCase(this.lifecycle.className)
|
|
907
|
+
};
|
|
908
|
+
}
|
|
884
909
|
/**
|
|
885
910
|
* Send one protocol frame. Serialization is the caller's contract — every
|
|
886
911
|
* frame built here is plain JSON — while a send failure is tolerated: the
|
|
@@ -1002,4 +1027,4 @@ async function _dispatchCallable(name, invoke, connection) {
|
|
|
1002
1027
|
//#endregion
|
|
1003
1028
|
export { getConnectionFlag as a, isConnectionReadonly as c, setConnectionProtocolEnabled as d, setConnectionReadonly as f, ensureConnectionWrapped as i, registerInternalConnectionKeys as l, CF_NO_PROTOCOL_KEY as n, getConnectionRawState as o, CF_READONLY_KEY as r, isConnectionProtocolEnabled as s, WebSockets as t, setConnectionFlag as u };
|
|
1004
1029
|
|
|
1005
|
-
//# sourceMappingURL=websockets-
|
|
1030
|
+
//# sourceMappingURL=websockets-Ci-LZFHH.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"websockets-D7IzWbZb.js","names":["RpcTarget","RpcTarget"],"sources":["../src/websockets/connection-flags.ts","../src/websockets/connection.ts","../src/websockets/callables-target.ts","../src/websockets/transport.ts","../src/websockets/websockets.ts"],"sourcesContent":["import type { Connection } from \"../lifecycle\";\n\n/**\n * Internal per-connection flags, stored inside the connection's own state\n * under `_cf_`-prefixed keys so they ride the hibernation attachment (or a\n * bridged connection's synced state) and survive a wake. The state wrapper\n * installed by {@link ensureConnectionWrapped} hides them from\n * `connection.state` and preserves them across user `setState` calls.\n *\n * Owned by the WebSockets capability; `Agent` and framework mixins reach it\n * through the capability or, for their own keys, through\n * {@link registerInternalConnectionKeys}.\n */\n\n/** A readonly connection may not update host state. */\nexport const CF_READONLY_KEY = \"_cf_readonly\";\n\n/**\n * A no-protocol connection receives no protocol text frames (identity,\n * state sync, MCP servers) — neither on connect nor via broadcasts.\n */\nexport const CF_NO_PROTOCOL_KEY = \"_cf_no_protocol\";\n\nconst internalKeys = new Set<string>([CF_READONLY_KEY, CF_NO_PROTOCOL_KEY]);\n\n/**\n * Register additional `_cf_`-prefixed keys a host or mixin stores in\n * connection state, so they are hidden from `connection.state` and kept\n * across user `setState` calls like the capability's own flags.\n */\nexport function registerInternalConnectionKeys(...keys: string[]): void {\n for (const key of keys) internalKeys.add(key);\n}\n\nfunction rawHasInternalKeys(raw: Record<string, unknown>): boolean {\n for (const key of Object.keys(raw)) {\n if (internalKeys.has(key)) return true;\n }\n return false;\n}\n\n/** A copy of `raw` without internal keys, or null when no user keys remain. */\nfunction stripInternalKeys(\n raw: Record<string, unknown>\n): Record<string, unknown> | null {\n const result: Record<string, unknown> = {};\n let hasUserKeys = false;\n for (const key of Object.keys(raw)) {\n if (!internalKeys.has(key)) {\n result[key] = raw[key];\n hasUserKeys = true;\n }\n }\n return hasUserKeys ? result : null;\n}\n\n/** A copy containing only the internal keys present in `raw`. */\nfunction extractInternalFlags(\n raw: Record<string, unknown>\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(raw)) {\n if (internalKeys.has(key)) result[key] = raw[key];\n }\n return result;\n}\n\ntype RawAccessors = {\n getRaw: () => Record<string, unknown> | null;\n setRaw: (state: unknown) => unknown;\n};\n\n/**\n * Per-connection raw accessors, keyed by the live connection object. The\n * map is in-memory: after hibernation it is empty, and every entry point\n * re-wraps the connection on first use.\n */\nconst rawStateAccessors = new WeakMap<Connection, RawAccessors>();\n\n/**\n * Wrap `connection.state` / `connection.setState` so internal flags are\n * hidden from user code and preserved when user code sets state.\n * Idempotent, and safe to call after hibernation.\n */\nexport function ensureConnectionWrapped(connection: Connection): void {\n if (rawStateAccessors.has(connection)) return;\n\n // Hibernating connections expose attachment-backed state as a\n // configurable accessor. Virtual (bridged) connections use a data\n // property, so both projections are retained below.\n const descriptor = Object.getOwnPropertyDescriptor(connection, \"state\");\n\n let getRaw: RawAccessors[\"getRaw\"];\n let setRaw: RawAccessors[\"setRaw\"];\n\n if (descriptor?.get) {\n // Accessor property: bind the original getter. It reads the serialized\n // attachment, so it always returns the latest value after setState.\n getRaw = descriptor.get.bind(connection) as RawAccessors[\"getRaw\"];\n setRaw = connection.setState.bind(connection);\n } else {\n // Data property: track the raw value in a closure. Reading\n // `connection.state` after the override would hit the filtered getter.\n let rawState = (connection.state ?? null) as Record<string, unknown> | null;\n getRaw = () => rawState;\n setRaw = (state: unknown) => {\n rawState = state as Record<string, unknown> | null;\n return rawState;\n };\n }\n\n rawStateAccessors.set(connection, { getRaw, setRaw });\n\n Object.defineProperty(connection, \"state\", {\n configurable: true,\n enumerable: true,\n get() {\n const raw = getRaw();\n if (raw != null && typeof raw === \"object\" && rawHasInternalKeys(raw)) {\n return stripInternalKeys(raw);\n }\n return raw;\n }\n });\n\n Object.defineProperty(connection, \"setState\", {\n configurable: true,\n writable: true,\n value(stateOrFn: unknown | ((prev: unknown) => unknown)) {\n const raw = getRaw();\n const flags =\n raw != null && typeof raw === \"object\"\n ? extractInternalFlags(raw as Record<string, unknown>)\n : {};\n const hasFlags = Object.keys(flags).length > 0;\n\n let newUserState: unknown;\n if (typeof stateOrFn === \"function\") {\n // The callback sees only user-visible state.\n const userVisible = hasFlags\n ? stripInternalKeys(raw as Record<string, unknown>)\n : raw;\n newUserState = (stateOrFn as (prev: unknown) => unknown)(userVisible);\n } else {\n newUserState = stateOrFn;\n }\n\n if (hasFlags) {\n if (newUserState != null && typeof newUserState === \"object\") {\n return setRaw({\n ...(newUserState as Record<string, unknown>),\n ...flags\n });\n }\n // User set null: keep just the flags.\n return setRaw(flags);\n }\n return setRaw(newUserState);\n }\n });\n}\n\n/** The raw connection state, internal flags included. */\nexport function getConnectionRawState(\n connection: Connection\n): Record<string, unknown> | null {\n ensureConnectionWrapped(connection);\n return rawStateAccessors.get(connection)!.getRaw();\n}\n\n/** Read an internal flag from the raw connection state. */\nexport function getConnectionFlag(\n connection: Connection,\n key: string\n): unknown {\n ensureConnectionWrapped(connection);\n return rawStateAccessors.get(connection)!.getRaw()?.[key];\n}\n\n/**\n * Write an internal flag to the raw connection state. `undefined` removes\n * the key rather than storing a dead value; the last key removed leaves\n * `null`.\n */\nexport function setConnectionFlag(\n connection: Connection,\n key: string,\n value: unknown\n): void {\n ensureConnectionWrapped(connection);\n const accessors = rawStateAccessors.get(connection)!;\n const raw = accessors.getRaw() ?? {};\n if (value === undefined) {\n const { [key]: _, ...rest } = raw;\n accessors.setRaw(Object.keys(rest).length > 0 ? rest : null);\n } else {\n accessors.setRaw({ ...raw, [key]: value });\n }\n}\n\nexport function isConnectionReadonly(connection: Connection): boolean {\n return !!getConnectionFlag(connection, CF_READONLY_KEY);\n}\n\nexport function setConnectionReadonly(\n connection: Connection,\n readonly: boolean\n): void {\n setConnectionFlag(connection, CF_READONLY_KEY, readonly ? true : undefined);\n}\n\nexport function isConnectionProtocolEnabled(connection: Connection): boolean {\n return !getConnectionFlag(connection, CF_NO_PROTOCOL_KEY);\n}\n\nexport function setConnectionProtocolEnabled(\n connection: Connection,\n enabled: boolean\n): void {\n setConnectionFlag(connection, CF_NO_PROTOCOL_KEY, enabled ? undefined : true);\n}\n","// Polyfill WebSocket status code constants for environments that don't have them\n// in order to support libraries that expect standards-compatible WebSocket\n// implementations (e.g. PartySocket)\n\nimport type {\n Connection,\n ConnectionSetStateFn,\n ConnectionState,\n LifecycleSockets\n} from \"../lifecycle\";\n\nif (!(\"OPEN\" in WebSocket)) {\n const WebSocketStatus = {\n // @ts-expect-error\n CONNECTING: WebSocket.READY_STATE_CONNECTING,\n // @ts-expect-error\n OPEN: WebSocket.READY_STATE_OPEN,\n // @ts-expect-error\n CLOSING: WebSocket.READY_STATE_CLOSING,\n // @ts-expect-error\n CLOSED: WebSocket.READY_STATE_CLOSED\n };\n\n Object.assign(WebSocket, WebSocketStatus);\n // @ts-expect-error\n Object.assign(WebSocket.prototype, WebSocketStatus);\n}\n\n/**\n * Store both platform attachments and user attachments in different namespaces\n */\ntype ConnectionAttachments = {\n __pk: {\n id: string;\n tags: string[];\n uri?: string;\n };\n __user?: unknown;\n};\n\nfunction tryGetManagedWebSocketMeta(\n ws: WebSocket\n): ConnectionAttachments[\"__pk\"] | null {\n try {\n // Avoid AttachmentCache.get() here: externally accepted sockets\n // can have an attachment without the managed __pk namespace.\n const attachment = WebSocket.prototype.deserializeAttachment.call(\n ws\n ) as unknown;\n if (!attachment || typeof attachment !== \"object\") {\n return null;\n }\n if (!(\"__pk\" in attachment)) {\n return null;\n }\n const pk = (attachment as ConnectionAttachments).__pk as unknown;\n if (!pk || typeof pk !== \"object\") {\n return null;\n }\n const { id, tags } = pk as {\n id?: unknown;\n tags?: unknown;\n };\n if (typeof id !== \"string\") {\n return null;\n }\n const { uri } = pk as { uri?: unknown };\n return {\n id,\n tags: Array.isArray(tags) ? tags : [],\n uri: typeof uri === \"string\" ? uri : undefined\n } satisfies ConnectionAttachments[\"__pk\"];\n } catch {\n return null;\n }\n}\n\nexport function isManagedWebSocket(ws: WebSocket): boolean {\n return tryGetManagedWebSocketMeta(ws) !== null;\n}\n\n/**\n * Cache websocket attachments to avoid having to rehydrate them on every property access.\n */\nclass AttachmentCache {\n #cache = new WeakMap<WebSocket, ConnectionAttachments>();\n\n get(ws: WebSocket): ConnectionAttachments {\n let attachment = this.#cache.get(ws);\n if (!attachment) {\n attachment = WebSocket.prototype.deserializeAttachment.call(\n ws\n ) as ConnectionAttachments;\n if (attachment !== undefined) {\n this.#cache.set(ws, attachment);\n } else {\n throw new Error(\"Missing managed WebSocket lifecycle attachment\");\n }\n }\n\n return attachment;\n }\n\n set(ws: WebSocket, attachment: ConnectionAttachments) {\n this.#cache.set(ws, attachment);\n WebSocket.prototype.serializeAttachment.call(ws, attachment);\n }\n}\n\nconst attachments = new AttachmentCache();\nconst connections = new WeakSet<Connection>();\nconst isWrapped = (ws: WebSocket): ws is Connection => {\n return connections.has(ws as Connection);\n};\n\n/**\n * Wraps a WebSocket with Connection fields that rehydrate the\n * socket attachments lazily only when requested.\n */\nexport const createConnection = (ws: WebSocket | Connection): Connection => {\n if (isWrapped(ws)) {\n return ws;\n }\n\n // if state was set on the socket before initializing the connection,\n // capture it here so we can persist it again\n let initialState;\n if (\"state\" in ws) {\n initialState = ws.state;\n delete ws.state;\n }\n\n const connection = Object.defineProperties(ws, {\n id: {\n configurable: true,\n get() {\n return attachments.get(ws).__pk.id;\n }\n },\n uri: {\n configurable: true,\n get() {\n return attachments.get(ws).__pk.uri ?? null;\n }\n },\n tags: {\n configurable: true,\n get() {\n // Default to [] for connections accepted before tags were stored\n return attachments.get(ws).__pk.tags ?? [];\n }\n },\n state: {\n configurable: true,\n get() {\n const attachment = attachments.get(ws);\n return (attachment.__user ?? null) as ConnectionState<unknown>;\n }\n },\n setState: {\n configurable: true,\n value: function setState<T>(setState: T | ConnectionSetStateFn<T>) {\n const state =\n setState instanceof Function\n ? setState((this as Connection<T>).state)\n : setState;\n attachments.set(ws, {\n ...attachments.get(ws),\n __user: state ?? null\n });\n return state as ConnectionState<T>;\n }\n }\n }) as Connection;\n\n if (initialState) {\n connection.setState(initialState);\n }\n\n connections.add(connection);\n return connection;\n};\n\nclass ConnectionIterator<T> implements IterableIterator<Connection<T>> {\n private index = 0;\n #sockets: WebSocket[] | undefined;\n constructor(\n private sockets: LifecycleSockets,\n private tag?: string\n ) {}\n\n [Symbol.iterator](): IterableIterator<Connection<T>> {\n return this;\n }\n\n next(): IteratorResult<Connection<T>, number | undefined> {\n const sockets =\n this.#sockets ?? (this.#sockets = this.sockets.get(this.tag));\n\n let socket: WebSocket;\n while ((socket = sockets[this.index++])) {\n // Only yield open sockets.\n if (socket.readyState === WebSocket.OPEN) {\n // Durable Objects hibernation APIs allow storing arbitrary sockets via\n // `state.acceptWebSocket()`. Ignore sockets without our attachment.\n if (!isManagedWebSocket(socket)) {\n continue;\n }\n const value = createConnection(socket) as Connection<T>;\n return { done: false, value };\n }\n }\n\n // reached the end of the iteratee\n return { done: true, value: undefined };\n }\n}\n\n/**\n * Deduplicate and validate connection tags.\n * Returns the final tag array (always includes the connection id as the first tag).\n */\nexport function prepareTags(\n connectionId: string,\n userTags: string[]\n): string[] {\n const tags = [connectionId, ...userTags.filter((t) => t !== connectionId)];\n\n // validate tags against documented restrictions\n // https://developers.cloudflare.com/durable-objects/api/hibernatable-websockets-api/#state-methods-for-websockets\n if (tags.length > 10) {\n throw new Error(\n \"A connection can only have 10 tags, including the default id tag.\"\n );\n }\n\n for (const tag of tags) {\n if (typeof tag !== \"string\") {\n throw new Error(`A connection tag must be a string. Received: ${tag}`);\n }\n if (tag === \"\") {\n throw new Error(\"A connection tag must not be an empty string.\");\n }\n if (tag.length > 256) {\n throw new Error(\"A connection tag must not exceed 256 characters\");\n }\n }\n\n return tags;\n}\n\n/** The platform-backed manager for hibernating WebSockets. */\nexport class ConnectionManager<TState = unknown> {\n constructor(private controller: LifecycleSockets) {}\n\n getConnection<T = TState>(id: string) {\n // TODO: Should we cache the connections?\n const sockets = this.controller.get(id);\n const matching = sockets.filter((ws) => {\n return tryGetManagedWebSocketMeta(ws)?.id === id;\n });\n\n if (matching.length === 0) return undefined;\n if (matching.length === 1)\n return createConnection(matching[0]) as Connection<T>;\n\n throw new Error(\n `More than one connection found for id ${id}. Did you mean to use getConnections(tag) instead?`\n );\n }\n\n getConnections<T = TState>(tag?: string | undefined) {\n return new ConnectionIterator<T>(this.controller, tag);\n }\n\n accept(connection: Connection, options: { tags: string[] }) {\n const tags = prepareTags(connection.id, options.tags);\n\n this.controller.accept(connection, tags);\n attachments.set(connection, {\n __pk: {\n id: connection.id,\n tags,\n uri: connection.uri ?? undefined\n },\n __user: null\n });\n\n return createConnection(connection);\n }\n}\n","import { RpcTarget } from \"cloudflare:workers\";\nimport { CAPNWEB_TRANSPORT_SEND } from \"./transport-protocol\";\n\n/** A named remote method ready to be exposed on a callables root. */\nexport type CallableInvoker = (...args: unknown[]) => unknown;\n\n/**\n * The single exposure policy for callable names. `Object.prototype` and\n * `RpcTarget.prototype` members are unreachable over Cap'n Web anyway\n * and are silently excluded; `then` is rejected loudly because exposing\n * it would make the remote stub thenable.\n */\nfunction assertExposable(name: string): boolean {\n if (name === \"then\") {\n throw new Error(\n 'A callables target cannot expose a method named \"then\" — it would make the remote stub thenable'\n );\n }\n if (name === CAPNWEB_TRANSPORT_SEND) {\n throw new Error(\n `A callables target cannot expose \"${CAPNWEB_TRANSPORT_SEND}\"; it is the transport's frame pipe`\n );\n }\n return !(\n name === \"constructor\" ||\n name in Object.prototype ||\n name in RpcTarget.prototype\n );\n}\n\n/**\n * The exposable prototype methods of a callables target, each bound to\n * invoke on the real instance (so private fields and `this` behave).\n *\n * Cap'n Web resolves methods on the prototype chain and rejects own\n * instance properties, so only prototype methods participate. The\n * nearest declaration wins for overridden names.\n *\n * @param target - The callables target to enumerate.\n * @returns Method names mapped to invokers on the target.\n */\nexport function exposableMethods(\n target: RpcTarget\n): ReadonlyMap<string, CallableInvoker> {\n const methods = new Map<string, CallableInvoker>();\n const seen = new Set<string>();\n let prototype: object | null = Object.getPrototypeOf(target);\n while (\n prototype &&\n prototype !== RpcTarget.prototype &&\n prototype !== Object.prototype\n ) {\n for (const name of Object.getOwnPropertyNames(prototype)) {\n if (seen.has(name)) continue;\n seen.add(name);\n if (!assertExposable(name)) continue;\n const descriptor = Object.getOwnPropertyDescriptor(prototype, name);\n if (!descriptor || typeof descriptor.value !== \"function\") continue;\n // SAFETY: `typeof descriptor.value === \"function\"` was checked\n // above; TypeScript cannot narrow a descriptor's `value` field.\n const method = descriptor.value as CallableInvoker;\n methods.set(name, (...args) => Reflect.apply(method, target, args));\n }\n prototype = Object.getPrototypeOf(prototype);\n }\n return methods;\n}\n\n/**\n * Build a Cap'n Web session root exposing exactly the given methods.\n *\n * Cap'n Web resolves methods on the prototype chain, rejects own\n * instance properties, and breaks on Proxy-wrapped roots — so the root\n * is a private `RpcTarget` subclass whose prototype carries the methods\n * and nothing else.\n */\nexport function buildRoot(\n methods: ReadonlyMap<string, CallableInvoker>\n): RpcTarget {\n class Root extends RpcTarget {}\n for (const [name, invoke] of methods) {\n Object.defineProperty(Root.prototype, name, {\n value: invoke,\n writable: true,\n configurable: true,\n enumerable: false\n });\n }\n return new Root();\n}\n","import { newWebSocketRpcSession, type RpcStub } from \"capnweb\";\nimport type {\n Connection,\n ConnectionContext,\n ConnectionSetStateFn,\n ConnectionState\n} from \"../lifecycle\";\nimport { buildRoot, type CallableInvoker } from \"./callables-target\";\nimport { prepareTags } from \"./connection\";\nimport {\n CAPNWEB_TRANSPORT_SEND,\n type TransportClientEvents,\n type TransportMessage\n} from \"./transport-protocol\";\n\n/**\n * A non-hibernating connection with the public `Connection` contract,\n * backed by a Cap'n Web session instead of a hibernating socket. It lives\n * only in memory and disappears with the isolate.\n */\nclass CapnWebConnection extends EventTarget {\n readonly CONNECTING = WebSocket.CONNECTING;\n readonly OPEN = WebSocket.OPEN;\n readonly CLOSING = WebSocket.CLOSING;\n readonly CLOSED = WebSocket.CLOSED;\n readyState: number = WebSocket.OPEN;\n state: ConnectionState<unknown> = null;\n tags: readonly string[] = [];\n\n constructor(\n readonly id: string,\n readonly uri: string,\n private readonly pipe: {\n send(message: TransportMessage): void;\n close(code?: number, reason?: string): void;\n }\n ) {\n super();\n }\n\n send(message: TransportMessage): void {\n if (this.readyState !== WebSocket.OPEN) {\n throw new TypeError(\"WebSocket send() after close\");\n }\n this.pipe.send(message);\n }\n\n close(code?: number, reason?: string): void {\n if (this.readyState >= WebSocket.CLOSING) return;\n this.pipe.close(code, reason);\n this.readyState = WebSocket.CLOSING;\n }\n\n setState<T = unknown>(\n next: T | ConnectionSetStateFn<T> | null\n ): ConnectionState<T> {\n const state =\n typeof next === \"function\"\n ? (next as ConnectionSetStateFn<T>)(this.state as ConnectionState<T>)\n : next;\n this.state = state as ConnectionState<unknown>;\n return state as ConnectionState<T>;\n }\n}\n\n/** One live transport session. */\nexport type CapnWebSession = {\n readonly connection: Connection;\n /** Tear the session down; runs the close handler once. */\n dispose(): void;\n};\n\n/** What the capability supplies to run one session. */\nexport type CapnWebSessionOptions = {\n readonly request: Request;\n readonly connectionId: string;\n readonly tags: (\n connection: Connection,\n ctx: ConnectionContext\n ) => string[] | Promise<string[]>;\n readonly onConnect: (\n connection: Connection,\n ctx: ConnectionContext\n ) => Promise<void>;\n readonly onMessage: (\n connection: Connection,\n message: TransportMessage\n ) => Promise<void>;\n readonly onClose: (\n connection: Connection,\n code: number,\n reason: string,\n wasClean: boolean\n ) => Promise<void>;\n readonly onError: (connection: Connection, error: unknown) => Promise<void>;\n /**\n * Native methods served on the session root beside the frame pipe. Each\n * invoker already runs inside the host boundary for this connection.\n * Results pass by Cap'n Web semantics: an `RpcTarget` becomes a live\n * stub, a `ReadableStream` streams, and calls pipeline.\n */\n readonly callables: (\n connection: Connection\n ) => ReadonlyMap<string, CallableInvoker>;\n /**\n * Called once the connection exists, before `onConnect`, so it is already\n * visible in `getConnections()` while the connect handler runs — the same\n * ordering as a hibernating socket, which is accepted before `onConnect`.\n */\n readonly onOpen: (session: CapnWebSession) => void;\n /** Called exactly once when the session ends, before `onClose`. */\n readonly onDispose: (session: CapnWebSession) => void;\n};\n\n/**\n * Accept a Cap'n Web transport upgrade.\n *\n * The session root carries the frame pipe plus the host's native\n * callables. The client's protocol frames arrive through the pipe and are\n * handed to `onMessage`; the host's frames go out through the client's\n * `message` callback; `useAgent().stub` calls hit the callables directly.\n * The socket is a plain in-memory `WebSocketPair`, so it pins the Durable\n * Object and does not survive hibernation.\n */\nexport async function openCapnWebSession(\n options: CapnWebSessionOptions\n): Promise<{ response: Response; session: CapnWebSession }> {\n const { request, connectionId } = options;\n const pair = new WebSocketPair();\n const server = pair[0];\n server.accept();\n\n let client: RpcStub<TransportClientEvents> | undefined;\n let closed = false;\n let close = { code: 1000, reason: \"\", wasClean: true };\n\n const connection = new CapnWebConnection(connectionId, request.url, {\n send: (message) => {\n void client?.message(message).catch((error: unknown) => {\n if (!closed) console.error(\"Cap'n Web frame delivery failed:\", error);\n });\n },\n close: (code = 1000, reason = \"\") => {\n // Same contract as WebSocket.close(): a reserved code or an oversize\n // reason throws before anything changes, and the socket stays open\n // and tracked. Only a started handshake finishes the session.\n server.close(code, reason);\n close = { code, reason, wasClean: true };\n void finish();\n }\n }) as unknown as Connection & CapnWebConnection;\n\n const session: CapnWebSession = {\n connection,\n dispose: () => connection.close(1001, \"Session replaced\")\n };\n\n const finish = async () => {\n if (closed) return;\n closed = true;\n connection.readyState = WebSocket.CLOSED;\n try {\n client?.[Symbol.dispose]();\n } catch {\n // The session already ended with the socket.\n }\n options.onDispose(session);\n await options.onClose(connection, close.code, close.reason, close.wasClean);\n };\n\n const rootMethods = new Map<string, CallableInvoker>(\n options.callables(connection)\n );\n rootMethods.set(CAPNWEB_TRANSPORT_SEND, (message) =>\n options.onMessage(connection, message as TransportMessage)\n );\n client = newWebSocketRpcSession<TransportClientEvents>(\n server,\n buildRoot(rootMethods)\n );\n\n server.addEventListener(\n \"close\",\n (event) => {\n close = {\n code: event.code,\n reason: event.reason,\n wasClean: event.wasClean\n };\n void finish();\n },\n { once: true }\n );\n server.addEventListener(\n \"error\",\n (event) => {\n if (closed) return;\n close = { ...close, wasClean: false };\n const error =\n event instanceof ErrorEvent\n ? (event.error ?? new Error(event.message))\n : new Error(\"Cap'n Web transport socket error\");\n void options\n .onError(connection, error)\n .catch((handlerError: unknown) => {\n console.error(\"Cap'n Web onError handler failed:\", handlerError);\n })\n .finally(finish);\n },\n { once: true }\n );\n\n const ctx = { request };\n // Same limits as the hibernating wire (count, emptiness, length), so a\n // handler sees one tag policy whichever transport the client chose.\n connection.tags = prepareTags(\n connectionId,\n await options.tags(connection, ctx)\n );\n options.onOpen(session);\n try {\n await options.onConnect(connection, ctx);\n } catch (error) {\n connection.close(1011, \"onConnect failed\");\n throw error;\n }\n\n return {\n response: new Response(null, { status: 101, webSocket: pair[1] }),\n session\n };\n}\n","import { RpcTarget } from \"cloudflare:workers\";\nimport { nanoid } from \"nanoid\";\nimport {\n LifecycleCapability,\n type CapabilityWebSocketUpgradeContext,\n type Connection,\n type ConnectionContext,\n type ConnectionSetStateFn,\n type ConnectionState\n} from \"../lifecycle\";\nimport { MessageType } from \"../types\";\nimport { camelCaseToKebabCase } from \"../utils\";\nimport {\n ConnectionManager,\n createConnection,\n isManagedWebSocket\n} from \"./connection\";\nimport {\n ensureConnectionWrapped,\n isConnectionProtocolEnabled,\n isConnectionReadonly,\n setConnectionProtocolEnabled,\n setConnectionReadonly\n} from \"./connection-flags\";\nimport { exposableMethods, type CallableInvoker } from \"./callables-target\";\nimport type {\n SyncedState,\n WebSocketHandlers,\n WebSocketMessage,\n WebSocketsOptions\n} from \"./options\";\nimport { openCapnWebSession, type CapnWebSession } from \"./transport\";\nimport { isCapnWebTransportUpgrade } from \"./transport-protocol\";\n\n/**\n * Reserved close codes the runtime synthesizes when there was no real\n * Close frame from the peer (1005 NoStatusReceived, 1006 AbnormalClosure,\n * 1015 TLSHandshake). They cannot appear in an outgoing Close frame, and\n * there is no peer left to receive a reciprocation.\n */\nfunction isReservedCloseCode(code: number): boolean {\n return code === 1005 || code === 1006 || code === 1015;\n}\n\n/**\n * Reciprocate a peer-initiated Close frame to complete the handshake, as\n * the Hibernation API contract requires. Best-effort: swallows errors\n * from already-closed sockets or invalid codes/reasons, and skips\n * reciprocation entirely for reserved codes (dead transport).\n */\nfunction reciprocateClose(ws: WebSocket, code: number, reason: string): void {\n if (isReservedCloseCode(code)) return;\n try {\n ws.close(code, reason);\n } catch {\n // Already closed, oversize reason, or another unrecoverable\n // invariant — the handshake is either done or out of our control.\n }\n}\n\n/** The `rpc` request frame `useAgent().call` and `AgentClient.call` send. */\ntype RpcRequest = {\n readonly type: \"rpc\";\n readonly id: string;\n readonly method: string;\n readonly args: unknown[];\n};\n\ntype RpcResponse =\n | { type: \"rpc\"; id: string; success: true; done: boolean; result: unknown }\n | { type: \"rpc\"; id: string; success: false; error: string };\n\n/** The `cf_agent_state` frame a client sends to update host state. */\ntype StateFrame = { readonly type: \"cf_agent_state\"; readonly state: unknown };\n\nfunction isStateFrame(value: unknown): value is StateFrame {\n if (typeof value !== \"object\" || value === null) return false;\n const frame = value as Record<string, unknown>;\n return frame.type === MessageType.CF_AGENT_STATE && \"state\" in frame;\n}\n\n/** Parse a text frame; anything that is not JSON is `undefined`. */\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\nfunction isRpcRequest(value: unknown): value is RpcRequest {\n if (typeof value !== \"object\" || value === null) return false;\n const frame = value as Record<string, unknown>;\n return (\n frame.type === MessageType.RPC &&\n typeof frame.id === \"string\" &&\n typeof frame.method === \"string\" &&\n Array.isArray(frame.args)\n );\n}\n\n/**\n * Opt-in WebSocket support for Lifecycle Objects.\n *\n * Lifecycle itself does not model WebSockets — hosts that want them\n * install this capability, which owns the connection subsystem end to\n * end: it claims upgrades, dispatches `onConnect`/`onMessage`/`onClose`\n * inside the host invocation boundary, reciprocates close handshakes,\n * and answers `getConnections()`/`getConnection()`.\n *\n * ```ts\n * class Room extends DurableObject<Env> {\n * readonly webSockets = new WebSockets({\n * handlers: {\n * onConnect: (connection) => connection.send(\"welcome\"),\n * onMessage: (connection, message) => { ... }\n * },\n * callables: new RoomCallables()\n * });\n * readonly lifecycle = Lifecycle.install(this).use(this.webSockets);\n * }\n * ```\n *\n * Connections arrive on one of two wires, chosen by the client:\n *\n * - **cf-websocket** (default): accepted with the Hibernation API. Idle\n * clients stay connected while the Durable Object leaves memory.\n * - **capnweb** (`?__agents_transport=capnweb`): protocol frames through\n * one pipe method on a Cap'n Web session whose root also carries the\n * host's callables natively. Non-hibernating — the object stays pinned\n * while the connection is open.\n *\n * Both wires dispatch the same handlers and appear in `getConnections()`.\n * On both, the capability speaks the Agent protocol a plain host needs\n * for `useAgent` and `AgentClient`: it sends the identity frame on\n * connect, and it serves `callables` — as `rpc` JSON frames on the\n * WebSocket wire, and natively on the Cap'n Web session root, where an\n * `RpcTarget` result becomes a live stub and calls pipeline. `call()`\n * and `stub` work against a plain Durable Object exactly as against an\n * `Agent`. Pass a `State` capability as `state` and the hook's\n * `state`/`setState` work too: the current value is pushed on connect\n * and client updates are validated and applied; the state owner\n * broadcasts changes with `broadcastState()`. Per-connection readonly\n * and no-protocol flags live here as well, for every host.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class WebSockets extends LifecycleCapability {\n /** Claims every upgrade, so Lifecycle dispatches it after all others. */\n override readonly claims = \"catch-all\";\n\n readonly #handlers: WebSocketHandlers | undefined;\n readonly #getConnectionTags: WebSocketsOptions[\"getConnectionTags\"];\n readonly #protocol: WebSocketsOptions[\"protocol\"];\n readonly #readonly: WebSocketsOptions[\"readonly\"];\n readonly #state: SyncedState | undefined;\n /**\n * Connections inside their connect sequence, before the state push.\n * `broadcastState()` skips them: reading state for the push can seed the\n * initial value, whose change broadcast would otherwise reach a\n * connection that is about to receive the same value directly.\n */\n readonly #connecting = new Set<Connection>();\n readonly #callables: ReadonlyMap<string, CallableInvoker>;\n readonly #sessions = new Map<string, CapnWebSession>();\n #manager: ConnectionManager | undefined;\n\n constructor(options: WebSocketsOptions = {}) {\n super(\"websockets\");\n this.#handlers = options.handlers;\n this.#getConnectionTags = options.getConnectionTags;\n this.#protocol = options.protocol ?? true;\n this.#readonly = options.readonly;\n this.#state = options.state;\n this.#callables = options.callables\n ? exposableMethods(options.callables)\n : new Map();\n }\n\n // ── Lifecycle capability hooks ─────────────────────────────────────────\n\n /**\n * Claim every upgrade, never declining: a Cap'n Web transport upgrade\n * becomes a session, everything else a tracked hibernating connection,\n * whether or not handlers or callables are configured. Handlers only add\n * behavior on connect, message, close, and error.\n */\n onWebSocketUpgrade({\n request\n }: CapabilityWebSocketUpgradeContext): Promise<Response> {\n return isCapnWebTransportUpgrade(request)\n ? this.#acceptCapnWebSession(request)\n : this.#acceptConnection(request);\n }\n\n /** Dispatch a platform message wake for a capability-owned socket. */\n async onWebSocketMessage(\n ws: WebSocket,\n message: WebSocketMessage\n ): Promise<boolean> {\n if (!isManagedWebSocket(ws)) return false;\n await this.#message(createConnection(ws), message);\n return true;\n }\n\n /** Dispatch and reciprocate a close wake for an owned socket. */\n async onWebSocketClose(\n ws: WebSocket,\n code: number,\n reason: string,\n wasClean: boolean\n ): Promise<boolean> {\n if (!isManagedWebSocket(ws)) return false;\n try {\n await this.#close(createConnection(ws), code, reason, wasClean);\n } finally {\n reciprocateClose(ws, code, reason);\n }\n return true;\n }\n\n /** Dispatch an error wake for an owned socket. */\n async onWebSocketError(ws: WebSocket, error: unknown): Promise<boolean> {\n if (!isManagedWebSocket(ws)) return false;\n await this.#error(createConnection(ws), error);\n return true;\n }\n\n /**\n * Close every owned connection during explicit host destruction. The\n * capability owns its sockets' lifetimes, so it also owns tearing\n * them down.\n */\n dispose(): void {\n for (const connection of this.getConnections()) {\n try {\n connection.close(1001, \"Durable Object destroyed\");\n } catch {\n // Already closed or mid-handshake — nothing left to tear down.\n }\n }\n }\n\n // ── Connections ────────────────────────────────────────────────────────\n\n /** Open connections on either wire, optionally by tag. */\n *getConnections<TState = unknown>(\n tag?: string\n ): IterableIterator<Connection<TState>> {\n for (const { connection } of this.#sessions.values()) {\n if (connection.readyState !== WebSocket.OPEN) continue;\n if (!tag || connection.tags.includes(tag)) {\n yield connection as Connection<TState>;\n }\n }\n yield* this.#connectionManager.getConnections<TState>(tag);\n }\n\n /** One connection on either wire, by id. */\n getConnection<TState = unknown>(id: string): Connection<TState> | undefined {\n const session = this.#sessions.get(id)?.connection;\n if (session && session.readyState === WebSocket.OPEN) {\n return session as Connection<TState>;\n }\n return this.#connectionManager.getConnection<TState>(id);\n }\n\n get #connectionManager(): ConnectionManager {\n this.#manager ??= new ConnectionManager(this.lifecycle.sockets);\n return this.#manager;\n }\n\n // ── Wire-independent protocol ──────────────────────────────────────────\n\n async #connect(\n connection: Connection,\n ctx: ConnectionContext\n ): Promise<void> {\n ensureConnectionWrapped(connection);\n // Flags first, so they are set before the client can respond.\n if (this.#readonly?.(connection, ctx)) {\n setConnectionReadonly(connection, true);\n }\n if (this.#protocol !== false) {\n const enabled =\n typeof this.#protocol === \"function\"\n ? this.#protocol(connection, ctx)\n : true;\n if (enabled) {\n this.#connecting.add(connection);\n try {\n this.sendIdentity(connection);\n this.sendState(connection);\n } finally {\n this.#connecting.delete(connection);\n }\n } else {\n setConnectionProtocolEnabled(connection, false);\n }\n }\n await this.lifecycle.runInHostContext(\n () => this.#handlers?.onConnect?.(connection, ctx),\n { connection, request: ctx.request }\n );\n }\n\n async #message(\n connection: Connection,\n message: WebSocketMessage\n ): Promise<void> {\n if (\n this.#state &&\n this.#protocol !== false &&\n typeof message === \"string\"\n ) {\n const frame = parseJson(message);\n if (isStateFrame(frame)) {\n // Inside the host boundary, so the host's validator and change\n // hook see the sending connection through the ambient context.\n await this.lifecycle.runInHostContext(\n () => this.applyStateFrame(connection, frame),\n { connection }\n );\n return;\n }\n }\n if (\n this.#callables.size > 0 &&\n (await this.#answerRpc(connection, message))\n ) {\n return;\n }\n await this.lifecycle.runInHostContext(\n () => this.#handlers?.onMessage?.(connection, message),\n { connection }\n );\n }\n\n #close(\n connection: Connection,\n code: number,\n reason: string,\n wasClean: boolean\n ): Promise<unknown> {\n return this.lifecycle.runInHostContext(\n () => this.#handlers?.onClose?.(connection, code, reason, wasClean),\n { connection }\n );\n }\n\n #error(connection: Connection, error: unknown): Promise<unknown> {\n return this.lifecycle.runInHostContext(\n () => this.#handlers?.onError?.(connection, error),\n { connection }\n );\n }\n\n // ── Hibernating wire ───────────────────────────────────────────────────\n\n async #acceptConnection(request: Request): Promise<Response> {\n const { 0: clientWebSocket, 1: serverWebSocket } = new WebSocketPair();\n const url = new URL(request.url);\n // `||`, not `??`: an empty `?_pk=` value must fall back to a\n // generated id — an empty connection id would later throw in tag\n // validation and reject the upgrade.\n const connectionId = url.searchParams.get(\"_pk\") || nanoid();\n\n let connection: Connection = Object.assign(serverWebSocket, {\n id: connectionId,\n uri: request.url,\n tags: [] as string[],\n state: null as unknown as ConnectionState<unknown>,\n setState<T = unknown>(setState: T | ConnectionSetStateFn<T>) {\n // Pre-accept shim: hold state on the socket until accept()\n // persists it into the hibernation attachment.\n const state =\n setState instanceof Function\n ? setState(this.state as ConnectionState<T>)\n : setState;\n this.state = state as ConnectionState<T>;\n return this.state as ConnectionState<T>;\n }\n });\n\n const ctx = { request };\n const tags = this.#getConnectionTags\n ? await this.#getConnectionTags(connection, ctx)\n : [];\n\n // Hibernating WebSockets remain connected while the object is evicted.\n connection = this.#connectionManager.accept(connection, { tags });\n await this.#connect(connection, ctx);\n\n return new Response(null, { status: 101, webSocket: clientWebSocket });\n }\n\n // ── Cap'n Web wire ─────────────────────────────────────────────────────\n\n async #acceptCapnWebSession(request: Request): Promise<Response> {\n const connectionId =\n new URL(request.url).searchParams.get(\"_pk\") || nanoid();\n // A reconnect reusing the id replaces the previous session.\n this.#sessions.get(connectionId)?.dispose();\n\n const { response } = await openCapnWebSession({\n request,\n connectionId,\n tags: (connection, ctx) =>\n this.#getConnectionTags?.(connection, ctx) ?? [],\n onConnect: (connection, ctx) => this.#connect(connection, ctx),\n onMessage: (connection, message) => this.#message(connection, message),\n onClose: (connection, code, reason, wasClean) =>\n this.#close(connection, code, reason, wasClean).then(() => undefined),\n onError: (connection, error) =>\n this.#error(connection, error).then(() => undefined),\n callables: (connection) => this.#nativeCallables(connection),\n onOpen: (session) => this.#sessions.set(connectionId, session),\n onDispose: (ended) => {\n if (this.#sessions.get(connectionId) === ended) {\n this.#sessions.delete(connectionId);\n }\n }\n });\n return response;\n }\n\n // ── Protocol frames ────────────────────────────────────────────────────\n //\n // The Agent protocol a client (`useAgent`, `AgentClient`) speaks, owned\n // here for every host. With `protocol: true` the capability drives the\n // connect sequence and consumes state frames itself; with\n // `protocol: false` the host calls these at the moments it chooses.\n\n /**\n * Send the identity frame, unless the connection is no-protocol. The\n * defaults are the Durable Object's routed name and host class; a host\n * whose public identity differs — an `Agent` facet, whose routed name\n * is an internal encoding of its logical name — passes its own.\n */\n sendIdentity(\n connection: Connection,\n identity: { name: string; agent: string } = {\n name: this.lifecycle.name,\n agent: camelCaseToKebabCase(this.lifecycle.className)\n }\n ): void {\n if (!isConnectionProtocolEnabled(connection)) return;\n this.#sendFrame(connection, {\n type: MessageType.CF_AGENT_IDENTITY,\n name: identity.name,\n agent: identity.agent\n });\n }\n\n /**\n * Send the current state to one connection, unless nothing is stored\n * or the connection is no-protocol. Reading the state may seed the\n * initial value; see `#connecting`.\n */\n sendState(connection: Connection): void {\n if (!this.#state || !isConnectionProtocolEnabled(connection)) return;\n const current = this.#state.get();\n if (current === undefined) return;\n this.#sendFrame(connection, {\n type: MessageType.CF_AGENT_STATE,\n state: current\n });\n }\n\n /**\n * Apply a parsed `cf_agent_state` frame from a client. A readonly\n * connection is refused; a change the host's validator rejects is\n * logged in full server-side and answered with a generic\n * `cf_agent_state_error`. Broadcasting the accepted change is the state\n * owner's call, through its `onChanged` hook. Callers that drive the\n * protocol themselves call this inside their own invocation context;\n * the capability's automatic path does so via `runInHostContext`.\n *\n * @returns Whether the frame was a state frame (handled either way).\n */\n applyStateFrame(connection: Connection, frame: unknown): boolean {\n if (!this.#state || !isStateFrame(frame)) return false;\n if (isConnectionReadonly(connection)) {\n this.#sendFrame(connection, {\n type: MessageType.CF_AGENT_STATE_ERROR,\n error: \"Connection is readonly\"\n });\n return true;\n }\n try {\n // `never` on the port keeps any `State<T>` assignable; the value\n // came off the wire, so the host's validator is what checks it.\n this.#state.set(frame.state as never, connection);\n } catch (error) {\n console.error(\"[WebSockets] State update rejected:\", error);\n this.#sendFrame(connection, {\n type: MessageType.CF_AGENT_STATE_ERROR,\n error: \"State update rejected\"\n });\n }\n return true;\n }\n\n /**\n * Push the current state to every protocol-enabled connection except\n * the one a change came from, which already has the value it sent.\n * Wire a `State`'s `onChanged` to this.\n */\n broadcastState(except?: Connection | \"server\"): void {\n if (!this.#state) return;\n const current = this.#state.get();\n if (current === undefined) return;\n const frame = { type: MessageType.CF_AGENT_STATE, state: current };\n for (const connection of this.getConnections()) {\n // Object identity, not id: `_pk` is client-supplied, so two live\n // sockets can share an id, and excluding by id would starve the\n // other one. `createConnection` returns one wrapper per socket.\n if (connection === except) continue;\n if (this.#connecting.has(connection)) continue;\n if (!isConnectionProtocolEnabled(connection)) continue;\n this.#sendFrame(connection, frame);\n }\n }\n\n // ── Connection flags ───────────────────────────────────────────────────\n\n /** Whether the connection may update host state over the wire. */\n isReadonly(connection: Connection): boolean {\n return isConnectionReadonly(connection);\n }\n\n /** Mark a connection readonly, or writable again. */\n setReadonly(connection: Connection, readonly = true): void {\n setConnectionReadonly(connection, readonly);\n }\n\n /** Whether protocol text frames reach the connection. */\n isProtocolEnabled(connection: Connection): boolean {\n return isConnectionProtocolEnabled(connection);\n }\n\n /** Enable or suppress protocol text frames for a connection. */\n setProtocolEnabled(connection: Connection, enabled: boolean): void {\n setConnectionProtocolEnabled(connection, enabled);\n }\n\n /**\n * Send one protocol frame. Serialization is the caller's contract — every\n * frame built here is plain JSON — while a send failure is tolerated: the\n * peer may have disconnected between the wake and the send.\n */\n #sendFrame(connection: Connection, frame: Record<string, unknown>): void {\n this.#send(connection, JSON.stringify(frame));\n }\n\n /** Write one already-serialized frame, tolerating a closed peer. */\n #send(connection: Connection, text: string): void {\n try {\n connection.send(text);\n } catch {\n // The socket closed between the wake and the send.\n }\n }\n\n // ── Callables ──────────────────────────────────────────────────────────\n\n /**\n * The `callables` target as native Cap'n Web methods for one session:\n * every method dispatches through the host boundary with this\n * connection in scope and emits `rpc`/`rpc:error` events. Return values\n * keep Cap'n Web semantics — an `RpcTarget` comes back as a live stub.\n */\n #nativeCallables(\n connection: Connection\n ): ReadonlyMap<string, CallableInvoker> {\n const methods = new Map<string, CallableInvoker>();\n for (const [name, invoke] of this.#callables) {\n methods.set(name, (...args) =>\n this.#dispatchCallable(name, () => invoke(...args), connection)\n );\n }\n return methods;\n }\n\n /**\n * Answer one `rpc` frame against `callables`. A `ReadableStream`\n * result streams as `done: false` chunks followed by a final\n * `done: true` frame, matching the client's stream callbacks.\n *\n * @returns Whether the message was an `rpc` frame (answered or not).\n */\n async #answerRpc(\n connection: Connection,\n raw: WebSocketMessage\n ): Promise<boolean> {\n if (typeof raw !== \"string\") return false;\n let frame: unknown;\n try {\n frame = JSON.parse(raw);\n } catch {\n return false;\n }\n if (!isRpcRequest(frame)) return false;\n const { id, method, args } = frame;\n\n const invoke = this.#callables.get(method);\n if (!invoke) {\n this.#reply(connection, {\n type: \"rpc\",\n id,\n success: false,\n error: `Method ${method} does not exist`\n });\n return true;\n }\n\n try {\n const result = await this.#dispatchCallable(\n method,\n () => invoke(...args),\n connection\n );\n if (result instanceof RpcTarget) {\n // By-reference results only exist on the Cap'n Web wire; a JSON\n // frame would silently flatten the target to `{}`.\n throw new Error(\n `Method ${method} returns an RpcTarget, which only the capnweb transport can carry`\n );\n }\n if (result instanceof ReadableStream) {\n for await (const chunk of result) {\n this.#reply(connection, {\n type: \"rpc\",\n id,\n success: true,\n done: false,\n result: chunk\n });\n }\n this.#reply(connection, {\n type: \"rpc\",\n id,\n success: true,\n done: true,\n result: undefined\n });\n } else {\n this.#reply(connection, {\n type: \"rpc\",\n id,\n success: true,\n done: true,\n result\n });\n }\n } catch (error) {\n this.#reply(connection, {\n type: \"rpc\",\n id,\n success: false,\n error: error instanceof Error ? error.message : String(error)\n });\n }\n return true;\n }\n\n #reply(connection: Connection, response: RpcResponse): void {\n let text: string;\n try {\n text = JSON.stringify(response);\n } catch (error) {\n // A result that JSON cannot carry (a BigInt, a cycle) must still\n // settle the caller: answer with an error instead of silence.\n text = JSON.stringify({\n type: \"rpc\",\n id: response.id,\n success: false,\n error: `Result is not JSON-serializable: ${\n error instanceof Error ? error.message : String(error)\n }`\n } satisfies RpcResponse);\n }\n this.#send(connection, text);\n }\n\n async #dispatchCallable(\n name: string,\n invoke: () => unknown,\n connection: Connection\n ): Promise<unknown> {\n // Throws with installation guidance when the capability was never\n // installed with Lifecycle.use().\n const services = this.lifecycle;\n try {\n const result = await services.runInHostContext(invoke, { connection });\n services.events.emit(\"rpc\", {\n method: name,\n streaming: result instanceof ReadableStream\n });\n return result;\n } catch (error) {\n services.events.emit(\"rpc:error\", {\n method: name,\n error: error instanceof Error ? error.message : String(error)\n });\n throw error;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAeA,MAAa,kBAAkB;;;;;AAM/B,MAAa,qBAAqB;AAElC,MAAM,+BAAe,IAAI,IAAY,CAAC,iBAAiB,kBAAkB,CAAC;;;;;;AAO1E,SAAgB,+BAA+B,GAAG,MAAsB;CACtE,KAAK,MAAM,OAAO,MAAM,aAAa,IAAI,GAAG;AAC9C;AAEA,SAAS,mBAAmB,KAAuC;CACjE,KAAK,MAAM,OAAO,OAAO,KAAK,GAAG,GAC/B,IAAI,aAAa,IAAI,GAAG,GAAG,OAAO;CAEpC,OAAO;AACT;;AAGA,SAAS,kBACP,KACgC;CAChC,MAAM,SAAkC,CAAC;CACzC,IAAI,cAAc;CAClB,KAAK,MAAM,OAAO,OAAO,KAAK,GAAG,GAC/B,IAAI,CAAC,aAAa,IAAI,GAAG,GAAG;EAC1B,OAAO,OAAO,IAAI;EAClB,cAAc;CAChB;CAEF,OAAO,cAAc,SAAS;AAChC;;AAGA,SAAS,qBACP,KACyB;CACzB,MAAM,SAAkC,CAAC;CACzC,KAAK,MAAM,OAAO,OAAO,KAAK,GAAG,GAC/B,IAAI,aAAa,IAAI,GAAG,GAAG,OAAO,OAAO,IAAI;CAE/C,OAAO;AACT;;;;;;AAYA,MAAM,oCAAoB,IAAI,QAAkC;;;;;;AAOhE,SAAgB,wBAAwB,YAA8B;CACpE,IAAI,kBAAkB,IAAI,UAAU,GAAG;CAKvC,MAAM,aAAa,OAAO,yBAAyB,YAAY,OAAO;CAEtE,IAAI;CACJ,IAAI;CAEJ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
|
+
{"version":3,"file":"websockets-Ci-LZFHH.js","names":["RpcTarget","RpcTarget"],"sources":["../src/websockets/connection-flags.ts","../src/websockets/connection.ts","../src/websockets/callables-target.ts","../src/websockets/transport.ts","../src/websockets/websockets.ts"],"sourcesContent":["import type { Connection } from \"../lifecycle\";\n\n/**\n * Internal per-connection flags, stored inside the connection's own state\n * under `_cf_`-prefixed keys so they ride the hibernation attachment (or a\n * bridged connection's synced state) and survive a wake. The state wrapper\n * installed by {@link ensureConnectionWrapped} hides them from\n * `connection.state` and preserves them across user `setState` calls.\n *\n * Owned by the WebSockets capability; `Agent` and framework mixins reach it\n * through the capability or, for their own keys, through\n * {@link registerInternalConnectionKeys}.\n */\n\n/** A readonly connection may not update host state. */\nexport const CF_READONLY_KEY = \"_cf_readonly\";\n\n/**\n * A no-protocol connection receives no protocol text frames (identity,\n * state sync, MCP servers) — neither on connect nor via broadcasts.\n */\nexport const CF_NO_PROTOCOL_KEY = \"_cf_no_protocol\";\n\nconst internalKeys = new Set<string>([CF_READONLY_KEY, CF_NO_PROTOCOL_KEY]);\n\n/**\n * Register additional `_cf_`-prefixed keys a host or mixin stores in\n * connection state, so they are hidden from `connection.state` and kept\n * across user `setState` calls like the capability's own flags.\n */\nexport function registerInternalConnectionKeys(...keys: string[]): void {\n for (const key of keys) internalKeys.add(key);\n}\n\nfunction rawHasInternalKeys(raw: Record<string, unknown>): boolean {\n for (const key of Object.keys(raw)) {\n if (internalKeys.has(key)) return true;\n }\n return false;\n}\n\n/** A copy of `raw` without internal keys, or null when no user keys remain. */\nfunction stripInternalKeys(\n raw: Record<string, unknown>\n): Record<string, unknown> | null {\n const result: Record<string, unknown> = {};\n let hasUserKeys = false;\n for (const key of Object.keys(raw)) {\n if (!internalKeys.has(key)) {\n result[key] = raw[key];\n hasUserKeys = true;\n }\n }\n return hasUserKeys ? result : null;\n}\n\n/** A copy containing only the internal keys present in `raw`. */\nfunction extractInternalFlags(\n raw: Record<string, unknown>\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(raw)) {\n if (internalKeys.has(key)) result[key] = raw[key];\n }\n return result;\n}\n\ntype RawAccessors = {\n getRaw: () => Record<string, unknown> | null;\n setRaw: (state: unknown) => unknown;\n};\n\n/**\n * Per-connection raw accessors, keyed by the live connection object. The\n * map is in-memory: after hibernation it is empty, and every entry point\n * re-wraps the connection on first use.\n */\nconst rawStateAccessors = new WeakMap<Connection, RawAccessors>();\n\n/**\n * Wrap `connection.state` / `connection.setState` so internal flags are\n * hidden from user code and preserved when user code sets state.\n * Idempotent, and safe to call after hibernation.\n */\nexport function ensureConnectionWrapped(connection: Connection): void {\n if (rawStateAccessors.has(connection)) return;\n\n // Hibernating connections expose attachment-backed state as a\n // configurable accessor. Virtual (bridged) connections use a data\n // property, so both projections are retained below.\n const descriptor = Object.getOwnPropertyDescriptor(connection, \"state\");\n\n let getRaw: RawAccessors[\"getRaw\"];\n let setRaw: RawAccessors[\"setRaw\"];\n\n if (descriptor?.get) {\n // Accessor property: bind the original getter. It reads the serialized\n // attachment, so it always returns the latest value after setState.\n getRaw = descriptor.get.bind(connection) as RawAccessors[\"getRaw\"];\n setRaw = connection.setState.bind(connection);\n } else {\n // Data property: track the raw value in a closure. Reading\n // `connection.state` after the override would hit the filtered getter.\n let rawState = (connection.state ?? null) as Record<string, unknown> | null;\n getRaw = () => rawState;\n setRaw = (state: unknown) => {\n rawState = state as Record<string, unknown> | null;\n return rawState;\n };\n }\n\n rawStateAccessors.set(connection, { getRaw, setRaw });\n\n Object.defineProperty(connection, \"state\", {\n configurable: true,\n enumerable: true,\n get() {\n const raw = getRaw();\n if (raw != null && typeof raw === \"object\" && rawHasInternalKeys(raw)) {\n return stripInternalKeys(raw);\n }\n return raw;\n }\n });\n\n Object.defineProperty(connection, \"setState\", {\n configurable: true,\n writable: true,\n value(stateOrFn: unknown | ((prev: unknown) => unknown)) {\n const raw = getRaw();\n const flags =\n raw != null && typeof raw === \"object\"\n ? extractInternalFlags(raw as Record<string, unknown>)\n : {};\n const hasFlags = Object.keys(flags).length > 0;\n\n let newUserState: unknown;\n if (typeof stateOrFn === \"function\") {\n // The callback sees only user-visible state.\n const userVisible = hasFlags\n ? stripInternalKeys(raw as Record<string, unknown>)\n : raw;\n newUserState = (stateOrFn as (prev: unknown) => unknown)(userVisible);\n } else {\n newUserState = stateOrFn;\n }\n\n if (hasFlags) {\n if (newUserState != null && typeof newUserState === \"object\") {\n return setRaw({\n ...(newUserState as Record<string, unknown>),\n ...flags\n });\n }\n // User set null: keep just the flags.\n return setRaw(flags);\n }\n return setRaw(newUserState);\n }\n });\n}\n\n/** The raw connection state, internal flags included. */\nexport function getConnectionRawState(\n connection: Connection\n): Record<string, unknown> | null {\n ensureConnectionWrapped(connection);\n return rawStateAccessors.get(connection)!.getRaw();\n}\n\n/** Read an internal flag from the raw connection state. */\nexport function getConnectionFlag(\n connection: Connection,\n key: string\n): unknown {\n ensureConnectionWrapped(connection);\n return rawStateAccessors.get(connection)!.getRaw()?.[key];\n}\n\n/**\n * Write an internal flag to the raw connection state. `undefined` removes\n * the key rather than storing a dead value; the last key removed leaves\n * `null`.\n */\nexport function setConnectionFlag(\n connection: Connection,\n key: string,\n value: unknown\n): void {\n ensureConnectionWrapped(connection);\n const accessors = rawStateAccessors.get(connection)!;\n const raw = accessors.getRaw() ?? {};\n if (value === undefined) {\n const { [key]: _, ...rest } = raw;\n accessors.setRaw(Object.keys(rest).length > 0 ? rest : null);\n } else {\n accessors.setRaw({ ...raw, [key]: value });\n }\n}\n\nexport function isConnectionReadonly(connection: Connection): boolean {\n return !!getConnectionFlag(connection, CF_READONLY_KEY);\n}\n\nexport function setConnectionReadonly(\n connection: Connection,\n readonly: boolean\n): void {\n setConnectionFlag(connection, CF_READONLY_KEY, readonly ? true : undefined);\n}\n\nexport function isConnectionProtocolEnabled(connection: Connection): boolean {\n return !getConnectionFlag(connection, CF_NO_PROTOCOL_KEY);\n}\n\nexport function setConnectionProtocolEnabled(\n connection: Connection,\n enabled: boolean\n): void {\n setConnectionFlag(connection, CF_NO_PROTOCOL_KEY, enabled ? undefined : true);\n}\n","// Polyfill WebSocket status code constants for environments that don't have them\n// in order to support libraries that expect standards-compatible WebSocket\n// implementations (e.g. PartySocket)\n\nimport type {\n Connection,\n ConnectionSetStateFn,\n ConnectionState,\n LifecycleSockets\n} from \"../lifecycle\";\n\nif (!(\"OPEN\" in WebSocket)) {\n const WebSocketStatus = {\n // @ts-expect-error\n CONNECTING: WebSocket.READY_STATE_CONNECTING,\n // @ts-expect-error\n OPEN: WebSocket.READY_STATE_OPEN,\n // @ts-expect-error\n CLOSING: WebSocket.READY_STATE_CLOSING,\n // @ts-expect-error\n CLOSED: WebSocket.READY_STATE_CLOSED\n };\n\n Object.assign(WebSocket, WebSocketStatus);\n // @ts-expect-error\n Object.assign(WebSocket.prototype, WebSocketStatus);\n}\n\n/**\n * Store both platform attachments and user attachments in different namespaces\n */\ntype ConnectionAttachments = {\n __pk: {\n id: string;\n tags: string[];\n uri?: string;\n };\n __user?: unknown;\n};\n\nfunction tryGetManagedWebSocketMeta(\n ws: WebSocket\n): ConnectionAttachments[\"__pk\"] | null {\n try {\n // Avoid AttachmentCache.get() here: externally accepted sockets\n // can have an attachment without the managed __pk namespace.\n const attachment = WebSocket.prototype.deserializeAttachment.call(\n ws\n ) as unknown;\n if (!attachment || typeof attachment !== \"object\") {\n return null;\n }\n if (!(\"__pk\" in attachment)) {\n return null;\n }\n const pk = (attachment as ConnectionAttachments).__pk as unknown;\n if (!pk || typeof pk !== \"object\") {\n return null;\n }\n const { id, tags } = pk as {\n id?: unknown;\n tags?: unknown;\n };\n if (typeof id !== \"string\") {\n return null;\n }\n const { uri } = pk as { uri?: unknown };\n return {\n id,\n tags: Array.isArray(tags) ? tags : [],\n uri: typeof uri === \"string\" ? uri : undefined\n } satisfies ConnectionAttachments[\"__pk\"];\n } catch {\n return null;\n }\n}\n\nexport function isManagedWebSocket(ws: WebSocket): boolean {\n return tryGetManagedWebSocketMeta(ws) !== null;\n}\n\n/**\n * Cache websocket attachments to avoid having to rehydrate them on every property access.\n */\nclass AttachmentCache {\n #cache = new WeakMap<WebSocket, ConnectionAttachments>();\n\n get(ws: WebSocket): ConnectionAttachments {\n let attachment = this.#cache.get(ws);\n if (!attachment) {\n attachment = WebSocket.prototype.deserializeAttachment.call(\n ws\n ) as ConnectionAttachments;\n if (attachment !== undefined) {\n this.#cache.set(ws, attachment);\n } else {\n throw new Error(\"Missing managed WebSocket lifecycle attachment\");\n }\n }\n\n return attachment;\n }\n\n set(ws: WebSocket, attachment: ConnectionAttachments) {\n this.#cache.set(ws, attachment);\n WebSocket.prototype.serializeAttachment.call(ws, attachment);\n }\n}\n\nconst attachments = new AttachmentCache();\nconst connections = new WeakSet<Connection>();\nconst isWrapped = (ws: WebSocket): ws is Connection => {\n return connections.has(ws as Connection);\n};\n\n/**\n * Wraps a WebSocket with Connection fields that rehydrate the\n * socket attachments lazily only when requested.\n */\nexport const createConnection = (ws: WebSocket | Connection): Connection => {\n if (isWrapped(ws)) {\n return ws;\n }\n\n // if state was set on the socket before initializing the connection,\n // capture it here so we can persist it again\n let initialState;\n if (\"state\" in ws) {\n initialState = ws.state;\n delete ws.state;\n }\n\n const connection = Object.defineProperties(ws, {\n id: {\n configurable: true,\n get() {\n return attachments.get(ws).__pk.id;\n }\n },\n uri: {\n configurable: true,\n get() {\n return attachments.get(ws).__pk.uri ?? null;\n }\n },\n tags: {\n configurable: true,\n get() {\n // Default to [] for connections accepted before tags were stored\n return attachments.get(ws).__pk.tags ?? [];\n }\n },\n state: {\n configurable: true,\n get() {\n const attachment = attachments.get(ws);\n return (attachment.__user ?? null) as ConnectionState<unknown>;\n }\n },\n setState: {\n configurable: true,\n value: function setState<T>(setState: T | ConnectionSetStateFn<T>) {\n const state =\n setState instanceof Function\n ? setState((this as Connection<T>).state)\n : setState;\n attachments.set(ws, {\n ...attachments.get(ws),\n __user: state ?? null\n });\n return state as ConnectionState<T>;\n }\n }\n }) as Connection;\n\n if (initialState) {\n connection.setState(initialState);\n }\n\n connections.add(connection);\n return connection;\n};\n\nclass ConnectionIterator<T> implements IterableIterator<Connection<T>> {\n private index = 0;\n #sockets: WebSocket[] | undefined;\n constructor(\n private sockets: LifecycleSockets,\n private tag?: string\n ) {}\n\n [Symbol.iterator](): IterableIterator<Connection<T>> {\n return this;\n }\n\n next(): IteratorResult<Connection<T>, number | undefined> {\n const sockets =\n this.#sockets ?? (this.#sockets = this.sockets.get(this.tag));\n\n let socket: WebSocket;\n while ((socket = sockets[this.index++])) {\n // Only yield open sockets.\n if (socket.readyState === WebSocket.OPEN) {\n // Durable Objects hibernation APIs allow storing arbitrary sockets via\n // `state.acceptWebSocket()`. Ignore sockets without our attachment.\n if (!isManagedWebSocket(socket)) {\n continue;\n }\n const value = createConnection(socket) as Connection<T>;\n return { done: false, value };\n }\n }\n\n // reached the end of the iteratee\n return { done: true, value: undefined };\n }\n}\n\n/**\n * Deduplicate and validate connection tags.\n * Returns the final tag array (always includes the connection id as the first tag).\n */\nexport function prepareTags(\n connectionId: string,\n userTags: string[]\n): string[] {\n const tags = [connectionId, ...userTags.filter((t) => t !== connectionId)];\n\n // validate tags against documented restrictions\n // https://developers.cloudflare.com/durable-objects/api/hibernatable-websockets-api/#state-methods-for-websockets\n if (tags.length > 10) {\n throw new Error(\n \"A connection can only have 10 tags, including the default id tag.\"\n );\n }\n\n for (const tag of tags) {\n if (typeof tag !== \"string\") {\n throw new Error(`A connection tag must be a string. Received: ${tag}`);\n }\n if (tag === \"\") {\n throw new Error(\"A connection tag must not be an empty string.\");\n }\n if (tag.length > 256) {\n throw new Error(\"A connection tag must not exceed 256 characters\");\n }\n }\n\n return tags;\n}\n\n/** The platform-backed manager for hibernating WebSockets. */\nexport class ConnectionManager<TState = unknown> {\n constructor(private controller: LifecycleSockets) {}\n\n getConnection<T = TState>(id: string) {\n // TODO: Should we cache the connections?\n const sockets = this.controller.get(id);\n const matching = sockets.filter((ws) => {\n return tryGetManagedWebSocketMeta(ws)?.id === id;\n });\n\n if (matching.length === 0) return undefined;\n if (matching.length === 1)\n return createConnection(matching[0]) as Connection<T>;\n\n throw new Error(\n `More than one connection found for id ${id}. Did you mean to use getConnections(tag) instead?`\n );\n }\n\n getConnections<T = TState>(tag?: string | undefined) {\n return new ConnectionIterator<T>(this.controller, tag);\n }\n\n accept(connection: Connection, options: { tags: string[] }) {\n const tags = prepareTags(connection.id, options.tags);\n\n this.controller.accept(connection, tags);\n attachments.set(connection, {\n __pk: {\n id: connection.id,\n tags,\n uri: connection.uri ?? undefined\n },\n __user: null\n });\n\n return createConnection(connection);\n }\n}\n","import { RpcTarget } from \"cloudflare:workers\";\nimport { CAPNWEB_TRANSPORT_SEND } from \"./transport-protocol\";\n\n/** A named remote method ready to be exposed on a callables root. */\nexport type CallableInvoker = (...args: unknown[]) => unknown;\n\n/**\n * The single exposure policy for callable names. `Object.prototype` and\n * `RpcTarget.prototype` members are unreachable over Cap'n Web anyway\n * and are silently excluded; `then` is rejected loudly because exposing\n * it would make the remote stub thenable.\n */\nfunction assertExposable(name: string): boolean {\n if (name === \"then\") {\n throw new Error(\n 'A callables target cannot expose a method named \"then\" — it would make the remote stub thenable'\n );\n }\n if (name === CAPNWEB_TRANSPORT_SEND) {\n throw new Error(\n `A callables target cannot expose \"${CAPNWEB_TRANSPORT_SEND}\"; it is the transport's frame pipe`\n );\n }\n return !(\n name === \"constructor\" ||\n name in Object.prototype ||\n name in RpcTarget.prototype\n );\n}\n\n/**\n * The exposable prototype methods of a callables target, each bound to\n * invoke on the real instance (so private fields and `this` behave).\n *\n * Cap'n Web resolves methods on the prototype chain and rejects own\n * instance properties, so only prototype methods participate. The\n * nearest declaration wins for overridden names.\n *\n * @param target - The callables target to enumerate.\n * @returns Method names mapped to invokers on the target.\n */\nexport function exposableMethods(\n target: RpcTarget\n): ReadonlyMap<string, CallableInvoker> {\n const methods = new Map<string, CallableInvoker>();\n const seen = new Set<string>();\n let prototype: object | null = Object.getPrototypeOf(target);\n while (\n prototype &&\n prototype !== RpcTarget.prototype &&\n prototype !== Object.prototype\n ) {\n for (const name of Object.getOwnPropertyNames(prototype)) {\n if (seen.has(name)) continue;\n seen.add(name);\n if (!assertExposable(name)) continue;\n const descriptor = Object.getOwnPropertyDescriptor(prototype, name);\n if (!descriptor || typeof descriptor.value !== \"function\") continue;\n // SAFETY: `typeof descriptor.value === \"function\"` was checked\n // above; TypeScript cannot narrow a descriptor's `value` field.\n const method = descriptor.value as CallableInvoker;\n methods.set(name, (...args) => Reflect.apply(method, target, args));\n }\n prototype = Object.getPrototypeOf(prototype);\n }\n return methods;\n}\n\n/**\n * Build a Cap'n Web session root exposing exactly the given methods.\n *\n * Cap'n Web resolves methods on the prototype chain, rejects own\n * instance properties, and breaks on Proxy-wrapped roots — so the root\n * is a private `RpcTarget` subclass whose prototype carries the methods\n * and nothing else.\n */\nexport function buildRoot(\n methods: ReadonlyMap<string, CallableInvoker>\n): RpcTarget {\n class Root extends RpcTarget {}\n for (const [name, invoke] of methods) {\n Object.defineProperty(Root.prototype, name, {\n value: invoke,\n writable: true,\n configurable: true,\n enumerable: false\n });\n }\n return new Root();\n}\n","import { newWebSocketRpcSession, type RpcStub } from \"capnweb\";\nimport type {\n Connection,\n ConnectionContext,\n ConnectionSetStateFn,\n ConnectionState\n} from \"../lifecycle\";\nimport { buildRoot, type CallableInvoker } from \"./callables-target\";\nimport { prepareTags } from \"./connection\";\nimport {\n CAPNWEB_TRANSPORT_SEND,\n type TransportClientEvents,\n type TransportMessage\n} from \"./transport-protocol\";\n\n/**\n * A non-hibernating connection with the public `Connection` contract,\n * backed by a Cap'n Web session instead of a hibernating socket. It lives\n * only in memory and disappears with the isolate.\n */\nclass CapnWebConnection extends EventTarget {\n readonly CONNECTING = WebSocket.CONNECTING;\n readonly OPEN = WebSocket.OPEN;\n readonly CLOSING = WebSocket.CLOSING;\n readonly CLOSED = WebSocket.CLOSED;\n readyState: number = WebSocket.OPEN;\n state: ConnectionState<unknown> = null;\n tags: readonly string[] = [];\n\n constructor(\n readonly id: string,\n readonly uri: string,\n private readonly pipe: {\n send(message: TransportMessage): void;\n close(code?: number, reason?: string): void;\n }\n ) {\n super();\n }\n\n send(message: TransportMessage): void {\n if (this.readyState !== WebSocket.OPEN) {\n throw new TypeError(\"WebSocket send() after close\");\n }\n this.pipe.send(message);\n }\n\n close(code?: number, reason?: string): void {\n if (this.readyState >= WebSocket.CLOSING) return;\n this.pipe.close(code, reason);\n this.readyState = WebSocket.CLOSING;\n }\n\n setState<T = unknown>(\n next: T | ConnectionSetStateFn<T> | null\n ): ConnectionState<T> {\n const state =\n typeof next === \"function\"\n ? (next as ConnectionSetStateFn<T>)(this.state as ConnectionState<T>)\n : next;\n this.state = state as ConnectionState<unknown>;\n return state as ConnectionState<T>;\n }\n}\n\n/** One live transport session. */\nexport type CapnWebSession = {\n readonly connection: Connection;\n /** Tear the session down; runs the close handler once. */\n dispose(): void;\n};\n\n/** What the capability supplies to run one session. */\nexport type CapnWebSessionOptions = {\n readonly request: Request;\n readonly connectionId: string;\n readonly tags: (\n connection: Connection,\n ctx: ConnectionContext\n ) => string[] | Promise<string[]>;\n readonly onConnect: (\n connection: Connection,\n ctx: ConnectionContext\n ) => Promise<void>;\n readonly onMessage: (\n connection: Connection,\n message: TransportMessage\n ) => Promise<void>;\n readonly onClose: (\n connection: Connection,\n code: number,\n reason: string,\n wasClean: boolean\n ) => Promise<void>;\n readonly onError: (connection: Connection, error: unknown) => Promise<void>;\n /**\n * Native methods served on the session root beside the frame pipe. Each\n * invoker already runs inside the host boundary for this connection.\n * Results pass by Cap'n Web semantics: an `RpcTarget` becomes a live\n * stub, a `ReadableStream` streams, and calls pipeline.\n */\n readonly callables: (\n connection: Connection\n ) => ReadonlyMap<string, CallableInvoker>;\n /**\n * Called once the connection exists, before `onConnect`, so it is already\n * visible in `getConnections()` while the connect handler runs — the same\n * ordering as a hibernating socket, which is accepted before `onConnect`.\n */\n readonly onOpen: (session: CapnWebSession) => void;\n /** Called exactly once when the session ends, before `onClose`. */\n readonly onDispose: (session: CapnWebSession) => void;\n};\n\n/**\n * Accept a Cap'n Web transport upgrade.\n *\n * The session root carries the frame pipe plus the host's native\n * callables. The client's protocol frames arrive through the pipe and are\n * handed to `onMessage`; the host's frames go out through the client's\n * `message` callback; `useAgent().stub` calls hit the callables directly.\n * The socket is a plain in-memory `WebSocketPair`, so it pins the Durable\n * Object and does not survive hibernation.\n */\nexport async function openCapnWebSession(\n options: CapnWebSessionOptions\n): Promise<{ response: Response; session: CapnWebSession }> {\n const { request, connectionId } = options;\n const pair = new WebSocketPair();\n const server = pair[0];\n server.accept();\n\n let client: RpcStub<TransportClientEvents> | undefined;\n let closed = false;\n let close = { code: 1000, reason: \"\", wasClean: true };\n\n const connection = new CapnWebConnection(connectionId, request.url, {\n send: (message) => {\n void client?.message(message).catch((error: unknown) => {\n if (!closed) console.error(\"Cap'n Web frame delivery failed:\", error);\n });\n },\n close: (code = 1000, reason = \"\") => {\n // Same contract as WebSocket.close(): a reserved code or an oversize\n // reason throws before anything changes, and the socket stays open\n // and tracked. Only a started handshake finishes the session.\n server.close(code, reason);\n close = { code, reason, wasClean: true };\n void finish();\n }\n }) as unknown as Connection & CapnWebConnection;\n\n const session: CapnWebSession = {\n connection,\n dispose: () => connection.close(1001, \"Session replaced\")\n };\n\n const finish = async () => {\n if (closed) return;\n closed = true;\n connection.readyState = WebSocket.CLOSED;\n try {\n client?.[Symbol.dispose]();\n } catch {\n // The session already ended with the socket.\n }\n options.onDispose(session);\n await options.onClose(connection, close.code, close.reason, close.wasClean);\n };\n\n const rootMethods = new Map<string, CallableInvoker>(\n options.callables(connection)\n );\n rootMethods.set(CAPNWEB_TRANSPORT_SEND, (message) =>\n options.onMessage(connection, message as TransportMessage)\n );\n client = newWebSocketRpcSession<TransportClientEvents>(\n server,\n buildRoot(rootMethods)\n );\n\n server.addEventListener(\n \"close\",\n (event) => {\n close = {\n code: event.code,\n reason: event.reason,\n wasClean: event.wasClean\n };\n void finish();\n },\n { once: true }\n );\n server.addEventListener(\n \"error\",\n (event) => {\n if (closed) return;\n close = { ...close, wasClean: false };\n const error =\n event instanceof ErrorEvent\n ? (event.error ?? new Error(event.message))\n : new Error(\"Cap'n Web transport socket error\");\n void options\n .onError(connection, error)\n .catch((handlerError: unknown) => {\n console.error(\"Cap'n Web onError handler failed:\", handlerError);\n })\n .finally(finish);\n },\n { once: true }\n );\n\n const ctx = { request };\n // Same limits as the hibernating wire (count, emptiness, length), so a\n // handler sees one tag policy whichever transport the client chose.\n connection.tags = prepareTags(\n connectionId,\n await options.tags(connection, ctx)\n );\n options.onOpen(session);\n try {\n await options.onConnect(connection, ctx);\n } catch (error) {\n connection.close(1011, \"onConnect failed\");\n throw error;\n }\n\n return {\n response: new Response(null, { status: 101, webSocket: pair[1] }),\n session\n };\n}\n","import { RpcTarget } from \"cloudflare:workers\";\nimport { nanoid } from \"nanoid\";\nimport {\n LifecycleCapability,\n type CapabilityWebSocketUpgradeContext,\n type Connection,\n type ConnectionContext,\n type ConnectionSetStateFn,\n type ConnectionState\n} from \"../lifecycle\";\nimport { MessageType } from \"../types\";\nimport { camelCaseToKebabCase } from \"../utils\";\nimport {\n ConnectionManager,\n createConnection,\n isManagedWebSocket\n} from \"./connection\";\nimport {\n ensureConnectionWrapped,\n isConnectionProtocolEnabled,\n isConnectionReadonly,\n setConnectionProtocolEnabled,\n setConnectionReadonly\n} from \"./connection-flags\";\nimport { exposableMethods, type CallableInvoker } from \"./callables-target\";\nimport type {\n SyncedState,\n WebSocketHandlers,\n WebSocketMessage,\n WebSocketsOptions\n} from \"./options\";\nimport { openCapnWebSession, type CapnWebSession } from \"./transport\";\nimport { isCapnWebTransportUpgrade } from \"./transport-protocol\";\n\n/**\n * Reserved close codes the runtime synthesizes when there was no real\n * Close frame from the peer (1005 NoStatusReceived, 1006 AbnormalClosure,\n * 1015 TLSHandshake). They cannot appear in an outgoing Close frame, and\n * there is no peer left to receive a reciprocation.\n */\nfunction isReservedCloseCode(code: number): boolean {\n return code === 1005 || code === 1006 || code === 1015;\n}\n\n/**\n * Reciprocate a peer-initiated Close frame to complete the handshake, as\n * the Hibernation API contract requires. Best-effort: swallows errors\n * from already-closed sockets or invalid codes/reasons, and skips\n * reciprocation entirely for reserved codes (dead transport).\n */\nfunction reciprocateClose(ws: WebSocket, code: number, reason: string): void {\n if (isReservedCloseCode(code)) return;\n try {\n ws.close(code, reason);\n } catch {\n // Already closed, oversize reason, or another unrecoverable\n // invariant — the handshake is either done or out of our control.\n }\n}\n\n/** The `rpc` request frame `useAgent().call` and `AgentClient.call` send. */\ntype RpcRequest = {\n readonly type: \"rpc\";\n readonly id: string;\n readonly method: string;\n readonly args: unknown[];\n};\n\ntype RpcResponse =\n | { type: \"rpc\"; id: string; success: true; done: boolean; result: unknown }\n | { type: \"rpc\"; id: string; success: false; error: string };\n\n/** The `cf_agent_state` frame a client sends to update host state. */\ntype StateFrame = { readonly type: \"cf_agent_state\"; readonly state: unknown };\n\nfunction isStateFrame(value: unknown): value is StateFrame {\n if (typeof value !== \"object\" || value === null) return false;\n const frame = value as Record<string, unknown>;\n return frame.type === MessageType.CF_AGENT_STATE && \"state\" in frame;\n}\n\n/** Parse a text frame; anything that is not JSON is `undefined`. */\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\nfunction isRpcRequest(value: unknown): value is RpcRequest {\n if (typeof value !== \"object\" || value === null) return false;\n const frame = value as Record<string, unknown>;\n return (\n frame.type === MessageType.RPC &&\n typeof frame.id === \"string\" &&\n typeof frame.method === \"string\" &&\n Array.isArray(frame.args)\n );\n}\n\n/**\n * Opt-in WebSocket support for Lifecycle Objects.\n *\n * Lifecycle itself does not model WebSockets — hosts that want them\n * install this capability, which owns the connection subsystem end to\n * end: it claims upgrades, dispatches `onConnect`/`onMessage`/`onClose`\n * inside the host invocation boundary, reciprocates close handshakes,\n * and answers `getConnections()`/`getConnection()`.\n *\n * ```ts\n * class Room extends DurableObject<Env> {\n * readonly webSockets = new WebSockets({\n * handlers: {\n * onConnect: (connection) => connection.send(\"welcome\"),\n * onMessage: (connection, message) => { ... }\n * },\n * callables: new RoomCallables()\n * });\n * readonly lifecycle = Lifecycle.install(this).use(this.webSockets);\n * }\n * ```\n *\n * Connections arrive on one of two wires, chosen by the client:\n *\n * - **cf-websocket** (default): accepted with the Hibernation API. Idle\n * clients stay connected while the Durable Object leaves memory.\n * - **capnweb** (`?__agents_transport=capnweb`): protocol frames through\n * one pipe method on a Cap'n Web session whose root also carries the\n * host's callables natively. Non-hibernating — the object stays pinned\n * while the connection is open.\n *\n * Both wires dispatch the same handlers and appear in `getConnections()`.\n * On both, the capability speaks the Agent protocol a plain host needs\n * for `useAgent` and `AgentClient`: it sends the identity frame on\n * connect, and it serves `callables` — as `rpc` JSON frames on the\n * WebSocket wire, and natively on the Cap'n Web session root, where an\n * `RpcTarget` result becomes a live stub and calls pipeline. `call()`\n * and `stub` work against a plain Durable Object exactly as against an\n * `Agent`. Pass a `State` capability as `state` and the hook's\n * `state`/`setState` work too: the current value is pushed on connect\n * and client updates are validated and applied; the state owner\n * broadcasts changes with `broadcastState()`. Per-connection readonly\n * and no-protocol flags live here as well, for every host.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class WebSockets extends LifecycleCapability {\n /** Claims every upgrade, so Lifecycle dispatches it after all others. */\n override readonly claims = \"catch-all\";\n\n readonly #handlers: WebSocketHandlers | undefined;\n readonly #getConnectionTags: WebSocketsOptions[\"getConnectionTags\"];\n readonly #protocol: WebSocketsOptions[\"protocol\"];\n readonly #readonly: WebSocketsOptions[\"readonly\"];\n readonly #state: SyncedState | undefined;\n /**\n * Connections inside their connect sequence, before the state push.\n * `broadcastState()` skips them: reading state for the push can seed the\n * initial value, whose change broadcast would otherwise reach a\n * connection that is about to receive the same value directly.\n */\n readonly #connecting = new Set<Connection>();\n readonly #callables: ReadonlyMap<string, CallableInvoker>;\n readonly #sessions = new Map<string, CapnWebSession>();\n #manager: ConnectionManager | undefined;\n\n constructor(options: WebSocketsOptions = {}) {\n super(\"websockets\");\n this.#handlers = options.handlers;\n this.#getConnectionTags = options.getConnectionTags;\n this.#protocol = options.protocol ?? true;\n this.#readonly = options.readonly;\n this.#state = options.state;\n this.#callables = options.callables\n ? exposableMethods(options.callables)\n : new Map();\n }\n\n // ── Lifecycle capability hooks ─────────────────────────────────────────\n\n /**\n * Claim every upgrade, never declining: a Cap'n Web transport upgrade\n * becomes a session, everything else a tracked hibernating connection,\n * whether or not handlers or callables are configured. Handlers only add\n * behavior on connect, message, close, and error.\n */\n onWebSocketUpgrade({\n request\n }: CapabilityWebSocketUpgradeContext): Promise<Response> {\n return isCapnWebTransportUpgrade(request)\n ? this.#acceptCapnWebSession(request)\n : this.#acceptConnection(request);\n }\n\n /** Dispatch a platform message wake for a capability-owned socket. */\n async onWebSocketMessage(\n ws: WebSocket,\n message: WebSocketMessage\n ): Promise<boolean> {\n if (!isManagedWebSocket(ws)) return false;\n await this.#message(createConnection(ws), message);\n return true;\n }\n\n /** Dispatch and reciprocate a close wake for an owned socket. */\n async onWebSocketClose(\n ws: WebSocket,\n code: number,\n reason: string,\n wasClean: boolean\n ): Promise<boolean> {\n if (!isManagedWebSocket(ws)) return false;\n try {\n await this.#close(createConnection(ws), code, reason, wasClean);\n } finally {\n reciprocateClose(ws, code, reason);\n }\n return true;\n }\n\n /** Dispatch an error wake for an owned socket. */\n async onWebSocketError(ws: WebSocket, error: unknown): Promise<boolean> {\n if (!isManagedWebSocket(ws)) return false;\n await this.#error(createConnection(ws), error);\n return true;\n }\n\n /**\n * Close every owned connection during explicit host destruction. The\n * capability owns its sockets' lifetimes, so it also owns tearing\n * them down.\n */\n dispose(): void {\n for (const connection of this.getConnections()) {\n try {\n connection.close(1001, \"Durable Object destroyed\");\n } catch {\n // Already closed or mid-handshake — nothing left to tear down.\n }\n }\n }\n\n // ── Connections ────────────────────────────────────────────────────────\n\n /** Open connections on either wire, optionally by tag. */\n *getConnections<TState = unknown>(\n tag?: string\n ): IterableIterator<Connection<TState>> {\n for (const { connection } of this.#sessions.values()) {\n if (connection.readyState !== WebSocket.OPEN) continue;\n if (!tag || connection.tags.includes(tag)) {\n yield connection as Connection<TState>;\n }\n }\n yield* this.#connectionManager.getConnections<TState>(tag);\n }\n\n /** One connection on either wire, by id. */\n getConnection<TState = unknown>(id: string): Connection<TState> | undefined {\n const session = this.#sessions.get(id)?.connection;\n if (session && session.readyState === WebSocket.OPEN) {\n return session as Connection<TState>;\n }\n return this.#connectionManager.getConnection<TState>(id);\n }\n\n get #connectionManager(): ConnectionManager {\n this.#manager ??= new ConnectionManager(this.lifecycle.sockets);\n return this.#manager;\n }\n\n // ── Wire-independent protocol ──────────────────────────────────────────\n\n async #connect(\n connection: Connection,\n ctx: ConnectionContext\n ): Promise<void> {\n ensureConnectionWrapped(connection);\n // Flags first, so they are set before the client can respond.\n if (this.#readonly?.(connection, ctx)) {\n setConnectionReadonly(connection, true);\n }\n if (this.#protocol !== false) {\n const enabled =\n typeof this.#protocol === \"function\"\n ? this.#protocol(connection, ctx)\n : true;\n if (enabled) {\n this.sendConnectFrames(connection);\n } else {\n setConnectionProtocolEnabled(connection, false);\n }\n }\n await this.lifecycle.runInHostContext(\n () => this.#handlers?.onConnect?.(connection, ctx),\n { connection, request: ctx.request }\n );\n }\n\n async #message(\n connection: Connection,\n message: WebSocketMessage\n ): Promise<void> {\n if (\n this.#state &&\n this.#protocol !== false &&\n typeof message === \"string\"\n ) {\n const frame = parseJson(message);\n if (isStateFrame(frame)) {\n // Inside the host boundary, so the host's validator and change\n // hook see the sending connection through the ambient context.\n await this.lifecycle.runInHostContext(\n () => this.applyStateFrame(connection, frame),\n { connection }\n );\n return;\n }\n }\n if (\n this.#callables.size > 0 &&\n (await this.#answerRpc(connection, message))\n ) {\n return;\n }\n await this.lifecycle.runInHostContext(\n () => this.#handlers?.onMessage?.(connection, message),\n { connection }\n );\n }\n\n #close(\n connection: Connection,\n code: number,\n reason: string,\n wasClean: boolean\n ): Promise<unknown> {\n return this.lifecycle.runInHostContext(\n () => this.#handlers?.onClose?.(connection, code, reason, wasClean),\n { connection }\n );\n }\n\n #error(connection: Connection, error: unknown): Promise<unknown> {\n return this.lifecycle.runInHostContext(\n () => this.#handlers?.onError?.(connection, error),\n { connection }\n );\n }\n\n // ── Hibernating wire ───────────────────────────────────────────────────\n\n async #acceptConnection(request: Request): Promise<Response> {\n const { 0: clientWebSocket, 1: serverWebSocket } = new WebSocketPair();\n const url = new URL(request.url);\n // `||`, not `??`: an empty `?_pk=` value must fall back to a\n // generated id — an empty connection id would later throw in tag\n // validation and reject the upgrade.\n const connectionId = url.searchParams.get(\"_pk\") || nanoid();\n\n let connection: Connection = Object.assign(serverWebSocket, {\n id: connectionId,\n uri: request.url,\n tags: [] as string[],\n state: null as unknown as ConnectionState<unknown>,\n setState<T = unknown>(setState: T | ConnectionSetStateFn<T>) {\n // Pre-accept shim: hold state on the socket until accept()\n // persists it into the hibernation attachment.\n const state =\n setState instanceof Function\n ? setState(this.state as ConnectionState<T>)\n : setState;\n this.state = state as ConnectionState<T>;\n return this.state as ConnectionState<T>;\n }\n });\n\n const ctx = { request };\n const tags = this.#getConnectionTags\n ? await this.#getConnectionTags(connection, ctx)\n : [];\n\n // Hibernating WebSockets remain connected while the object is evicted.\n connection = this.#connectionManager.accept(connection, { tags });\n await this.#connect(connection, ctx);\n\n return new Response(null, { status: 101, webSocket: clientWebSocket });\n }\n\n // ── Cap'n Web wire ─────────────────────────────────────────────────────\n\n async #acceptCapnWebSession(request: Request): Promise<Response> {\n const connectionId =\n new URL(request.url).searchParams.get(\"_pk\") || nanoid();\n // A reconnect reusing the id replaces the previous session.\n this.#sessions.get(connectionId)?.dispose();\n\n const { response } = await openCapnWebSession({\n request,\n connectionId,\n tags: (connection, ctx) =>\n this.#getConnectionTags?.(connection, ctx) ?? [],\n onConnect: (connection, ctx) => this.#connect(connection, ctx),\n onMessage: (connection, message) => this.#message(connection, message),\n onClose: (connection, code, reason, wasClean) =>\n this.#close(connection, code, reason, wasClean).then(() => undefined),\n onError: (connection, error) =>\n this.#error(connection, error).then(() => undefined),\n callables: (connection) => this.#nativeCallables(connection),\n onOpen: (session) => this.#sessions.set(connectionId, session),\n onDispose: (ended) => {\n if (this.#sessions.get(connectionId) === ended) {\n this.#sessions.delete(connectionId);\n }\n }\n });\n return response;\n }\n\n // ── Protocol frames ────────────────────────────────────────────────────\n //\n // The Agent protocol a client (`useAgent`, `AgentClient`) speaks, owned\n // here for every host. With `protocol: true` the capability drives the\n // connect sequence and consumes state frames itself; with\n // `protocol: false` the host calls these at the moments it chooses.\n\n /**\n * Send the connect sequence: the identity frame, then the current state\n * when one is stored. The identity carries `stateFollows` in that case,\n * so clients resolve `ready` only once the state has landed. Nothing is\n * sent to a no-protocol connection. Identity defaults as for\n * `sendIdentity()`.\n */\n sendConnectFrames(\n connection: Connection,\n identity: { name: string; agent: string } = this.#defaultIdentity()\n ): void {\n if (!isConnectionProtocolEnabled(connection)) return;\n this.#connecting.add(connection);\n try {\n const current = this.#state?.get();\n // Serialized first: a flagged identity must never go out without\n // the state frame the client will wait for.\n const stateFrame =\n current === undefined\n ? undefined\n : JSON.stringify({\n type: MessageType.CF_AGENT_STATE,\n state: current\n });\n this.#sendFrame(connection, {\n type: MessageType.CF_AGENT_IDENTITY,\n name: identity.name,\n agent: identity.agent,\n ...(stateFrame !== undefined && { stateFollows: true })\n });\n if (stateFrame !== undefined) this.#send(connection, stateFrame);\n } finally {\n this.#connecting.delete(connection);\n }\n }\n\n /**\n * Send the identity frame alone, unless the connection is no-protocol.\n * Clients resolve `ready` on it, so a host that also pushes state on\n * connect should use `sendConnectFrames()`. The defaults are the Durable\n * Object's routed name and host class; a host whose public identity\n * differs — an `Agent` facet, whose routed name is an internal encoding\n * of its logical name — passes its own.\n */\n sendIdentity(\n connection: Connection,\n identity: { name: string; agent: string } = this.#defaultIdentity()\n ): void {\n if (!isConnectionProtocolEnabled(connection)) return;\n this.#sendFrame(connection, {\n type: MessageType.CF_AGENT_IDENTITY,\n name: identity.name,\n agent: identity.agent\n });\n }\n\n #defaultIdentity(): { name: string; agent: string } {\n return {\n name: this.lifecycle.name,\n agent: camelCaseToKebabCase(this.lifecycle.className)\n };\n }\n\n /**\n * Send the current state to one connection, unless nothing is stored\n * or the connection is no-protocol. Reading the state may seed the\n * initial value; see `#connecting`.\n */\n sendState(connection: Connection): void {\n if (!this.#state || !isConnectionProtocolEnabled(connection)) return;\n const current = this.#state.get();\n if (current === undefined) return;\n this.#sendFrame(connection, {\n type: MessageType.CF_AGENT_STATE,\n state: current\n });\n }\n\n /**\n * Apply a parsed `cf_agent_state` frame from a client. A readonly\n * connection is refused; a change the host's validator rejects is\n * logged in full server-side and answered with a generic\n * `cf_agent_state_error`. Broadcasting the accepted change is the state\n * owner's call, through its `onChanged` hook. Callers that drive the\n * protocol themselves call this inside their own invocation context;\n * the capability's automatic path does so via `runInHostContext`.\n *\n * @returns Whether the frame was a state frame (handled either way).\n */\n applyStateFrame(connection: Connection, frame: unknown): boolean {\n if (!this.#state || !isStateFrame(frame)) return false;\n if (isConnectionReadonly(connection)) {\n this.#sendFrame(connection, {\n type: MessageType.CF_AGENT_STATE_ERROR,\n error: \"Connection is readonly\"\n });\n return true;\n }\n try {\n // `never` on the port keeps any `State<T>` assignable; the value\n // came off the wire, so the host's validator is what checks it.\n this.#state.set(frame.state as never, connection);\n } catch (error) {\n console.error(\"[WebSockets] State update rejected:\", error);\n this.#sendFrame(connection, {\n type: MessageType.CF_AGENT_STATE_ERROR,\n error: \"State update rejected\"\n });\n }\n return true;\n }\n\n /**\n * Push the current state to every protocol-enabled connection except\n * the one a change came from, which already has the value it sent.\n * Wire a `State`'s `onChanged` to this.\n */\n broadcastState(except?: Connection | \"server\"): void {\n if (!this.#state) return;\n const current = this.#state.get();\n if (current === undefined) return;\n const frame = { type: MessageType.CF_AGENT_STATE, state: current };\n for (const connection of this.getConnections()) {\n // Object identity, not id: `_pk` is client-supplied, so two live\n // sockets can share an id, and excluding by id would starve the\n // other one. `createConnection` returns one wrapper per socket.\n if (connection === except) continue;\n if (this.#connecting.has(connection)) continue;\n if (!isConnectionProtocolEnabled(connection)) continue;\n this.#sendFrame(connection, frame);\n }\n }\n\n // ── Connection flags ───────────────────────────────────────────────────\n\n /** Whether the connection may update host state over the wire. */\n isReadonly(connection: Connection): boolean {\n return isConnectionReadonly(connection);\n }\n\n /** Mark a connection readonly, or writable again. */\n setReadonly(connection: Connection, readonly = true): void {\n setConnectionReadonly(connection, readonly);\n }\n\n /** Whether protocol text frames reach the connection. */\n isProtocolEnabled(connection: Connection): boolean {\n return isConnectionProtocolEnabled(connection);\n }\n\n /** Enable or suppress protocol text frames for a connection. */\n setProtocolEnabled(connection: Connection, enabled: boolean): void {\n setConnectionProtocolEnabled(connection, enabled);\n }\n\n /**\n * Send one protocol frame. Serialization is the caller's contract — every\n * frame built here is plain JSON — while a send failure is tolerated: the\n * peer may have disconnected between the wake and the send.\n */\n #sendFrame(connection: Connection, frame: Record<string, unknown>): void {\n this.#send(connection, JSON.stringify(frame));\n }\n\n /** Write one already-serialized frame, tolerating a closed peer. */\n #send(connection: Connection, text: string): void {\n try {\n connection.send(text);\n } catch {\n // The socket closed between the wake and the send.\n }\n }\n\n // ── Callables ──────────────────────────────────────────────────────────\n\n /**\n * The `callables` target as native Cap'n Web methods for one session:\n * every method dispatches through the host boundary with this\n * connection in scope and emits `rpc`/`rpc:error` events. Return values\n * keep Cap'n Web semantics — an `RpcTarget` comes back as a live stub.\n */\n #nativeCallables(\n connection: Connection\n ): ReadonlyMap<string, CallableInvoker> {\n const methods = new Map<string, CallableInvoker>();\n for (const [name, invoke] of this.#callables) {\n methods.set(name, (...args) =>\n this.#dispatchCallable(name, () => invoke(...args), connection)\n );\n }\n return methods;\n }\n\n /**\n * Answer one `rpc` frame against `callables`. A `ReadableStream`\n * result streams as `done: false` chunks followed by a final\n * `done: true` frame, matching the client's stream callbacks.\n *\n * @returns Whether the message was an `rpc` frame (answered or not).\n */\n async #answerRpc(\n connection: Connection,\n raw: WebSocketMessage\n ): Promise<boolean> {\n if (typeof raw !== \"string\") return false;\n let frame: unknown;\n try {\n frame = JSON.parse(raw);\n } catch {\n return false;\n }\n if (!isRpcRequest(frame)) return false;\n const { id, method, args } = frame;\n\n const invoke = this.#callables.get(method);\n if (!invoke) {\n this.#reply(connection, {\n type: \"rpc\",\n id,\n success: false,\n error: `Method ${method} does not exist`\n });\n return true;\n }\n\n try {\n const result = await this.#dispatchCallable(\n method,\n () => invoke(...args),\n connection\n );\n if (result instanceof RpcTarget) {\n // By-reference results only exist on the Cap'n Web wire; a JSON\n // frame would silently flatten the target to `{}`.\n throw new Error(\n `Method ${method} returns an RpcTarget, which only the capnweb transport can carry`\n );\n }\n if (result instanceof ReadableStream) {\n for await (const chunk of result) {\n this.#reply(connection, {\n type: \"rpc\",\n id,\n success: true,\n done: false,\n result: chunk\n });\n }\n this.#reply(connection, {\n type: \"rpc\",\n id,\n success: true,\n done: true,\n result: undefined\n });\n } else {\n this.#reply(connection, {\n type: \"rpc\",\n id,\n success: true,\n done: true,\n result\n });\n }\n } catch (error) {\n this.#reply(connection, {\n type: \"rpc\",\n id,\n success: false,\n error: error instanceof Error ? error.message : String(error)\n });\n }\n return true;\n }\n\n #reply(connection: Connection, response: RpcResponse): void {\n let text: string;\n try {\n text = JSON.stringify(response);\n } catch (error) {\n // A result that JSON cannot carry (a BigInt, a cycle) must still\n // settle the caller: answer with an error instead of silence.\n text = JSON.stringify({\n type: \"rpc\",\n id: response.id,\n success: false,\n error: `Result is not JSON-serializable: ${\n error instanceof Error ? error.message : String(error)\n }`\n } satisfies RpcResponse);\n }\n this.#send(connection, text);\n }\n\n async #dispatchCallable(\n name: string,\n invoke: () => unknown,\n connection: Connection\n ): Promise<unknown> {\n // Throws with installation guidance when the capability was never\n // installed with Lifecycle.use().\n const services = this.lifecycle;\n try {\n const result = await services.runInHostContext(invoke, { connection });\n services.events.emit(\"rpc\", {\n method: name,\n streaming: result instanceof ReadableStream\n });\n return result;\n } catch (error) {\n services.events.emit(\"rpc:error\", {\n method: name,\n error: error instanceof Error ? error.message : String(error)\n });\n throw error;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAeA,MAAa,kBAAkB;;;;;AAM/B,MAAa,qBAAqB;AAElC,MAAM,+BAAe,IAAI,IAAY,CAAC,iBAAiB,kBAAkB,CAAC;;;;;;AAO1E,SAAgB,+BAA+B,GAAG,MAAsB;CACtE,KAAK,MAAM,OAAO,MAAM,aAAa,IAAI,GAAG;AAC9C;AAEA,SAAS,mBAAmB,KAAuC;CACjE,KAAK,MAAM,OAAO,OAAO,KAAK,GAAG,GAC/B,IAAI,aAAa,IAAI,GAAG,GAAG,OAAO;CAEpC,OAAO;AACT;;AAGA,SAAS,kBACP,KACgC;CAChC,MAAM,SAAkC,CAAC;CACzC,IAAI,cAAc;CAClB,KAAK,MAAM,OAAO,OAAO,KAAK,GAAG,GAC/B,IAAI,CAAC,aAAa,IAAI,GAAG,GAAG;EAC1B,OAAO,OAAO,IAAI;EAClB,cAAc;CAChB;CAEF,OAAO,cAAc,SAAS;AAChC;;AAGA,SAAS,qBACP,KACyB;CACzB,MAAM,SAAkC,CAAC;CACzC,KAAK,MAAM,OAAO,OAAO,KAAK,GAAG,GAC/B,IAAI,aAAa,IAAI,GAAG,GAAG,OAAO,OAAO,IAAI;CAE/C,OAAO;AACT;;;;;;AAYA,MAAM,oCAAoB,IAAI,QAAkC;;;;;;AAOhE,SAAgB,wBAAwB,YAA8B;CACpE,IAAI,kBAAkB,IAAI,UAAU,GAAG;CAKvC,MAAM,aAAa,OAAO,yBAAyB,YAAY,OAAO;CAEtE,IAAI;CACJ,IAAI;CAEJ,IAAI,YAAY,KAAK;EAGnB,SAAS,WAAW,IAAI,KAAK,UAAU;EACvC,SAAS,WAAW,SAAS,KAAK,UAAU;CAC9C,OAAO;EAGL,IAAI,WAAY,WAAW,SAAS;EACpC,eAAe;EACf,UAAU,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B;CACA,kBAAA,mBAAA,MAAA,KAAA,CAAA,CAAA,KAAA,MAAW,YAAY,IAAI;AAC7B;AAEA,eAAA,kBACE,MACA,QACA,YACkB;CAGlB,MAAM,WAAW,KAAK;CACtB,IAAI;EACF,MAAM,SAAS,MAAM,SAAS,iBAAiB,QAAQ,EAAE,WAAW,CAAC;EACrE,SAAS,OAAO,KAAK,OAAO;GAC1B,QAAQ;GACR,WAAW,kBAAkB;EAC/B,CAAC;EACD,OAAO;CACT,SAAS,OAAO;EACd,SAAS,OAAO,KAAK,aAAa;GAChC,QAAQ;GACR,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,CAAC;EACD,MAAM;CACR;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wire-types-CnMt6_HR.js","names":[],"sources":["../src/chat/wire-types.ts"],"sourcesContent":["import type { JSONSchema7, UIMessage } from \"ai\";\nimport type { StreamResumeNoneReason } from \"./protocol\";\n\n/**\n * Enum for message types to improve type safety and maintainability\n */\nexport enum MessageType {\n CF_AGENT_CHAT_MESSAGES = \"cf_agent_chat_messages\",\n CF_AGENT_USE_CHAT_REQUEST = \"cf_agent_use_chat_request\",\n CF_AGENT_USE_CHAT_RESPONSE = \"cf_agent_use_chat_response\",\n CF_AGENT_CHAT_CLEAR = \"cf_agent_chat_clear\",\n CF_AGENT_CHAT_REQUEST_CANCEL = \"cf_agent_chat_request_cancel\",\n\n /** Sent by server when client connects and there's an active stream to resume */\n CF_AGENT_STREAM_RESUMING = \"cf_agent_stream_resuming\",\n /** Sent by client to acknowledge stream resuming notification and request chunks */\n CF_AGENT_STREAM_RESUME_ACK = \"cf_agent_stream_resume_ack\",\n /** Sent by client after message handler is ready, requesting stream resume check */\n CF_AGENT_STREAM_RESUME_REQUEST = \"cf_agent_stream_resume_request\",\n /** Sent by server when client requests resume but no active stream exists */\n CF_AGENT_STREAM_RESUME_NONE = \"cf_agent_stream_resume_none\",\n /**\n * Sent by server when a turn is accepted but its resumable stream has not\n * started yet (queued / debouncing / waiting on MCP / async setup). Tells a\n * reconnecting client to keep waiting rather than resolve its resume probe to\n * \"no stream\". Resolved by a later `CF_AGENT_STREAM_RESUMING` (stream started)\n * or `CF_AGENT_STREAM_RESUME_NONE` (settled without streaming). See #1784.\n */\n CF_AGENT_STREAM_PENDING = \"cf_agent_stream_pending\",\n\n /** Client sends tool result to server (for client-side tools) */\n CF_AGENT_TOOL_RESULT = \"cf_agent_tool_result\",\n /** Server notifies client that a message was updated (e.g., tool result applied) */\n CF_AGENT_MESSAGE_UPDATED = \"cf_agent_message_updated\",\n /** Client sends tool approval response to server (for tools with needsApproval) */\n CF_AGENT_TOOL_APPROVAL = \"cf_agent_tool_approval\",\n\n /**\n * Server→client progress hint: a durable chat turn is being recovered\n * (interrupted by a deploy/eviction or a stream-stall watchdog abort and now\n * resuming). Sent when a recovery continuation is scheduled and cleared on\n * every terminal outcome. (`@cloudflare/think` also replays it on connect;\n * `@cloudflare/ai-chat` broadcasts the live signal only — see #1645.)\n * Backward-compatible — clients that don't understand it ignore it. See #1620.\n */\n CF_AGENT_CHAT_RECOVERING = \"cf_agent_chat_recovering\"\n}\n\n/**\n * Types of messages sent from the Agent to clients\n */\nexport type OutgoingMessage<ChatMessage extends UIMessage = UIMessage> =\n | {\n /** Indicates this message is a command to clear chat history */\n type: MessageType.CF_AGENT_CHAT_CLEAR;\n }\n | {\n /** Indicates this message contains updated chat messages */\n type: MessageType.CF_AGENT_CHAT_MESSAGES;\n /** Array of chat messages */\n messages: readonly ChatMessage[];\n }\n | {\n /** Indicates this message is a response to a chat request */\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE;\n /** Unique ID of the request this response corresponds to */\n id: string;\n /** Content body of the response */\n body: string;\n /** Whether this is the final chunk of the response */\n done: boolean;\n /** Whether this response contains an error */\n error?: boolean;\n /** Whether this is a continuation (append to last assistant message) */\n continuation?: boolean;\n /** Whether this chunk is being replayed from storage (stream resumption) */\n replay?: boolean;\n /** Signals that replay of stored chunks is complete (stream is still active) */\n replayComplete?: boolean;\n }\n | {\n /** Indicates the server is resuming an active stream */\n type: MessageType.CF_AGENT_STREAM_RESUMING;\n /** The request ID of the stream being resumed */\n id: string;\n /** Present when this offer directly answers a client resume probe. */\n probeId?: string;\n }\n | {\n /** Server notifies client that a message was updated (e.g., tool result applied) */\n type: MessageType.CF_AGENT_MESSAGE_UPDATED;\n /** The updated message */\n message: ChatMessage;\n }\n | {\n /** Server responds to a resume request with no stream for this client. */\n type: MessageType.CF_AGENT_STREAM_RESUME_NONE;\n /**\n * Why no stream was offered. Only `idle` proves global inactivity;\n * omitted by older servers and by non-authoritative delayed releases.\n */\n reason?: StreamResumeNoneReason;\n /** Correlates an authoritative response to its client resume probe. */\n probeId?: string;\n }\n | {\n /**\n * Server signals an accepted turn whose resumable stream has not started\n * yet — the client should keep waiting for `STREAM_RESUMING` (or a later\n * `STREAM_RESUME_NONE`) rather than give up. See #1784.\n */\n type: MessageType.CF_AGENT_STREAM_PENDING;\n /** The accepted request id, when known. */\n id?: string;\n /** Correlates a direct keep-waiting response to its client probe. */\n probeId?: string;\n }\n | {\n /**\n * Progress hint: a durable chat turn is being recovered (`recovering:\n * true`) or recovery has resolved (`recovering: false`). Purely advisory;\n * a client renders a \"recovering…\" indicator while true.\n */\n type: MessageType.CF_AGENT_CHAT_RECOVERING;\n /** Whether recovery is in progress (true) or has resolved (false). */\n recovering: boolean;\n /** The recovery-root request id of the turn being recovered, if known. */\n id?: string;\n };\n\n/**\n * Types of messages sent from clients to the Agent\n */\nexport type IncomingMessage<ChatMessage extends UIMessage = UIMessage> =\n | {\n /** Indicates this message is a command to clear chat history */\n type: MessageType.CF_AGENT_CHAT_CLEAR;\n }\n | {\n /** Indicates this message is a request to the chat API */\n type: MessageType.CF_AGENT_USE_CHAT_REQUEST;\n /** Unique ID for this request */\n id: string;\n /** Request initialization options */\n init: Pick<\n RequestInit,\n | \"method\"\n | \"keepalive\"\n | \"headers\"\n | \"body\"\n | \"redirect\"\n | \"integrity\"\n | \"credentials\"\n | \"mode\"\n | \"referrer\"\n | \"referrerPolicy\"\n | \"window\"\n >;\n }\n | {\n /** Indicates this message contains updated chat messages */\n type: MessageType.CF_AGENT_CHAT_MESSAGES;\n /** Array of chat messages */\n messages: ChatMessage[];\n }\n | {\n /** Indicates the user wants to stop generation of this message */\n type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL;\n id: string;\n }\n | {\n /** Client acknowledges stream resuming notification and is ready to receive chunks */\n type: MessageType.CF_AGENT_STREAM_RESUME_ACK;\n /** The request ID of the stream being resumed */\n id: string;\n }\n | {\n /** Client requests stream resume check after message handler is registered */\n type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST;\n /** Opaque correlation id echoed by direct server responses. */\n probeId?: string;\n }\n | {\n /** Client sends tool result to server (for client-side tools) */\n type: MessageType.CF_AGENT_TOOL_RESULT;\n /** The tool call ID this result is for */\n toolCallId: string;\n /** The name of the tool */\n toolName: string;\n /** The output from the tool execution */\n output: unknown;\n /** Override the tool part state (e.g. \"output-error\" for custom denial) */\n state?: \"output-available\" | \"output-error\";\n /** Error message when state is \"output-error\" */\n errorText?: string;\n /** Whether server should auto-continue the conversation after applying result */\n autoContinue?: boolean;\n /** Client tool schemas for continuation (client is source of truth) */\n clientTools?: Array<{\n name: string;\n description?: string;\n parameters?: JSONSchema7;\n }>;\n }\n | {\n /** Client sends tool approval response to server (for tools with needsApproval) */\n type: MessageType.CF_AGENT_TOOL_APPROVAL;\n /** The tool call ID this approval is for */\n toolCallId: string;\n /** Whether the tool execution was approved */\n approved: boolean;\n /** Whether server should auto-continue the conversation after applying approval */\n autoContinue?: boolean;\n };\n"],"mappings":";;;;AAMA,IAAY,cAAL,yBAAA,aAAA;CACL,YAAA,4BAAA;CACA,YAAA,+BAAA;CACA,YAAA,gCAAA;CACA,YAAA,yBAAA;CACA,YAAA,kCAAA;;CAGA,YAAA,8BAAA;;CAEA,YAAA,gCAAA;;CAEA,YAAA,oCAAA;;CAEA,YAAA,iCAAA;;;;;;;;CAQA,YAAA,6BAAA;;CAGA,YAAA,0BAAA;;CAEA,YAAA,8BAAA;;CAEA,YAAA,4BAAA;;;;;;;;;CAUA,YAAA,8BAAA;;AACF,EAAA,CAAA,CAAA"}
|
|
1
|
+
{"version":3,"file":"wire-types-CnMt6_HR.js","names":[],"sources":["../src/chat/wire-types.ts"],"sourcesContent":["import type { JSONSchema7, UIMessage } from \"ai\";\nimport type { StreamResumeNoneReason } from \"./protocol\";\n\n/**\n * How a chat request ended.\n *\n * - `completed`: the turn finished normally.\n * - `error`: the turn failed.\n * - `aborted`: the turn was cancelled while it ran.\n * - `skipped`: the turn never ran, because a newer send superseded it or the\n * concurrency policy dropped it.\n * - `recovering`: this request stopped, but recovery continues the same turn\n * under a new request that carries the same `messageIds`.\n */\nexport type ChatTurnOutcome =\n | \"completed\"\n | \"error\"\n | \"aborted\"\n | \"skipped\"\n | \"recovering\";\n\n/**\n * Enum for message types to improve type safety and maintainability\n */\nexport enum MessageType {\n CF_AGENT_CHAT_MESSAGES = \"cf_agent_chat_messages\",\n CF_AGENT_USE_CHAT_REQUEST = \"cf_agent_use_chat_request\",\n CF_AGENT_USE_CHAT_RESPONSE = \"cf_agent_use_chat_response\",\n CF_AGENT_CHAT_CLEAR = \"cf_agent_chat_clear\",\n CF_AGENT_CHAT_REQUEST_CANCEL = \"cf_agent_chat_request_cancel\",\n\n /** Sent by server when client connects and there's an active stream to resume */\n CF_AGENT_STREAM_RESUMING = \"cf_agent_stream_resuming\",\n /** Sent by client to acknowledge stream resuming notification and request chunks */\n CF_AGENT_STREAM_RESUME_ACK = \"cf_agent_stream_resume_ack\",\n /** Sent by client after message handler is ready, requesting stream resume check */\n CF_AGENT_STREAM_RESUME_REQUEST = \"cf_agent_stream_resume_request\",\n /** Sent by server when client requests resume but no active stream exists */\n CF_AGENT_STREAM_RESUME_NONE = \"cf_agent_stream_resume_none\",\n /**\n * Sent by server when a turn is accepted but its resumable stream has not\n * started yet (queued / debouncing / waiting on MCP / async setup). Tells a\n * reconnecting client to keep waiting rather than resolve its resume probe to\n * \"no stream\". Resolved by a later `CF_AGENT_STREAM_RESUMING` (stream started)\n * or `CF_AGENT_STREAM_RESUME_NONE` (settled without streaming). See #1784.\n */\n CF_AGENT_STREAM_PENDING = \"cf_agent_stream_pending\",\n\n /** Client sends tool result to server (for client-side tools) */\n CF_AGENT_TOOL_RESULT = \"cf_agent_tool_result\",\n /** Server notifies client that a message was updated (e.g., tool result applied) */\n CF_AGENT_MESSAGE_UPDATED = \"cf_agent_message_updated\",\n /** Client sends tool approval response to server (for tools with needsApproval) */\n CF_AGENT_TOOL_APPROVAL = \"cf_agent_tool_approval\",\n\n /**\n * Server→client progress hint: a durable chat turn is being recovered\n * (interrupted by a deploy/eviction or a stream-stall watchdog abort and now\n * resuming). Sent when a recovery continuation is scheduled and cleared on\n * every terminal outcome. (`@cloudflare/think` also replays it on connect;\n * `@cloudflare/ai-chat` broadcasts the live signal only — see #1645.)\n * Backward-compatible — clients that don't understand it ignore it. See #1620.\n */\n CF_AGENT_CHAT_RECOVERING = \"cf_agent_chat_recovering\"\n}\n\n/**\n * Types of messages sent from the Agent to clients\n */\nexport type OutgoingMessage<ChatMessage extends UIMessage = UIMessage> =\n | {\n /** Indicates this message is a command to clear chat history */\n type: MessageType.CF_AGENT_CHAT_CLEAR;\n }\n | {\n /** Indicates this message contains updated chat messages */\n type: MessageType.CF_AGENT_CHAT_MESSAGES;\n /** Array of chat messages */\n messages: readonly ChatMessage[];\n /**\n * Set on the transcript a server sends to a newly connected client. It\n * predates any request the client buffered while disconnected, so the\n * client keeps those optimistic sends; any other snapshot is\n * authoritative (#1983).\n */\n connect?: boolean;\n }\n | {\n /** Indicates this message is a response to a chat request */\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE;\n /** Unique ID of the request this response corresponds to */\n id: string;\n /** Content body of the response */\n body: string;\n /** Whether this is the final chunk of the response */\n done: boolean;\n /** Whether this response contains an error */\n error?: boolean;\n /** Whether this is a continuation (append to last assistant message) */\n continuation?: boolean;\n /** Whether this chunk is being replayed from storage (stream resumption) */\n replay?: boolean;\n /** Signals that replay of stored chunks is complete (stream is still active) */\n replayComplete?: boolean;\n /**\n * Index of this chunk within its stream. A live chunk carries the index\n * its replay will carry, so a client can skip replayed chunks it has\n * already applied.\n */\n seq?: number;\n /**\n * IDs of the user messages the originating request carried (the\n * trailing user messages of its `messages`). Set on terminal frames\n * (`done` or `error`), live and replayed, when the server knows them,\n * so a client can settle exactly the sends a completion, error, or\n * cancellation belongs to.\n */\n messageIds?: string[];\n /**\n * How the request ended, on its terminal `done` frame. Absent means\n * `\"error\"` when the frame (or an earlier frame for the request) carried\n * `error`, and `\"completed\"` otherwise.\n */\n outcome?: ChatTurnOutcome;\n }\n | {\n /** Indicates the server is resuming an active stream */\n type: MessageType.CF_AGENT_STREAM_RESUMING;\n /** The request ID of the stream being resumed */\n id: string;\n /** Present when this offer directly answers a client resume probe. */\n probeId?: string;\n }\n | {\n /** Server notifies client that a message was updated (e.g., tool result applied) */\n type: MessageType.CF_AGENT_MESSAGE_UPDATED;\n /** The updated message */\n message: ChatMessage;\n }\n | {\n /** Server responds to a resume request with no stream for this client. */\n type: MessageType.CF_AGENT_STREAM_RESUME_NONE;\n /**\n * Why no stream was offered. Only `idle` proves global inactivity;\n * omitted by older servers and by non-authoritative delayed releases.\n */\n reason?: StreamResumeNoneReason;\n /** Correlates an authoritative response to its client resume probe. */\n probeId?: string;\n }\n | {\n /**\n * Server signals an accepted turn whose resumable stream has not started\n * yet — the client should keep waiting for `STREAM_RESUMING` (or a later\n * `STREAM_RESUME_NONE`) rather than give up. See #1784.\n */\n type: MessageType.CF_AGENT_STREAM_PENDING;\n /** The accepted request id, when known. */\n id?: string;\n /** Correlates a direct keep-waiting response to its client probe. */\n probeId?: string;\n }\n | {\n /**\n * Progress hint: a durable chat turn is being recovered (`recovering:\n * true`) or recovery has resolved (`recovering: false`). Purely advisory;\n * a client renders a \"recovering…\" indicator while true.\n */\n type: MessageType.CF_AGENT_CHAT_RECOVERING;\n /** Whether recovery is in progress (true) or has resolved (false). */\n recovering: boolean;\n /** The recovery-root request id of the turn being recovered, if known. */\n id?: string;\n };\n\n/**\n * Types of messages sent from clients to the Agent\n */\nexport type IncomingMessage<ChatMessage extends UIMessage = UIMessage> =\n | {\n /** Indicates this message is a command to clear chat history */\n type: MessageType.CF_AGENT_CHAT_CLEAR;\n }\n | {\n /** Indicates this message is a request to the chat API */\n type: MessageType.CF_AGENT_USE_CHAT_REQUEST;\n /** Unique ID for this request */\n id: string;\n /** Request initialization options */\n init: Pick<\n RequestInit,\n | \"method\"\n | \"keepalive\"\n | \"headers\"\n | \"body\"\n | \"redirect\"\n | \"integrity\"\n | \"credentials\"\n | \"mode\"\n | \"referrer\"\n | \"referrerPolicy\"\n | \"window\"\n >;\n }\n | {\n /** Indicates this message contains updated chat messages */\n type: MessageType.CF_AGENT_CHAT_MESSAGES;\n /** Array of chat messages */\n messages: ChatMessage[];\n }\n | {\n /** Indicates the user wants to stop generation of this message */\n type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL;\n id: string;\n }\n | {\n /** Client acknowledges stream resuming notification and is ready to receive chunks */\n type: MessageType.CF_AGENT_STREAM_RESUME_ACK;\n /** The request ID of the stream being resumed */\n id: string;\n }\n | {\n /** Client requests stream resume check after message handler is registered */\n type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST;\n /** Opaque correlation id echoed by direct server responses. */\n probeId?: string;\n }\n | {\n /** Client sends tool result to server (for client-side tools) */\n type: MessageType.CF_AGENT_TOOL_RESULT;\n /** The tool call ID this result is for */\n toolCallId: string;\n /** The name of the tool */\n toolName: string;\n /** The output from the tool execution */\n output: unknown;\n /** Override the tool part state (e.g. \"output-error\" for custom denial) */\n state?: \"output-available\" | \"output-error\";\n /** Error message when state is \"output-error\" */\n errorText?: string;\n /** Whether server should auto-continue the conversation after applying result */\n autoContinue?: boolean;\n /** Client tool schemas for continuation (client is source of truth) */\n clientTools?: Array<{\n name: string;\n description?: string;\n parameters?: JSONSchema7;\n }>;\n }\n | {\n /** Client sends tool approval response to server (for tools with needsApproval) */\n type: MessageType.CF_AGENT_TOOL_APPROVAL;\n /** The tool call ID this approval is for */\n toolCallId: string;\n /** Whether the tool execution was approved */\n approved: boolean;\n /** Whether server should auto-continue the conversation after applying approval */\n autoContinue?: boolean;\n };\n"],"mappings":";;;;AAwBA,IAAY,cAAL,yBAAA,aAAA;CACL,YAAA,4BAAA;CACA,YAAA,+BAAA;CACA,YAAA,gCAAA;CACA,YAAA,yBAAA;CACA,YAAA,kCAAA;;CAGA,YAAA,8BAAA;;CAEA,YAAA,gCAAA;;CAEA,YAAA,oCAAA;;CAEA,YAAA,iCAAA;;;;;;;;CAQA,YAAA,6BAAA;;CAGA,YAAA,0BAAA;;CAEA,YAAA,8BAAA;;CAEA,YAAA,4BAAA;;;;;;;;;CAUA,YAAA,8BAAA;;AACF,EAAA,CAAA,CAAA"}
|