@agentconnect.md/daemon 1.41.0-rc.122 → 1.41.0-rc.124

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.
@@ -1 +1 @@
1
- {"version":3,"file":"cli-upgrade-C0m01RLc.js","names":["z.object","z.literal","z.string","z.unknown","z.number","z.object","z.string","z.literal","z\n .object","z.number","z.enum","z.boolean","z.string","z.object","z.enum","z.array","z.number","z\n .array","z.boolean","z.enum","z\n .object","z.string","z.object","z.boolean","z.array","z.object","z.string","z.enum","z.array","z.enum","z.object","z.string","z.number","z.boolean","z.array","z\n .string","z\n .array","z.enum","z.object","z.string","z.boolean","z.array","z.object","z.number","z.enum","z.array","z.string","z.discriminatedUnion","z.literal","z.boolean","z.record","z.unknown","z.enum","z.object","z.string","z.boolean","z.record","z.unknown","z\n .object","z.string","z.number","z.boolean","z.enum","z.object","z.literal","z.string","z.discriminatedUnion","EventEmitter","http","randomBytes","createHash","Duplex","createHash","WebSocket","WebSocket"],"sources":["../../protocol/dist/envelope.js","../../protocol/dist/frames/auth.js","../../protocol/dist/frames/duty.js","../../protocol/dist/frames/skill.js","../../protocol/dist/frames/channel.js","../../protocol/dist/frames/workspace.js","../../protocol/dist/frames/task.js","../../protocol/dist/frames/telemetry.js","../../protocol/dist/frames/error.js","../../protocol/dist/frames/remote-mcp.js","../../protocol/dist/frame.js","../../protocol/dist/wire.js","../../protocol/dist/codec.js","../../connection/dist/clock.js","../../connection/dist/correlator.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/constants.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/buffer-util.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/limiter.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/permessage-deflate.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/validation.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/receiver.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/sender.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/event-target.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/extension.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/websocket.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/stream.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/subprotocol.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/websocket-server.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/wrapper.mjs","../../connection/dist/ws-client-transport.js","../src/lifecycle/cli-upgrade.ts"],"sourcesContent":["import { z } from 'zod';\n/**\n * The protocol envelope — every frame, both directions, is wrapped in this.\n * Mirrors daemon-cp-ws-protocol.md §1.1.\n *\n * `payload` is left as `unknown` here and validated by the per-type schema in\n * `frames/*` via `FRAME_SCHEMAS[type]` (see `frame.ts`). This two-step parse is\n * what lets the codec answer an unknown `type` with `UNKNOWN_FRAME` (a REP)\n * instead of a hard close — forward-compat, protocol §1.\n */\nexport const Envelope = z.object({\n v: z.literal(1), // protocol major; bump = breaking\n id: z.string().uuid(), // unique per frame (sender-generated)\n ts: z.string().datetime(), // RFC3339, sender clock (advisory only)\n type: z.string(), // frame discriminator, e.g. \"register\"\n corr: z.string().uuid().optional(), // correlation: set on a reply to the request's `id`\n orgId: z.string().min(1).max(64).optional(), // tenant context on an install-wide daemon connection\n payload: z.unknown() // validated by the per-type schema\n});\n/**\n * Control-frame envelope extension — protocol §4.2.\n *\n * Fenced C→D frames carry this block alongside `payload`. It is the fencing\n * surface: `epoch` (sessionEpoch this frame was issued under), the `agentId` an\n * agent-scoped frame belongs to, and the `launchId` fence. Daemon validation\n * order: epoch → launchId.\n */\nexport const ControlExt = z.object({\n epoch: z.number().int(), // sessionEpoch this frame was issued under (§3.1 fencing)\n agentId: z.string().uuid().optional(), // present on agent-scoped frames\n launchId: z.string().uuid().optional() // per-launch fence, §4.4\n});\n/** The all-zero UUID used when a frame is malformed past the point of reading `id`. */\nexport const NIL_UUID = '00000000-0000-0000-0000-000000000000';\n/**\n * Builds the envelope schema for one frame `type` — the `type` literal plus the\n * typed payload — so a wire's discriminated union infers `payload` precisely.\n * Shared by the daemon↔CP union (`frame.ts`) and the relay wire unions\n * (`frames/relay-cp.ts` / `frames/relay-daemon.ts`), which are deliberately\n * SEPARATE unions over the same envelope shape (shared-bot-relay.md §8).\n */\nexport function frameSchema(type, payload) {\n return z.object({\n v: z.literal(1),\n id: z.string().uuid(),\n ts: z.string().datetime(),\n type: z.literal(type),\n corr: z.string().uuid().optional(),\n orgId: z.string().min(1).max(64).optional(),\n payload\n });\n}\n//# sourceMappingURL=envelope.js.map","import { z } from 'zod';\n/**\n * Auth & identity — protocol §3.1 / §3.2.\n *\n * `auth` is the first frame after the socket opens. `auth/ok` carries the\n * minted `sessionEpoch` (the global fencing token), heartbeat cadence, and the\n * resume verdict.\n */\nexport const AuthReq = z.object({\n // Long-lived, revocable API key — a bare opaque `<secret><crc>`, hashed at rest and looked up\n // by that unique hash (see docs/designs/daemon-api-key-auth.md). A daemon with no Kubernetes\n // identity carries this; an in-cluster one sends `serviceAccountToken` instead.\n apiKey: z.string().optional(),\n // Projected ServiceAccount token of an operator-provisioned daemon pod, audience-scoped to\n // CP_TOKEN_AUDIENCE and verified by TokenReview against the org's cluster (see \"Daemon\n // identity\" in docs/designs/agentconnect-org-operator.md). Takes precedence over `apiKey`.\n serviceAccountToken: z.string().optional(),\n // Optional echo of the daemonId. If present it must equal the daemonId the ApiKey row\n // resolves to; otherwise the daemon adopts the authoritative id from `auth/ok`.\n daemonId: z.string().uuid().optional(),\n machineId: z.string().uuid().optional(), // 🅼 machine identity (scope-attestation, §3.2) — NOT the auth credential\n attestation: z.string().optional(), // 🅼 signed proof (JWS), §3.2\n agentVersion: z.string(), // daemon build/version\n // Auth-time lifecycle support; optional for rolling compatibility.\n bootstrapProtocolVersion: z.literal(1).optional(),\n resume: z\n .object({\n lastEpoch: z.number().int() // sessionEpoch the daemon last held\n })\n .optional()\n});\nexport const BootstrapLifecycle = z.object({\n operationId: z.string(),\n action: z.literal('upgrade'),\n targetVersion: z.string()\n});\nexport const AuthOk = z.object({\n daemonId: z.string().uuid(),\n sessionEpoch: z.number().int(), // monotonic; bumped each successful (re)auth — fencing token\n heartbeatSec: z.number().int(), // cadence the daemon must emit heartbeat at\n // How long the CP keeps a duty lease alive past the last heartbeat it renewed from\n // (T_reassign). The member self-fences strictly earlier, so it must be told the CP's\n // own value rather than duplicate it. Optional: an older CP omits it.\n dutyLeaseMs: z.number().int().positive().optional(),\n serverTime: z.string().datetime(),\n // Single-org daemons inherit tenant context from auth; install-wide pool members require\n // every org-scoped post-auth frame to carry `Envelope.orgId`.\n organizationMode: z.enum(['connection', 'frame']).default('connection'),\n // Base URL of the Web App console (the CP's own public origin), so the daemon can build\n // session deep links without local config. Omitted when the CP has no console URL\n // configured; a daemon-local `webAppUrl` overrides it.\n webAppUrl: z.string().optional(),\n // Slug of the org this daemon's api key belongs to. The console is org-scoped\n // (`<webAppUrl>/<orgSlug>/sessions/<id>`), so the daemon needs it to build a link that\n // resolves. Omitted when the CP can't resolve it; then the daemon drops the segment.\n orgSlug: z.string().optional(),\n // Durable upgrade intent returned only to bootstrap-capable callers.\n lifecycle: BootstrapLifecycle.optional(),\n resume: z\n .object({\n accepted: z.boolean() // false ⇒ daemon must do a full register reconcile\n })\n .optional()\n});\n//# sourceMappingURL=auth.js.map","// Duty lease wire (k8s daemons). The exchange rides the existing heartbeat\n// cadence: the heartbeat's optional `duties` field carries the member's held\n// digest and remaining headroom; the CP answers — only when there is something\n// to say — with `duty/grant` and `duty/revoke` EVTs on the same connection, and\n// a draining member returns groups explicitly with the `duty/release` REQ.\n// Single-org daemons never send `duties`, which keeps the whole path dormant.\nimport { z } from 'zod';\nimport { AgentSpec } from './agent.js';\nimport { IntegrationSpec } from './integration.js';\nimport { CronUpsert } from './cron.js';\nimport { McpServerSpec } from './mcpserver.js';\nimport { MemoryConnectionSpec } from './memory-connection.js';\n/** A per-group fencing term — bigint as a decimal string (JSON-safe). */\nexport const DutyTerm = z.string().regex(/^\\d+$/);\n/** One member of a duty group: an agent to serve or a daemon-held bot to connect.\n * `configRevision` is the freshness signal for AGENT members — the CP's current\n * `AgentSpec.configRevision` — so a member that already has the agent can tell a\n * current replica from a frozen one and refetch only the frozen ones. Optional:\n * an older CP omits it and the member falls back to presence alone. */\nexport const DutyMemberRef = z.object({\n kind: z.enum(['agent', 'bot']),\n refId: z.string().uuid(),\n configRevision: z.string().regex(/^\\d+$/).optional()\n});\n/** Hard cap on one grant entry's member list. A connected component past this is\n * not deliverable over this wire at all — it is the dedicated-tier signal, and\n * the CP refuses to grant it rather than emit a frame the daemon must reject. */\nexport const DUTY_GRANT_MEMBERS_MAX = 1000;\n/** The heartbeat's lease fields: what I hold (with the terms I believe), and\n * how many more groups I will accept. Capacity gating is member-side. */\nexport const HeartbeatDuties = z.object({\n held: z.array(z.object({ groupId: z.string().uuid(), term: DutyTerm })).max(1000),\n headroom: z.number().int().min(0)\n});\n/** One granted (or re-confirmed) duty group. A groupId the daemon already holds\n * REPLACES its entry — a bumped term after a composition change, or a term the\n * daemon missed because the original grant EVT was lost. */\nexport const DutyGrantEntry = z.object({\n groupId: z.string().uuid(),\n orgId: z.string().min(1).max(64),\n term: DutyTerm,\n members: z.array(DutyMemberRef).max(DUTY_GRANT_MEMBERS_MAX)\n});\n/** C→D EVT: duties granted to (or re-confirmed for) this member. */\nexport const DutyGrant = z.object({\n grants: z.array(DutyGrantEntry).min(1).max(100)\n});\n/**\n * C→D EVT: the renewal the CP just performed for this member, emitted on every\n * duty-carrying heartbeat it actually processed. `leaseMs` is RELATIVE — \"the\n * leases I hold for you live this much longer, measured from when I renewed\n * them\" — so the daemon anchors its self-fence on RECEIPT and the two sides\n * never compare wall clocks. Receipt is strictly after the CP's renew, which is\n * what makes the daemon's deadline conservative and `T_reassign > T_fence`\n * sound. A beat the CP dropped produces no confirmation, so a member's fence\n * countdown keeps running — sending a beat is not renewing a lease.\n */\nexport const DutyRenewed = z.object({\n leaseMs: z.number().int().positive()\n});\n/** Why a held group is being taken away: `superseded` = another member holds it\n * now (term reassigned), `gone` = the group no longer exists (edges removed). */\nexport const DutyRevokeReason = z.enum(['superseded', 'gone']);\n/** C→D EVT: stop serving these groups and tear down their platform connections. */\nexport const DutyRevoke = z.object({\n revocations: z\n .array(z.object({ groupId: z.string().uuid(), reason: DutyRevokeReason }))\n .min(1)\n .max(1000)\n});\n/** D→C REQ (reply: generic `ack`): a draining member returns groups explicitly,\n * vacating them immediately instead of waiting out T_reassign. */\nexport const DutyRelease = z.object({\n groupIds: z.array(z.string().uuid()).min(1).max(1000)\n});\n/**\n * D→C REQ (reply: `duty/claim/ok`) — the activation rendezvous of the design's\n * §4.4. A member handed a trigger for an agent it does not serve claims that\n * agent's group on receipt: winning creates or takes the lease and it serves the\n * trigger; losing names the incumbent so the router can re-route. Idempotent for\n * the current holder, so a retry never churns a term.\n */\nexport const DutyClaim = z.object({\n agentId: z.string().uuid()\n});\n/** C→D REP to `duty/claim`. `granted` ⇒ `grant` carries the lease exactly as a\n * `duty/grant` entry would; otherwise `holder` names the live incumbent (absent\n * when the CP cannot resolve one, e.g. an unknown agent). */\nexport const DutyClaimOk = z.object({\n granted: z.boolean(),\n grant: DutyGrantEntry.optional(),\n holder: z.string().uuid().optional()\n});\n/**\n * D→C REQ (reply: `duty/fetch/ok`) — a grant opens the SERVING gate; it does not\n * install. A member that wins a duty for an agent it has never had pulls that\n * agent's definition here, so grants stay thin and a member asks only for what\n * it lacks. Holding the duty IS the authorization: the CP answers only for an\n * agent the asking daemon currently holds.\n */\nexport const DutyFetch = z.object({\n agentId: z.string().uuid()\n});\n/**\n * One agent's complete installable definition — the trio `agent/activate` carries,\n * without the move token or the staging fence, plus the two definition kinds the\n * spec only NAMES: the proxied MCP servers its `mcpServers` list enables and its\n * external-memory connection. Those arrive separately on the placement-keyed\n * paths, so a duty holder that is not the placement would otherwise install an\n * agent referencing tools and a memory backend it has no definitions for.\n *\n * Both are token-bearing (relay proxy url + grant key, memory grant + secret\n * leases) — NEVER log this bundle. They are scoped to what THIS agent references,\n * so the reply widens nothing beyond the duty the asker already holds. Optional\n * for decode tolerance: an older CP omits them and the member installs the trio.\n */\nexport const DutyAgentBundle = z.object({\n agentId: z.string().uuid(),\n spec: AgentSpec,\n integrations: z.array(IntegrationSpec),\n crons: z.array(CronUpsert),\n mcpServers: z.array(McpServerSpec).default([]),\n memoryConnections: z.array(MemoryConnectionSpec).default([])\n});\n/** C→D REP to `duty/fetch`. An absent `bundle` means the asker does not hold\n * this agent's duty, or the agent is gone — never an error frame, because\n * either way the correct member behavior is to install nothing. */\nexport const DutyFetchOk = z.object({\n bundle: DutyAgentBundle.optional()\n});\n//# sourceMappingURL=duty.js.map","import { z } from 'zod';\n// Read-only inventory of the skills an agent's materialized workspace can load,\n// so the console has one place to see them. Bodies stay daemon-local; this frame\n// carries only per-skill metadata (name, description, origin, path).\nexport const LocalSkillOrigin = z.enum(['dream-accepted', 'managed', 'git-source', 'repo']);\nexport const LocalSkillEntry = z\n .object({\n /** Skill name from SKILL.md frontmatter, falling back to the directory name. */\n name: z.string(),\n /** SKILL.md description, or null when absent/unparseable. */\n description: z.string().nullable(),\n origin: LocalSkillOrigin,\n /** Path relative to the workspace cwd, e.g. \".claude/skills/deploy\". */\n path: z.string()\n})\n .strict();\n/** CP → daemon: list the skills the agent's workspace can load. */\nexport const LocalSkillsReq = z.object({ agentId: z.string().min(1) }).strict();\n/** daemon → CP: the inventory. `materialized` is false when the agent's\n * workspace has not been prepared yet (so an empty list means \"unknown\", not\n * \"no skills\"). */\nexport const LocalSkillsList = z.object({ materialized: z.boolean(), skills: z.array(LocalSkillEntry) }).strict();\n//# sourceMappingURL=skill.js.map","import { z } from 'zod';\nimport { Platform } from './route.js';\n/**\n * Channel agent directory (D→C REQ → REP) — agent collaboration lookup.\n *\n * An agent asks (via a daemon-side tool) \"who else is in this channel?\". The\n * daemon forwards it to the CP — the ONLY authority for the FULL channel roster,\n * because agents in one channel may run on different daemons (each daemon knows\n * only its own agents). The CP joins the channel's integrations to their agents\n * and returns their public metadata (name / displayName / description / status).\n * Metadata only — never message content (§1/§12).\n *\n * Direction is daemon→CP (like `auth` / `register`): the daemon sends the REQ and\n * the CP replies with `channel/agents/ok` (corr = the req id).\n *\n * `channel` is OPTIONAL, and that is the whole scope switch:\n * - ABSENT → the ORG-WIDE peer directory. Channel membership plays no part; a\n * session with no IM integration at all (webchat, hook, dream) can still\n * discover peers.\n * - PRESENT → the same directory, ADDITIONALLY narrowed to agents present in that\n * channel. A filter, never a gate.\n * Only a CP advertising `agent-directory-org-scope-v1` understands the channel-less\n * form; against an older CP the daemon substitutes the caller's current channel\n * (today's behavior) rather than sending a payload that CP would reject.\n *\n * The REQ is bound to the requesting daemon's authenticated org AND to the\n * session-derived `requesterAgentId` (never a tool input — §2.2/§6.1). The roster is\n * POLICY-filtered, not membership-gated: an entry survives iff the caller's outbound\n * policy admits it and its own inbound `callPolicy` admits the caller, within the one\n * org (the caller always sees itself). Discovery IS the authorization surface — a peer\n * that fails the predicate is omitted entirely, never listed-but-uncallable — so an\n * agent still cannot probe peers it may not call, and cross-org never resolves.\n */\n/** One agent visible in a channel — the collaboration directory entry. */\nexport const ChannelAgent = z.object({\n agentId: z.string().uuid(),\n name: z.string(), // slug\n displayName: z.string().optional(), // human-readable name, if set\n description: z.string().optional(), // what the agent does (its system-prompt seed)\n status: z.enum(['active', 'inactive', 'paused']),\n /**\n * The exact platform-native address for this agent in the LISTED conversation —\n * `<@U_REVIEWER>` for a dedicated bot, `<@U_SHARED> reviewer` for a shared one\n * (send-message-routing-rework.md §8.5).\n *\n * Present only on a CHANNEL-FILTERED listing: an org-wide listing has no single\n * conversation-specific address, and offering a wrong token would silently address\n * nobody. It gives the model an exact string to put in its ordinary reply (§2.1)\n * instead of guessing from a display name, without exposing any credential.\n *\n * The DAEMON fills this from its local conversation directory; it is not a CP field.\n */\n mention: z.string().optional()\n});\n/** D→C REQ: list the caller's callable peers (for the asking agent's collaboration tool). */\nexport const ChannelAgentsReq = z.object({\n platform: Platform,\n /** Platform channel id. Omit for the org-wide directory; present = channel filter. */\n channel: z.string().optional(),\n /** The agent asking, derived by the daemon from the MCP session context — NEVER\n * a tool input (§6.1). The CP resolves it in the org directory and applies the\n * bidirectional call-policy filter; an unknown requester fails CLOSED. */\n requesterAgentId: z.string().uuid()\n});\n/** C→D REP (corr = req id): the policy-filtered roster across all daemons. `channel`\n * echoes the REQ's scope — absent when the listing was org-wide. */\nexport const ChannelAgentsOk = z.object({\n platform: Platform,\n channel: z.string().optional(),\n agents: z.array(ChannelAgent)\n});\n//# sourceMappingURL=channel.js.map","import { z } from 'zod';\n/**\n * Agent workspace files (C→D REQ → REP) — the console's on-demand access.\n *\n * The CP stores NO workspace data — directory listings and file bytes are pulled\n * live from the owning daemon and proxied to the console, never persisted\n * (body-locality). Missing paths are DATA (`exists:false`), not errors; only\n * path-containment violations (`BAD_PAYLOAD`) and unexpected fs failures\n * (`INTERNAL`) come back as `error` frames.\n *\n * - `workspace/list`: one cursor-paginated page of a directory's entries.\n * - `workspace/read`: one byte slice of a file. A DIRECTORY is DATA too\n * (`type:'dir'`, no `content`) — a path naming a directory is a fact about the\n * path, not a transport failure. Any other non-regular target (a symlink out of\n * the workspace, a device) stays a containment violation. `limit` is only a ceiling — the\n * daemon returns FEWER bytes when needed to keep the JSON-escaped REP under the\n * 256 KiB frame cap (control bytes escape to `\\uXXXX`, a 6× blowup), and always\n * ends the slice on a UTF-8 character boundary. `nextOffset` is the authoritative\n * byte offset to request next — callers must NOT recompute it from the decoded\n * `content` (a split multi-byte char would make the byte count drift).\n * - `workspace/write`: create a text file when `ifMatchMtime` is absent, or\n * replace one when it matches the last read. Content is base64 so arbitrary\n * UTF-8 text has a predictable wire size.\n * - `workspace/delete`: delete one regular file when its mtime still matches the\n * last read, so a console action never removes a newer agent revision.\n */\n/** Machine-readable `reason` on a workspace `BAD_PAYLOAD` / `CONFLICT` error\n * frame's `details`, so the CP can answer a bad request with a status and a code\n * the console can branch on instead of the 503 that reads as an offline daemon.\n * A closed vocabulary: both sides agree on it, and the messages beside it stay\n * hand-written and host-path-free. */\nexport const WorkspaceErrorReason = z.enum([\n 'unknown-agent', // no such agent on this daemon (or no worktree for that sessionId)\n 'path-escape', // absolute path, or one resolving outside the workspace root\n 'git-internals', // the path reaches into `.git`\n 'not-a-file', // the path exists but is not a regular file (mutations only; reads report it as DATA)\n 'not-a-directory', // a parent component of a write target is not a directory\n 'read-only-workspace', // edits are scratch-workspace only\n 'too-large', // the edit exceeds MAX_WORKSPACE_EDIT_BYTES\n 'binary', // the target is not UTF-8 text\n 'not-utf8', // the supplied content is not valid UTF-8\n 'stale', // optimistic-concurrency failure (CONFLICT)\n // The workspace is on a sandbox volume no bound channel can reach right now (a suspended or\n // not-yet-launched pod). The one reason here that is TRANSIENT rather than a bad request, so the\n // CP answers it 503-with-a-code: retrying is the right move, and it must not read as \"there is no\n // repository here\" or \"this directory is empty\", which is what the panels said before it existed.\n 'sandbox-unavailable'\n]);\n/** Raw UTF-8 ceiling for one console workspace-file edit. Base64 expansion still\n * leaves enough envelope headroom under the shared 256 KiB frame cap. */\nexport const MAX_WORKSPACE_EDIT_BYTES = 180_000;\n/** One directory entry in a workspace listing (name-only; not a full path). */\nexport const WorkspaceEntry = z.object({\n name: z.string(),\n type: z.enum(['dir', 'file', 'symlink', 'other']),\n size: z.number().int().nonnegative().optional(), // regular files only\n mtime: z.string().optional() // RFC3339\n});\n/** C→D REQ: list one page of a directory in the agent's workspace. */\nexport const WorkspaceListReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. Omit for the\n * agent's primary checkout. The CP authorizes the session before forwarding. */\n sessionId: z.string().min(1).optional(),\n path: z.string().default(''), // workspace-relative POSIX path; '' ⇒ workspace root\n cursor: z.string().optional(), // opaque; omit ⇒ first page\n limit: z.number().int().positive().max(500).default(200)\n});\n/** D→C REP (corr = the req id): a page of entries + the cursor for the next page. */\nexport const WorkspaceListPage = z.object({\n agentId: z.string(),\n path: z.string(),\n exists: z.boolean(), // false ⇒ workspace root or the dir does not exist (NOT an error)\n entries: z.array(WorkspaceEntry),\n nextCursor: z.string().optional() // absent ⇒ no more entries\n});\n/** C→D REQ: read one byte slice of a file in the agent's workspace. */\nexport const WorkspaceReadReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional(),\n path: z.string().min(1), // workspace-relative POSIX path to a file\n offset: z.number().int().nonnegative().default(0), // byte offset\n limit: z.number().int().positive().max(65536).default(65536) // byte count per slice (64 KiB, see docblock)\n});\n/** D→C REP (corr = the req id): the file slice (or `exists:false` / binary-detected\n * / `type:'dir'`). */\nexport const WorkspaceReadContent = z.object({\n agentId: z.string(),\n path: z.string(),\n exists: z.boolean(), // false ⇒ the file does not exist (NOT an error)\n type: z.enum(['file', 'dir']).optional(), // what the path IS; 'dir' ⇒ no content (absent from an older daemon)\n size: z.number().int().nonnegative().optional(),\n mtime: z.string().optional(), // RFC3339\n encoding: z.enum(['utf8', 'none']).optional(), // 'none' ⇒ binary detected, content omitted\n content: z.string().optional(), // utf8 text slice\n offset: z.number().int().nonnegative().optional(), // byte offset this slice starts at\n nextOffset: z.number().int().nonnegative().optional(), // byte offset to request next (offset + bytes in this slice)\n truncated: z.boolean().optional() // true ⇒ nextOffset < size (more bytes remain)\n});\nconst CanonicalBase64 = z\n .string()\n .max(Math.ceil(MAX_WORKSPACE_EDIT_BYTES / 3) * 4)\n .regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/);\n/** C→D REQ: atomically create or replace one scratch-workspace text file.\n * Omitting `ifMatchMtime` is an exclusive create; supplying it is an optimistic\n * replace, so neither operation silently overwrites a concurrent change. */\nexport const WorkspaceWriteReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n path: z.string().min(1).max(4096), // workspace-relative POSIX path to a regular file\n contentBase64: CanonicalBase64, // complete new UTF-8 contents\n ifMatchMtime: z.string().datetime().optional()\n});\n/** D→C REP (corr = the req id): the atomically written file state. */\nexport const WorkspaceWriteOk = z.object({\n agentId: z.string(),\n path: z.string(),\n size: z.number().int().nonnegative(),\n mtime: z.string()\n});\n/** C→D REQ: delete one scratch-workspace file if it still matches the last read. */\nexport const WorkspaceDeleteReq = z.object({\n agentId: z.string().min(1),\n path: z.string().min(1).max(4096),\n ifMatchMtime: z.string().datetime()\n});\n/** D→C REP (corr = the req id): the deleted file identity. */\nexport const WorkspaceDeleteOk = z.object({\n agentId: z.string(),\n path: z.string()\n});\n/**\n * Agent workspace git ops (C→D REQ → REP) — the console's on-demand controls for\n * a git-repo workspace. Like list/read these run daemon-local; the CP proxies the\n * outcome and stores nothing.\n *\n * These are DATA-oriented: a non-repo workspace (`isRepo:false`), a dirty tree,\n * or a pull that can't fast-forward (offline, diverged, local edits) all come\n * back as a normal REP — NOT an `error` frame. Only an unknown agent\n * (`BAD_PAYLOAD`) or an unexpected git/fs failure (`INTERNAL`) is an error.\n *\n * - `workspace/gitstatus`: the working tree. Per-file `additions`/`deletions` are\n * `git diff HEAD --numstat` counts — staged AND unstaged, i.e. what the file\n * changed vs HEAD. Optional: an untracked file has no counts, and an older\n * daemon reports none at all.\n * - `workspace/gitdiff`: unified-diff text for ONE path, bounded like\n * `workspace/read` (the daemon shrinks the slice until the JSON-escaped REP\n * fits the 256 KiB frame cap and flags `truncated`). A binary path, a path with\n * no changes and a non-repo workspace are all DATA.\n * - `workspace/gitlog`: the newest commits of the checked-out branch, each marked\n * `pushed` when the branch's upstream ref already contains it.\n *\n * The write half (`workspace/gitstage` / `gitunstage` / `gitcommit` / `gitpush`) is\n * DATA-oriented in the same way, and more strictly: nothing to stage, a commit with\n * an empty index, a daemon with no registered commit identity, a push with no\n * upstream, from a detached HEAD, or one the remote rejects are all normal REPs the\n * console renders. Stage/unstage answer with the FRESH `WorkspaceGitStatus` so the\n * panel never re-polls for the result of its own action.\n */\n/** C→D REQ: report `git status` of the agent's workspace (is it clean?). */\nexport const WorkspaceGitStatusReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional()\n});\n/** One changed path in a `git status`. `index`/`workingDir` are git's per-file XY\n * status chars (' ', 'M', 'A', 'D', 'R', 'C', 'U', '?', …). */\nexport const WorkspaceGitFile = z.object({\n path: z.string(),\n index: z.string(), // staged (X) status char\n workingDir: z.string(), // unstaged (Y) status char\n additions: z.number().int().nonnegative().optional(), // `git diff HEAD --numstat` lines added (absent ⇒ untracked / binary / older daemon)\n deletions: z.number().int().nonnegative().optional() // …and lines removed\n});\n/** The HEAD commit of the checkout. */\nexport const WorkspaceGitCommit = z.object({\n sha: z.string(), // full 40-hex commit hash\n shortSha: z.string(), // abbreviated hash (7 hex) for display\n subject: z.string(), // first line of the commit message\n committedAt: z.string() // RFC3339 committer date\n});\n/** D→C REP (corr = the req id): the working-tree status. */\nexport const WorkspaceGitStatus = z.object({\n agentId: z.string(),\n isRepo: z.boolean(), // false ⇒ from-scratch workspace (no .git) — git ops are N/A\n clean: z.boolean(), // true ⇒ no staged / unstaged / untracked changes\n branch: z.string().optional(), // current branch (absent ⇒ detached / unknown)\n tracking: z.string().optional(), // upstream ref, if the branch tracks one\n ahead: z.number().int().nonnegative().optional(), // commits ahead of upstream\n behind: z.number().int().nonnegative().optional(), // commits behind upstream\n files: z.array(WorkspaceGitFile).optional(), // changed paths (bounded; see `truncated`)\n truncated: z.boolean().optional(), // true ⇒ the `files` list was capped\n lastCommit: WorkspaceGitCommit.optional(), // HEAD commit (absent ⇒ empty repo / no commits yet)\n lastFetchAt: z.string().optional() // RFC3339 mtime of .git/FETCH_HEAD — when the repo last fetched/pulled\n});\n/** C→D REQ: unified-diff text for ONE workspace path, staged or unstaged. */\nexport const WorkspaceGitDiffReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional(),\n path: z.string().min(1).max(4096), // workspace-relative POSIX path (a directory diffs its subtree)\n staged: z.boolean().default(false) // true ⇒ index vs HEAD (`--cached`); false ⇒ worktree vs index\n});\n/** D→C REP (corr = the req id): the unified diff, or the DATA that says why there\n * is none. `diff` absent with `exists:true` and no `binary` ⇒ this path has no\n * changes in the requested scope. */\nexport const WorkspaceGitDiffResult = z.object({\n agentId: z.string(),\n path: z.string(),\n isRepo: z.boolean(), // false ⇒ from-scratch workspace (no .git) — nothing to diff\n exists: z.boolean(), // false ⇒ the path is neither changed nor present in the workspace\n diff: z.string().optional(), // unified-diff text as git emits it (bounded; see `truncated`)\n binary: z.boolean().optional(), // true ⇒ git reports a binary change, so there is no text to show\n truncated: z.boolean().optional() // true ⇒ `diff` is only the head of a bigger diff\n});\n/** Display ceilings for one `workspace/gitlog` row. 50 commits × (200 + 100)\n * characters stay under MAX_FRAME_BYTES even at JSON's 6× control-byte escape\n * blowup (50 × 300 × 6 ≈ 90 KB), so the REP can never overflow the frame. */\nexport const MAX_WORKSPACE_LOG_COMMITS = 50;\nexport const MAX_WORKSPACE_COMMIT_SUBJECT = 200;\nexport const MAX_WORKSPACE_COMMIT_AUTHOR = 100;\n/** C→D REQ: the newest commits of the workspace's checked-out branch. */\nexport const WorkspaceGitLogReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional(),\n limit: z.number().int().positive().max(MAX_WORKSPACE_LOG_COMMITS).default(20) // commits per REP\n});\n/** One commit in the log. `pushed` is reachability from the branch's upstream ref:\n * false means \"not known to be on a remote\", which is also what every commit\n * reports when the branch tracks nothing (`tracking` absent on the REP). */\nexport const WorkspaceGitLogCommit = WorkspaceGitCommit.extend({\n subject: z.string().max(MAX_WORKSPACE_COMMIT_SUBJECT), // first line of the message (display-capped)\n author: z.string().max(MAX_WORKSPACE_COMMIT_AUTHOR), // commit author name (display-capped)\n pushed: z.boolean()\n});\n/** D→C REP (corr = the req id): newest-first commits. An empty repo is DATA\n * (`commits: []`), not an error frame. */\nexport const WorkspaceGitLog = z.object({\n agentId: z.string(),\n isRepo: z.boolean(), // false ⇒ from-scratch workspace (no .git) — no log\n commits: z.array(WorkspaceGitLogCommit).max(MAX_WORKSPACE_LOG_COMMITS),\n truncated: z.boolean(), // true ⇒ more commits in this range than `limit`\n tracking: z.string().optional(), // upstream ref `pushed` was computed against (absent ⇒ tracks nothing)\n // The base ref the listing EXCLUDES, set only when the checkout sits on some other branch: the\n // commits are then `<base>..HEAD`, this branch's own work, not the repository's whole history.\n base: z.string().optional()\n});\n/** C→D REQ: force a fast-forward-only `git pull` in the agent's workspace now. */\nexport const WorkspaceGitPullReq = z.object({\n agentId: z.string().min(1) // local agent id (NOT a wire UUID)\n});\n/** D→C REP (corr = the req id): the pull outcome. A failed pull is DATA\n * (`ok:false` + `detail`), not an error frame (see the section docblock). */\nexport const WorkspaceGitPullResult = z.object({\n agentId: z.string(),\n isRepo: z.boolean(), // false ⇒ from-scratch workspace (no .git) — nothing to pull\n ok: z.boolean(), // true ⇒ pull succeeded (fast-forwarded or already up to date)\n detail: z.string().optional(), // human summary or failure reason (host paths stripped)\n changed: z.number().int().nonnegative().optional(), // files changed by the pull\n insertions: z.number().int().nonnegative().optional(),\n deletions: z.number().int().nonnegative().optional()\n});\n/** How many paths one stage/unstage REQ may carry. 500 matches the daemon's own cap on\n * `WorkspaceGitStatus.files`, so a console \"Stage all\" over a full status page is one REQ. */\nexport const MAX_WORKSPACE_STAGE_PATHS = 500;\n/** Total UTF-8 bytes across those paths — the bound that actually keeps the REQ inside the\n * 256 KiB frame cap, which 500 × 4096 could not. A path may legally contain control bytes and\n * JSON escapes each to `\\uXXXX` (6 wire bytes), so 32 KiB of paths is the worst-case ceiling\n * (pinned by a codec test). Ample for 500 ordinary paths; a bigger selection is chunked. */\nexport const MAX_WORKSPACE_STAGE_PATH_BYTES = 32 * 1024;\n/** Ceiling on one console commit message (subject + body), generated or hand-written. */\nexport const MAX_WORKSPACE_COMMIT_MESSAGE = 8_000;\nfunction stagePathBytes(paths) {\n const encoder = new TextEncoder();\n return paths.reduce((total, path) => total + encoder.encode(path).byteLength, 0);\n}\n/** C→D REQ: stage (`gitstage`) or unstage (`gitunstage`) exactly these paths. An EMPTY list is\n * a no-op that still answers with the fresh status — staging nothing is data, not a bad\n * request. Paths the checkout does not currently report as changed are skipped the same way. */\nexport const WorkspaceGitStageReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional(),\n paths: z\n .array(z.string().min(1).max(4096)) // workspace-relative POSIX paths, bounded like write/delete\n .max(MAX_WORKSPACE_STAGE_PATHS)\n .refine((paths) => stagePathBytes(paths) <= MAX_WORKSPACE_STAGE_PATH_BYTES, {\n message: `paths exceed ${MAX_WORKSPACE_STAGE_PATH_BYTES} bytes in total`\n })\n});\n/** Why a git write did not do what was asked. Present only when `ok:false`, and a closed\n * vocabulary because the console offers a different next action for each: pull before pushing,\n * stage something first, commit from the agent instead. The `detail` beside it is hand-written\n * or scrubbed of host paths, never raw git output with the workspace path in it. */\nexport const WorkspaceGitWriteReason = z.enum([\n 'not-a-repo', // from-scratch workspace (no .git) — git writes are N/A\n 'nothing-staged', // commit with an empty index diff\n 'empty-message', // commit message is blank once trimmed\n 'no-identity', // no `gitCommitIdentity` was registered, so the commit would take the host operator's\n 'detached-head', // push from a worktree with no branch checked out\n 'no-upstream', // the branch tracks nothing, so there is no ref to push to\n 'unsafe-origin', // the checkout's `origin` is not the daemon-authorized remote\n 'unsafe-config', // the checkout's local config carries a disallowed override (audit refused)\n 'diverged', // push rejected as non-fast-forward — the remote has commits this branch lacks\n 'rejected', // the remote refused the push (protected branch, hook, credentials, permissions)\n 'failed' // anything else git reported; `detail` carries the scrubbed message\n]);\n/** C→D REQ: commit the staged changes of the workspace (or session worktree). */\nexport const WorkspaceGitCommitReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional(),\n message: z.string().min(1).max(MAX_WORKSPACE_COMMIT_MESSAGE) // subject + optional body, as git receives it\n});\n/** D→C REP (corr = the req id): the commit outcome. A refusal is DATA (`ok:false` + `reason` +\n * `detail`), not an error frame. */\nexport const WorkspaceGitCommitResult = z.object({\n agentId: z.string(),\n isRepo: z.boolean(), // false ⇒ from-scratch workspace (no .git) — nothing to commit\n ok: z.boolean(), // true ⇒ a commit was created\n sha: z.string().optional(), // full 40-hex hash of the new commit (present iff ok)\n detail: z.string().optional(), // human summary or refusal reason (host paths stripped)\n reason: WorkspaceGitWriteReason.optional() // machine reason, present only when ok:false\n});\n/** C→D REQ: push the checked-out branch to the daemon-authorized remote. No refspec and no\n * force option on the wire: the daemon derives both, and a console push never forces. */\nexport const WorkspaceGitPushReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional()\n});\n/** D→C REP (corr = the req id): the push outcome. A rejection is DATA (`ok:false` + `reason` +\n * `detail`), not an error frame. A push with nothing to send is `ok:true` with `ahead:0` — the\n * requested state already holds. */\nexport const WorkspaceGitPushResult = z.object({\n agentId: z.string(),\n isRepo: z.boolean(), // false ⇒ from-scratch workspace (no .git) — nothing to push\n ok: z.boolean(), // true ⇒ the remote now has every local commit on this branch\n detail: z.string().optional(), // human summary or refusal reason (host paths stripped)\n ahead: z.number().int().nonnegative().optional(), // commits STILL ahead of the upstream (0 once pushed)\n reason: WorkspaceGitWriteReason.optional() // machine reason, present only when ok:false\n});\n/** C→D REQ: draft a commit message from the workspace's STAGED diff, on the agent's OWN runtime\n * (the CP never calls a model provider — webchat-side-panels.md §2). A bounded utility call, not\n * an agent turn: no tools, no transcript entry, no session state change. Writes nothing — the\n * reader edits the draft and commits it with `workspace/gitcommit`. It costs model tokens, so it\n * is only ever sent for an explicit press (§5.1), never prefetched. */\nexport const WorkspaceGitMessageReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional()\n});\n/** D→C REP (corr = the req id): the drafted message. EVERY way this can fail to produce one is\n * DATA (`ok:false` + `detail`) — nothing staged, a runtime with no read-only mode, a runtime that\n * answers with prose, a timeout, a cancel. `message` is a validated conventional-commit subject\n * plus optional body, ready to put straight in the commit box. */\nexport const WorkspaceGitMessageResult = z.object({\n agentId: z.string(),\n ok: z.boolean(), // true ⇒ `message` is present and usable\n message: z.string().max(MAX_WORKSPACE_COMMIT_MESSAGE).optional(),\n detail: z.string().optional() // human explanation of a refusal (host paths stripped)\n});\n//# sourceMappingURL=workspace.js.map","import { z } from 'zod';\n/**\n * Agent background tasks (C→D REQ → REP) — the console Tasks panel's on-demand read.\n *\n * The CP stores NO task data: descriptions are model-authored strings and states live only\n * in the owning daemon's in-memory background-task lease, pulled live and proxied, never\n * persisted (body-locality — webchat-side-panels.md §2).\n *\n * Scoped per (agent, ACP session) because the lease already is: ACP session ids are\n * runtime-local, so two agents can each expose an `acp-1`\n * (background-task-aware-reclaim.md §3).\n *\n * `task/list` is the ONLY frame here. There is deliberately no `task/cancel`: the single\n * cancellation primitive an ACP runtime exposes is `session/cancel`, whose payload is\n * `{ sessionId }` — it cancels a whole prompt turn, and the only hard stop is killing the\n * agent's shared adapter process. Neither can address one background task, so a per-task\n * cancel could only report a cancellation it did not perform or silently cancel unrelated\n * work. It becomes possible when a task-addressed cancel exists upstream.\n */\n/** Machine-readable `reason` on a task `BAD_PAYLOAD` error frame's `details`, so the CP can\n * answer with a status and a code the console can branch on instead of the 503 that reads as\n * an offline daemon. Everything else about tasks is DATA: an untracked session, a session\n * with no tasks and a runtime that reports none are all normal answers. */\nexport const TaskErrorReason = z.enum([\n 'unknown-agent' // no such agent on this daemon\n]);\n/** Tasks per REP. The lease holds every live task plus a bounded settled history, so this is a\n * display ceiling rather than a pagination cursor — a panel showing 50 rows is already past\n * useful, and `truncated` says the daemon had more. */\nexport const MAX_TASK_LIST_TASKS = 50;\n/** Display ceiling for one task's description. Model-authored, so it is bounded on the wire\n * rather than trusted; the daemon truncates rather than dropping the row. */\nexport const MAX_TASK_DESCRIPTION = 500;\n/** Display ceiling for the `detail` line beside a settled task. */\nexport const MAX_TASK_DETAIL = 200;\n/**\n * What the daemon can actually know about a task, and nothing more.\n *\n * - `running` — the task is in the lease's live set, i.e. it is the thing fencing host reclaim.\n * - `done` — the task settled and no terminal edge reported a failure.\n * - `failed` — a terminal edge reported `failed` or `killed`.\n *\n * There is NO `queued`: the SDK lifecycle feed's only start signal is `task_started`, so a task\n * is either live in the lease or gone. Most settle edges (the authoritative snapshot, and\n * `task_notification`) carry no status at all, which is why `done` means \"settled without a\n * reported failure\" rather than \"reported successful\"; `detail` carries the reported status\n * when there was one.\n */\nexport const TaskState = z.enum(['running', 'done', 'failed']);\n/** C→D REQ: the background tasks of ONE ACP session of one agent. */\nexport const TaskListReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id — the lease's own scope, so this is required rather than optional. */\n sessionId: z.string().min(1)\n});\n/** One background task. `subagent` is the runtime's own internal Task/subagent invocation: it\n * is carried rather than filtered out, because the same records are what fence host reclaim —\n * a panel that hid them at the SOURCE would show \"no tasks\" beside a host refusing to be\n * reclaimed. Consumers filter at RENDER. */\nexport const TaskEntry = z.object({\n id: z.string(), // runtime-local task id\n description: z.string().max(MAX_TASK_DESCRIPTION).optional(), // absent when the runtime omitted it\n state: TaskState,\n subagent: z.boolean(),\n startedAt: z.string(), // RFC3339, from the `task_started` edge\n endedAt: z.string().optional(), // RFC3339; present iff the task settled\n detail: z.string().max(MAX_TASK_DETAIL).optional() // the terminal status the runtime reported, when any\n});\n/** D→C REP (corr = the req id): live tasks newest-first, then the retained settled ones\n * newest-first. `tracked:false` means this daemon holds no lease for the session — a\n * non-Claude runtime, an adapter without the lifecycle extension, or a session that has not\n * emitted an accepted lifecycle event yet. That is a different statement from \"this session\n * has no background tasks\", and the console says so. */\nexport const TaskList = z.object({\n agentId: z.string(),\n sessionId: z.string(),\n tracked: z.boolean(),\n tasks: z.array(TaskEntry).max(MAX_TASK_LIST_TASKS),\n truncated: z.boolean() // true ⇒ the daemon held more tasks than this REP carries\n});\n//# sourceMappingURL=task.js.map","import { z } from 'zod';\nimport { SessionUsage } from './session.js';\nimport { Platform } from './route.js';\nimport { HeartbeatDuties } from './duty.js';\n/**\n * Telemetry & facts (D→C) — protocol §7.\n *\n * The dashboard's real-time source. `event/session` is the converged milestone\n * feed (NOT the message stream); `facts/daemon-runtimes` is the observed runtime\n * capability feed; `heartbeat` drives the watchdog.\n */\nexport const Heartbeat = z.object({\n load: z.object({\n cpu: z.number(), // 0..1 CPU utilization fraction (busy-time across cores) — NOT a raw load average\n mem: z.number(), // 0..1 utilization fraction\n agents: z.number().int()\n }),\n health: z.enum(['ok', 'degraded']),\n activeSessions: z.number().int(),\n degradedScopes: z.array(z.string()).default([]), // e.g. expired-lease bindings (§6)\n // Duty lease exchange (k8s daemons only; frames/duty.ts). Absent ⇒ this daemon\n // does not participate in the duty ledger and the CP-side path stays dormant.\n duties: HeartbeatDuties.optional()\n});\nconst ExternalKey = z.string().min(1).max(200);\nconst GithubId = z.string().regex(/^[1-9]\\d*$/);\n/** Immutable audience identity inherited by A2A descendants. Credential proof\n * stays on the direct root only; children inherit this tuple from their parent. */\nexport const ExternalSessionAudience = z.discriminatedUnion('provider', [\n z.object({\n provider: z.literal('slack'),\n realmKey: ExternalKey.optional(),\n resourceKind: z.literal('conversation'),\n resourceKey: ExternalKey\n }),\n z.object({\n provider: z.literal('feishu'),\n realmKey: ExternalKey.optional(),\n resourceKind: z.literal('conversation'),\n resourceKey: ExternalKey\n }),\n z.object({\n provider: z.literal('github'),\n realmKey: z.literal('github.com'),\n resourceKind: z.literal('repository'),\n // Rename-proof GitHub repository id, never owner/repo.\n resourceKey: GithubId\n })\n]);\n/** Direct-ingress audience plus the provider-specific proof the CP validates\n * before binding a durable ExternalScope. */\nexport const ExternalSessionOrigin = z.discriminatedUnion('provider', [\n ExternalSessionAudience.options[0].extend({\n integrationId: z.string().uuid().optional()\n }),\n ExternalSessionAudience.options[1].extend({\n integrationId: z.string().uuid().optional()\n }),\n ExternalSessionAudience.options[2].extend({\n hookId: z.string().uuid(),\n deliveryKey: ExternalKey,\n sourceInstallationId: GithubId,\n // Trusted webhook snapshot; display/API-routing hint only. repoId above is\n // the authorization identity and must still match the accepted HookRun.\n repoFullName: ExternalKey\n })\n]);\n/** Converged session lifecycle milestone — protocol §7.2. NOT the message stream. */\nexport const EventSession = z.object({\n sessionId: z.string(), // ACP session id (agent-assigned; a free string, NOT a wire UUID — matches usage/report)\n // Stable ACP session id of the session that spawned this one. Absent for roots.\n // Stored as metadata so the console can navigate the session family.\n parentSessionId: z.string().optional(),\n agentId: z.string().uuid(),\n launchId: z.string().uuid().optional(), // 🅰️ CP launch fence — absent for sessions created on the Slack/Discord→daemon path (no CP-initiated launch)\n phase: z.enum(['start', 'plan', 'problem', 'end']),\n // sessionKey echo — where the session lives; the CP stores it so a deep-link\n // detail page (…/sessions/:id) can show the channel without the daemon online.\n platform: Platform.optional(),\n channel: z.string().optional(),\n thread: z.string().optional(),\n link: z.string().optional(), // deep-link to detail view\n summary: z.string().optional(), // short, human-facing milestone text\n // Dashboard-list metadata snapshot. Still metadata-only: no message bodies,\n // transcript stream, attachment bytes, or tool payloads cross into the CP store.\n title: z.string().optional(),\n status: z.string().optional(),\n lastActivityAt: z.string().datetime().optional(),\n triggeredBy: z.string().optional(),\n channelName: z.string().optional(),\n triggeredByName: z.string().optional(),\n threadUrl: z.string().optional(),\n // ── visibility classification inputs (session-visibility.md §4.1) ──\n // What kind of conversation the session lives in, from the daemon's own\n // NormalizedMessage.isDm/isGroupDm. Absent (old daemon) ⇒ 'channel' behavior,\n // i.e. the CP classifies the session `org`.\n conversationKind: z.enum(['dm', 'group_dm', 'channel']).optional(),\n // DURABLE workspace/tenant scope for ownerIdentity (§2) — a Slack team id,\n // Feishu tenant key, or a minted stable per-integration scope. NOT the\n // daemon's credential-derived transport scope (that rotates with tokens).\n // Absent ⇒ the CP records no IM owner (fail closed).\n transportScope: z.string().min(1).max(200).optional(),\n // Web API launch provenance (§4.4): the correlation id the CP minted on\n // `agent/launch`, echoed back so ingest can attribute the session to the\n // launching console user. NOT the launchId fence above.\n launchCorrelationId: z.string().uuid().optional(),\n // Durable daemon-local source provenance. `local` distinguishes synthetic or\n // otherwise non-provider sessions that retain platform-shaped coordinates\n // for session-key compatibility. Absent keeps mixed-version ingest on the\n // conservative legacy path.\n sourceBindingKind: z.enum(['local', 'external']).optional(),\n // Immutable audience candidate for a supported shared input. This is\n // metadata-only: the CP validates the integration before binding a scope and\n // resolves current provider membership only on authorized read paths.\n externalOrigin: ExternalSessionOrigin.optional(),\n // Effective execution-config snapshot: what the session actually ran with\n // (per-session sticky override, else the agent's config at run time; absent ⇒\n // the runtime's own default). Recorded so the console shows what a session\n // USED, not the owning agent's config at view time. The reporting daemon is\n // NOT echoed here — the CP stamps it from the authenticated WS connection.\n runtime: z.string().optional(),\n model: z.string().optional(),\n // Runtime observation for this milestone. `null` means the runtime exposed\n // only an opaque/default model; absent is a legacy/config-only snapshot. New\n // readers prioritize this over `model`, while old readers safely ignore it.\n observedModel: z.string().nullable().optional(),\n effort: z.string().optional(), // reasoning effort level (runtime-owned vocabulary)\n fastMode: z.boolean().optional(),\n // Effective session permission preset. Usually the runtime-owned mode; Codex Auto\n // is the AgentConnect composite value that the daemon decomposes before ACP.\n permissionMode: z.string().optional(),\n outputMode: z.string().optional(), // daemon-side output verbosity (none/minimal/low/medium/high)\n // Workspace choice pinned when the logical session was created. This is\n // metadata only; it lets the console offer a link to an isolated worktree\n // without assuming the Agent's current setting still matches this session.\n workspaceIsolation: z.enum(['shared', 'session']).optional(),\n ts: z.string().datetime()\n});\n/**\n * Metadata-only transcript invalidation. Message/tool bodies remain daemon-local;\n * an authorized browser uses this signal to pull the changed rows through\n * `session/history.after`.\n */\nexport const SessionActivity = z.object({\n sessionId: z.string(),\n agentId: z.string().uuid(),\n revision: z.string().regex(/^\\d+$/),\n ts: z.string().datetime()\n});\n/** Why a daemon dropped a session's local content. Only the retention sweep\n * (#485) purges autonomously today; the vocabulary is an enum so an explicit\n * operator-initiated delete can join it without a frame revision. */\nexport const SessionPurgeReason = z.enum(['retention']);\n/**\n * Retention-GC receipt — D→C REQ, answered with the generic `ack` (#485).\n *\n * The daemon deleted these sessions' local rows (and any per-session worktree)\n * after `sessions.retention` elapsed, so their transcripts can never be pulled\n * again. The CP keeps the metadata row and MARKS it purged — that is what lets\n * the console explain an empty transcript instead of rendering it as \"this\n * session said nothing\".\n *\n * Correlated rather than fire-and-forget precisely because the local row is\n * already gone: an unacknowledged report cannot be re-derived from daemon state\n * later, so the daemon holds a durable receipt until this ACKs. Delivery is\n * therefore at-least-once and the CP applies it idempotently (a re-reported\n * session keeps its first `contentPurgedAt`).\n */\nexport const SessionPurged = z.object({\n // One agent per frame: the CP authorizes the report by checking that THIS\n // agent is placed on the reporting daemon, the same trust boundary as\n // `event/session`. A sweep spanning several agents sends several frames.\n agentId: z.string().uuid(),\n // ACP session ids (agent-assigned strings, NOT wire UUIDs). Batched because a\n // single sweep commonly expires many sessions at once; capped well under the\n // frame budget so the daemon chunks instead of overflowing the wire.\n sessionIds: z.array(z.string().min(1)).min(1).max(200),\n reason: SessionPurgeReason,\n ts: z.string().datetime()\n});\n/**\n * Per-session token-usage report — D→C EVT. The daemon meters usage from the\n * agent's ACP stream and reports the session's CUMULATIVE snapshot (latest-wins)\n * so the CP can persist it for the console's historical usage aggregates. This is\n * dashboard metadata (token counts + cost), never the message stream. Idempotent\n * by `sessionId`: re-sending the same snapshot is a no-op upsert on the CP.\n */\nexport const UsageReport = z.object({\n sessionId: z.string(), // ACP session id (agent-assigned; NOT a wire UUID)\n agentId: z.string().uuid(),\n platform: z.string().optional(), // denormalized sessionKey echo for dashboard filters\n channel: z.string().optional(),\n // The model observed for the usage delta ending at this cumulative snapshot.\n // `null` is an explicit runtime-owned default/unknown; absent is an old daemon.\n observedModel: z.string().nullable().optional(),\n lastActivityAt: z.string(), // ISO ts of the session's last activity\n usage: SessionUsage\n});\n/**\n * Observed capabilities of an installed runtime — protocol §7.3. The element\n * type of the `facts/daemon-runtimes` snapshot. As a standalone per-runtime\n * frame (`facts/runtime-profile`, upsert-only) it is DEPRECATED: current\n * daemons report the full snapshot instead; the CP keeps accepting the old\n * frame from older daemons.\n */\n/**\n * MCP transports a runtime accepts on `session/new` `mcpServers` (from the ACP\n * `initialize` response's `agentCapabilities.mcpCapabilities`). Stdio is the ACP\n * baseline every agent must accept, so only the optional transports are listed.\n */\nexport const McpTransportCapabilities = z.object({\n http: z.boolean(),\n sse: z.boolean()\n});\n/**\n * One thought-level (reasoning-effort) choice a model offers — value is the\n * wire vocabulary the runtime accepts; name/description are display metadata\n * straight from the runtime's select options (or catalog driver), when present.\n */\nexport const EffortOption = z.object({\n value: z.string(),\n name: z.string().optional(),\n description: z.string().optional()\n});\n/** One runtime permission-mode choice. The display metadata is forwarded\n * verbatim from the runtime's ACP `category: \"mode\"` select option. */\nexport const PermissionModeOption = z.object({\n value: z.string(),\n name: z.string().optional(),\n description: z.string().optional()\n});\n/**\n * Per-model capability entry of a runtime's model catalog (design doc\n * runtime-model-catalog.md). `efforts` carries the thought_level vocabulary the\n * daemon will actually offer when this model is selected (daemon-side synthetic\n * levels included): `[]` = the model has no effort selector; absent = not yet\n * discovered. `fastMode` mirrors whether the model_config fast toggle appears\n * for this model; absent = unknown.\n */\nexport const RuntimeModelCapability = z.object({\n id: z.string(), // model-selector value\n name: z.string().optional(), // display name (sent only when it differs from id)\n efforts: z.array(EffortOption).optional(),\n defaultEffort: z.string().optional(),\n fastMode: z.boolean().optional()\n});\n/**\n * A runtime's discovered model × config capability matrix. One shape shared by\n * the wire, the CP's `runtime_profile.modelCatalog` JSONB column, and the DTO —\n * no field renames between layers.\n */\nexport const RuntimeModelCatalog = z.object({\n models: z.array(RuntimeModelCapability).max(128),\n defaultModel: z.string().optional(), // resolved concrete model id (never the literal \"default\")\n permissionModes: z.array(PermissionModeOption).optional(),\n // The mode select's currentValue on a fresh probe session — the runtime's own\n // default permission mode (e.g. copilot 'agent'). Absent = not observed.\n defaultPermissionMode: z.string().optional(),\n source: z.enum(['native', 'acp']), // native = catalog driver, acp = per-model enumeration / probe seed\n observedAt: z.string().datetime()\n});\nexport const FactsRuntimeProfile = z.object({\n runtime: z.string(), // \"claude\" / \"codex\" / ...\n version: z.string(),\n models: z.array(z.string()),\n contextWindow: z.number().int().optional(),\n acpSupport: z.enum(['full', 'partial', 'none']), // gates the dual-mode decision (#1)\n // ACP protocol version the runtime negotiated at `initialize` (the number the\n // agent echoed/downgraded to). Absent for older daemons / runtimes not probed yet.\n acpProtocolVersion: z.number().int().optional(),\n toolCalling: z.boolean(),\n // MCP transports the runtime advertised at `initialize`. Absent for older\n // daemons / runtimes not probed yet (⇒ assume stdio-only).\n mcpCapabilities: McpTransportCapabilities.optional(),\n // Provenance of `models[]`: 'cached' = hydrated from the daemon's local\n // last-good catalog cache (a live probe has not confirmed it this process) —\n // capability gates (agent move / activation model checks) MUST treat it as\n // permissive, exactly like an empty list; 'probed' = confirmed by a live\n // probe. Absent ⇒ 'probed' semantics.\n modelsSource: z.enum(['cached', 'probed']).optional(),\n // The last probe was rejected with the ACP auth-required error (-32000): the\n // runtime is installed but needs an interactive login on the daemon host\n // before sessions can start. Cleared (absent) once a probe succeeds; absent\n // also for older daemons that don't report it.\n authRequired: z.boolean().optional(),\n // Discovered model × config capability matrix (last-good; survives probe\n // failures — advertisement (`models`) empties on failure, capability\n // knowledge does not). Absent = this daemon has no catalog for the runtime.\n modelCatalog: RuntimeModelCatalog.optional()\n});\n/**\n * One daemon-configured MCP server (daemon config `mcpServers`), surfaced so the\n * console can list the servers an agent may enable. Name + transport only —\n * derived directly from config; the daemon does NOT connect to the server.\n * Definitions (commands, URLs, headers) stay daemon-local.\n */\nexport const FactsMcpServer = z.object({\n name: z.string(), // config key; what AgentSpec.mcpServers references\n transport: z.enum(['stdio', 'http', 'sse'])\n});\n/**\n * Full snapshot of the daemon's installed runtimes — D→C EVT (protocol §7.3a),\n * emitted on each register and again once the background probe sweep completes\n * (with the learned `models[]`). REPLACE semantics: the CP reconciles its\n * stored runtime list for the daemon to exactly `runtimes[]`, pruning runtimes\n * that are no longer installed. Idempotent (latest-wins). Supersedes the\n * per-runtime `facts/runtime-profile` upsert.\n */\nexport const DaemonRuntimes = z.object({\n runtimes: z.array(FactsRuntimeProfile),\n // Daemon-level (not per-runtime) MCP-server list (name + transport, from\n // config) — same REPLACE semantics as `runtimes`. Default [] so older daemons\n // parse clean.\n mcpServers: z.array(FactsMcpServer).default([]),\n // Per-connection monotonic snapshot ordinal. The CP resets its stored value\n // on register and ignores snapshots whose seq is <= the stored one, so two\n // frames whose DB transactions interleave (sweep frame vs catalog frame; the\n // CP dispatches inbound frames without awaiting) cannot commit out of order.\n // Absent (older daemon) ⇒ latest-commit-wins as before.\n seq: z.number().int().optional()\n});\n/** Non-secret config update — C→D EVT, protocol §8.3 / frame #26. */\nexport const ConfigPush = z.object({\n keys: z.record(z.string(), z.unknown())\n});\n/** Auth-time upgrade result, legal before full registration. */\nexport const DaemonBootstrapResult = z.object({\n operationId: z.string(),\n status: z.enum(['installed', 'failed']),\n reason: z.string().max(500).optional()\n});\n/** Fleet: drain+exit, supervisor restarts — C→D REQ, protocol §8.3 / frame #27. */\nexport const DaemonRestart = z.object({\n reason: z.string(),\n drainFirst: z.boolean().default(true)\n});\n/** Fleet: drain+exit for version bump — C→D REQ, protocol §8.3 / frame #28. */\nexport const DaemonUpgrade = z.object({\n targetVersion: z.string(),\n drainFirst: z.boolean().default(true)\n});\n/** Reply to a fleet restart/upgrade REQ (protocol §8.3). */\nexport const DaemonControlAck = z.object({\n accepted: z.boolean(),\n willDrainUntil: z.string().datetime().optional(),\n // Why the daemon declined (`accepted:false`) — e.g. no supervisor, CLI not\n // locatable, another lifecycle op in flight (cli-daemon-split.md §7.1).\n // Optional + backward-compatible: an older daemon simply omits it.\n reason: z.string().optional()\n});\n/**\n * Generic acknowledgement for REQs whose reply is just `ack` in the frame index\n * (cron/upsert, cron/remove, agent/stop). Kept permissive but typed.\n */\nexport const Ack = z.object({\n ok: z.boolean(),\n reason: z.string().optional()\n});\n//# sourceMappingURL=telemetry.js.map","import { z } from 'zod';\n/**\n * Error model — protocol §9.\n *\n * Every REQ can be answered by an `error` REP (`corr` = request `id`). Errors\n * are typed and actionable, not free text.\n */\nexport const ErrorCode = z.enum([\n // protocol / framing\n 'UNKNOWN_FRAME',\n 'FRAME_TOO_LARGE',\n 'PROTOCOL_STATE',\n 'BAD_PAYLOAD',\n // auth / identity\n 'AUTH_FAILED',\n 'ATTESTATION_INVALID',\n // fencing / ordering\n 'STALE_EPOCH',\n 'STALE_LAUNCH',\n // delivery\n 'NO_SESSION',\n 'SCOPE_DENIED',\n // delegated MCP authority / invocation binding\n 'DELEGATION_DENIED',\n 'INVOCATION_CONFLICT',\n // secrets\n 'LEASE_EXPIRED',\n 'LEASE_DENIED',\n // generic\n 'RATE_LIMITED',\n 'CONFLICT',\n 'INTERNAL'\n]);\nexport const ErrorFrame = z.object({\n code: ErrorCode,\n message: z.string(), // human-readable, redacted of secrets\n retryable: z.boolean(),\n details: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * WebSocket close codes — protocol §9.\n *\n * `4401` requires a fresh credential before reconnecting; everything else uses\n * exponential backoff with jitter.\n */\nexport const CloseCode = {\n BAD_SUBPROTOCOL: 4400, // bad subprotocol/handshake\n AUTH_FAILED: 4401, // auth failed (don't auto-retry)\n EPOCH_CONFLICT: 4409, // epoch conflict on handshake (do full reconcile)\n UNSUPPORTED_ENCODING: 4415, // binary/unsupported encoding\n RATE_LIMITED: 4429, // rate-limited (backoff)\n SERVER_INTERNAL: 1011, // server internal\n SERVER_RESTARTING: 1012, // server restarting (reconnect with backoff)\n /** soft 256 KiB cap exceeded → ws library close (protocol §1). */\n MESSAGE_TOO_BIG: 1009\n};\n//# sourceMappingURL=error.js.map","import { z } from 'zod';\n/** Non-secret entitlement carried CP → relay → daemon after webchat verification. */\nexport const WebchatRemoteMcpEntitlement = z\n .object({\n authorityId: z.string().uuid(),\n authorityGeneration: z.number().int().positive(),\n expiresAt: z.string().datetime()\n})\n .strict();\nconst DescriptorFence = z\n .object({\n authorityId: z.string().uuid(),\n authorityGeneration: z.number().int().positive(),\n conversationId: z.string().uuid(),\n descriptorInstanceId: z.string().uuid(),\n grantRevision: z.number().int().positive()\n})\n .strict();\nexport const WebchatMcpGrantIssue = z\n .object({\n authorityId: z.string().uuid(),\n authorityGeneration: z.number().int().positive(),\n conversationId: z.string().uuid(),\n descriptorInstanceId: z.string().uuid()\n})\n .strict();\nexport const WebchatMcpGrantIssued = DescriptorFence.extend({\n grantId: z.string().uuid(),\n token: z.string().min(32),\n expiresAt: z.string().datetime(),\n mcpUrl: z.string().url()\n}).strict();\nexport const WebchatMcpGrantAccept = DescriptorFence.extend({\n grantId: z.string().uuid()\n}).strict();\nexport const WebchatMcpGrantActivate = WebchatMcpGrantAccept.extend({\n activated: z.boolean()\n}).strict();\nexport const WebchatMcpGrantRevoke = z\n .object({\n authorityId: z.string().uuid(),\n authorityGeneration: z.number().int().positive(),\n conversationId: z.string().uuid(),\n reason: z.enum(['session_closed', 'session_expired', 'agent_detached', 'feature_disabled', 'security'])\n})\n .strict();\nexport const WebchatMcpGrantRevoked = WebchatMcpGrantRevoke.pick({\n authorityId: true,\n authorityGeneration: true,\n conversationId: true\n})\n .extend({ revoked: z.boolean() })\n .strict();\n//# sourceMappingURL=remote-mcp.js.map","import { z } from 'zod';\nimport { AuthReq, AuthOk } from './frames/auth.js';\nimport { RegisterReq, RegisterOk, RelayRosterUpdate, CapabilitiesUpdate } from './frames/register.js';\nimport { CollabRoutesSnapshot } from './frames/collab.js';\nimport { RouteAssign, RouteAssignAck, RouteUpdate, Drain, DrainProgress, DrainDone } from './frames/route.js';\nimport { AgentLaunch, AgentLaunched, AgentStop, AgentUpsert, AgentRemove, AgentDetach, AgentActivate, AgentActivity, AgentScopeDenied, AgentPermissionRequestList, AgentPermissionRequestPage, AgentPermissionDecision } from './frames/agent.js';\nimport { CronUpsert, CronRemove, CronReport, CronRunNow } from './frames/cron.js';\nimport { DutyGrant, DutyRenewed, DutyRevoke, DutyRelease, DutyClaim, DutyClaimOk, DutyFetch, DutyFetchOk } from './frames/duty.js';\nimport { GithubReviewAuthorize, GithubReviewAuthorized, GithubReviewResultOk, GithubReviewResultReport, HookReport, HookStart, HookStartOk } from './frames/hook.js';\nimport { IntegrationUpsert, IntegrationRemove, IntegrationChannels, IntegrationForget, IntegrationLeave, IntegrationLeaveOk } from './frames/integration.js';\nimport { McpServerUpsert, McpServerRemove } from './frames/mcpserver.js';\nimport { MemoryConnectionUpsert, MemoryConnectionRemove, MemoryConnectionFacts } from './frames/memory-connection.js';\nimport { GitCredRequest, GitCredGrant } from './frames/gitcred.js';\nimport { SecretsRequest, SecretsGrant, SecretsRenew, SecretsRevoke, ScopeAttestation } from './frames/secrets.js';\nimport { SessionHistoryReq, SessionHistoryPage, SessionListReq, SessionListPage, SessionToolBodyReq, SessionToolBodyChunk, ChildSessionStatus, ChildSessionStatusReq, ChildSessionStatusProbe, SessionVisibilityPush, SessionVisibilityOk, SessionVisibilitySnapshot } from './frames/session.js';\nimport { ChannelAgentsReq, ChannelAgentsOk } from './frames/channel.js';\nimport { WorkspaceListReq, WorkspaceListPage, WorkspaceReadReq, WorkspaceReadContent, WorkspaceWriteReq, WorkspaceWriteOk, WorkspaceDeleteReq, WorkspaceDeleteOk, WorkspaceGitStatusReq, WorkspaceGitStatus, WorkspaceGitDiffReq, WorkspaceGitDiffResult, WorkspaceGitLogReq, WorkspaceGitLog, WorkspaceGitPullReq, WorkspaceGitPullResult, WorkspaceGitStageReq, WorkspaceGitCommitReq, WorkspaceGitCommitResult, WorkspaceGitPushReq, WorkspaceGitPushResult, WorkspaceGitMessageReq, WorkspaceGitMessageResult } from './frames/workspace.js';\nimport { TaskListReq, TaskList } from './frames/task.js';\nimport { MemoryChannelsReq, MemoryChannelsPage, MemoryListReq, MemoryListPage, MemoryReadReq, MemoryReadContent, MemoryWriteReq, MemoryWriteOk, MemoryHistoryReq, MemoryHistoryPage, MemorySurfaceReq, MemorySurfaceInfo, MemoryRecordSearchReq, MemoryRecordSearchPage, MemoryRecordListReq, MemoryRecordListPage, MemoryRecordGetReq, MemoryRecordGetResult, MemoryRecordCreateReq, MemoryRecordCreateResult, MemoryRecordUpdateReq, MemoryRecordUpdateResult, MemoryRecordDeleteReq, MemoryRecordDeleteResult, MemoryRecordHistoryReq, MemoryRecordHistoryPage, DreamStartReq, DreamState, DreamCancelReq, DreamListReq, DreamListPage, DreamGetReq, DreamAdoptReq, DreamDiscardReq, DreamFilesReq, DreamFilesPage, DreamFileReadReq, DreamFileReadContent, DreamSkillReviewReq, DreamSkillReadReq, DreamSkillContent } from './frames/memory.js';\nimport { LocalSkillsReq, LocalSkillsList } from './frames/skill.js';\nimport { KnowledgeSearchReq, KnowledgeSearchOk, KnowledgeListReq, KnowledgeListOk, OrgSkillsReq, OrgSkillsOk, OrganizationSuggestionsSyncReq, OrganizationSuggestionsSyncOk, OrganizationSuggestionReadReq, OrganizationSuggestionChunk, OrganizationSuggestionReviewReq, ManagedSkillReadReq, ManagedSkillChunk } from './frames/organization-knowledge.js';\nimport { Heartbeat, EventSession, SessionActivity, SessionPurged, UsageReport, FactsRuntimeProfile, DaemonRuntimes, ConfigPush, DaemonBootstrapResult, DaemonRestart, DaemonUpgrade, DaemonControlAck, Ack } from './frames/telemetry.js';\nimport { ErrorFrame } from './frames/error.js';\nimport { WebchatMcpGrantAccept, WebchatMcpGrantActivate, WebchatMcpGrantIssue, WebchatMcpGrantIssued, WebchatMcpGrantRevoke, WebchatMcpGrantRevoked } from './frames/remote-mcp.js';\n// webchat CONTENT frames were retired in milestone A4 — content rides the relay's rd/*\n// wire now, not the daemon↔CP control WS. The reply-payload schemas live on in\n// frames/webchat.ts (reused by rd/chat); remote-MCP grant lifecycle frames\n// remain valid on the control WebSocket.\n/**\n * The single source of truth for the wire: `type` string → payload zod schema.\n *\n * Mirrors the frame index in daemon-cp-ws-protocol.md §10 (the 29 numbered\n * frames) plus the correlated REP types named in the \"Reply\" column\n * (`route/assign/ack`, `drain/done`, and the generic `ack` replies) that also\n * travel on the wire and must be decodable.\n *\n * `ws/codec.ts` validates every inbound `payload` against `FRAME_SCHEMAS[type]`;\n * an unknown `type` → `ErrorFrame{code:\"UNKNOWN_FRAME\"}` (a REP, not a close).\n */\nexport const FRAME_SCHEMAS = {\n // ── auth / identity ──\n auth: AuthReq,\n 'auth/ok': AuthOk,\n // ── register / reconcile ──\n register: RegisterReq,\n 'register/ok': RegisterOk,\n // ── capability refresh (D→C hot update of register.capabilities) ──\n 'capabilities/update': CapabilitiesUpdate,\n // ── relay roster (C→D hot update of register/ok.relays) ──\n 'relay/roster': RelayRosterUpdate,\n // ── collaboration routing snapshot (C→D hot push; baseline in register/ok) ──\n 'collaboration/routes': CollabRoutesSnapshot,\n // ── telemetry ──\n heartbeat: Heartbeat,\n 'duty/grant': DutyGrant,\n 'duty/renewed': DutyRenewed,\n 'duty/revoke': DutyRevoke,\n 'duty/release': DutyRelease,\n 'duty/claim': DutyClaim,\n 'duty/claim/ok': DutyClaimOk,\n 'duty/fetch': DutyFetch,\n 'duty/fetch/ok': DutyFetchOk,\n // ── agent lifecycle / delivery ──\n 'agent/launch': AgentLaunch,\n 'agent/launched': AgentLaunched,\n 'agent/stop': AgentStop,\n 'agent/upsert': AgentUpsert,\n 'agent/remove': AgentRemove,\n 'agent/detach': AgentDetach,\n 'agent/activate': AgentActivate,\n 'agent/activity': AgentActivity,\n 'agent/scope-denied': AgentScopeDenied,\n 'agent/permission-requests': AgentPermissionRequestList,\n 'agent/permission-requests/page': AgentPermissionRequestPage,\n 'agent/permission-decision': AgentPermissionDecision,\n // ── routing / orchestration ──\n 'route/assign': RouteAssign,\n 'route/assign/ack': RouteAssignAck,\n 'route/update': RouteUpdate,\n 'daemon/drain': Drain,\n 'drain/progress': DrainProgress,\n 'drain/done': DrainDone,\n // ── cron ──\n 'cron/upsert': CronUpsert,\n 'cron/remove': CronRemove,\n 'cron/report': CronReport,\n 'cron/run': CronRunNow,\n // ── hooks (content fires ride rd/*; only metadata/effect control is here) ──\n 'hook/report': HookReport,\n 'hook/start': HookStart,\n 'hook/start/ok': HookStartOk,\n 'github/review-authorize': GithubReviewAuthorize,\n 'github/review-authorized': GithubReviewAuthorized,\n 'github/review-result': GithubReviewResultReport,\n 'github/review-result/ok': GithubReviewResultOk,\n // ── integrations (platform config distribution; token-bearing — never log) ──\n 'integration/upsert': IntegrationUpsert,\n 'integration/remove': IntegrationRemove,\n 'integration/channels': IntegrationChannels,\n 'integration/forget': IntegrationForget,\n 'integration/leave': IntegrationLeave,\n 'integration/leave/ok': IntegrationLeaveOk,\n // ── MCP provider registry (CP-owned defs pushed to daemons; grant-key-bearing — never log) ──\n 'mcpserver/upsert': McpServerUpsert,\n 'mcpserver/remove': McpServerRemove,\n // ── external-memory connection registry (grant-bearing; never log) ──\n 'memoryconnection/upsert': MemoryConnectionUpsert,\n 'memoryconnection/remove': MemoryConnectionRemove,\n // ── git credentials (github-app workspaces; token-bearing — never log) ──\n 'gitcred/request': GitCredRequest,\n 'gitcred/grant': GitCredGrant,\n // ── secrets ──\n 'secrets/request': SecretsRequest,\n 'secrets/grant': SecretsGrant,\n 'secrets/renew': SecretsRenew,\n 'secrets/revoke': SecretsRevoke,\n 'scope-attestation': ScopeAttestation,\n // ── webchat-scoped remote AgentConnect MCP grants ──\n 'webchat/mcp-grant/issue': WebchatMcpGrantIssue,\n 'webchat/mcp-grant/issued': WebchatMcpGrantIssued,\n 'webchat/mcp-grant/accept': WebchatMcpGrantAccept,\n 'webchat/mcp-grant/activate': WebchatMcpGrantActivate,\n 'webchat/mcp-grant/revoke': WebchatMcpGrantRevoke,\n 'webchat/mcp-grant/revoked': WebchatMcpGrantRevoked,\n // ── dashboard / facts ──\n 'event/session': EventSession,\n // Durable latest-wins metadata snapshot — D→C REQ, replied with `ack`.\n 'event/session-sync': EventSession,\n 'event/session-activity': SessionActivity,\n // Retention-GC receipt (#485) — D→C REQ, replied with the generic `ack`.\n 'event/session-purged': SessionPurged,\n 'usage/report': UsageReport,\n 'facts/runtime-profile': FactsRuntimeProfile,\n 'facts/daemon-runtimes': DaemonRuntimes,\n 'facts/memory-connections': MemoryConnectionFacts,\n // ── session read-back (console history pull) ──\n 'session/list': SessionListReq,\n 'session/list/page': SessionListPage,\n 'session/history': SessionHistoryReq,\n 'session/history/page': SessionHistoryPage,\n 'session/tool-body': SessionToolBodyReq,\n 'session/tool-body/chunk': SessionToolBodyChunk,\n // ── child-session status (session-concept §5.4). Two legs: D→C asks the CP (the placement\n // authority) about a child on another daemon; C→D forwards the lineage pair to the OWNING\n // daemon, which authorizes it. Metadata only — the CP never persists the answer.\n 'session/child-status': ChildSessionStatusReq,\n 'session/child-status/ok': ChildSessionStatus,\n 'session/child-status/probe': ChildSessionStatusProbe,\n 'session/child-status/probe/ok': ChildSessionStatus,\n // ── session visibility gate push (session-visibility.md §5.1). C→D REQs: a single\n // per-session push (reply: typed `session/visibility/ok`) and the register-time\n // snapshot replay (reply: generic `ack`). Rev-fenced in the payload — a stale rev\n // is acked `superseded`, never answered with an error frame.\n 'session/visibility': SessionVisibilityPush,\n 'session/visibility/ok': SessionVisibilityOk,\n 'session/visibility/snapshot': SessionVisibilitySnapshot,\n // ── channel agent directory (agent collaboration; D→C REQ → REP) ──\n 'channel/agents': ChannelAgentsReq,\n 'channel/agents/ok': ChannelAgentsOk,\n // ── workspace files (console live access; bytes transit, never stored) ──\n 'workspace/list': WorkspaceListReq,\n 'workspace/list/page': WorkspaceListPage,\n 'workspace/read': WorkspaceReadReq,\n 'workspace/read/content': WorkspaceReadContent,\n 'workspace/write': WorkspaceWriteReq,\n 'workspace/write/ok': WorkspaceWriteOk,\n 'workspace/delete': WorkspaceDeleteReq,\n 'workspace/delete/ok': WorkspaceDeleteOk,\n 'workspace/gitstatus': WorkspaceGitStatusReq,\n 'workspace/gitstatus/result': WorkspaceGitStatus,\n 'workspace/gitdiff': WorkspaceGitDiffReq,\n 'workspace/gitdiff/result': WorkspaceGitDiffResult,\n 'workspace/gitlog': WorkspaceGitLogReq,\n 'workspace/gitlog/result': WorkspaceGitLog,\n 'workspace/gitpull': WorkspaceGitPullReq,\n 'workspace/gitpull/result': WorkspaceGitPullResult,\n // ── workspace git writes: stage/unstage answer with the FRESH status; commit/push\n // report a refusal as DATA (`ok:false` + `reason`), never as an error frame.\n 'workspace/gitstage': WorkspaceGitStageReq,\n 'workspace/gitstage/result': WorkspaceGitStatus,\n 'workspace/gitunstage': WorkspaceGitStageReq,\n 'workspace/gitunstage/result': WorkspaceGitStatus,\n 'workspace/gitcommit': WorkspaceGitCommitReq,\n 'workspace/gitcommit/result': WorkspaceGitCommitResult,\n 'workspace/gitpush': WorkspaceGitPushReq,\n 'workspace/gitpush/result': WorkspaceGitPushResult,\n // ── AI commit message: a bounded model pass on the DAEMON's runtime, no write of any kind.\n 'workspace/gitmessage': WorkspaceGitMessageReq,\n 'workspace/gitmessage/result': WorkspaceGitMessageResult,\n // ── background tasks: a read of the daemon's in-memory lease. No cancel frame — see task.ts.\n 'task/list': TaskListReq,\n 'task/list/result': TaskList,\n 'memory/channels': MemoryChannelsReq,\n 'memory/channels/page': MemoryChannelsPage,\n 'memory/list': MemoryListReq,\n 'memory/list/page': MemoryListPage,\n 'memory/read': MemoryReadReq,\n 'memory/read/content': MemoryReadContent,\n 'memory/write': MemoryWriteReq,\n 'memory/write/ok': MemoryWriteOk,\n 'memory/history': MemoryHistoryReq,\n 'memory/history/page': MemoryHistoryPage,\n 'memory/surface': MemorySurfaceReq,\n 'memory/surface/info': MemorySurfaceInfo,\n 'memory/record/search': MemoryRecordSearchReq,\n 'memory/record/search/page': MemoryRecordSearchPage,\n 'memory/record/list': MemoryRecordListReq,\n 'memory/record/list/page': MemoryRecordListPage,\n 'memory/record/get': MemoryRecordGetReq,\n 'memory/record/get/result': MemoryRecordGetResult,\n 'memory/record/create': MemoryRecordCreateReq,\n 'memory/record/create/result': MemoryRecordCreateResult,\n 'memory/record/update': MemoryRecordUpdateReq,\n 'memory/record/update/result': MemoryRecordUpdateResult,\n 'memory/record/delete': MemoryRecordDeleteReq,\n 'memory/record/delete/result': MemoryRecordDeleteResult,\n 'memory/record/history': MemoryRecordHistoryReq,\n 'memory/record/history/page': MemoryRecordHistoryPage,\n // ── memory dreaming (managed-store consolidation jobs; REPs carry DreamState) ──\n 'memory/dream/start': DreamStartReq,\n 'memory/dream/start/ok': DreamState,\n 'memory/dream/cancel': DreamCancelReq,\n 'memory/dream/cancel/ok': DreamState,\n 'memory/dream/list': DreamListReq,\n 'memory/dream/list/page': DreamListPage,\n 'memory/dream/get': DreamGetReq,\n 'memory/dream/get/result': DreamState,\n 'memory/dream/adopt': DreamAdoptReq,\n 'memory/dream/adopt/ok': DreamState,\n 'memory/dream/discard': DreamDiscardReq,\n 'memory/dream/discard/ok': DreamState,\n 'memory/dream/files': DreamFilesReq,\n 'memory/dream/files/page': DreamFilesPage,\n 'memory/dream/file/read': DreamFileReadReq,\n 'memory/dream/file/read/content': DreamFileReadContent,\n 'memory/dream/skill/read': DreamSkillReadReq,\n 'memory/dream/skill/read/ok': DreamSkillContent,\n 'memory/dream/skill/accept': DreamSkillReviewReq,\n 'memory/dream/skill/accept/ok': DreamState,\n 'memory/dream/skill/dismiss': DreamSkillReviewReq,\n 'memory/dream/skill/dismiss/ok': DreamState,\n 'skills/local': LocalSkillsReq,\n 'skills/local/list': LocalSkillsList,\n // ── organization knowledge + managed skills ──\n 'knowledge/search': KnowledgeSearchReq,\n 'knowledge/search/ok': KnowledgeSearchOk,\n 'knowledge/list': KnowledgeListReq,\n 'knowledge/list/ok': KnowledgeListOk,\n 'skills/org': OrgSkillsReq,\n 'skills/org/ok': OrgSkillsOk,\n 'knowledge/suggestions/sync': OrganizationSuggestionsSyncReq,\n 'knowledge/suggestions/sync/ok': OrganizationSuggestionsSyncOk,\n 'knowledge/suggestion/read': OrganizationSuggestionReadReq,\n 'knowledge/suggestion/content': OrganizationSuggestionChunk,\n 'knowledge/suggestion/review': OrganizationSuggestionReviewReq,\n 'managed-skill/read': ManagedSkillReadReq,\n 'managed-skill/chunk': ManagedSkillChunk,\n // ── fleet / config ──\n 'config/push': ConfigPush,\n 'daemon/bootstrap/result': DaemonBootstrapResult,\n 'daemon/restart': DaemonRestart,\n 'daemon/upgrade': DaemonUpgrade,\n // ── generic replies ──\n 'daemon/control/ack': DaemonControlAck,\n ack: Ack,\n // ── error ──\n error: ErrorFrame\n};\n/** All frame `type` strings, as a runtime array (used by guards / tests). */\nexport const FRAME_TYPES = Object.keys(FRAME_SCHEMAS);\n/**\n * Builds the envelope schema for one frame `type` with a `type` literal and the\n * typed payload, so the discriminated union infers `payload` precisely.\n *\n * Kept as a local generic (payload pinned to `FRAME_SCHEMAS[T]`) so a\n * mispaired member — `frame('auth', FRAME_SCHEMAS['register'])` — is a compile\n * error; a bare `frameSchema` alias would accept it. The body is deliberately\n * inlined rather than delegated: `return frameSchema(type, payload)` under\n * THIS generic signature collapses every union member's `payload` to `unknown`\n * (113 × TS18046 under TS 6.0.3 / zod 4.4.3 — reproducible by making exactly\n * that substitution), while the small relay unions call `frameSchema` with\n * concrete schemas and infer fine.\n */\nfunction frame(type, payload) {\n return z.object({\n v: z.literal(1),\n id: z.string().uuid(),\n ts: z.string().datetime(),\n type: z.literal(type),\n corr: z.string().uuid().optional(),\n orgId: z.string().min(1).max(64).optional(),\n payload\n });\n}\n/**\n * `AnyFrame` — the discriminated union over `type` of every fully-validated\n * frame (envelope + typed payload). This is the runtime guard at the socket\n * edge and the precise inferred type the handlers switch on.\n */\nexport const AnyFrame = z.discriminatedUnion('type', [\n frame('auth', FRAME_SCHEMAS['auth']),\n frame('auth/ok', FRAME_SCHEMAS['auth/ok']),\n frame('register', FRAME_SCHEMAS['register']),\n frame('register/ok', FRAME_SCHEMAS['register/ok']),\n frame('capabilities/update', FRAME_SCHEMAS['capabilities/update']),\n frame('relay/roster', FRAME_SCHEMAS['relay/roster']),\n frame('collaboration/routes', FRAME_SCHEMAS['collaboration/routes']),\n frame('heartbeat', FRAME_SCHEMAS['heartbeat']),\n frame('duty/grant', FRAME_SCHEMAS['duty/grant']),\n frame('duty/renewed', FRAME_SCHEMAS['duty/renewed']),\n frame('duty/revoke', FRAME_SCHEMAS['duty/revoke']),\n frame('duty/release', FRAME_SCHEMAS['duty/release']),\n frame('duty/claim', FRAME_SCHEMAS['duty/claim']),\n frame('duty/claim/ok', FRAME_SCHEMAS['duty/claim/ok']),\n frame('duty/fetch', FRAME_SCHEMAS['duty/fetch']),\n frame('duty/fetch/ok', FRAME_SCHEMAS['duty/fetch/ok']),\n frame('agent/launch', FRAME_SCHEMAS['agent/launch']),\n frame('agent/launched', FRAME_SCHEMAS['agent/launched']),\n frame('agent/stop', FRAME_SCHEMAS['agent/stop']),\n frame('agent/upsert', FRAME_SCHEMAS['agent/upsert']),\n frame('agent/remove', FRAME_SCHEMAS['agent/remove']),\n frame('agent/detach', FRAME_SCHEMAS['agent/detach']),\n frame('agent/activate', FRAME_SCHEMAS['agent/activate']),\n frame('agent/activity', FRAME_SCHEMAS['agent/activity']),\n frame('agent/scope-denied', FRAME_SCHEMAS['agent/scope-denied']),\n frame('agent/permission-requests', FRAME_SCHEMAS['agent/permission-requests']),\n frame('agent/permission-requests/page', FRAME_SCHEMAS['agent/permission-requests/page']),\n frame('agent/permission-decision', FRAME_SCHEMAS['agent/permission-decision']),\n // ── routing and daemon control ──\n frame('route/assign', FRAME_SCHEMAS['route/assign']),\n frame('route/assign/ack', FRAME_SCHEMAS['route/assign/ack']),\n frame('route/update', FRAME_SCHEMAS['route/update']),\n frame('daemon/drain', FRAME_SCHEMAS['daemon/drain']),\n frame('drain/progress', FRAME_SCHEMAS['drain/progress']),\n frame('drain/done', FRAME_SCHEMAS['drain/done']),\n frame('cron/upsert', FRAME_SCHEMAS['cron/upsert']),\n frame('cron/remove', FRAME_SCHEMAS['cron/remove']),\n frame('cron/report', FRAME_SCHEMAS['cron/report']),\n frame('cron/run', FRAME_SCHEMAS['cron/run']),\n frame('hook/report', FRAME_SCHEMAS['hook/report']),\n frame('hook/start', FRAME_SCHEMAS['hook/start']),\n frame('hook/start/ok', FRAME_SCHEMAS['hook/start/ok']),\n frame('github/review-authorize', FRAME_SCHEMAS['github/review-authorize']),\n frame('github/review-authorized', FRAME_SCHEMAS['github/review-authorized']),\n frame('github/review-result', FRAME_SCHEMAS['github/review-result']),\n frame('github/review-result/ok', FRAME_SCHEMAS['github/review-result/ok']),\n frame('integration/upsert', FRAME_SCHEMAS['integration/upsert']),\n frame('integration/remove', FRAME_SCHEMAS['integration/remove']),\n frame('integration/channels', FRAME_SCHEMAS['integration/channels']),\n frame('integration/forget', FRAME_SCHEMAS['integration/forget']),\n frame('integration/leave', FRAME_SCHEMAS['integration/leave']),\n frame('integration/leave/ok', FRAME_SCHEMAS['integration/leave/ok']),\n frame('mcpserver/upsert', FRAME_SCHEMAS['mcpserver/upsert']),\n frame('mcpserver/remove', FRAME_SCHEMAS['mcpserver/remove']),\n frame('memoryconnection/upsert', FRAME_SCHEMAS['memoryconnection/upsert']),\n frame('memoryconnection/remove', FRAME_SCHEMAS['memoryconnection/remove']),\n frame('gitcred/request', FRAME_SCHEMAS['gitcred/request']),\n frame('gitcred/grant', FRAME_SCHEMAS['gitcred/grant']),\n frame('secrets/request', FRAME_SCHEMAS['secrets/request']),\n frame('secrets/grant', FRAME_SCHEMAS['secrets/grant']),\n frame('secrets/renew', FRAME_SCHEMAS['secrets/renew']),\n frame('secrets/revoke', FRAME_SCHEMAS['secrets/revoke']),\n frame('scope-attestation', FRAME_SCHEMAS['scope-attestation']),\n frame('webchat/mcp-grant/issue', FRAME_SCHEMAS['webchat/mcp-grant/issue']),\n frame('webchat/mcp-grant/issued', FRAME_SCHEMAS['webchat/mcp-grant/issued']),\n frame('webchat/mcp-grant/accept', FRAME_SCHEMAS['webchat/mcp-grant/accept']),\n frame('webchat/mcp-grant/activate', FRAME_SCHEMAS['webchat/mcp-grant/activate']),\n frame('webchat/mcp-grant/revoke', FRAME_SCHEMAS['webchat/mcp-grant/revoke']),\n frame('webchat/mcp-grant/revoked', FRAME_SCHEMAS['webchat/mcp-grant/revoked']),\n frame('event/session', FRAME_SCHEMAS['event/session']),\n frame('event/session-sync', FRAME_SCHEMAS['event/session-sync']),\n frame('event/session-activity', FRAME_SCHEMAS['event/session-activity']),\n frame('event/session-purged', FRAME_SCHEMAS['event/session-purged']),\n frame('usage/report', FRAME_SCHEMAS['usage/report']),\n frame('facts/runtime-profile', FRAME_SCHEMAS['facts/runtime-profile']),\n frame('facts/daemon-runtimes', FRAME_SCHEMAS['facts/daemon-runtimes']),\n frame('facts/memory-connections', FRAME_SCHEMAS['facts/memory-connections']),\n frame('session/list', FRAME_SCHEMAS['session/list']),\n frame('session/list/page', FRAME_SCHEMAS['session/list/page']),\n frame('session/history', FRAME_SCHEMAS['session/history']),\n frame('session/history/page', FRAME_SCHEMAS['session/history/page']),\n frame('session/tool-body', FRAME_SCHEMAS['session/tool-body']),\n frame('session/tool-body/chunk', FRAME_SCHEMAS['session/tool-body/chunk']),\n frame('session/child-status', FRAME_SCHEMAS['session/child-status']),\n frame('session/child-status/ok', FRAME_SCHEMAS['session/child-status/ok']),\n frame('session/child-status/probe', FRAME_SCHEMAS['session/child-status/probe']),\n frame('session/child-status/probe/ok', FRAME_SCHEMAS['session/child-status/probe/ok']),\n frame('session/visibility', FRAME_SCHEMAS['session/visibility']),\n frame('session/visibility/ok', FRAME_SCHEMAS['session/visibility/ok']),\n frame('session/visibility/snapshot', FRAME_SCHEMAS['session/visibility/snapshot']),\n frame('channel/agents', FRAME_SCHEMAS['channel/agents']),\n frame('channel/agents/ok', FRAME_SCHEMAS['channel/agents/ok']),\n frame('workspace/list', FRAME_SCHEMAS['workspace/list']),\n frame('workspace/list/page', FRAME_SCHEMAS['workspace/list/page']),\n frame('workspace/read', FRAME_SCHEMAS['workspace/read']),\n frame('workspace/read/content', FRAME_SCHEMAS['workspace/read/content']),\n frame('workspace/write', FRAME_SCHEMAS['workspace/write']),\n frame('workspace/write/ok', FRAME_SCHEMAS['workspace/write/ok']),\n frame('workspace/delete', FRAME_SCHEMAS['workspace/delete']),\n frame('workspace/delete/ok', FRAME_SCHEMAS['workspace/delete/ok']),\n frame('workspace/gitstatus', FRAME_SCHEMAS['workspace/gitstatus']),\n frame('workspace/gitstatus/result', FRAME_SCHEMAS['workspace/gitstatus/result']),\n frame('workspace/gitdiff', FRAME_SCHEMAS['workspace/gitdiff']),\n frame('workspace/gitdiff/result', FRAME_SCHEMAS['workspace/gitdiff/result']),\n frame('workspace/gitlog', FRAME_SCHEMAS['workspace/gitlog']),\n frame('workspace/gitlog/result', FRAME_SCHEMAS['workspace/gitlog/result']),\n frame('workspace/gitpull', FRAME_SCHEMAS['workspace/gitpull']),\n frame('workspace/gitpull/result', FRAME_SCHEMAS['workspace/gitpull/result']),\n frame('workspace/gitstage', FRAME_SCHEMAS['workspace/gitstage']),\n frame('workspace/gitstage/result', FRAME_SCHEMAS['workspace/gitstage/result']),\n frame('workspace/gitunstage', FRAME_SCHEMAS['workspace/gitunstage']),\n frame('workspace/gitunstage/result', FRAME_SCHEMAS['workspace/gitunstage/result']),\n frame('workspace/gitcommit', FRAME_SCHEMAS['workspace/gitcommit']),\n frame('workspace/gitcommit/result', FRAME_SCHEMAS['workspace/gitcommit/result']),\n frame('workspace/gitpush', FRAME_SCHEMAS['workspace/gitpush']),\n frame('workspace/gitpush/result', FRAME_SCHEMAS['workspace/gitpush/result']),\n frame('workspace/gitmessage', FRAME_SCHEMAS['workspace/gitmessage']),\n frame('workspace/gitmessage/result', FRAME_SCHEMAS['workspace/gitmessage/result']),\n frame('task/list', FRAME_SCHEMAS['task/list']),\n frame('task/list/result', FRAME_SCHEMAS['task/list/result']),\n frame('memory/channels', FRAME_SCHEMAS['memory/channels']),\n frame('memory/channels/page', FRAME_SCHEMAS['memory/channels/page']),\n frame('memory/list', FRAME_SCHEMAS['memory/list']),\n frame('memory/list/page', FRAME_SCHEMAS['memory/list/page']),\n frame('memory/read', FRAME_SCHEMAS['memory/read']),\n frame('memory/read/content', FRAME_SCHEMAS['memory/read/content']),\n frame('memory/write', FRAME_SCHEMAS['memory/write']),\n frame('memory/write/ok', FRAME_SCHEMAS['memory/write/ok']),\n frame('memory/history', FRAME_SCHEMAS['memory/history']),\n frame('memory/history/page', FRAME_SCHEMAS['memory/history/page']),\n frame('memory/surface', FRAME_SCHEMAS['memory/surface']),\n frame('memory/surface/info', FRAME_SCHEMAS['memory/surface/info']),\n frame('memory/record/search', FRAME_SCHEMAS['memory/record/search']),\n frame('memory/record/search/page', FRAME_SCHEMAS['memory/record/search/page']),\n frame('memory/record/list', FRAME_SCHEMAS['memory/record/list']),\n frame('memory/record/list/page', FRAME_SCHEMAS['memory/record/list/page']),\n frame('memory/record/get', FRAME_SCHEMAS['memory/record/get']),\n frame('memory/record/get/result', FRAME_SCHEMAS['memory/record/get/result']),\n frame('memory/record/create', FRAME_SCHEMAS['memory/record/create']),\n frame('memory/record/create/result', FRAME_SCHEMAS['memory/record/create/result']),\n frame('memory/record/update', FRAME_SCHEMAS['memory/record/update']),\n frame('memory/record/update/result', FRAME_SCHEMAS['memory/record/update/result']),\n frame('memory/record/delete', FRAME_SCHEMAS['memory/record/delete']),\n frame('memory/record/delete/result', FRAME_SCHEMAS['memory/record/delete/result']),\n frame('memory/record/history', FRAME_SCHEMAS['memory/record/history']),\n frame('memory/record/history/page', FRAME_SCHEMAS['memory/record/history/page']),\n frame('memory/dream/start', FRAME_SCHEMAS['memory/dream/start']),\n frame('memory/dream/start/ok', FRAME_SCHEMAS['memory/dream/start/ok']),\n frame('memory/dream/cancel', FRAME_SCHEMAS['memory/dream/cancel']),\n frame('memory/dream/cancel/ok', FRAME_SCHEMAS['memory/dream/cancel/ok']),\n frame('memory/dream/list', FRAME_SCHEMAS['memory/dream/list']),\n frame('memory/dream/list/page', FRAME_SCHEMAS['memory/dream/list/page']),\n frame('memory/dream/get', FRAME_SCHEMAS['memory/dream/get']),\n frame('memory/dream/get/result', FRAME_SCHEMAS['memory/dream/get/result']),\n frame('memory/dream/adopt', FRAME_SCHEMAS['memory/dream/adopt']),\n frame('memory/dream/adopt/ok', FRAME_SCHEMAS['memory/dream/adopt/ok']),\n frame('memory/dream/discard', FRAME_SCHEMAS['memory/dream/discard']),\n frame('memory/dream/discard/ok', FRAME_SCHEMAS['memory/dream/discard/ok']),\n frame('memory/dream/files', FRAME_SCHEMAS['memory/dream/files']),\n frame('memory/dream/files/page', FRAME_SCHEMAS['memory/dream/files/page']),\n frame('memory/dream/file/read', FRAME_SCHEMAS['memory/dream/file/read']),\n frame('memory/dream/file/read/content', FRAME_SCHEMAS['memory/dream/file/read/content']),\n frame('memory/dream/skill/read', FRAME_SCHEMAS['memory/dream/skill/read']),\n frame('memory/dream/skill/read/ok', FRAME_SCHEMAS['memory/dream/skill/read/ok']),\n frame('memory/dream/skill/accept', FRAME_SCHEMAS['memory/dream/skill/accept']),\n frame('memory/dream/skill/accept/ok', FRAME_SCHEMAS['memory/dream/skill/accept/ok']),\n frame('memory/dream/skill/dismiss', FRAME_SCHEMAS['memory/dream/skill/dismiss']),\n frame('memory/dream/skill/dismiss/ok', FRAME_SCHEMAS['memory/dream/skill/dismiss/ok']),\n frame('skills/local', FRAME_SCHEMAS['skills/local']),\n frame('skills/local/list', FRAME_SCHEMAS['skills/local/list']),\n frame('knowledge/search', FRAME_SCHEMAS['knowledge/search']),\n frame('knowledge/list', FRAME_SCHEMAS['knowledge/list']),\n frame('knowledge/list/ok', FRAME_SCHEMAS['knowledge/list/ok']),\n frame('skills/org', FRAME_SCHEMAS['skills/org']),\n frame('skills/org/ok', FRAME_SCHEMAS['skills/org/ok']),\n frame('knowledge/search/ok', FRAME_SCHEMAS['knowledge/search/ok']),\n frame('knowledge/suggestions/sync', FRAME_SCHEMAS['knowledge/suggestions/sync']),\n frame('knowledge/suggestions/sync/ok', FRAME_SCHEMAS['knowledge/suggestions/sync/ok']),\n frame('knowledge/suggestion/read', FRAME_SCHEMAS['knowledge/suggestion/read']),\n frame('knowledge/suggestion/content', FRAME_SCHEMAS['knowledge/suggestion/content']),\n frame('knowledge/suggestion/review', FRAME_SCHEMAS['knowledge/suggestion/review']),\n frame('managed-skill/read', FRAME_SCHEMAS['managed-skill/read']),\n frame('managed-skill/chunk', FRAME_SCHEMAS['managed-skill/chunk']),\n frame('config/push', FRAME_SCHEMAS['config/push']),\n frame('daemon/bootstrap/result', FRAME_SCHEMAS['daemon/bootstrap/result']),\n frame('daemon/restart', FRAME_SCHEMAS['daemon/restart']),\n frame('daemon/upgrade', FRAME_SCHEMAS['daemon/upgrade']),\n frame('daemon/control/ack', FRAME_SCHEMAS['daemon/control/ack']),\n frame('ack', FRAME_SCHEMAS['ack']),\n frame('error', FRAME_SCHEMAS['error'])\n]);\n/** Runtime guard: is `t` a known frame `type`? */\nexport function isFrameType(t) {\n return Object.prototype.hasOwnProperty.call(FRAME_SCHEMAS, t);\n}\n//# sourceMappingURL=frame.js.map","import { randomUUID } from 'node:crypto';\nimport { Envelope, NIL_UUID } from './envelope.js';\n/**\n * Generic envelope codec — the schema-map-agnostic core shared by every wire.\n *\n * The daemon↔CP wire (`codec.ts` over `FRAME_SCHEMAS`) and the two relay wires\n * (`frames/relay-cp.ts` / `frames/relay-daemon.ts` over their OWN maps) all\n * decode the same envelope shape but accept disjoint frame families — a relay\n * socket must answer a daemon↔CP frame with `UNKNOWN_FRAME`, and vice versa\n * (shared-bot-relay.md §8 \"standalone frame union, not mixed into the daemon protocol\").\n */\n/** Soft cap per frame — 256 KiB (protocol §1). Over this → FRAME_TOO_LARGE. */\nexport const MAX_FRAME_BYTES = 256 * 1024;\nconst textEncoder = new TextEncoder();\nfunction byteLength(text) {\n return textEncoder.encode(text).length;\n}\nfunction extractControlExt(json) {\n if (typeof json !== 'object' || json === null)\n return undefined;\n const o = json;\n const ext = {};\n if (typeof o.epoch === 'number')\n ext.epoch = o.epoch;\n if (typeof o.agentId === 'string')\n ext.agentId = o.agentId;\n if (typeof o.launchId === 'string')\n ext.launchId = o.launchId;\n return Object.keys(ext).length > 0 ? ext : undefined;\n}\n/**\n * Decode one wire frame against `schemas` (the wire's `type` → payload map).\n * Two-step parse: envelope first, then the per-type payload schema — an unknown\n * `type` is a typed `UNKNOWN_FRAME` failure (a REP, never a hard close).\n */\nexport function decodeEnvelopeWith(schemas, text) {\n if (byteLength(text) > MAX_FRAME_BYTES) {\n return { ok: false, id: NIL_UUID, msg: 'FRAME_TOO_LARGE' };\n }\n let json;\n try {\n json = JSON.parse(text);\n }\n catch {\n return { ok: false, id: NIL_UUID, msg: 'invalid json' };\n }\n const env = Envelope.safeParse(json);\n if (!env.success) {\n const id = typeof json === 'object' && json !== null && typeof json.id === 'string'\n ? json.id\n : NIL_UUID;\n return { ok: false, id, msg: env.error.message };\n }\n const schema = Object.hasOwn(schemas, env.data.type) ? schemas[env.data.type] : undefined;\n if (!schema) {\n return {\n ok: false,\n id: env.data.id,\n msg: 'UNKNOWN_FRAME',\n ...(env.data.corr ? { corr: env.data.corr } : {})\n };\n }\n const payload = schema.safeParse(env.data.payload);\n if (!payload.success) {\n return {\n ok: false,\n id: env.data.id,\n msg: payload.error.message,\n ...(env.data.corr ? { corr: env.data.corr } : {})\n };\n }\n const ext = extractControlExt(json);\n return {\n ok: true,\n frame: { ...env.data, payload: payload.data },\n ...(ext ? { ext } : {})\n };\n}\n/**\n * Wrap a payload in the wire envelope. Untyped core — each wire exports a typed\n * wrapper (`buildEnvelope` / `buildRelayCpFrame` / `buildRelayDaemonFrame`) that\n * pins `type` to its own union and casts the result.\n */\nexport function buildEnvelopeRaw(type, payload, opts = {}) {\n return {\n v: 1,\n id: opts.id ?? randomUUID(),\n ts: opts.ts ?? new Date().toISOString(),\n type,\n payload,\n ...(opts.corr ? { corr: opts.corr } : {}),\n ...(opts.orgId ? { orgId: opts.orgId } : {}),\n ...(opts.ext ?? {})\n };\n}\n//# sourceMappingURL=wire.js.map","import { FRAME_SCHEMAS } from './index.js';\nimport { MAX_FRAME_BYTES, buildEnvelopeRaw, decodeEnvelopeWith } from './wire.js';\n/**\n * The daemon↔CP wire codec — the `FRAME_SCHEMAS` instantiation of the generic\n * envelope codec in `wire.ts`. The relay wires (`frames/relay-*.ts`) build their\n * own instantiations over their own schema maps; the unions never mix.\n */\nexport { MAX_FRAME_BYTES };\nexport function decodeEnvelope(text) {\n return decodeEnvelopeWith(FRAME_SCHEMAS, text);\n}\nexport function buildEnvelope(type, payload, opts = {}) {\n return buildEnvelopeRaw(type, payload, opts);\n}\nexport function encode(frame) {\n return JSON.stringify(frame);\n}\n//# sourceMappingURL=codec.js.map","export class SystemClock {\n now() {\n return Date.now();\n }\n setTimeout(fn, ms) {\n return globalThis.setTimeout(fn, ms);\n }\n clearTimeout(h) {\n globalThis.clearTimeout(h);\n }\n}\nexport const systemClock = new SystemClock();\n/**\n * A deterministic Clock for unit tests: `now` only advances via {@link advance},\n * which fires every timer whose deadline has passed (in deadline order). No real\n * timers arm, so tests never race the wall clock.\n */\nexport class FakeClock {\n t = 0;\n seq = 0;\n timers = new Map();\n constructor(startMs = 0) {\n this.t = startMs;\n }\n now() {\n return this.t;\n }\n setTimeout(fn, ms) {\n const id = ++this.seq;\n this.timers.set(id, { at: this.t + Math.max(0, ms), fn });\n return id;\n }\n clearTimeout(h) {\n this.timers.delete(h);\n }\n /** Advance time by `ms`, firing every timer that comes due, earliest first. */\n advance(ms) {\n const until = this.t + ms;\n for (;;) {\n let next;\n for (const [id, e] of this.timers) {\n if (e.at <= until && (!next || e.at < next.at))\n next = { id, at: e.at, fn: e.fn };\n }\n if (!next)\n break;\n this.timers.delete(next.id);\n this.t = next.at;\n next.fn();\n }\n this.t = until;\n }\n}\n//# sourceMappingURL=clock.js.map","/** Transport-free representation of a typed wire `error` REP. */\nexport class WireError extends Error {\n code;\n retryable;\n details;\n constructor(code, message, retryable = false, details) {\n super(message);\n this.name = 'WireError';\n this.code = code;\n this.retryable = retryable;\n if (details)\n this.details = details;\n }\n}\nexport class ReqRep {\n clock;\n ackTimeoutMs;\n maxTries;\n pending = new Map();\n constructor(clock, ackTimeoutMs, maxTries = 5) {\n this.clock = clock;\n this.ackTimeoutMs = ackTimeoutMs;\n this.maxTries = maxTries;\n }\n request(frame, write, opts = {}) {\n const encoded = JSON.stringify(frame);\n return new Promise((resolve, reject) => {\n const entry = {\n id: frame.id,\n encoded,\n resolve,\n reject,\n tries: 1,\n maxTries: opts.maxTries ?? this.maxTries\n };\n this.pending.set(frame.id, entry);\n this.arm(entry, write, opts.ackTimeoutMs ?? this.ackTimeoutMs);\n // A dead transport must reject THIS request — never throw into the caller\n // (or, on the timer path below, crash the process as an uncaught throw).\n try {\n write(encoded);\n }\n catch (e) {\n this.fail(entry, new WireError('INTERNAL', `send failed: ${e.message}`, true));\n }\n });\n }\n arm(entry, write, ackTimeoutMs) {\n entry.timer = this.clock.setTimeout(() => {\n if (!this.pending.has(entry.id))\n return;\n if (entry.tries >= entry.maxTries) {\n this.pending.delete(entry.id);\n entry.reject(new WireError('INTERNAL', `no ack after ${entry.maxTries} tries for ${entry.id}`, true));\n return;\n }\n entry.tries += 1;\n this.arm(entry, write, ackTimeoutMs);\n try {\n write(entry.encoded);\n }\n catch (e) {\n this.fail(entry, new WireError('INTERNAL', `send failed: ${e.message}`, true));\n }\n }, ackTimeoutMs);\n }\n fail(entry, err) {\n if (!this.pending.has(entry.id))\n return;\n this.pending.delete(entry.id);\n if (entry.timer !== undefined)\n this.clock.clearTimeout(entry.timer);\n entry.reject(err);\n }\n /**\n * Settle a pending REQ from an inbound correlated frame. Returns true when\n * `frame.corr` matched a pending REQ (a REP resolves it; an `error` frame\n * rejects with a {@link WireError}), false when it correlates nothing.\n */\n settle(frame) {\n const corr = frame.corr;\n if (!corr)\n return false;\n if (frame.type === 'error') {\n const e = frame.payload;\n return this.reject(corr, new WireError(e.code, e.message, e.retryable, e.details));\n }\n const entry = this.pending.get(corr);\n if (!entry)\n return false;\n this.pending.delete(corr);\n if (entry.timer !== undefined)\n this.clock.clearTimeout(entry.timer);\n entry.resolve(frame);\n return true;\n }\n /** Reject one pending request by correlation id (e.g. a REP whose envelope is\n * valid but whose payload cannot be decoded). Returns false when nothing matches. */\n reject(corr, err) {\n const entry = this.pending.get(corr);\n if (!entry)\n return false;\n this.pending.delete(corr);\n if (entry.timer !== undefined)\n this.clock.clearTimeout(entry.timer);\n entry.reject(err);\n return true;\n }\n inflight() {\n return this.pending.size;\n }\n rejectAll(err) {\n for (const entry of this.pending.values()) {\n if (entry.timer !== undefined)\n this.clock.clearTimeout(entry.timer);\n entry.reject(err);\n }\n this.pending.clear();\n }\n}\n//# sourceMappingURL=correlator.js.map","'use strict';\n\nconst BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];\nconst hasBlob = typeof Blob !== 'undefined';\n\nif (hasBlob) BINARY_TYPES.push('blob');\n\nmodule.exports = {\n BINARY_TYPES,\n CLOSE_TIMEOUT: 30000,\n EMPTY_BUFFER: Buffer.alloc(0),\n GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',\n hasBlob,\n kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),\n kListener: Symbol('kListener'),\n kStatusCode: Symbol('status-code'),\n kWebSocket: Symbol('websocket'),\n NOOP: () => {}\n};\n","'use strict';\n\nconst { EMPTY_BUFFER } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\n\n/**\n * Merges an array of buffers into a new buffer.\n *\n * @param {Buffer[]} list The array of buffers to concat\n * @param {Number} totalLength The total length of buffers in the list\n * @return {Buffer} The resulting buffer\n * @public\n */\nfunction concat(list, totalLength) {\n if (list.length === 0) return EMPTY_BUFFER;\n if (list.length === 1) return list[0];\n\n const target = Buffer.allocUnsafe(totalLength);\n let offset = 0;\n\n for (let i = 0; i < list.length; i++) {\n const buf = list[i];\n target.set(buf, offset);\n offset += buf.length;\n }\n\n if (offset < totalLength) {\n return new FastBuffer(target.buffer, target.byteOffset, offset);\n }\n\n return target;\n}\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nfunction _mask(source, mask, output, offset, length) {\n for (let i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n}\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nfunction _unmask(buffer, mask) {\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n}\n\n/**\n * Converts a buffer to an `ArrayBuffer`.\n *\n * @param {Buffer} buf The buffer to convert\n * @return {ArrayBuffer} Converted buffer\n * @public\n */\nfunction toArrayBuffer(buf) {\n if (buf.length === buf.buffer.byteLength) {\n return buf.buffer;\n }\n\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);\n}\n\n/**\n * Converts `data` to a `Buffer`.\n *\n * @param {*} data The data to convert\n * @return {Buffer} The buffer\n * @throws {TypeError}\n * @public\n */\nfunction toBuffer(data) {\n toBuffer.readOnly = true;\n\n if (Buffer.isBuffer(data)) return data;\n\n let buf;\n\n if (data instanceof ArrayBuffer) {\n buf = new FastBuffer(data);\n } else if (ArrayBuffer.isView(data)) {\n buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);\n } else {\n buf = Buffer.from(data);\n toBuffer.readOnly = false;\n }\n\n return buf;\n}\n\nmodule.exports = {\n concat,\n mask: _mask,\n toArrayBuffer,\n toBuffer,\n unmask: _unmask\n};\n\n/* istanbul ignore else */\nif (!process.env.WS_NO_BUFFER_UTIL) {\n try {\n const bufferUtil = require('bufferutil');\n\n module.exports.mask = function (source, mask, output, offset, length) {\n if (length < 48) _mask(source, mask, output, offset, length);\n else bufferUtil.mask(source, mask, output, offset, length);\n };\n\n module.exports.unmask = function (buffer, mask) {\n if (buffer.length < 32) _unmask(buffer, mask);\n else bufferUtil.unmask(buffer, mask);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst kDone = Symbol('kDone');\nconst kRun = Symbol('kRun');\n\n/**\n * A very simple job queue with adjustable concurrency. Adapted from\n * https://github.com/STRML/async-limiter\n */\nclass Limiter {\n /**\n * Creates a new `Limiter`.\n *\n * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed\n * to run concurrently\n */\n constructor(concurrency) {\n this[kDone] = () => {\n this.pending--;\n this[kRun]();\n };\n this.concurrency = concurrency || Infinity;\n this.jobs = [];\n this.pending = 0;\n }\n\n /**\n * Adds a job to the queue.\n *\n * @param {Function} job The job to run\n * @public\n */\n add(job) {\n this.jobs.push(job);\n this[kRun]();\n }\n\n /**\n * Removes a job from the queue and runs it if possible.\n *\n * @private\n */\n [kRun]() {\n if (this.pending === this.concurrency) return;\n\n if (this.jobs.length) {\n const job = this.jobs.shift();\n\n this.pending++;\n job(this[kDone]);\n }\n }\n}\n\nmodule.exports = Limiter;\n","'use strict';\n\nconst zlib = require('zlib');\n\nconst bufferUtil = require('./buffer-util');\nconst Limiter = require('./limiter');\nconst { kStatusCode } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);\nconst kPerMessageDeflate = Symbol('permessage-deflate');\nconst kTotalLength = Symbol('total-length');\nconst kCallback = Symbol('callback');\nconst kBuffers = Symbol('buffers');\nconst kError = Symbol('error');\n\n//\n// We limit zlib concurrency, which prevents severe memory fragmentation\n// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913\n// and https://github.com/websockets/ws/issues/1202\n//\n// Intentionally global; it's the global thread pool that's an issue.\n//\nlet zlibLimiter;\n\n/**\n * permessage-deflate implementation.\n */\nclass PerMessageDeflate {\n /**\n * Creates a PerMessageDeflate instance.\n *\n * @param {Object} [options] Configuration options\n * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support\n * for, or request, a custom client window size\n * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/\n * acknowledge disabling of client context takeover\n * @param {Number} [options.concurrencyLimit=10] The number of concurrent\n * calls to zlib\n * @param {Boolean} [options.isServer=false] Create the instance in either\n * server or client mode\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the\n * use of a custom server window size\n * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept\n * disabling of server context takeover\n * @param {Number} [options.threshold=1024] Size (in bytes) below which\n * messages should not be compressed if context takeover is disabled\n * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on\n * deflate\n * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on\n * inflate\n */\n constructor(options) {\n this._options = options || {};\n this._threshold =\n this._options.threshold !== undefined ? this._options.threshold : 1024;\n this._maxPayload = this._options.maxPayload | 0;\n this._isServer = !!this._options.isServer;\n this._deflate = null;\n this._inflate = null;\n\n this.params = null;\n\n if (!zlibLimiter) {\n const concurrency =\n this._options.concurrencyLimit !== undefined\n ? this._options.concurrencyLimit\n : 10;\n zlibLimiter = new Limiter(concurrency);\n }\n }\n\n /**\n * @type {String}\n */\n static get extensionName() {\n return 'permessage-deflate';\n }\n\n /**\n * Create an extension negotiation offer.\n *\n * @return {Object} Extension parameters\n * @public\n */\n offer() {\n const params = {};\n\n if (this._options.serverNoContextTakeover) {\n params.server_no_context_takeover = true;\n }\n if (this._options.clientNoContextTakeover) {\n params.client_no_context_takeover = true;\n }\n if (this._options.serverMaxWindowBits) {\n params.server_max_window_bits = this._options.serverMaxWindowBits;\n }\n if (this._options.clientMaxWindowBits) {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n } else if (this._options.clientMaxWindowBits == null) {\n params.client_max_window_bits = true;\n }\n\n return params;\n }\n\n /**\n * Accept an extension negotiation offer/response.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Object} Accepted configuration\n * @public\n */\n accept(configurations) {\n configurations = this.normalizeParams(configurations);\n\n this.params = this._isServer\n ? this.acceptAsServer(configurations)\n : this.acceptAsClient(configurations);\n\n return this.params;\n }\n\n /**\n * Releases all resources used by the extension.\n *\n * @public\n */\n cleanup() {\n if (this._inflate) {\n this._inflate.close();\n this._inflate = null;\n }\n\n if (this._deflate) {\n const callback = this._deflate[kCallback];\n\n this._deflate.close();\n this._deflate = null;\n\n if (callback) {\n callback(\n new Error(\n 'The deflate stream was closed while data was being processed'\n )\n );\n }\n }\n }\n\n /**\n * Accept an extension negotiation offer.\n *\n * @param {Array} offers The extension negotiation offers\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsServer(offers) {\n const opts = this._options;\n const accepted = offers.find((params) => {\n if (\n (opts.serverNoContextTakeover === false &&\n params.server_no_context_takeover) ||\n (params.server_max_window_bits &&\n (opts.serverMaxWindowBits === false ||\n (typeof opts.serverMaxWindowBits === 'number' &&\n opts.serverMaxWindowBits > params.server_max_window_bits))) ||\n (typeof opts.clientMaxWindowBits === 'number' &&\n !params.client_max_window_bits)\n ) {\n return false;\n }\n\n return true;\n });\n\n if (!accepted) {\n throw new Error('None of the extension offers can be accepted');\n }\n\n if (opts.serverNoContextTakeover) {\n accepted.server_no_context_takeover = true;\n }\n if (opts.clientNoContextTakeover) {\n accepted.client_no_context_takeover = true;\n }\n if (typeof opts.serverMaxWindowBits === 'number') {\n accepted.server_max_window_bits = opts.serverMaxWindowBits;\n }\n if (typeof opts.clientMaxWindowBits === 'number') {\n accepted.client_max_window_bits = opts.clientMaxWindowBits;\n } else if (\n accepted.client_max_window_bits === true ||\n opts.clientMaxWindowBits === false\n ) {\n delete accepted.client_max_window_bits;\n }\n\n return accepted;\n }\n\n /**\n * Accept the extension negotiation response.\n *\n * @param {Array} response The extension negotiation response\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsClient(response) {\n const params = response[0];\n\n if (\n this._options.clientNoContextTakeover === false &&\n params.client_no_context_takeover\n ) {\n throw new Error('Unexpected parameter \"client_no_context_takeover\"');\n }\n\n if (!params.client_max_window_bits) {\n if (typeof this._options.clientMaxWindowBits === 'number') {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n }\n } else if (\n this._options.clientMaxWindowBits === false ||\n (typeof this._options.clientMaxWindowBits === 'number' &&\n params.client_max_window_bits > this._options.clientMaxWindowBits)\n ) {\n throw new Error(\n 'Unexpected or invalid parameter \"client_max_window_bits\"'\n );\n }\n\n return params;\n }\n\n /**\n * Normalize parameters.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Array} The offers/response with normalized parameters\n * @private\n */\n normalizeParams(configurations) {\n configurations.forEach((params) => {\n Object.keys(params).forEach((key) => {\n let value = params[key];\n\n if (value.length > 1) {\n throw new Error(`Parameter \"${key}\" must have only a single value`);\n }\n\n value = value[0];\n\n if (key === 'client_max_window_bits') {\n if (value !== true) {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (!this._isServer) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else if (key === 'server_max_window_bits') {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (\n key === 'client_no_context_takeover' ||\n key === 'server_no_context_takeover'\n ) {\n if (value !== true) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else {\n throw new Error(`Unknown parameter \"${key}\"`);\n }\n\n params[key] = value;\n });\n });\n\n return configurations;\n }\n\n /**\n * Decompress data. Concurrency limited.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n decompress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._decompress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Compress data. Concurrency limited.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n compress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._compress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Decompress data.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _decompress(data, fin, callback) {\n const endpoint = this._isServer ? 'client' : 'server';\n\n if (!this._inflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._inflate = zlib.createInflateRaw({\n ...this._options.zlibInflateOptions,\n windowBits\n });\n this._inflate[kPerMessageDeflate] = this;\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n this._inflate.on('error', inflateOnError);\n this._inflate.on('data', inflateOnData);\n }\n\n this._inflate[kCallback] = callback;\n\n this._inflate.write(data);\n if (fin) this._inflate.write(TRAILER);\n\n this._inflate.flush(() => {\n const err = this._inflate[kError];\n\n if (err) {\n this._inflate.close();\n this._inflate = null;\n callback(err);\n return;\n }\n\n const data = bufferUtil.concat(\n this._inflate[kBuffers],\n this._inflate[kTotalLength]\n );\n\n if (this._inflate._readableState.endEmitted) {\n this._inflate.close();\n this._inflate = null;\n } else {\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._inflate.reset();\n }\n }\n\n callback(null, data);\n });\n }\n\n /**\n * Compress data.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _compress(data, fin, callback) {\n const endpoint = this._isServer ? 'server' : 'client';\n\n if (!this._deflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._deflate = zlib.createDeflateRaw({\n ...this._options.zlibDeflateOptions,\n windowBits\n });\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n this._deflate.on('data', deflateOnData);\n }\n\n this._deflate[kCallback] = callback;\n\n this._deflate.write(data);\n this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {\n if (!this._deflate) {\n //\n // The deflate stream was closed while data was being processed.\n //\n return;\n }\n\n let data = bufferUtil.concat(\n this._deflate[kBuffers],\n this._deflate[kTotalLength]\n );\n\n if (fin) {\n data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);\n }\n\n //\n // Ensure that the callback will not be called again in\n // `PerMessageDeflate#cleanup()`.\n //\n this._deflate[kCallback] = null;\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._deflate.reset();\n }\n\n callback(null, data);\n });\n }\n}\n\nmodule.exports = PerMessageDeflate;\n\n/**\n * The listener of the `zlib.DeflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction deflateOnData(chunk) {\n this[kBuffers].push(chunk);\n this[kTotalLength] += chunk.length;\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction inflateOnData(chunk) {\n this[kTotalLength] += chunk.length;\n\n if (\n this[kPerMessageDeflate]._maxPayload < 1 ||\n this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload\n ) {\n this[kBuffers].push(chunk);\n return;\n }\n\n this[kError] = new RangeError('Max payload size exceeded');\n this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';\n this[kError][kStatusCode] = 1009;\n this.removeListener('data', inflateOnData);\n\n //\n // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the\n // fact that in Node.js versions prior to 13.10.0, the callback for\n // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing\n // `zlib.reset()` ensures that either the callback is invoked or an error is\n // emitted.\n //\n this.reset();\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'error'` event.\n *\n * @param {Error} err The emitted error\n * @private\n */\nfunction inflateOnError(err) {\n //\n // There is no need to call `Zlib#close()` as the handle is automatically\n // closed when an error is emitted.\n //\n this[kPerMessageDeflate]._inflate = null;\n\n if (this[kError]) {\n this[kCallback](this[kError]);\n return;\n }\n\n err[kStatusCode] = 1007;\n this[kCallback](err);\n}\n","'use strict';\n\nconst { isUtf8 } = require('buffer');\n\nconst { hasBlob } = require('./constants');\n\n//\n// Allowed token characters:\n//\n// '!', '#', '$', '%', '&', ''', '*', '+', '-',\n// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'\n//\n// tokenChars[32] === 0 // ' '\n// tokenChars[33] === 1 // '!'\n// tokenChars[34] === 0 // '\"'\n// ...\n//\n// prettier-ignore\nconst tokenChars = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31\n 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127\n];\n\n/**\n * Checks if a status code is allowed in a close frame.\n *\n * @param {Number} code The status code\n * @return {Boolean} `true` if the status code is valid, else `false`\n * @public\n */\nfunction isValidStatusCode(code) {\n return (\n (code >= 1000 &&\n code <= 1014 &&\n code !== 1004 &&\n code !== 1005 &&\n code !== 1006) ||\n (code >= 3000 && code <= 4999)\n );\n}\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction _isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0) {\n // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) {\n // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // Overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) {\n // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong\n (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) {\n // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong\n (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||\n buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Determines whether a value is a `Blob`.\n *\n * @param {*} value The value to be tested\n * @return {Boolean} `true` if `value` is a `Blob`, else `false`\n * @private\n */\nfunction isBlob(value) {\n return (\n hasBlob &&\n typeof value === 'object' &&\n typeof value.arrayBuffer === 'function' &&\n typeof value.type === 'string' &&\n typeof value.stream === 'function' &&\n (value[Symbol.toStringTag] === 'Blob' ||\n value[Symbol.toStringTag] === 'File')\n );\n}\n\nmodule.exports = {\n isBlob,\n isValidStatusCode,\n isValidUTF8: _isValidUTF8,\n tokenChars\n};\n\nif (isUtf8) {\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);\n };\n} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {\n try {\n const isValidUTF8 = require('utf-8-validate');\n\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst { Writable } = require('stream');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n kStatusCode,\n kWebSocket\n} = require('./constants');\nconst { concat, toArrayBuffer, unmask } = require('./buffer-util');\nconst { isValidStatusCode, isValidUTF8 } = require('./validation');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst GET_INFO = 0;\nconst GET_PAYLOAD_LENGTH_16 = 1;\nconst GET_PAYLOAD_LENGTH_64 = 2;\nconst GET_MASK = 3;\nconst GET_DATA = 4;\nconst INFLATING = 5;\nconst DEFER_EVENT = 6;\n\n/**\n * HyBi Receiver implementation.\n *\n * @extends Writable\n */\nclass Receiver extends Writable {\n /**\n * Creates a Receiver instance.\n *\n * @param {Object} [options] Options object\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {String} [options.binaryType=nodebuffer] The type for binary data\n * @param {Object} [options.extensions] An object containing the negotiated\n * extensions\n * @param {Boolean} [options.isServer=false] Specifies whether to operate in\n * client or server mode\n * @param {Number} [options.maxBufferedChunks=0] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=0] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n */\n constructor(options = {}) {\n super();\n\n this._allowSynchronousEvents =\n options.allowSynchronousEvents !== undefined\n ? options.allowSynchronousEvents\n : true;\n this._binaryType = options.binaryType || BINARY_TYPES[0];\n this._extensions = options.extensions || {};\n this._isServer = !!options.isServer;\n this._maxBufferedChunks = options.maxBufferedChunks | 0;\n this._maxFragments = options.maxFragments | 0;\n this._maxPayload = options.maxPayload | 0;\n this._skipUTF8Validation = !!options.skipUTF8Validation;\n this[kWebSocket] = undefined;\n\n this._bufferedBytes = 0;\n this._buffers = [];\n\n this._compressed = false;\n this._payloadLength = 0;\n this._mask = undefined;\n this._fragmented = 0;\n this._masked = false;\n this._fin = false;\n this._opcode = 0;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._numFragments = 0;\n this._fragments = [];\n\n this._errored = false;\n this._loop = false;\n this._state = GET_INFO;\n }\n\n /**\n * Implements `Writable.prototype._write()`.\n *\n * @param {Buffer} chunk The chunk of data to write\n * @param {String} encoding The character encoding of `chunk`\n * @param {Function} cb Callback\n * @private\n */\n _write(chunk, encoding, cb) {\n if (this._opcode === 0x08 && this._state == GET_INFO) return cb();\n\n if (\n this._maxBufferedChunks > 0 &&\n this._buffers.length >= this._maxBufferedChunks\n ) {\n cb(\n this.createError(\n RangeError,\n 'Too many buffered chunks',\n false,\n 1008,\n 'WS_ERR_TOO_MANY_BUFFERED_PARTS'\n )\n );\n return;\n }\n\n this._bufferedBytes += chunk.length;\n this._buffers.push(chunk);\n this.startLoop(cb);\n }\n\n /**\n * Consumes `n` bytes from the buffered data.\n *\n * @param {Number} n The number of bytes to consume\n * @return {Buffer} The consumed bytes\n * @private\n */\n consume(n) {\n this._bufferedBytes -= n;\n\n if (n === this._buffers[0].length) return this._buffers.shift();\n\n if (n < this._buffers[0].length) {\n const buf = this._buffers[0];\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n\n return new FastBuffer(buf.buffer, buf.byteOffset, n);\n }\n\n const dst = Buffer.allocUnsafe(n);\n\n do {\n const buf = this._buffers[0];\n const offset = dst.length - n;\n\n if (n >= buf.length) {\n dst.set(this._buffers.shift(), offset);\n } else {\n dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n }\n\n n -= buf.length;\n } while (n > 0);\n\n return dst;\n }\n\n /**\n * Starts the parsing loop.\n *\n * @param {Function} cb Callback\n * @private\n */\n startLoop(cb) {\n this._loop = true;\n\n do {\n switch (this._state) {\n case GET_INFO:\n this.getInfo(cb);\n break;\n case GET_PAYLOAD_LENGTH_16:\n this.getPayloadLength16(cb);\n break;\n case GET_PAYLOAD_LENGTH_64:\n this.getPayloadLength64(cb);\n break;\n case GET_MASK:\n this.getMask();\n break;\n case GET_DATA:\n this.getData(cb);\n break;\n case INFLATING:\n case DEFER_EVENT:\n this._loop = false;\n return;\n }\n } while (this._loop);\n\n if (!this._errored) cb();\n }\n\n /**\n * Reads the first two bytes of a frame.\n *\n * @param {Function} cb Callback\n * @private\n */\n getInfo(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(2);\n\n if ((buf[0] & 0x30) !== 0x00) {\n const error = this.createError(\n RangeError,\n 'RSV2 and RSV3 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_2_3'\n );\n\n cb(error);\n return;\n }\n\n const compressed = (buf[0] & 0x40) === 0x40;\n\n if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n this._fin = (buf[0] & 0x80) === 0x80;\n this._opcode = buf[0] & 0x0f;\n this._payloadLength = buf[1] & 0x7f;\n\n if (this._opcode === 0x00) {\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fragmented) {\n const error = this.createError(\n RangeError,\n 'invalid opcode 0',\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._opcode = this._fragmented;\n } else if (this._opcode === 0x01 || this._opcode === 0x02) {\n if (this._fragmented) {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._compressed = compressed;\n } else if (this._opcode > 0x07 && this._opcode < 0x0b) {\n if (!this._fin) {\n const error = this.createError(\n RangeError,\n 'FIN must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_FIN'\n );\n\n cb(error);\n return;\n }\n\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (\n this._payloadLength > 0x7d ||\n (this._opcode === 0x08 && this._payloadLength === 1)\n ) {\n const error = this.createError(\n RangeError,\n `invalid payload length ${this._payloadLength}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n } else {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fin && !this._fragmented) this._fragmented = this._opcode;\n this._masked = (buf[1] & 0x80) === 0x80;\n\n if (this._isServer) {\n if (!this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n } else if (this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n\n if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;\n else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;\n else this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+16).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength16(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n this._payloadLength = this.consume(2).readUInt16BE(0);\n this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+64).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength64(cb) {\n if (this._bufferedBytes < 8) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(8);\n const num = buf.readUInt32BE(0);\n\n //\n // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned\n // if payload length is greater than this number.\n //\n if (num > Math.pow(2, 53 - 32) - 1) {\n const error = this.createError(\n RangeError,\n 'Unsupported WebSocket frame: payload length > 2^53 - 1',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);\n this.haveLength(cb);\n }\n\n /**\n * Payload length has been read.\n *\n * @param {Function} cb Callback\n * @private\n */\n haveLength(cb) {\n if (this._payloadLength && this._opcode < 0x08) {\n this._totalPayloadLength += this._payloadLength;\n if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n }\n\n if (this._masked) this._state = GET_MASK;\n else this._state = GET_DATA;\n }\n\n /**\n * Reads mask bytes.\n *\n * @private\n */\n getMask() {\n if (this._bufferedBytes < 4) {\n this._loop = false;\n return;\n }\n\n this._mask = this.consume(4);\n this._state = GET_DATA;\n }\n\n /**\n * Reads data bytes.\n *\n * @param {Function} cb Callback\n * @private\n */\n getData(cb) {\n let data = EMPTY_BUFFER;\n\n if (this._payloadLength) {\n if (this._bufferedBytes < this._payloadLength) {\n this._loop = false;\n return;\n }\n\n data = this.consume(this._payloadLength);\n\n if (\n this._masked &&\n (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0\n ) {\n unmask(data, this._mask);\n }\n }\n\n if (this._opcode > 0x07) {\n this.controlMessage(data, cb);\n return;\n }\n\n if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {\n const error = this.createError(\n RangeError,\n 'Too many message fragments',\n false,\n 1008,\n 'WS_ERR_TOO_MANY_BUFFERED_PARTS'\n );\n\n cb(error);\n return;\n }\n\n if (this._compressed) {\n this._state = INFLATING;\n this.decompress(data, cb);\n return;\n }\n\n if (data.length) {\n //\n // This message is not compressed so its length is the sum of the payload\n // length of all fragments.\n //\n this._messageLength = this._totalPayloadLength;\n this._fragments.push(data);\n }\n\n this.dataMessage(cb);\n }\n\n /**\n * Decompresses data.\n *\n * @param {Buffer} data Compressed data\n * @param {Function} cb Callback\n * @private\n */\n decompress(data, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n perMessageDeflate.decompress(data, this._fin, (err, buf) => {\n if (err) return cb(err);\n\n if (buf.length) {\n this._messageLength += buf.length;\n if (this._messageLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._fragments.push(buf);\n }\n\n this.dataMessage(cb);\n if (this._state === GET_INFO) this.startLoop(cb);\n });\n }\n\n /**\n * Handles a data message.\n *\n * @param {Function} cb Callback\n * @private\n */\n dataMessage(cb) {\n if (!this._fin) {\n this._state = GET_INFO;\n return;\n }\n\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._numFragments = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n let data;\n\n if (this._binaryType === 'nodebuffer') {\n data = concat(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(concat(fragments, messageLength));\n } else if (this._binaryType === 'blob') {\n data = new Blob(fragments);\n } else {\n data = fragments;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit('message', data, true);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', data, true);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n } else {\n const buf = concat(fragments, messageLength);\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n if (this._state === INFLATING || this._allowSynchronousEvents) {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n }\n\n /**\n * Handles a control message.\n *\n * @param {Buffer} data Data to handle\n * @return {(Error|RangeError|undefined)} A possible error\n * @private\n */\n controlMessage(data, cb) {\n if (this._opcode === 0x08) {\n if (data.length === 0) {\n this._loop = false;\n this.emit('conclude', 1005, EMPTY_BUFFER);\n this.end();\n } else {\n const code = data.readUInt16BE(0);\n\n if (!isValidStatusCode(code)) {\n const error = this.createError(\n RangeError,\n `invalid status code ${code}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CLOSE_CODE'\n );\n\n cb(error);\n return;\n }\n\n const buf = new FastBuffer(\n data.buffer,\n data.byteOffset + 2,\n data.length - 2\n );\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n this._loop = false;\n this.emit('conclude', code, buf);\n this.end();\n }\n\n this._state = GET_INFO;\n return;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n\n /**\n * Builds an error object.\n *\n * @param {function(new:Error|RangeError)} ErrorCtor The error constructor\n * @param {String} message The error message\n * @param {Boolean} prefix Specifies whether or not to add a default prefix to\n * `message`\n * @param {Number} statusCode The status code\n * @param {String} errorCode The exposed error code\n * @return {(Error|RangeError)} The error\n * @private\n */\n createError(ErrorCtor, message, prefix, statusCode, errorCode) {\n this._loop = false;\n this._errored = true;\n\n const err = new ErrorCtor(\n prefix ? `Invalid WebSocket frame: ${message}` : message\n );\n\n Error.captureStackTrace(err, this.createError);\n err.code = errorCode;\n err[kStatusCode] = statusCode;\n return err;\n }\n}\n\nmodule.exports = Receiver;\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex\" }] */\n\n'use strict';\n\nconst { Duplex } = require('stream');\nconst { randomFillSync } = require('crypto');\nconst {\n types: { isUint8Array }\n} = require('util');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');\nconst { isBlob, isValidStatusCode } = require('./validation');\nconst { mask: applyMask, toBuffer } = require('./buffer-util');\n\nconst kByteLength = Symbol('kByteLength');\nconst maskBuffer = Buffer.alloc(4);\nconst RANDOM_POOL_SIZE = 8 * 1024;\nlet randomPool;\nlet randomPoolPointer = RANDOM_POOL_SIZE;\n\nconst DEFAULT = 0;\nconst DEFLATING = 1;\nconst GET_BLOB_DATA = 2;\n\n/**\n * HyBi Sender implementation.\n */\nclass Sender {\n /**\n * Creates a Sender instance.\n *\n * @param {Duplex} socket The connection socket\n * @param {Object} [extensions] An object containing the negotiated extensions\n * @param {Function} [generateMask] The function used to generate the masking\n * key\n */\n constructor(socket, extensions, generateMask) {\n this._extensions = extensions || {};\n\n if (generateMask) {\n this._generateMask = generateMask;\n this._maskBuffer = Buffer.alloc(4);\n }\n\n this._socket = socket;\n\n this._firstFragment = true;\n this._compress = false;\n\n this._bufferedBytes = 0;\n this._queue = [];\n this._state = DEFAULT;\n this.onerror = NOOP;\n this[kWebSocket] = undefined;\n }\n\n /**\n * Frames a piece of data according to the HyBi WebSocket protocol.\n *\n * @param {(Buffer|String)} data The data to frame\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @return {(Buffer|String)[]} The framed data\n * @public\n */\n static frame(data, options) {\n let mask;\n let merge = false;\n let offset = 2;\n let skipMasking = false;\n\n if (options.mask) {\n mask = options.maskBuffer || maskBuffer;\n\n if (options.generateMask) {\n options.generateMask(mask);\n } else {\n if (randomPoolPointer === RANDOM_POOL_SIZE) {\n /* istanbul ignore else */\n if (randomPool === undefined) {\n //\n // This is lazily initialized because server-sent frames must not\n // be masked so it may never be used.\n //\n randomPool = Buffer.alloc(RANDOM_POOL_SIZE);\n }\n\n randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);\n randomPoolPointer = 0;\n }\n\n mask[0] = randomPool[randomPoolPointer++];\n mask[1] = randomPool[randomPoolPointer++];\n mask[2] = randomPool[randomPoolPointer++];\n mask[3] = randomPool[randomPoolPointer++];\n }\n\n skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;\n offset = 6;\n }\n\n let dataLength;\n\n if (typeof data === 'string') {\n if (\n (!options.mask || skipMasking) &&\n options[kByteLength] !== undefined\n ) {\n dataLength = options[kByteLength];\n } else {\n data = Buffer.from(data);\n dataLength = data.length;\n }\n } else {\n dataLength = data.length;\n merge = options.mask && options.readOnly && !skipMasking;\n }\n\n let payloadLength = dataLength;\n\n if (dataLength >= 65536) {\n offset += 8;\n payloadLength = 127;\n } else if (dataLength > 125) {\n offset += 2;\n payloadLength = 126;\n }\n\n const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);\n\n target[0] = options.fin ? options.opcode | 0x80 : options.opcode;\n if (options.rsv1) target[0] |= 0x40;\n\n target[1] = payloadLength;\n\n if (payloadLength === 126) {\n target.writeUInt16BE(dataLength, 2);\n } else if (payloadLength === 127) {\n target[2] = target[3] = 0;\n target.writeUIntBE(dataLength, 4, 6);\n }\n\n if (!options.mask) return [target, data];\n\n target[1] |= 0x80;\n target[offset - 4] = mask[0];\n target[offset - 3] = mask[1];\n target[offset - 2] = mask[2];\n target[offset - 1] = mask[3];\n\n if (skipMasking) return [target, data];\n\n if (merge) {\n applyMask(data, mask, target, offset, dataLength);\n return [target];\n }\n\n applyMask(data, mask, data, 0, dataLength);\n return [target, data];\n }\n\n /**\n * Sends a close message to the other peer.\n *\n * @param {Number} [code] The status code component of the body\n * @param {(String|Buffer)} [data] The message component of the body\n * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n * @param {Function} [cb] Callback\n * @public\n */\n close(code, data, mask, cb) {\n let buf;\n\n if (code === undefined) {\n buf = EMPTY_BUFFER;\n } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n throw new TypeError('First argument must be a valid error code number');\n } else if (data === undefined || !data.length) {\n buf = Buffer.allocUnsafe(2);\n buf.writeUInt16BE(code, 0);\n } else {\n const length = Buffer.byteLength(data);\n\n if (length > 123) {\n throw new RangeError('The message must not be greater than 123 bytes');\n }\n\n buf = Buffer.allocUnsafe(2 + length);\n buf.writeUInt16BE(code, 0);\n\n if (typeof data === 'string') {\n buf.write(data, 2);\n } else if (isUint8Array(data)) {\n buf.set(data, 2);\n } else {\n throw new TypeError('Second argument must be a string or a Uint8Array');\n }\n }\n\n const options = {\n [kByteLength]: buf.length,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x08,\n readOnly: false,\n rsv1: false\n };\n\n if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, buf, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(buf, options), cb);\n }\n }\n\n /**\n * Sends a ping message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n ping(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x09,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a pong message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n pong(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x0a,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a data message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Object} options Options object\n * @param {Boolean} [options.binary=false] Specifies whether `data` is binary\n * or text\n * @param {Boolean} [options.compress=false] Specifies whether or not to\n * compress `data`\n * @param {Boolean} [options.fin=false] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Function} [cb] Callback\n * @public\n */\n send(data, options, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n let opcode = options.binary ? 2 : 1;\n let rsv1 = options.compress;\n\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (this._firstFragment) {\n this._firstFragment = false;\n if (\n rsv1 &&\n perMessageDeflate &&\n perMessageDeflate.params[\n perMessageDeflate._isServer\n ? 'server_no_context_takeover'\n : 'client_no_context_takeover'\n ]\n ) {\n rsv1 = byteLength >= perMessageDeflate._threshold;\n }\n this._compress = rsv1;\n } else {\n rsv1 = false;\n opcode = 0;\n }\n\n if (options.fin) this._firstFragment = true;\n\n const opts = {\n [kByteLength]: byteLength,\n fin: options.fin,\n generateMask: this._generateMask,\n mask: options.mask,\n maskBuffer: this._maskBuffer,\n opcode,\n readOnly,\n rsv1\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, this._compress, opts, cb]);\n } else {\n this.getBlobData(data, this._compress, opts, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, this._compress, opts, cb]);\n } else {\n this.dispatch(data, this._compress, opts, cb);\n }\n }\n\n /**\n * Gets the contents of a blob as binary data.\n *\n * @param {Blob} blob The blob\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * the data\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n getBlobData(blob, compress, options, cb) {\n this._bufferedBytes += options[kByteLength];\n this._state = GET_BLOB_DATA;\n\n blob\n .arrayBuffer()\n .then((arrayBuffer) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while the blob was being read'\n );\n\n //\n // `callCallbacks` is called in the next tick to ensure that errors\n // that might be thrown in the callbacks behave like errors thrown\n // outside the promise chain.\n //\n process.nextTick(callCallbacks, this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n const data = toBuffer(arrayBuffer);\n\n if (!compress) {\n this._state = DEFAULT;\n this.sendFrame(Sender.frame(data, options), cb);\n this.dequeue();\n } else {\n this.dispatch(data, compress, options, cb);\n }\n })\n .catch((err) => {\n //\n // `onError` is called in the next tick for the same reason that\n // `callCallbacks` above is.\n //\n process.nextTick(onError, this, err, cb);\n });\n }\n\n /**\n * Dispatches a message.\n *\n * @param {(Buffer|String)} data The message to send\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * `data`\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n dispatch(data, compress, options, cb) {\n if (!compress) {\n this.sendFrame(Sender.frame(data, options), cb);\n return;\n }\n\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n this._bufferedBytes += options[kByteLength];\n this._state = DEFLATING;\n perMessageDeflate.compress(data, options.fin, (_, buf) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while data was being compressed'\n );\n\n callCallbacks(this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n this._state = DEFAULT;\n options.readOnly = false;\n this.sendFrame(Sender.frame(buf, options), cb);\n this.dequeue();\n });\n }\n\n /**\n * Executes queued send operations.\n *\n * @private\n */\n dequeue() {\n while (this._state === DEFAULT && this._queue.length) {\n const params = this._queue.shift();\n\n this._bufferedBytes -= params[3][kByteLength];\n Reflect.apply(params[0], this, params.slice(1));\n }\n }\n\n /**\n * Enqueues a send operation.\n *\n * @param {Array} params Send operation parameters.\n * @private\n */\n enqueue(params) {\n this._bufferedBytes += params[3][kByteLength];\n this._queue.push(params);\n }\n\n /**\n * Sends a frame.\n *\n * @param {(Buffer | String)[]} list The frame to send\n * @param {Function} [cb] Callback\n * @private\n */\n sendFrame(list, cb) {\n if (list.length === 2) {\n this._socket.cork();\n this._socket.write(list[0]);\n this._socket.write(list[1], cb);\n this._socket.uncork();\n } else {\n this._socket.write(list[0], cb);\n }\n }\n}\n\nmodule.exports = Sender;\n\n/**\n * Calls queued callbacks with an error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error to call the callbacks with\n * @param {Function} [cb] The first callback\n * @private\n */\nfunction callCallbacks(sender, err, cb) {\n if (typeof cb === 'function') cb(err);\n\n for (let i = 0; i < sender._queue.length; i++) {\n const params = sender._queue[i];\n const callback = params[params.length - 1];\n\n if (typeof callback === 'function') callback(err);\n }\n}\n\n/**\n * Handles a `Sender` error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error\n * @param {Function} [cb] The first pending callback\n * @private\n */\nfunction onError(sender, err, cb) {\n callCallbacks(sender, err, cb);\n sender.onerror(err);\n}\n","'use strict';\n\nconst { kForOnEventAttribute, kListener } = require('./constants');\n\nconst kCode = Symbol('kCode');\nconst kData = Symbol('kData');\nconst kError = Symbol('kError');\nconst kMessage = Symbol('kMessage');\nconst kReason = Symbol('kReason');\nconst kTarget = Symbol('kTarget');\nconst kType = Symbol('kType');\nconst kWasClean = Symbol('kWasClean');\n\n/**\n * Class representing an event.\n */\nclass Event {\n /**\n * Create a new `Event`.\n *\n * @param {String} type The name of the event\n * @throws {TypeError} If the `type` argument is not specified\n */\n constructor(type) {\n this[kTarget] = null;\n this[kType] = type;\n }\n\n /**\n * @type {*}\n */\n get target() {\n return this[kTarget];\n }\n\n /**\n * @type {String}\n */\n get type() {\n return this[kType];\n }\n}\n\nObject.defineProperty(Event.prototype, 'target', { enumerable: true });\nObject.defineProperty(Event.prototype, 'type', { enumerable: true });\n\n/**\n * Class representing a close event.\n *\n * @extends Event\n */\nclass CloseEvent extends Event {\n /**\n * Create a new `CloseEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {Number} [options.code=0] The status code explaining why the\n * connection was closed\n * @param {String} [options.reason=''] A human-readable string explaining why\n * the connection was closed\n * @param {Boolean} [options.wasClean=false] Indicates whether or not the\n * connection was cleanly closed\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kCode] = options.code === undefined ? 0 : options.code;\n this[kReason] = options.reason === undefined ? '' : options.reason;\n this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;\n }\n\n /**\n * @type {Number}\n */\n get code() {\n return this[kCode];\n }\n\n /**\n * @type {String}\n */\n get reason() {\n return this[kReason];\n }\n\n /**\n * @type {Boolean}\n */\n get wasClean() {\n return this[kWasClean];\n }\n}\n\nObject.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });\n\n/**\n * Class representing an error event.\n *\n * @extends Event\n */\nclass ErrorEvent extends Event {\n /**\n * Create a new `ErrorEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.error=null] The error that generated this event\n * @param {String} [options.message=''] The error message\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kError] = options.error === undefined ? null : options.error;\n this[kMessage] = options.message === undefined ? '' : options.message;\n }\n\n /**\n * @type {*}\n */\n get error() {\n return this[kError];\n }\n\n /**\n * @type {String}\n */\n get message() {\n return this[kMessage];\n }\n}\n\nObject.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });\nObject.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });\n\n/**\n * Class representing a message event.\n *\n * @extends Event\n */\nclass MessageEvent extends Event {\n /**\n * Create a new `MessageEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.data=null] The message content\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kData] = options.data === undefined ? null : options.data;\n }\n\n /**\n * @type {*}\n */\n get data() {\n return this[kData];\n }\n}\n\nObject.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });\n\n/**\n * This provides methods for emulating the `EventTarget` interface. It's not\n * meant to be used directly.\n *\n * @mixin\n */\nconst EventTarget = {\n /**\n * Register an event listener.\n *\n * @param {String} type A string representing the event type to listen for\n * @param {(Function|Object)} handler The listener to add\n * @param {Object} [options] An options object specifies characteristics about\n * the event listener\n * @param {Boolean} [options.once=false] A `Boolean` indicating that the\n * listener should be invoked at most once after being added. If `true`,\n * the listener would be automatically removed when invoked.\n * @public\n */\n addEventListener(type, handler, options = {}) {\n for (const listener of this.listeners(type)) {\n if (\n !options[kForOnEventAttribute] &&\n listener[kListener] === handler &&\n !listener[kForOnEventAttribute]\n ) {\n return;\n }\n }\n\n let wrapper;\n\n if (type === 'message') {\n wrapper = function onMessage(data, isBinary) {\n const event = new MessageEvent('message', {\n data: isBinary ? data : data.toString()\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'close') {\n wrapper = function onClose(code, message) {\n const event = new CloseEvent('close', {\n code,\n reason: message.toString(),\n wasClean: this._closeFrameReceived && this._closeFrameSent\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'error') {\n wrapper = function onError(error) {\n const event = new ErrorEvent('error', {\n error,\n message: error.message\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'open') {\n wrapper = function onOpen() {\n const event = new Event('open');\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else {\n return;\n }\n\n wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];\n wrapper[kListener] = handler;\n\n if (options.once) {\n this.once(type, wrapper);\n } else {\n this.on(type, wrapper);\n }\n },\n\n /**\n * Remove an event listener.\n *\n * @param {String} type A string representing the event type to remove\n * @param {(Function|Object)} handler The listener to remove\n * @public\n */\n removeEventListener(type, handler) {\n for (const listener of this.listeners(type)) {\n if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {\n this.removeListener(type, listener);\n break;\n }\n }\n }\n};\n\nmodule.exports = {\n CloseEvent,\n ErrorEvent,\n Event,\n EventTarget,\n MessageEvent\n};\n\n/**\n * Call an event listener\n *\n * @param {(Function|Object)} listener The listener to call\n * @param {*} thisArg The value to use as `this`` when calling the listener\n * @param {Event} event The event to pass to the listener\n * @private\n */\nfunction callListener(listener, thisArg, event) {\n if (typeof listener === 'object' && listener.handleEvent) {\n listener.handleEvent.call(listener, event);\n } else {\n listener.call(thisArg, event);\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Adds an offer to the map of extension offers or a parameter to the map of\n * parameters.\n *\n * @param {Object} dest The map of extension offers or parameters\n * @param {String} name The extension or parameter name\n * @param {(Object|Boolean|String)} elem The extension parameters or the\n * parameter value\n * @private\n */\nfunction push(dest, name, elem) {\n if (dest[name] === undefined) dest[name] = [elem];\n else dest[name].push(elem);\n}\n\n/**\n * Parses the `Sec-WebSocket-Extensions` header into an object.\n *\n * @param {String} header The field value of the header\n * @return {Object} The parsed object\n * @public\n */\nfunction parse(header) {\n const offers = Object.create(null);\n let params = Object.create(null);\n let mustUnescape = false;\n let isEscaping = false;\n let inQuotes = false;\n let extensionName;\n let paramName;\n let start = -1;\n let code = -1;\n let end = -1;\n let i = 0;\n\n for (; i < header.length; i++) {\n code = header.charCodeAt(i);\n\n if (extensionName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n const name = header.slice(start, end);\n if (code === 0x2c) {\n push(offers, name, params);\n params = Object.create(null);\n } else {\n extensionName = name;\n }\n\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (paramName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x20 || code === 0x09) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n push(params, header.slice(start, end), true);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n start = end = -1;\n } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {\n paramName = header.slice(start, i);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else {\n //\n // The value of a quoted-string after unescaping must conform to the\n // token ABNF, so only token characters are valid.\n // Ref: https://tools.ietf.org/html/rfc6455#section-9.1\n //\n if (isEscaping) {\n if (tokenChars[code] !== 1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n if (start === -1) start = i;\n else if (!mustUnescape) mustUnescape = true;\n isEscaping = false;\n } else if (inQuotes) {\n if (tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x22 /* '\"' */ && start !== -1) {\n inQuotes = false;\n end = i;\n } else if (code === 0x5c /* '\\' */) {\n isEscaping = true;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {\n inQuotes = true;\n } else if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (start !== -1 && (code === 0x20 || code === 0x09)) {\n if (end === -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n let value = header.slice(start, end);\n if (mustUnescape) {\n value = value.replace(/\\\\/g, '');\n mustUnescape = false;\n }\n push(params, paramName, value);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n paramName = undefined;\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n }\n\n if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n if (end === -1) end = i;\n const token = header.slice(start, end);\n if (extensionName === undefined) {\n push(offers, token, params);\n } else {\n if (paramName === undefined) {\n push(params, token, true);\n } else if (mustUnescape) {\n push(params, paramName, token.replace(/\\\\/g, ''));\n } else {\n push(params, paramName, token);\n }\n push(offers, extensionName, params);\n }\n\n return offers;\n}\n\n/**\n * Builds the `Sec-WebSocket-Extensions` header field value.\n *\n * @param {Object} extensions The map of extensions and parameters to format\n * @return {String} A string representing the given object\n * @public\n */\nfunction format(extensions) {\n return Object.keys(extensions)\n .map((extension) => {\n let configurations = extensions[extension];\n if (!Array.isArray(configurations)) configurations = [configurations];\n return configurations\n .map((params) => {\n return [extension]\n .concat(\n Object.keys(params).map((k) => {\n let values = params[k];\n if (!Array.isArray(values)) values = [values];\n return values\n .map((v) => (v === true ? k : `${k}=${v}`))\n .join('; ');\n })\n )\n .join('; ');\n })\n .join(', ');\n })\n .join(', ');\n}\n\nmodule.exports = { format, parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex|Readable$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst https = require('https');\nconst http = require('http');\nconst net = require('net');\nconst tls = require('tls');\nconst { randomBytes, createHash } = require('crypto');\nconst { Duplex, Readable } = require('stream');\nconst { URL } = require('url');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst Receiver = require('./receiver');\nconst Sender = require('./sender');\nconst { isBlob } = require('./validation');\n\nconst {\n BINARY_TYPES,\n CLOSE_TIMEOUT,\n EMPTY_BUFFER,\n GUID,\n kForOnEventAttribute,\n kListener,\n kStatusCode,\n kWebSocket,\n NOOP\n} = require('./constants');\nconst {\n EventTarget: { addEventListener, removeEventListener }\n} = require('./event-target');\nconst { format, parse } = require('./extension');\nconst { toBuffer } = require('./buffer-util');\n\nconst kAborted = Symbol('kAborted');\nconst protocolVersions = [8, 13];\nconst readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];\nconst subprotocolRegex = /^[!#$%&'*+\\-.0-9A-Z^_`|a-z~]+$/;\n\n/**\n * Class representing a WebSocket.\n *\n * @extends EventEmitter\n */\nclass WebSocket extends EventEmitter {\n /**\n * Create a new `WebSocket`.\n *\n * @param {(String|URL)} address The URL to which to connect\n * @param {(String|String[])} [protocols] The subprotocols\n * @param {Object} [options] Connection options\n */\n constructor(address, protocols, options) {\n super();\n\n this._binaryType = BINARY_TYPES[0];\n this._closeCode = 1006;\n this._closeFrameReceived = false;\n this._closeFrameSent = false;\n this._closeMessage = EMPTY_BUFFER;\n this._closeTimer = null;\n this._errorEmitted = false;\n this._extensions = {};\n this._paused = false;\n this._protocol = '';\n this._readyState = WebSocket.CONNECTING;\n this._receiver = null;\n this._sender = null;\n this._socket = null;\n\n if (address !== null) {\n this._bufferedAmount = 0;\n this._isServer = false;\n this._redirects = 0;\n\n if (protocols === undefined) {\n protocols = [];\n } else if (!Array.isArray(protocols)) {\n if (typeof protocols === 'object' && protocols !== null) {\n options = protocols;\n protocols = [];\n } else {\n protocols = [protocols];\n }\n }\n\n initAsClient(this, address, protocols, options);\n } else {\n this._autoPong = options.autoPong;\n this._closeTimeout = options.closeTimeout;\n this._isServer = true;\n }\n }\n\n /**\n * For historical reasons, the custom \"nodebuffer\" type is used by the default\n * instead of \"blob\".\n *\n * @type {String}\n */\n get binaryType() {\n return this._binaryType;\n }\n\n set binaryType(type) {\n if (!BINARY_TYPES.includes(type)) return;\n\n this._binaryType = type;\n\n //\n // Allow to change `binaryType` on the fly.\n //\n if (this._receiver) this._receiver._binaryType = type;\n }\n\n /**\n * @type {Number}\n */\n get bufferedAmount() {\n if (!this._socket) return this._bufferedAmount;\n\n return this._socket._writableState.length + this._sender._bufferedBytes;\n }\n\n /**\n * @type {String}\n */\n get extensions() {\n return Object.keys(this._extensions).join();\n }\n\n /**\n * @type {Boolean}\n */\n get isPaused() {\n return this._paused;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onclose() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onerror() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onopen() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onmessage() {\n return null;\n }\n\n /**\n * @type {String}\n */\n get protocol() {\n return this._protocol;\n }\n\n /**\n * @type {Number}\n */\n get readyState() {\n return this._readyState;\n }\n\n /**\n * @type {String}\n */\n get url() {\n return this._url;\n }\n\n /**\n * Set up the socket and the internal resources.\n *\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Object} options Options object\n * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.maxBufferedChunks=0] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=0] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=0] The maximum allowed message size\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\n setSocket(socket, head, options) {\n const receiver = new Receiver({\n allowSynchronousEvents: options.allowSynchronousEvents,\n binaryType: this.binaryType,\n extensions: this._extensions,\n isServer: this._isServer,\n maxBufferedChunks: options.maxBufferedChunks,\n maxFragments: options.maxFragments,\n maxPayload: options.maxPayload,\n skipUTF8Validation: options.skipUTF8Validation\n });\n\n const sender = new Sender(socket, this._extensions, options.generateMask);\n\n this._receiver = receiver;\n this._sender = sender;\n this._socket = socket;\n\n receiver[kWebSocket] = this;\n sender[kWebSocket] = this;\n socket[kWebSocket] = this;\n\n receiver.on('conclude', receiverOnConclude);\n receiver.on('drain', receiverOnDrain);\n receiver.on('error', receiverOnError);\n receiver.on('message', receiverOnMessage);\n receiver.on('ping', receiverOnPing);\n receiver.on('pong', receiverOnPong);\n\n sender.onerror = senderOnError;\n\n //\n // These methods may not be available if `socket` is just a `Duplex`.\n //\n if (socket.setTimeout) socket.setTimeout(0);\n if (socket.setNoDelay) socket.setNoDelay();\n\n if (head.length > 0) socket.unshift(head);\n\n socket.on('close', socketOnClose);\n socket.on('data', socketOnData);\n socket.on('end', socketOnEnd);\n socket.on('error', socketOnError);\n\n this._readyState = WebSocket.OPEN;\n this.emit('open');\n }\n\n /**\n * Emit the `'close'` event.\n *\n * @private\n */\n emitClose() {\n if (!this._socket) {\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n return;\n }\n\n if (this._extensions[PerMessageDeflate.extensionName]) {\n this._extensions[PerMessageDeflate.extensionName].cleanup();\n }\n\n this._receiver.removeAllListeners();\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n }\n\n /**\n * Start a closing handshake.\n *\n * +----------+ +-----------+ +----------+\n * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -\n * | +----------+ +-----------+ +----------+ |\n * +----------+ +-----------+ |\n * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING\n * +----------+ +-----------+ |\n * | | | +---+ |\n * +------------------------+-->|fin| - - - -\n * | +---+ | +---+\n * - - - - -|fin|<---------------------+\n * +---+\n *\n * @param {Number} [code] Status code explaining why the connection is closing\n * @param {(String|Buffer)} [data] The reason why the connection is\n * closing\n * @public\n */\n close(code, data) {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this.readyState === WebSocket.CLOSING) {\n if (\n this._closeFrameSent &&\n (this._closeFrameReceived || this._receiver._writableState.errorEmitted)\n ) {\n this._socket.end();\n }\n\n return;\n }\n\n this._readyState = WebSocket.CLOSING;\n this._sender.close(code, data, !this._isServer, (err) => {\n //\n // This error is handled by the `'error'` listener on the socket. We only\n // want to know if the close frame has been sent here.\n //\n if (err) return;\n\n this._closeFrameSent = true;\n\n if (\n this._closeFrameReceived ||\n this._receiver._writableState.errorEmitted\n ) {\n this._socket.end();\n }\n });\n\n setCloseTimer(this);\n }\n\n /**\n * Pause the socket.\n *\n * @public\n */\n pause() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = true;\n this._socket.pause();\n }\n\n /**\n * Send a ping.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the ping is sent\n * @public\n */\n ping(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.ping(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Send a pong.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the pong is sent\n * @public\n */\n pong(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.pong(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Resume the socket.\n *\n * @public\n */\n resume() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = false;\n if (!this._receiver._writableState.needDrain) this._socket.resume();\n }\n\n /**\n * Send a data message.\n *\n * @param {*} data The message to send\n * @param {Object} [options] Options object\n * @param {Boolean} [options.binary] Specifies whether `data` is binary or\n * text\n * @param {Boolean} [options.compress] Specifies whether or not to compress\n * `data`\n * @param {Boolean} [options.fin=true] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when data is written out\n * @public\n */\n send(data, options, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n const opts = {\n binary: typeof data !== 'string',\n mask: !this._isServer,\n compress: true,\n fin: true,\n ...options\n };\n\n if (!this._extensions[PerMessageDeflate.extensionName]) {\n opts.compress = false;\n }\n\n this._sender.send(data || EMPTY_BUFFER, opts, cb);\n }\n\n /**\n * Forcibly close the connection.\n *\n * @public\n */\n terminate() {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this._socket) {\n this._readyState = WebSocket.CLOSING;\n this._socket.destroy();\n }\n }\n}\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n[\n 'binaryType',\n 'bufferedAmount',\n 'extensions',\n 'isPaused',\n 'protocol',\n 'readyState',\n 'url'\n].forEach((property) => {\n Object.defineProperty(WebSocket.prototype, property, { enumerable: true });\n});\n\n//\n// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.\n// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface\n//\n['open', 'error', 'close', 'message'].forEach((method) => {\n Object.defineProperty(WebSocket.prototype, `on${method}`, {\n enumerable: true,\n get() {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) return listener[kListener];\n }\n\n return null;\n },\n set(handler) {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) {\n this.removeListener(method, listener);\n break;\n }\n }\n\n if (typeof handler !== 'function') return;\n\n this.addEventListener(method, handler, {\n [kForOnEventAttribute]: true\n });\n }\n });\n});\n\nWebSocket.prototype.addEventListener = addEventListener;\nWebSocket.prototype.removeEventListener = removeEventListener;\n\nmodule.exports = WebSocket;\n\n/**\n * Initialize a WebSocket client.\n *\n * @param {WebSocket} websocket The client to initialize\n * @param {(String|URL)} address The URL to which to connect\n * @param {Array} protocols The subprotocols\n * @param {Object} [options] Connection options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any\n * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple\n * times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait\n * for the closing handshake to finish after `websocket.close()` is called\n * @param {Function} [options.finishRequest] A function which can be used to\n * customize the headers of each http request before it is sent\n * @param {Boolean} [options.followRedirects=false] Whether or not to follow\n * redirects\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the\n * handshake request\n * @param {Number} [options.maxBufferedChunks=262144] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=16384] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Number} [options.maxRedirects=10] The maximum number of redirects\n * allowed\n * @param {String} [options.origin] Value of the `Origin` or\n * `Sec-WebSocket-Origin` header\n * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable\n * permessage-deflate\n * @param {Number} [options.protocolVersion=13] Value of the\n * `Sec-WebSocket-Version` header\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\nfunction initAsClient(websocket, address, protocols, options) {\n const opts = {\n allowSynchronousEvents: true,\n autoPong: true,\n closeTimeout: CLOSE_TIMEOUT,\n protocolVersion: protocolVersions[1],\n maxBufferedChunks: 256 * 1024,\n maxFragments: 16 * 1024,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: true,\n followRedirects: false,\n maxRedirects: 10,\n ...options,\n socketPath: undefined,\n hostname: undefined,\n protocol: undefined,\n timeout: undefined,\n method: 'GET',\n host: undefined,\n path: undefined,\n port: undefined\n };\n\n websocket._autoPong = opts.autoPong;\n websocket._closeTimeout = opts.closeTimeout;\n\n if (!protocolVersions.includes(opts.protocolVersion)) {\n throw new RangeError(\n `Unsupported protocol version: ${opts.protocolVersion} ` +\n `(supported versions: ${protocolVersions.join(', ')})`\n );\n }\n\n let parsedUrl;\n\n if (address instanceof URL) {\n parsedUrl = address;\n } else {\n try {\n parsedUrl = new URL(address);\n } catch {\n throw new SyntaxError(`Invalid URL: ${address}`);\n }\n }\n\n if (parsedUrl.protocol === 'http:') {\n parsedUrl.protocol = 'ws:';\n } else if (parsedUrl.protocol === 'https:') {\n parsedUrl.protocol = 'wss:';\n }\n\n websocket._url = parsedUrl.href;\n\n const isSecure = parsedUrl.protocol === 'wss:';\n const isIpcUrl = parsedUrl.protocol === 'ws+unix:';\n let invalidUrlMessage;\n\n if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {\n invalidUrlMessage =\n 'The URL\\'s protocol must be one of \"ws:\", \"wss:\", ' +\n '\"http:\", \"https:\", or \"ws+unix:\"';\n } else if (isIpcUrl && !parsedUrl.pathname) {\n invalidUrlMessage = \"The URL's pathname is empty\";\n } else if (parsedUrl.hash) {\n invalidUrlMessage = 'The URL contains a fragment identifier';\n }\n\n if (invalidUrlMessage) {\n const err = new SyntaxError(invalidUrlMessage);\n\n if (websocket._redirects === 0) {\n throw err;\n } else {\n emitErrorAndClose(websocket, err);\n return;\n }\n }\n\n const defaultPort = isSecure ? 443 : 80;\n const key = randomBytes(16).toString('base64');\n const request = isSecure ? https.request : http.request;\n const protocolSet = new Set();\n let perMessageDeflate;\n\n opts.createConnection =\n opts.createConnection || (isSecure ? tlsConnect : netConnect);\n opts.defaultPort = opts.defaultPort || defaultPort;\n opts.port = parsedUrl.port || defaultPort;\n opts.host = parsedUrl.hostname.startsWith('[')\n ? parsedUrl.hostname.slice(1, -1)\n : parsedUrl.hostname;\n opts.headers = {\n ...opts.headers,\n 'Sec-WebSocket-Version': opts.protocolVersion,\n 'Sec-WebSocket-Key': key,\n Connection: 'Upgrade',\n Upgrade: 'websocket'\n };\n opts.path = parsedUrl.pathname + parsedUrl.search;\n opts.timeout = opts.handshakeTimeout;\n\n if (opts.perMessageDeflate) {\n perMessageDeflate = new PerMessageDeflate({\n ...opts.perMessageDeflate,\n isServer: false,\n maxPayload: opts.maxPayload\n });\n opts.headers['Sec-WebSocket-Extensions'] = format({\n [PerMessageDeflate.extensionName]: perMessageDeflate.offer()\n });\n }\n if (protocols.length) {\n for (const protocol of protocols) {\n if (\n typeof protocol !== 'string' ||\n !subprotocolRegex.test(protocol) ||\n protocolSet.has(protocol)\n ) {\n throw new SyntaxError(\n 'An invalid or duplicated subprotocol was specified'\n );\n }\n\n protocolSet.add(protocol);\n }\n\n opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');\n }\n if (opts.origin) {\n if (opts.protocolVersion < 13) {\n opts.headers['Sec-WebSocket-Origin'] = opts.origin;\n } else {\n opts.headers.Origin = opts.origin;\n }\n }\n if (parsedUrl.username || parsedUrl.password) {\n opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;\n }\n\n if (isIpcUrl) {\n const parts = opts.path.split(':');\n\n opts.socketPath = parts[0];\n opts.path = parts[1];\n }\n\n let req;\n\n if (opts.followRedirects) {\n if (websocket._redirects === 0) {\n websocket._originalIpc = isIpcUrl;\n websocket._originalSecure = isSecure;\n websocket._originalHostOrSocketPath = isIpcUrl\n ? opts.socketPath\n : parsedUrl.host;\n\n const headers = options && options.headers;\n\n //\n // Shallow copy the user provided options so that headers can be changed\n // without mutating the original object.\n //\n options = { ...options, headers: {} };\n\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n options.headers[key.toLowerCase()] = value;\n }\n }\n } else if (websocket.listenerCount('redirect') === 0) {\n const isSameHost = isIpcUrl\n ? websocket._originalIpc\n ? opts.socketPath === websocket._originalHostOrSocketPath\n : false\n : websocket._originalIpc\n ? false\n : parsedUrl.host === websocket._originalHostOrSocketPath;\n\n if (!isSameHost || (websocket._originalSecure && !isSecure)) {\n //\n // Match curl 7.77.0 behavior and drop the following headers. These\n // headers are also dropped when following a redirect to a subdomain.\n //\n delete opts.headers.authorization;\n delete opts.headers.cookie;\n\n if (!isSameHost) delete opts.headers.host;\n\n opts.auth = undefined;\n }\n }\n\n //\n // Match curl 7.77.0 behavior and make the first `Authorization` header win.\n // If the `Authorization` header is set, then there is nothing to do as it\n // will take precedence.\n //\n if (opts.auth && !options.headers.authorization) {\n options.headers.authorization =\n 'Basic ' + Buffer.from(opts.auth).toString('base64');\n }\n\n req = websocket._req = request(opts);\n\n if (websocket._redirects) {\n //\n // Unlike what is done for the `'upgrade'` event, no early exit is\n // triggered here if the user calls `websocket.close()` or\n // `websocket.terminate()` from a listener of the `'redirect'` event. This\n // is because the user can also call `request.destroy()` with an error\n // before calling `websocket.close()` or `websocket.terminate()` and this\n // would result in an error being emitted on the `request` object with no\n // `'error'` event listeners attached.\n //\n websocket.emit('redirect', websocket.url, req);\n }\n } else {\n req = websocket._req = request(opts);\n }\n\n if (opts.timeout) {\n req.on('timeout', () => {\n abortHandshake(websocket, req, 'Opening handshake has timed out');\n });\n }\n\n req.on('error', (err) => {\n if (req === null || req[kAborted]) return;\n\n req = websocket._req = null;\n emitErrorAndClose(websocket, err);\n });\n\n req.on('response', (res) => {\n const location = res.headers.location;\n const statusCode = res.statusCode;\n\n if (\n location &&\n opts.followRedirects &&\n statusCode >= 300 &&\n statusCode < 400\n ) {\n if (++websocket._redirects > opts.maxRedirects) {\n abortHandshake(websocket, req, 'Maximum redirects exceeded');\n return;\n }\n\n req.abort();\n\n let addr;\n\n try {\n addr = new URL(location, address);\n } catch (e) {\n const err = new SyntaxError(`Invalid URL: ${location}`);\n emitErrorAndClose(websocket, err);\n return;\n }\n\n initAsClient(websocket, addr, protocols, options);\n } else if (!websocket.emit('unexpected-response', req, res)) {\n abortHandshake(\n websocket,\n req,\n `Unexpected server response: ${res.statusCode}`\n );\n }\n });\n\n req.on('upgrade', (res, socket, head) => {\n websocket.emit('upgrade', res);\n\n //\n // The user may have closed the connection from a listener of the\n // `'upgrade'` event.\n //\n if (websocket.readyState !== WebSocket.CONNECTING) return;\n\n req = websocket._req = null;\n\n const upgrade = res.headers.upgrade;\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n abortHandshake(websocket, socket, 'Invalid Upgrade header');\n return;\n }\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n if (res.headers['sec-websocket-accept'] !== digest) {\n abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');\n return;\n }\n\n const serverProt = res.headers['sec-websocket-protocol'];\n let protError;\n\n if (serverProt !== undefined) {\n if (!protocolSet.size) {\n protError = 'Server sent a subprotocol but none was requested';\n } else if (!protocolSet.has(serverProt)) {\n protError = 'Server sent an invalid subprotocol';\n }\n } else if (protocolSet.size) {\n protError = 'Server sent no subprotocol';\n }\n\n if (protError) {\n abortHandshake(websocket, socket, protError);\n return;\n }\n\n if (serverProt) websocket._protocol = serverProt;\n\n const secWebSocketExtensions = res.headers['sec-websocket-extensions'];\n\n if (secWebSocketExtensions !== undefined) {\n if (!perMessageDeflate) {\n const message =\n 'Server sent a Sec-WebSocket-Extensions header but no extension ' +\n 'was requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n let extensions;\n\n try {\n extensions = parse(secWebSocketExtensions);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n const extensionNames = Object.keys(extensions);\n\n if (\n extensionNames.length !== 1 ||\n extensionNames[0] !== PerMessageDeflate.extensionName\n ) {\n const message = 'Server indicated an extension that was not requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n try {\n perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n websocket._extensions[PerMessageDeflate.extensionName] =\n perMessageDeflate;\n }\n\n websocket.setSocket(socket, head, {\n allowSynchronousEvents: opts.allowSynchronousEvents,\n generateMask: opts.generateMask,\n maxBufferedChunks: opts.maxBufferedChunks,\n maxFragments: opts.maxFragments,\n maxPayload: opts.maxPayload,\n skipUTF8Validation: opts.skipUTF8Validation\n });\n });\n\n if (opts.finishRequest) {\n opts.finishRequest(req, websocket);\n } else {\n req.end();\n }\n}\n\n/**\n * Emit the `'error'` and `'close'` events.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {Error} The error to emit\n * @private\n */\nfunction emitErrorAndClose(websocket, err) {\n websocket._readyState = WebSocket.CLOSING;\n //\n // The following assignment is practically useless and is done only for\n // consistency.\n //\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n websocket.emitClose();\n}\n\n/**\n * Create a `net.Socket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {net.Socket} The newly created socket used to start the connection\n * @private\n */\nfunction netConnect(options) {\n options.path = options.socketPath;\n return net.connect(options);\n}\n\n/**\n * Create a `tls.TLSSocket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {tls.TLSSocket} The newly created socket used to start the connection\n * @private\n */\nfunction tlsConnect(options) {\n options.path = undefined;\n\n if (!options.servername && options.servername !== '') {\n options.servername = net.isIP(options.host) ? '' : options.host;\n }\n\n return tls.connect(options);\n}\n\n/**\n * Abort the handshake and emit an error.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to\n * abort or the socket to destroy\n * @param {String} message The error message\n * @private\n */\nfunction abortHandshake(websocket, stream, message) {\n websocket._readyState = WebSocket.CLOSING;\n\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshake);\n\n if (stream.setHeader) {\n stream[kAborted] = true;\n stream.abort();\n\n if (stream.socket && !stream.socket.destroyed) {\n //\n // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if\n // called after the request completed. See\n // https://github.com/websockets/ws/issues/1869.\n //\n stream.socket.destroy();\n }\n\n process.nextTick(emitErrorAndClose, websocket, err);\n } else {\n stream.destroy(err);\n stream.once('error', websocket.emit.bind(websocket, 'error'));\n stream.once('close', websocket.emitClose.bind(websocket));\n }\n}\n\n/**\n * Handle cases where the `ping()`, `pong()`, or `send()` methods are called\n * when the `readyState` attribute is `CLOSING` or `CLOSED`.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {*} [data] The data to send\n * @param {Function} [cb] Callback\n * @private\n */\nfunction sendAfterClose(websocket, data, cb) {\n if (data) {\n const length = isBlob(data) ? data.size : toBuffer(data).length;\n\n //\n // The `_bufferedAmount` property is used only when the peer is a client and\n // the opening handshake fails. Under these circumstances, in fact, the\n // `setSocket()` method is not called, so the `_socket` and `_sender`\n // properties are set to `null`.\n //\n if (websocket._socket) websocket._sender._bufferedBytes += length;\n else websocket._bufferedAmount += length;\n }\n\n if (cb) {\n const err = new Error(\n `WebSocket is not open: readyState ${websocket.readyState} ` +\n `(${readyStates[websocket.readyState]})`\n );\n process.nextTick(cb, err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'conclude'` event.\n *\n * @param {Number} code The status code\n * @param {Buffer} reason The reason for closing\n * @private\n */\nfunction receiverOnConclude(code, reason) {\n const websocket = this[kWebSocket];\n\n websocket._closeFrameReceived = true;\n websocket._closeMessage = reason;\n websocket._closeCode = code;\n\n if (websocket._socket[kWebSocket] === undefined) return;\n\n websocket._socket.removeListener('data', socketOnData);\n process.nextTick(resume, websocket._socket);\n\n if (code === 1005) websocket.close();\n else websocket.close(code, reason);\n}\n\n/**\n * The listener of the `Receiver` `'drain'` event.\n *\n * @private\n */\nfunction receiverOnDrain() {\n const websocket = this[kWebSocket];\n\n if (!websocket.isPaused) websocket._socket.resume();\n}\n\n/**\n * The listener of the `Receiver` `'error'` event.\n *\n * @param {(RangeError|Error)} err The emitted error\n * @private\n */\nfunction receiverOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket._socket[kWebSocket] !== undefined) {\n websocket._socket.removeListener('data', socketOnData);\n\n //\n // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See\n // https://github.com/websockets/ws/issues/1940.\n //\n process.nextTick(resume, websocket._socket);\n\n websocket.close(err[kStatusCode]);\n }\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'finish'` event.\n *\n * @private\n */\nfunction receiverOnFinish() {\n this[kWebSocket].emitClose();\n}\n\n/**\n * The listener of the `Receiver` `'message'` event.\n *\n * @param {Buffer|ArrayBuffer|Buffer[])} data The message\n * @param {Boolean} isBinary Specifies whether the message is binary or not\n * @private\n */\nfunction receiverOnMessage(data, isBinary) {\n this[kWebSocket].emit('message', data, isBinary);\n}\n\n/**\n * The listener of the `Receiver` `'ping'` event.\n *\n * @param {Buffer} data The data included in the ping frame\n * @private\n */\nfunction receiverOnPing(data) {\n const websocket = this[kWebSocket];\n\n if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);\n websocket.emit('ping', data);\n}\n\n/**\n * The listener of the `Receiver` `'pong'` event.\n *\n * @param {Buffer} data The data included in the pong frame\n * @private\n */\nfunction receiverOnPong(data) {\n this[kWebSocket].emit('pong', data);\n}\n\n/**\n * Resume a readable stream\n *\n * @param {Readable} stream The readable stream\n * @private\n */\nfunction resume(stream) {\n stream.resume();\n}\n\n/**\n * The `Sender` error event handler.\n *\n * @param {Error} The error\n * @private\n */\nfunction senderOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket.readyState === WebSocket.CLOSED) return;\n if (websocket.readyState === WebSocket.OPEN) {\n websocket._readyState = WebSocket.CLOSING;\n setCloseTimer(websocket);\n }\n\n //\n // `socket.end()` is used instead of `socket.destroy()` to allow the other\n // peer to finish sending queued data. There is no need to set a timer here\n // because `CLOSING` means that it is already set or not needed.\n //\n this._socket.end();\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * Set a timer to destroy the underlying raw socket of a WebSocket.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @private\n */\nfunction setCloseTimer(websocket) {\n websocket._closeTimer = setTimeout(\n websocket._socket.destroy.bind(websocket._socket),\n websocket._closeTimeout\n );\n}\n\n/**\n * The listener of the socket `'close'` event.\n *\n * @private\n */\nfunction socketOnClose() {\n const websocket = this[kWebSocket];\n\n this.removeListener('close', socketOnClose);\n this.removeListener('data', socketOnData);\n this.removeListener('end', socketOnEnd);\n\n websocket._readyState = WebSocket.CLOSING;\n\n //\n // The close frame might not have been received or the `'end'` event emitted,\n // for example, if the socket was destroyed due to an error. Ensure that the\n // `receiver` stream is closed after writing any remaining buffered data to\n // it. If the readable side of the socket is in flowing mode then there is no\n // buffered data as everything has been already written. If instead, the\n // socket is paused, any possible buffered data will be read as a single\n // chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n this._readableState.length !== 0\n ) {\n const chunk = this.read(this._readableState.length);\n\n websocket._receiver.write(chunk);\n }\n\n websocket._receiver.end();\n\n this[kWebSocket] = undefined;\n\n clearTimeout(websocket._closeTimer);\n\n if (\n websocket._receiver._writableState.finished ||\n websocket._receiver._writableState.errorEmitted\n ) {\n websocket.emitClose();\n } else {\n websocket._receiver.on('error', receiverOnFinish);\n websocket._receiver.on('finish', receiverOnFinish);\n }\n}\n\n/**\n * The listener of the socket `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction socketOnData(chunk) {\n if (!this[kWebSocket]._receiver.write(chunk)) {\n this.pause();\n }\n}\n\n/**\n * The listener of the socket `'end'` event.\n *\n * @private\n */\nfunction socketOnEnd() {\n const websocket = this[kWebSocket];\n\n websocket._readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}\n\n/**\n * The listener of the socket `'error'` event.\n *\n * @private\n */\nfunction socketOnError() {\n const websocket = this[kWebSocket];\n\n this.removeListener('error', socketOnError);\n this.on('error', NOOP);\n\n if (websocket) {\n websocket._readyState = WebSocket.CLOSING;\n this.destroy();\n }\n}\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^WebSocket$\" }] */\n'use strict';\n\nconst WebSocket = require('./websocket');\nconst { Duplex } = require('stream');\n\n/**\n * Emits the `'close'` event on a stream.\n *\n * @param {Duplex} stream The stream.\n * @private\n */\nfunction emitClose(stream) {\n stream.emit('close');\n}\n\n/**\n * The listener of the `'end'` event.\n *\n * @private\n */\nfunction duplexOnEnd() {\n if (!this.destroyed && this._writableState.finished) {\n this.destroy();\n }\n}\n\n/**\n * The listener of the `'error'` event.\n *\n * @param {Error} err The error\n * @private\n */\nfunction duplexOnError(err) {\n this.removeListener('error', duplexOnError);\n this.destroy();\n if (this.listenerCount('error') === 0) {\n // Do not suppress the throwing behavior.\n this.emit('error', err);\n }\n}\n\n/**\n * Wraps a `WebSocket` in a duplex stream.\n *\n * @param {WebSocket} ws The `WebSocket` to wrap\n * @param {Object} [options] The options for the `Duplex` constructor\n * @return {Duplex} The duplex stream\n * @public\n */\nfunction createWebSocketStream(ws, options) {\n let terminateOnDestroy = true;\n\n const duplex = new Duplex({\n ...options,\n autoDestroy: false,\n emitClose: false,\n objectMode: false,\n writableObjectMode: false\n });\n\n ws.on('message', function message(msg, isBinary) {\n const data =\n !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;\n\n if (!duplex.push(data)) ws.pause();\n });\n\n ws.once('error', function error(err) {\n if (duplex.destroyed) return;\n\n // Prevent `ws.terminate()` from being called by `duplex._destroy()`.\n //\n // - If the `'error'` event is emitted before the `'open'` event, then\n // `ws.terminate()` is a noop as no socket is assigned.\n // - Otherwise, the error is re-emitted by the listener of the `'error'`\n // event of the `Receiver` object. The listener already closes the\n // connection by calling `ws.close()`. This allows a close frame to be\n // sent to the other peer. If `ws.terminate()` is called right after this,\n // then the close frame might not be sent.\n terminateOnDestroy = false;\n duplex.destroy(err);\n });\n\n ws.once('close', function close() {\n if (duplex.destroyed) return;\n\n duplex.push(null);\n });\n\n duplex._destroy = function (err, callback) {\n if (ws.readyState === ws.CLOSED) {\n callback(err);\n process.nextTick(emitClose, duplex);\n return;\n }\n\n let called = false;\n\n ws.once('error', function error(err) {\n called = true;\n callback(err);\n });\n\n ws.once('close', function close() {\n if (!called) callback(err);\n process.nextTick(emitClose, duplex);\n });\n\n if (terminateOnDestroy) ws.terminate();\n };\n\n duplex._final = function (callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._final(callback);\n });\n return;\n }\n\n // If the value of the `_socket` property is `null` it means that `ws` is a\n // client websocket and the handshake failed. In fact, when this happens, a\n // socket is never assigned to the websocket. Wait for the `'error'` event\n // that will be emitted by the websocket.\n if (ws._socket === null) return;\n\n if (ws._socket._writableState.finished) {\n callback();\n if (duplex._readableState.endEmitted) duplex.destroy();\n } else {\n ws._socket.once('finish', function finish() {\n // `duplex` is not destroyed here because the `'end'` event will be\n // emitted on `duplex` after this `'finish'` event. The EOF signaling\n // `null` chunk is, in fact, pushed when the websocket emits `'close'`.\n callback();\n });\n ws.close();\n }\n };\n\n duplex._read = function () {\n if (ws.isPaused) ws.resume();\n };\n\n duplex._write = function (chunk, encoding, callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._write(chunk, encoding, callback);\n });\n return;\n }\n\n ws.send(chunk, callback);\n };\n\n duplex.on('end', duplexOnEnd);\n duplex.on('error', duplexOnError);\n return duplex;\n}\n\nmodule.exports = createWebSocketStream;\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.\n *\n * @param {String} header The field value of the header\n * @return {Set} The subprotocol names\n * @public\n */\nfunction parse(header) {\n const protocols = new Set();\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (i; i < header.length; i++) {\n const code = header.charCodeAt(i);\n\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n\n const protocol = header.slice(start, end);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n\n if (start === -1 || end !== -1) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n const protocol = header.slice(start, i);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n return protocols;\n}\n\nmodule.exports = { parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst http = require('http');\nconst { Duplex } = require('stream');\nconst { createHash } = require('crypto');\n\nconst extension = require('./extension');\nconst PerMessageDeflate = require('./permessage-deflate');\nconst subprotocol = require('./subprotocol');\nconst WebSocket = require('./websocket');\nconst { CLOSE_TIMEOUT, GUID, kWebSocket } = require('./constants');\n\nconst keyRegex = /^[+/0-9A-Za-z]{22}==$/;\n\nconst RUNNING = 0;\nconst CLOSING = 1;\nconst CLOSED = 2;\n\n/**\n * Class representing a WebSocket server.\n *\n * @extends EventEmitter\n */\nclass WebSocketServer extends EventEmitter {\n /**\n * Create a `WebSocketServer` instance.\n *\n * @param {Object} options Configuration options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.backlog=511] The maximum length of the queue of\n * pending connections\n * @param {Boolean} [options.clientTracking=true] Specifies whether or not to\n * track clients\n * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to\n * wait for the closing handshake to finish after `websocket.close()` is\n * called\n * @param {Function} [options.handleProtocols] A hook to handle protocols\n * @param {String} [options.host] The hostname where to bind the server\n * @param {Number} [options.maxBufferedChunks=262144] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=16384] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Boolean} [options.noServer=false] Enable no server mode\n * @param {String} [options.path] Accept only connections matching this path\n * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable\n * permessage-deflate\n * @param {Number} [options.port] The port where to bind the server\n * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S\n * server to use\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @param {Function} [options.verifyClient] A hook to reject connections\n * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`\n * class to use. It must be the `WebSocket` class or class that extends it\n * @param {Function} [callback] A listener for the `listening` event\n */\n constructor(options, callback) {\n super();\n\n options = {\n allowSynchronousEvents: true,\n autoPong: true,\n maxBufferedChunks: 256 * 1024,\n maxFragments: 16 * 1024,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: false,\n handleProtocols: null,\n clientTracking: true,\n closeTimeout: CLOSE_TIMEOUT,\n verifyClient: null,\n noServer: false,\n backlog: null, // use default (511 as implemented in net.js)\n server: null,\n host: null,\n path: null,\n port: null,\n WebSocket,\n ...options\n };\n\n if (\n (options.port == null && !options.server && !options.noServer) ||\n (options.port != null && (options.server || options.noServer)) ||\n (options.server && options.noServer)\n ) {\n throw new TypeError(\n 'One and only one of the \"port\", \"server\", or \"noServer\" options ' +\n 'must be specified'\n );\n }\n\n if (options.port != null) {\n this._server = http.createServer((req, res) => {\n const body = http.STATUS_CODES[426];\n\n res.writeHead(426, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain'\n });\n res.end(body);\n });\n this._server.listen(\n options.port,\n options.host,\n options.backlog,\n callback\n );\n } else if (options.server) {\n this._server = options.server;\n }\n\n if (this._server) {\n const emitConnection = this.emit.bind(this, 'connection');\n\n this._removeListeners = addListeners(this._server, {\n listening: this.emit.bind(this, 'listening'),\n error: this.emit.bind(this, 'error'),\n upgrade: (req, socket, head) => {\n this.handleUpgrade(req, socket, head, emitConnection);\n }\n });\n }\n\n if (options.perMessageDeflate === true) options.perMessageDeflate = {};\n if (options.clientTracking) {\n this.clients = new Set();\n this._shouldEmitClose = false;\n }\n\n this.options = options;\n this._state = RUNNING;\n }\n\n /**\n * Returns the bound address, the address family name, and port of the server\n * as reported by the operating system if listening on an IP socket.\n * If the server is listening on a pipe or UNIX domain socket, the name is\n * returned as a string.\n *\n * @return {(Object|String|null)} The address of the server\n * @public\n */\n address() {\n if (this.options.noServer) {\n throw new Error('The server is operating in \"noServer\" mode');\n }\n\n if (!this._server) return null;\n return this._server.address();\n }\n\n /**\n * Stop the server from accepting new connections and emit the `'close'` event\n * when all existing connections are closed.\n *\n * @param {Function} [cb] A one-time listener for the `'close'` event\n * @public\n */\n close(cb) {\n if (this._state === CLOSED) {\n if (cb) {\n this.once('close', () => {\n cb(new Error('The server is not running'));\n });\n }\n\n process.nextTick(emitClose, this);\n return;\n }\n\n if (cb) this.once('close', cb);\n\n if (this._state === CLOSING) return;\n this._state = CLOSING;\n\n if (this.options.noServer || this.options.server) {\n if (this._server) {\n this._removeListeners();\n this._removeListeners = this._server = null;\n }\n\n if (this.clients) {\n if (!this.clients.size) {\n process.nextTick(emitClose, this);\n } else {\n this._shouldEmitClose = true;\n }\n } else {\n process.nextTick(emitClose, this);\n }\n } else {\n const server = this._server;\n\n this._removeListeners();\n this._removeListeners = this._server = null;\n\n //\n // The HTTP/S server was created internally. Close it, and rely on its\n // `'close'` event.\n //\n server.close(() => {\n emitClose(this);\n });\n }\n }\n\n /**\n * See if a given request should be handled by this server instance.\n *\n * @param {http.IncomingMessage} req Request object to inspect\n * @return {Boolean} `true` if the request is valid, else `false`\n * @public\n */\n shouldHandle(req) {\n if (this.options.path) {\n const index = req.url.indexOf('?');\n const pathname = index !== -1 ? req.url.slice(0, index) : req.url;\n\n if (pathname !== this.options.path) return false;\n }\n\n return true;\n }\n\n /**\n * Handle a HTTP Upgrade request.\n *\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @public\n */\n handleUpgrade(req, socket, head, cb) {\n socket.on('error', socketOnError);\n\n const key = req.headers['sec-websocket-key'];\n const upgrade = req.headers.upgrade;\n const version = +req.headers['sec-websocket-version'];\n\n if (req.method !== 'GET') {\n const message = 'Invalid HTTP method';\n abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);\n return;\n }\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n const message = 'Invalid Upgrade header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (key === undefined || !keyRegex.test(key)) {\n const message = 'Missing or invalid Sec-WebSocket-Key header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (version !== 13 && version !== 8) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {\n 'Sec-WebSocket-Version': '13, 8'\n });\n return;\n }\n\n if (!this.shouldHandle(req)) {\n abortHandshake(socket, 400);\n return;\n }\n\n const secWebSocketProtocol = req.headers['sec-websocket-protocol'];\n let protocols = new Set();\n\n if (secWebSocketProtocol !== undefined) {\n try {\n protocols = subprotocol.parse(secWebSocketProtocol);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Protocol header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n const secWebSocketExtensions = req.headers['sec-websocket-extensions'];\n const extensions = {};\n\n if (\n this.options.perMessageDeflate &&\n secWebSocketExtensions !== undefined\n ) {\n const perMessageDeflate = new PerMessageDeflate({\n ...this.options.perMessageDeflate,\n isServer: true,\n maxPayload: this.options.maxPayload\n });\n\n try {\n const offers = extension.parse(secWebSocketExtensions);\n\n if (offers[PerMessageDeflate.extensionName]) {\n perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);\n extensions[PerMessageDeflate.extensionName] = perMessageDeflate;\n }\n } catch (err) {\n const message =\n 'Invalid or unacceptable Sec-WebSocket-Extensions header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n //\n // Optionally call external client verification handler.\n //\n if (this.options.verifyClient) {\n const info = {\n origin:\n req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],\n secure: !!(req.socket.authorized || req.socket.encrypted),\n req\n };\n\n if (this.options.verifyClient.length === 2) {\n this.options.verifyClient(info, (verified, code, message, headers) => {\n if (!verified) {\n return abortHandshake(socket, code || 401, message, headers);\n }\n\n this.completeUpgrade(\n extensions,\n key,\n protocols,\n req,\n socket,\n head,\n cb\n );\n });\n return;\n }\n\n if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);\n }\n\n this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);\n }\n\n /**\n * Upgrade the connection to WebSocket.\n *\n * @param {Object} extensions The accepted extensions\n * @param {String} key The value of the `Sec-WebSocket-Key` header\n * @param {Set} protocols The subprotocols\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @throws {Error} If called more than once with the same socket\n * @private\n */\n completeUpgrade(extensions, key, protocols, req, socket, head, cb) {\n //\n // Destroy the socket if the client has already sent a FIN packet.\n //\n if (!socket.readable || !socket.writable) return socket.destroy();\n\n if (socket[kWebSocket]) {\n throw new Error(\n 'server.handleUpgrade() was called more than once with the same ' +\n 'socket, possibly due to a misconfiguration'\n );\n }\n\n if (this._state > RUNNING) return abortHandshake(socket, 503);\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n const headers = [\n 'HTTP/1.1 101 Switching Protocols',\n 'Upgrade: websocket',\n 'Connection: Upgrade',\n `Sec-WebSocket-Accept: ${digest}`\n ];\n\n const ws = new this.options.WebSocket(null, undefined, this.options);\n\n if (protocols.size) {\n //\n // Optionally call external protocol selection handler.\n //\n const protocol = this.options.handleProtocols\n ? this.options.handleProtocols(protocols, req)\n : protocols.values().next().value;\n\n if (protocol) {\n headers.push(`Sec-WebSocket-Protocol: ${protocol}`);\n ws._protocol = protocol;\n }\n }\n\n if (extensions[PerMessageDeflate.extensionName]) {\n const params = extensions[PerMessageDeflate.extensionName].params;\n const value = extension.format({\n [PerMessageDeflate.extensionName]: [params]\n });\n headers.push(`Sec-WebSocket-Extensions: ${value}`);\n ws._extensions = extensions;\n }\n\n //\n // Allow external modification/inspection of handshake headers.\n //\n this.emit('headers', headers, req);\n\n socket.write(headers.concat('\\r\\n').join('\\r\\n'));\n socket.removeListener('error', socketOnError);\n\n ws.setSocket(socket, head, {\n allowSynchronousEvents: this.options.allowSynchronousEvents,\n maxBufferedChunks: this.options.maxBufferedChunks,\n maxFragments: this.options.maxFragments,\n maxPayload: this.options.maxPayload,\n skipUTF8Validation: this.options.skipUTF8Validation\n });\n\n if (this.clients) {\n this.clients.add(ws);\n ws.on('close', () => {\n this.clients.delete(ws);\n\n if (this._shouldEmitClose && !this.clients.size) {\n process.nextTick(emitClose, this);\n }\n });\n }\n\n cb(ws, req);\n }\n}\n\nmodule.exports = WebSocketServer;\n\n/**\n * Add event listeners on an `EventEmitter` using a map of <event, listener>\n * pairs.\n *\n * @param {EventEmitter} server The event emitter\n * @param {Object.<String, Function>} map The listeners to add\n * @return {Function} A function that will remove the added listeners when\n * called\n * @private\n */\nfunction addListeners(server, map) {\n for (const event of Object.keys(map)) server.on(event, map[event]);\n\n return function removeListeners() {\n for (const event of Object.keys(map)) {\n server.removeListener(event, map[event]);\n }\n };\n}\n\n/**\n * Emit a `'close'` event on an `EventEmitter`.\n *\n * @param {EventEmitter} server The event emitter\n * @private\n */\nfunction emitClose(server) {\n server._state = CLOSED;\n server.emit('close');\n}\n\n/**\n * Handle socket errors.\n *\n * @private\n */\nfunction socketOnError() {\n this.destroy();\n}\n\n/**\n * Close the connection when preconditions are not fulfilled.\n *\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} [message] The HTTP response body\n * @param {Object} [headers] Additional HTTP response headers\n * @private\n */\nfunction abortHandshake(socket, code, message, headers) {\n //\n // The socket is writable unless the user destroyed or ended it before calling\n // `server.handleUpgrade()` or in the `verifyClient` function, which is a user\n // error. Handling this does not make much sense as the worst that can happen\n // is that some of the data written by the user might be discarded due to the\n // call to `socket.end()` below, which triggers an `'error'` event that in\n // turn causes the socket to be destroyed.\n //\n message = message || http.STATUS_CODES[code];\n headers = {\n Connection: 'close',\n 'Content-Type': 'text/html',\n 'Content-Length': Buffer.byteLength(message),\n ...headers\n };\n\n socket.once('finish', socket.destroy);\n\n socket.end(\n `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\\r\\n` +\n Object.keys(headers)\n .map((h) => `${h}: ${headers[h]}`)\n .join('\\r\\n') +\n '\\r\\n\\r\\n' +\n message\n );\n}\n\n/**\n * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least\n * one listener for it, otherwise call `abortHandshake()`.\n *\n * @param {WebSocketServer} server The WebSocket server\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} message The HTTP response body\n * @param {Object} [headers] The HTTP response headers\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(\n server,\n req,\n socket,\n code,\n message,\n headers\n) {\n if (server.listenerCount('wsClientError')) {\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);\n\n server.emit('wsClientError', err, socket, req);\n } else {\n abortHandshake(socket, code, message, headers);\n }\n}\n","import createWebSocketStream from './lib/stream.js';\nimport extension from './lib/extension.js';\nimport PerMessageDeflate from './lib/permessage-deflate.js';\nimport Receiver from './lib/receiver.js';\nimport Sender from './lib/sender.js';\nimport subprotocol from './lib/subprotocol.js';\nimport WebSocket from './lib/websocket.js';\nimport WebSocketServer from './lib/websocket-server.js';\n\nexport {\n createWebSocketStream,\n extension,\n PerMessageDeflate,\n Receiver,\n Sender,\n subprotocol,\n WebSocket,\n WebSocketServer\n};\n\nexport default WebSocket;\n","/**\n * Dial-out WS transport seam — the no-real-socket boundary a client FSM depends\n * on, so tests inject a fake. {@link ClientTransport} is the production impl: it\n * DIALS OUT (the daemon/relay connects to its peer, never the reverse), resolves\n * once the socket is open, and arms a receive-idle watchdog to detect a half-open\n * peer. Wire-agnostic: the subprotocol and dial path are passed in, so the same\n * transport serves the daemon↔CP, relay↔CP, and relay↔daemon wires.\n */\nimport WebSocket from 'ws';\nimport { MAX_FRAME_BYTES } from '@agentconnect.md/protocol';\n// ws has NO default handshake timeout: against a black-holing host a dial can\n// hang past the OS connect timeout (or forever if TCP connects but the 101 never\n// arrives), stalling the reconnect loop on one attempt.\nconst DEFAULT_HANDSHAKE_TIMEOUT_MS = 10_000;\n// rx-idle watchdog: self-ping this often, and terminate if nothing has arrived\n// from the peer for IDLE_MS. The heartbeat is send-only, so a half-open socket\n// (peer gone without a FIN) is otherwise invisible until the OS TCP timeout\n// (~minutes). The peer auto-pongs, so the self-ping alone refreshes liveness.\nconst DEFAULT_SELF_PING_MS = 15_000;\nconst DEFAULT_RX_IDLE_MS = 45_000;\n/**\n * Arm a receive-idle watchdog on an open socket: every `selfPingMs` send a ping\n * (the peer auto-pongs, which counts as inbound), and if NOTHING has arrived for\n * `idleMs`, `terminate()` the socket — routing a dead half-open connection into\n * the normal `close` → reconnect path. Any inbound frame (message/ping/pong)\n * resets the idle clock. Cleared on `close`. Kept off the FSM's injected Clock so\n * it never perturbs the fake-clock client tests.\n */\nexport function armRxWatchdog(ws, opts) {\n const now = opts.now ?? (() => Date.now());\n const setIv = opts.setInterval ?? ((fn, ms) => globalThis.setInterval(fn, ms));\n const clearIv = opts.clearInterval ?? ((h) => globalThis.clearInterval(h));\n let lastRx = now();\n const touch = () => {\n lastRx = now();\n };\n ws.on('message', touch);\n ws.on('ping', touch);\n ws.on('pong', touch);\n const timer = setIv(() => {\n if (now() - lastRx > opts.idleMs) {\n ws.terminate();\n return;\n }\n if (ws.readyState === ws.OPEN)\n ws.ping();\n }, opts.selfPingMs);\n if (typeof timer.unref === 'function')\n timer.unref();\n ws.on('close', () => clearIv(timer));\n}\nexport class ClientTransport {\n ws;\n get subprotocol() {\n return this.ws.protocol;\n }\n constructor(ws, selfPingMs, idleMs) {\n this.ws = ws;\n // Detect a half-open peer socket (gone without a FIN) and force a reconnect,\n // instead of silently queueing heartbeats until the OS TCP timeout.\n armRxWatchdog(ws, { selfPingMs, idleMs });\n }\n /**\n * Dial `<url normalized to end in opts.path>` with `opts.subprotocol`.\n * Resolves once the socket is open; rejects on any error before open\n * (refused, bad handshake/subprotocol → HTTP 400).\n */\n static dial(url, opts) {\n const wsUrl = url.endsWith(opts.path) ? url : url.replace(/\\/+$/, '') + opts.path;\n const selfPingMs = opts.selfPingMs ?? DEFAULT_SELF_PING_MS;\n const idleMs = opts.idleMs ?? DEFAULT_RX_IDLE_MS;\n return new Promise((resolve, reject) => {\n const ws = new WebSocket(wsUrl, [opts.subprotocol], {\n maxPayload: MAX_FRAME_BYTES,\n handshakeTimeout: opts.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS\n });\n const onPreOpenError = (err) => {\n ws.removeAllListeners();\n reject(err);\n };\n ws.once('error', onPreOpenError);\n ws.once('open', () => {\n ws.removeListener('error', onPreOpenError);\n // Post-open socket errors (ETIMEDOUT on a half-open connection after the\n // peer dies without a FIN, an oversized frame, a mid-stream reset) MUST\n // NOT surface as an unhandled 'error' event — that crashes the process\n // (only unhandledRejection is trapped). Fold them into the close path:\n // terminate() emits 'close', and the client FSM reconnects from there.\n ws.on('error', () => ws.terminate());\n resolve(new ClientTransport(ws, selfPingMs, idleMs));\n });\n });\n }\n send(text) {\n this.ws.send(text);\n }\n onMessage(cb) {\n this.ws.on('message', (data, isBinary) => {\n if (isBinary)\n return; // JSON text frames only (protocol §1)\n cb(typeof data === 'string' ? data : String(data));\n });\n }\n onClose(cb) {\n this.ws.on('close', (code, reason) => cb(code, reason.toString()));\n }\n close(code, reason) {\n this.ws.close(code, reason);\n }\n}\n//# sourceMappingURL=ws-client-transport.js.map","import { spawn } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { cliEntryPointer } from '../paths.js'\n\nexport interface UpgradeLog {\n info(message: string): void\n error(message: string): void\n}\n\n/** Resolve the stable CLI entry that owns the daemon version store. */\nexport function readCliEntry(root: string): string | undefined {\n try {\n const entry = readFileSync(cliEntryPointer(root), 'utf8').trim()\n return entry && existsSync(entry) ? entry : undefined\n } catch {\n return undefined\n }\n}\n\n/** Install and atomically activate one CP-selected daemon version. */\nexport async function runCliUpgrade(\n cliEntry: string,\n targetVersion: string,\n root: string,\n log: UpgradeLog\n): Promise<boolean> {\n log.info(`cp: installing daemon ${targetVersion} via ${cliEntry}`)\n return await new Promise<boolean>((resolve) => {\n const child = spawn(process.execPath, [cliEntry, 'upgrade', '--to', targetVersion, '--root', root], {\n stdio: 'inherit'\n })\n child.on('exit', (code) => {\n if (code === 0) log.info(`cp: daemon ${targetVersion} installed and activated`)\n else log.error(`cp: CLI upgrade exited ${code ?? 'via signal'}`)\n resolve(code === 0)\n })\n child.on('error', (err) => {\n log.error(`cp: could not launch CLI upgrade: ${err.message}`)\n resolve(false)\n })\n })\n}\n"],"x_google_ignoreList":[15,16,17,18,19,20,21,22,23,24,25,26,27,28],"mappings":";;;;;;;;;;;;;;;;;;AAUA,MAAa,WAAWA,OAAS;CAC7B,GAAGC,QAAU,CAAC;CACd,IAAIC,OAAS,CAAC,CAAC,KAAK;CACpB,IAAIA,OAAS,CAAC,CAAC,SAAS;CACxB,MAAMA,OAAS;CACf,MAAMA,OAAS,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS;CACjC,OAAOA,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,SAAS;CAC1C,SAASC,QAAU;AACvB,CAAC;AASyBH,OAAS;CAC/B,OAAOI,OAAS,CAAC,CAAC,IAAI;CACtB,SAASF,OAAS,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS;CACpC,UAAUA,OAAS,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS;AACzC,CAAC;;AAED,MAAa,WAAW;;;;;;;;AAQ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,IAAI;EACR,KAAK,GAAG,GAAG,UAAU,MAAM,WAAW,GAAG,MAAM,OAAO,SAAS,CAAC,CAAC;CACrE;CACA,MAAM,MAAM,QAAQ;EAChB,KAAK,GAAG,MAAM,MAAM,MAAM;CAC9B;AACJ;;;;ACnGA,SAAgB,aAAa,MAAkC;CAC7D,IAAI;EACF,MAAM,QAAQ,aAAa,gBAAgB,IAAI,GAAG,MAAM,CAAC,CAAC,KAAK;EAC/D,OAAO,SAAS,WAAW,KAAK,IAAI,QAAQ,KAAA;CAC9C,QAAQ;EACN;CACF;AACF;;AAGA,eAAsB,cACpB,UACA,eACA,MACA,KACkB;CAClB,IAAI,KAAK,yBAAyB,cAAc,OAAO,UAAU;CACjE,OAAO,MAAM,IAAI,SAAkB,YAAY;EAC7C,MAAM,QAAQ,MAAM,QAAQ,UAAU;GAAC;GAAU;GAAW;GAAQ;GAAe;GAAU;EAAI,GAAG,EAClG,OAAO,UACT,CAAC;EACD,MAAM,GAAG,SAAS,SAAS;GACzB,IAAI,SAAS,GAAG,IAAI,KAAK,cAAc,cAAc,yBAAyB;QACzE,IAAI,MAAM,0BAA0B,QAAQ,cAAc;GAC/D,QAAQ,SAAS,CAAC;EACpB,CAAC;EACD,MAAM,GAAG,UAAU,QAAQ;GACzB,IAAI,MAAM,qCAAqC,IAAI,SAAS;GAC5D,QAAQ,KAAK;EACf,CAAC;CACH,CAAC;AACH"}
1
+ {"version":3,"file":"cli-upgrade-C0m01RLc.js","names":["z.object","z.literal","z.string","z.unknown","z.number","z.object","z.string","z.literal","z\n .object","z.number","z.enum","z.boolean","z.string","z.object","z.enum","z.array","z.number","z\n .array","z.boolean","z.enum","z\n .object","z.string","z.object","z.boolean","z.array","z.object","z.string","z.enum","z.array","z.enum","z.object","z.string","z.number","z.boolean","z.array","z\n .string","z\n .array","z.enum","z.object","z.string","z.boolean","z.array","z.object","z.number","z.enum","z.array","z.string","z.discriminatedUnion","z.literal","z.boolean","z.record","z.unknown","z.enum","z.object","z.string","z.boolean","z.record","z.unknown","z\n .object","z.string","z.number","z.boolean","z.enum","z.object","z.literal","z.string","z.discriminatedUnion","EventEmitter","http","randomBytes","createHash","Duplex","createHash","WebSocket","WebSocket"],"sources":["../../protocol/dist/envelope.js","../../protocol/dist/frames/auth.js","../../protocol/dist/frames/duty.js","../../protocol/dist/frames/skill.js","../../protocol/dist/frames/channel.js","../../protocol/dist/frames/workspace.js","../../protocol/dist/frames/task.js","../../protocol/dist/frames/telemetry.js","../../protocol/dist/frames/error.js","../../protocol/dist/frames/remote-mcp.js","../../protocol/dist/frame.js","../../protocol/dist/wire.js","../../protocol/dist/codec.js","../../connection/dist/clock.js","../../connection/dist/correlator.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/constants.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/buffer-util.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/limiter.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/permessage-deflate.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/validation.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/receiver.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/sender.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/event-target.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/extension.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/websocket.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/stream.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/subprotocol.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/websocket-server.js","../../../node_modules/.pnpm/ws@8.21.1/node_modules/ws/wrapper.mjs","../../connection/dist/ws-client-transport.js","../src/lifecycle/cli-upgrade.ts"],"sourcesContent":["import { z } from 'zod';\n/**\n * The protocol envelope — every frame, both directions, is wrapped in this.\n * Mirrors daemon-cp-ws-protocol.md §1.1.\n *\n * `payload` is left as `unknown` here and validated by the per-type schema in\n * `frames/*` via `FRAME_SCHEMAS[type]` (see `frame.ts`). This two-step parse is\n * what lets the codec answer an unknown `type` with `UNKNOWN_FRAME` (a REP)\n * instead of a hard close — forward-compat, protocol §1.\n */\nexport const Envelope = z.object({\n v: z.literal(1), // protocol major; bump = breaking\n id: z.string().uuid(), // unique per frame (sender-generated)\n ts: z.string().datetime(), // RFC3339, sender clock (advisory only)\n type: z.string(), // frame discriminator, e.g. \"register\"\n corr: z.string().uuid().optional(), // correlation: set on a reply to the request's `id`\n orgId: z.string().min(1).max(64).optional(), // tenant context on an install-wide daemon connection\n payload: z.unknown() // validated by the per-type schema\n});\n/**\n * Control-frame envelope extension — protocol §4.2.\n *\n * Fenced C→D frames carry this block alongside `payload`. It is the fencing\n * surface: `epoch` (sessionEpoch this frame was issued under), the `agentId` an\n * agent-scoped frame belongs to, and the `launchId` fence. Daemon validation\n * order: epoch → launchId.\n */\nexport const ControlExt = z.object({\n epoch: z.number().int(), // sessionEpoch this frame was issued under (§3.1 fencing)\n agentId: z.string().uuid().optional(), // present on agent-scoped frames\n launchId: z.string().uuid().optional() // per-launch fence, §4.4\n});\n/** The all-zero UUID used when a frame is malformed past the point of reading `id`. */\nexport const NIL_UUID = '00000000-0000-0000-0000-000000000000';\n/**\n * Builds the envelope schema for one frame `type` — the `type` literal plus the\n * typed payload — so a wire's discriminated union infers `payload` precisely.\n * Shared by the daemon↔CP union (`frame.ts`) and the relay wire unions\n * (`frames/relay-cp.ts` / `frames/relay-daemon.ts`), which are deliberately\n * SEPARATE unions over the same envelope shape (shared-bot-relay.md §8).\n */\nexport function frameSchema(type, payload) {\n return z.object({\n v: z.literal(1),\n id: z.string().uuid(),\n ts: z.string().datetime(),\n type: z.literal(type),\n corr: z.string().uuid().optional(),\n orgId: z.string().min(1).max(64).optional(),\n payload\n });\n}\n//# sourceMappingURL=envelope.js.map","import { z } from 'zod';\n/**\n * Auth & identity — protocol §3.1 / §3.2.\n *\n * `auth` is the first frame after the socket opens. `auth/ok` carries the\n * minted `sessionEpoch` (the global fencing token), heartbeat cadence, and the\n * resume verdict.\n */\nexport const AuthReq = z.object({\n // Long-lived, revocable API key — a bare opaque `<secret><crc>`, hashed at rest and looked up\n // by that unique hash (see docs/designs/daemon-api-key-auth.md). A daemon with no Kubernetes\n // identity carries this; an in-cluster one sends `serviceAccountToken` instead.\n apiKey: z.string().optional(),\n // Projected ServiceAccount token of an operator-provisioned daemon pod, audience-scoped to\n // CP_TOKEN_AUDIENCE and verified by TokenReview against the org's cluster (see \"Daemon\n // identity\" in docs/designs/agentconnect-org-operator.md). Takes precedence over `apiKey`.\n serviceAccountToken: z.string().optional(),\n // Optional echo of the daemonId. If present it must equal the daemonId the ApiKey row\n // resolves to; otherwise the daemon adopts the authoritative id from `auth/ok`.\n daemonId: z.string().uuid().optional(),\n machineId: z.string().uuid().optional(), // 🅼 machine identity (scope-attestation, §3.2) — NOT the auth credential\n attestation: z.string().optional(), // 🅼 signed proof (JWS), §3.2\n agentVersion: z.string(), // daemon build/version\n // Auth-time lifecycle support; optional for rolling compatibility.\n bootstrapProtocolVersion: z.literal(1).optional(),\n resume: z\n .object({\n lastEpoch: z.number().int() // sessionEpoch the daemon last held\n })\n .optional()\n});\nexport const BootstrapLifecycle = z.object({\n operationId: z.string(),\n action: z.literal('upgrade'),\n targetVersion: z.string()\n});\nexport const AuthOk = z.object({\n daemonId: z.string().uuid(),\n sessionEpoch: z.number().int(), // monotonic; bumped each successful (re)auth — fencing token\n heartbeatSec: z.number().int(), // cadence the daemon must emit heartbeat at\n // How long the CP keeps a duty lease alive past the last heartbeat it renewed from\n // (T_reassign). The member self-fences strictly earlier, so it must be told the CP's\n // own value rather than duplicate it. Optional: an older CP omits it.\n dutyLeaseMs: z.number().int().positive().optional(),\n serverTime: z.string().datetime(),\n // Single-org daemons inherit tenant context from auth; install-wide pool members require\n // every org-scoped post-auth frame to carry `Envelope.orgId`.\n organizationMode: z.enum(['connection', 'frame']).default('connection'),\n // Base URL of the Web App console (the CP's own public origin), so the daemon can build\n // session deep links without local config. Omitted when the CP has no console URL\n // configured; a daemon-local `webAppUrl` overrides it.\n webAppUrl: z.string().optional(),\n // Slug of the org this daemon's api key belongs to. The console is org-scoped\n // (`<webAppUrl>/<orgSlug>/sessions/<id>`), so the daemon needs it to build a link that\n // resolves. Omitted when the CP can't resolve it; then the daemon drops the segment.\n orgSlug: z.string().optional(),\n // Durable upgrade intent returned only to bootstrap-capable callers.\n lifecycle: BootstrapLifecycle.optional(),\n resume: z\n .object({\n accepted: z.boolean() // false ⇒ daemon must do a full register reconcile\n })\n .optional()\n});\n//# sourceMappingURL=auth.js.map","// Duty lease wire (k8s daemons). The exchange rides the existing heartbeat\n// cadence: the heartbeat's optional `duties` field carries the member's held\n// digest and remaining headroom; the CP answers — only when there is something\n// to say — with `duty/grant` and `duty/revoke` EVTs on the same connection, and\n// a draining member returns groups explicitly with the `duty/release` REQ.\n// Single-org daemons never send `duties`, which keeps the whole path dormant.\nimport { z } from 'zod';\nimport { AgentSpec } from './agent.js';\nimport { IntegrationSpec } from './integration.js';\nimport { CronUpsert } from './cron.js';\nimport { McpServerSpec } from './mcpserver.js';\nimport { MemoryConnectionSpec } from './memory-connection.js';\n/** A per-group fencing term — bigint as a decimal string (JSON-safe). */\nexport const DutyTerm = z.string().regex(/^\\d+$/);\n/** One member of a duty group: an agent to serve or a daemon-held bot to connect.\n * `configRevision` is the freshness signal for AGENT members — the CP's current\n * `AgentSpec.configRevision` — so a member that already has the agent can tell a\n * current replica from a frozen one and refetch only the frozen ones. Optional:\n * an older CP omits it and the member falls back to presence alone. */\nexport const DutyMemberRef = z.object({\n kind: z.enum(['agent', 'bot']),\n refId: z.string().uuid(),\n configRevision: z.string().regex(/^\\d+$/).optional()\n});\n/** Hard cap on one grant entry's member list. A connected component past this is\n * not deliverable over this wire at all — it is the dedicated-tier signal, and\n * the CP refuses to grant it rather than emit a frame the daemon must reject. */\nexport const DUTY_GRANT_MEMBERS_MAX = 1000;\n/** The heartbeat's lease fields: what I hold (with the terms I believe), and\n * how many more groups I will accept. Capacity gating is member-side. */\nexport const HeartbeatDuties = z.object({\n held: z.array(z.object({ groupId: z.string().uuid(), term: DutyTerm })).max(1000),\n headroom: z.number().int().min(0)\n});\n/** One granted (or re-confirmed) duty group. A groupId the daemon already holds\n * REPLACES its entry — a bumped term after a composition change, or a term the\n * daemon missed because the original grant EVT was lost. */\nexport const DutyGrantEntry = z.object({\n groupId: z.string().uuid(),\n orgId: z.string().min(1).max(64),\n term: DutyTerm,\n members: z.array(DutyMemberRef).max(DUTY_GRANT_MEMBERS_MAX)\n});\n/** C→D EVT: duties granted to (or re-confirmed for) this member. */\nexport const DutyGrant = z.object({\n grants: z.array(DutyGrantEntry).min(1).max(100)\n});\n/**\n * C→D EVT: the renewal the CP just performed for this member, emitted on every\n * duty-carrying heartbeat it actually processed. `leaseMs` is RELATIVE — \"the\n * leases I hold for you live this much longer, measured from when I renewed\n * them\" — so the daemon anchors its self-fence on RECEIPT and the two sides\n * never compare wall clocks. Receipt is strictly after the CP's renew, which is\n * what makes the daemon's deadline conservative and `T_reassign > T_fence`\n * sound. A beat the CP dropped produces no confirmation, so a member's fence\n * countdown keeps running — sending a beat is not renewing a lease.\n */\nexport const DutyRenewed = z.object({\n leaseMs: z.number().int().positive()\n});\n/** Why a held group is being taken away: `superseded` = another member holds it\n * now (term reassigned), `gone` = the group no longer exists (edges removed). */\nexport const DutyRevokeReason = z.enum(['superseded', 'gone']);\n/** C→D EVT: stop serving these groups and tear down their platform connections. */\nexport const DutyRevoke = z.object({\n revocations: z\n .array(z.object({ groupId: z.string().uuid(), reason: DutyRevokeReason }))\n .min(1)\n .max(1000)\n});\n/** D→C REQ (reply: generic `ack`): a draining member returns groups explicitly,\n * vacating them immediately instead of waiting out T_reassign. */\nexport const DutyRelease = z.object({\n groupIds: z.array(z.string().uuid()).min(1).max(1000)\n});\n/**\n * D→C REQ (reply: `duty/claim/ok`) — the activation rendezvous of the design's\n * §4.4. A member handed a trigger for an agent it does not serve claims that\n * agent's group on receipt: winning creates or takes the lease and it serves the\n * trigger; losing names the incumbent so the router can re-route. Idempotent for\n * the current holder, so a retry never churns a term.\n */\nexport const DutyClaim = z.object({\n agentId: z.string().uuid()\n});\n/** C→D REP to `duty/claim`. `granted` ⇒ `grant` carries the lease exactly as a\n * `duty/grant` entry would; otherwise `holder` names the live incumbent (absent\n * when the CP cannot resolve one, e.g. an unknown agent). */\nexport const DutyClaimOk = z.object({\n granted: z.boolean(),\n grant: DutyGrantEntry.optional(),\n holder: z.string().uuid().optional()\n});\n/**\n * D→C REQ (reply: `duty/fetch/ok`) — a grant opens the SERVING gate; it does not\n * install. A member that wins a duty for an agent it has never had pulls that\n * agent's definition here, so grants stay thin and a member asks only for what\n * it lacks. Holding the duty IS the authorization: the CP answers only for an\n * agent the asking daemon currently holds.\n */\nexport const DutyFetch = z.object({\n agentId: z.string().uuid()\n});\n/**\n * One agent's complete installable definition — the trio `agent/activate` carries,\n * without the move token or the staging fence, plus the two definition kinds the\n * spec only NAMES: the proxied MCP servers its `mcpServers` list enables and its\n * external-memory connection. Those arrive separately on the placement-keyed\n * paths, so a duty holder that is not the placement would otherwise install an\n * agent referencing tools and a memory backend it has no definitions for.\n *\n * Both are token-bearing (relay proxy url + grant key, memory grant + secret\n * leases) — NEVER log this bundle. They are scoped to what THIS agent references,\n * so the reply widens nothing beyond the duty the asker already holds. Optional\n * for decode tolerance: an older CP omits them and the member installs the trio.\n */\nexport const DutyAgentBundle = z.object({\n agentId: z.string().uuid(),\n spec: AgentSpec,\n integrations: z.array(IntegrationSpec),\n crons: z.array(CronUpsert),\n mcpServers: z.array(McpServerSpec).default([]),\n memoryConnections: z.array(MemoryConnectionSpec).default([])\n});\n/** C→D REP to `duty/fetch`. An absent `bundle` means the asker does not hold\n * this agent's duty, or the agent is gone — never an error frame, because\n * either way the correct member behavior is to install nothing. */\nexport const DutyFetchOk = z.object({\n bundle: DutyAgentBundle.optional()\n});\n//# sourceMappingURL=duty.js.map","import { z } from 'zod';\n// Read-only inventory of the skills an agent's materialized workspace can load,\n// so the console has one place to see them. Bodies stay daemon-local; this frame\n// carries only per-skill metadata (name, description, origin, path).\nexport const LocalSkillOrigin = z.enum(['dream-accepted', 'managed', 'git-source', 'repo']);\nexport const LocalSkillEntry = z\n .object({\n /** Skill name from SKILL.md frontmatter, falling back to the directory name. */\n name: z.string(),\n /** SKILL.md description, or null when absent/unparseable. */\n description: z.string().nullable(),\n origin: LocalSkillOrigin,\n /** Path relative to the workspace cwd, e.g. \".claude/skills/deploy\". */\n path: z.string()\n})\n .strict();\n/** CP → daemon: list the skills the agent's workspace can load. */\nexport const LocalSkillsReq = z.object({ agentId: z.string().min(1) }).strict();\n/** daemon → CP: the inventory. `materialized` is false when the agent's\n * workspace has not been prepared yet (so an empty list means \"unknown\", not\n * \"no skills\"). */\nexport const LocalSkillsList = z.object({ materialized: z.boolean(), skills: z.array(LocalSkillEntry) }).strict();\n//# sourceMappingURL=skill.js.map","import { z } from 'zod';\nimport { Platform } from './route.js';\n/**\n * Channel agent directory (D→C REQ → REP) — agent collaboration lookup.\n *\n * An agent asks (via a daemon-side tool) \"who else is in this channel?\". The\n * daemon forwards it to the CP — the ONLY authority for the FULL channel roster,\n * because agents in one channel may run on different daemons (each daemon knows\n * only its own agents). The CP joins the channel's integrations to their agents\n * and returns their public metadata (name / displayName / description / status).\n * Metadata only — never message content (§1/§12).\n *\n * Direction is daemon→CP (like `auth` / `register`): the daemon sends the REQ and\n * the CP replies with `channel/agents/ok` (corr = the req id).\n *\n * `channel` is OPTIONAL, and that is the whole scope switch:\n * - ABSENT → the ORG-WIDE peer directory. Channel membership plays no part; a\n * session with no IM integration at all (webchat, hook, dream) can still\n * discover peers.\n * - PRESENT → the same directory, ADDITIONALLY narrowed to agents present in that\n * channel. A filter, never a gate.\n * Only a CP advertising `agent-directory-org-scope-v1` understands the channel-less\n * form; against an older CP the daemon substitutes the caller's current channel\n * (today's behavior) rather than sending a payload that CP would reject.\n *\n * The REQ is bound to the requesting daemon's authenticated org AND to the\n * session-derived `requesterAgentId` (never a tool input — §2.2/§6.1). The roster is\n * POLICY-filtered, not membership-gated: an entry survives iff the caller's outbound\n * policy admits it and its own inbound `callPolicy` admits the caller, within the one\n * org (the caller always sees itself). Discovery IS the authorization surface — a peer\n * that fails the predicate is omitted entirely, never listed-but-uncallable — so an\n * agent still cannot probe peers it may not call, and cross-org never resolves.\n */\n/** One agent visible in a channel — the collaboration directory entry. */\nexport const ChannelAgent = z.object({\n agentId: z.string().uuid(),\n name: z.string(), // slug\n displayName: z.string().optional(), // human-readable name, if set\n description: z.string().optional(), // what the agent does (its system-prompt seed)\n status: z.enum(['active', 'inactive', 'paused']),\n /**\n * The exact platform-native address for this agent in the LISTED conversation —\n * `<@U_REVIEWER>` for a dedicated bot, `<@U_SHARED> reviewer` for a shared one\n * (send-message-routing-rework.md §8.5).\n *\n * Present only on a CHANNEL-FILTERED listing: an org-wide listing has no single\n * conversation-specific address, and offering a wrong token would silently address\n * nobody. It gives the model an exact string to put in its ordinary reply (§2.1)\n * instead of guessing from a display name, without exposing any credential.\n *\n * The DAEMON fills this from its local conversation directory; it is not a CP field.\n */\n mention: z.string().optional()\n});\n/** D→C REQ: list the caller's callable peers (for the asking agent's collaboration tool). */\nexport const ChannelAgentsReq = z.object({\n platform: Platform,\n /** Platform channel id. Omit for the org-wide directory; present = channel filter. */\n channel: z.string().optional(),\n /** The agent asking, derived by the daemon from the MCP session context — NEVER\n * a tool input (§6.1). The CP resolves it in the org directory and applies the\n * bidirectional call-policy filter; an unknown requester fails CLOSED. */\n requesterAgentId: z.string().uuid()\n});\n/** C→D REP (corr = req id): the policy-filtered roster across all daemons. `channel`\n * echoes the REQ's scope — absent when the listing was org-wide. */\nexport const ChannelAgentsOk = z.object({\n platform: Platform,\n channel: z.string().optional(),\n agents: z.array(ChannelAgent)\n});\n//# sourceMappingURL=channel.js.map","import { z } from 'zod';\n/**\n * Agent workspace files (C→D REQ → REP) — the console's on-demand access.\n *\n * The CP stores NO workspace data — directory listings and file bytes are pulled\n * live from the owning daemon and proxied to the console, never persisted\n * (body-locality). Missing paths are DATA (`exists:false`), not errors; only\n * path-containment violations (`BAD_PAYLOAD`) and unexpected fs failures\n * (`INTERNAL`) come back as `error` frames.\n *\n * - `workspace/list`: one cursor-paginated page of a directory's entries.\n * - `workspace/read`: one byte slice of a file. A DIRECTORY is DATA too\n * (`type:'dir'`, no `content`) — a path naming a directory is a fact about the\n * path, not a transport failure. Any other non-regular target (a symlink out of\n * the workspace, a device) stays a containment violation. `limit` is only a ceiling — the\n * daemon returns FEWER bytes when needed to keep the JSON-escaped REP under the\n * 256 KiB frame cap (control bytes escape to `\\uXXXX`, a 6× blowup), and always\n * ends the slice on a UTF-8 character boundary. `nextOffset` is the authoritative\n * byte offset to request next — callers must NOT recompute it from the decoded\n * `content` (a split multi-byte char would make the byte count drift).\n * - `workspace/write`: create a text file when `ifMatchMtime` is absent, or\n * replace one when it matches the last read. Content is base64 so arbitrary\n * UTF-8 text has a predictable wire size.\n * - `workspace/delete`: delete one regular file when its mtime still matches the\n * last read, so a console action never removes a newer agent revision.\n */\n/** Machine-readable `reason` on a workspace `BAD_PAYLOAD` / `CONFLICT` error\n * frame's `details`, so the CP can answer a bad request with a status and a code\n * the console can branch on instead of the 503 that reads as an offline daemon.\n * A closed vocabulary: both sides agree on it, and the messages beside it stay\n * hand-written and host-path-free. */\nexport const WorkspaceErrorReason = z.enum([\n 'unknown-agent', // no such agent on this daemon (or no worktree for that sessionId)\n 'path-escape', // absolute path, or one resolving outside the workspace root\n 'git-internals', // the path reaches into `.git`\n 'not-a-file', // the path exists but is not a regular file (mutations only; reads report it as DATA)\n 'not-a-directory', // a parent component of a write target is not a directory\n 'read-only-workspace', // edits are scratch-workspace only\n 'too-large', // the edit exceeds MAX_WORKSPACE_EDIT_BYTES\n 'binary', // the target is not UTF-8 text\n 'not-utf8', // the supplied content is not valid UTF-8\n 'stale', // optimistic-concurrency failure (CONFLICT)\n // The workspace is on a sandbox volume no bound channel can reach right now (a suspended or\n // not-yet-launched pod). The one reason here that is TRANSIENT rather than a bad request, so the\n // CP answers it 503-with-a-code: retrying is the right move, and it must not read as \"there is no\n // repository here\" or \"this directory is empty\", which is what the panels said before it existed.\n 'sandbox-unavailable'\n]);\n/** Raw UTF-8 ceiling for one console workspace-file edit. Base64 expansion still\n * leaves enough envelope headroom under the shared 256 KiB frame cap. */\nexport const MAX_WORKSPACE_EDIT_BYTES = 180_000;\n/** One directory entry in a workspace listing (name-only; not a full path). */\nexport const WorkspaceEntry = z.object({\n name: z.string(),\n type: z.enum(['dir', 'file', 'symlink', 'other']),\n size: z.number().int().nonnegative().optional(), // regular files only\n mtime: z.string().optional() // RFC3339\n});\n/** C→D REQ: list one page of a directory in the agent's workspace. */\nexport const WorkspaceListReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. Omit for the\n * agent's primary checkout. The CP authorizes the session before forwarding. */\n sessionId: z.string().min(1).optional(),\n path: z.string().default(''), // workspace-relative POSIX path; '' ⇒ workspace root\n cursor: z.string().optional(), // opaque; omit ⇒ first page\n limit: z.number().int().positive().max(500).default(200)\n});\n/** D→C REP (corr = the req id): a page of entries + the cursor for the next page. */\nexport const WorkspaceListPage = z.object({\n agentId: z.string(),\n path: z.string(),\n exists: z.boolean(), // false ⇒ workspace root or the dir does not exist (NOT an error)\n entries: z.array(WorkspaceEntry),\n nextCursor: z.string().optional() // absent ⇒ no more entries\n});\n/** C→D REQ: read one byte slice of a file in the agent's workspace. */\nexport const WorkspaceReadReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional(),\n path: z.string().min(1), // workspace-relative POSIX path to a file\n offset: z.number().int().nonnegative().default(0), // byte offset\n limit: z.number().int().positive().max(65536).default(65536) // byte count per slice (64 KiB, see docblock)\n});\n/** D→C REP (corr = the req id): the file slice (or `exists:false` / binary-detected\n * / `type:'dir'`). */\nexport const WorkspaceReadContent = z.object({\n agentId: z.string(),\n path: z.string(),\n exists: z.boolean(), // false ⇒ the file does not exist (NOT an error)\n type: z.enum(['file', 'dir']).optional(), // what the path IS; 'dir' ⇒ no content (absent from an older daemon)\n size: z.number().int().nonnegative().optional(),\n mtime: z.string().optional(), // RFC3339\n encoding: z.enum(['utf8', 'none']).optional(), // 'none' ⇒ binary detected, content omitted\n content: z.string().optional(), // utf8 text slice\n offset: z.number().int().nonnegative().optional(), // byte offset this slice starts at\n nextOffset: z.number().int().nonnegative().optional(), // byte offset to request next (offset + bytes in this slice)\n truncated: z.boolean().optional() // true ⇒ nextOffset < size (more bytes remain)\n});\nconst CanonicalBase64 = z\n .string()\n .max(Math.ceil(MAX_WORKSPACE_EDIT_BYTES / 3) * 4)\n .regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/);\n/** C→D REQ: atomically create or replace one scratch-workspace text file.\n * Omitting `ifMatchMtime` is an exclusive create; supplying it is an optimistic\n * replace, so neither operation silently overwrites a concurrent change. */\nexport const WorkspaceWriteReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n path: z.string().min(1).max(4096), // workspace-relative POSIX path to a regular file\n contentBase64: CanonicalBase64, // complete new UTF-8 contents\n ifMatchMtime: z.string().datetime().optional()\n});\n/** D→C REP (corr = the req id): the atomically written file state. */\nexport const WorkspaceWriteOk = z.object({\n agentId: z.string(),\n path: z.string(),\n size: z.number().int().nonnegative(),\n mtime: z.string()\n});\n/** C→D REQ: delete one scratch-workspace file if it still matches the last read. */\nexport const WorkspaceDeleteReq = z.object({\n agentId: z.string().min(1),\n path: z.string().min(1).max(4096),\n ifMatchMtime: z.string().datetime()\n});\n/** D→C REP (corr = the req id): the deleted file identity. */\nexport const WorkspaceDeleteOk = z.object({\n agentId: z.string(),\n path: z.string()\n});\n/**\n * Agent workspace git ops (C→D REQ → REP) — the console's on-demand controls for\n * a git-repo workspace. Like list/read these run daemon-local; the CP proxies the\n * outcome and stores nothing.\n *\n * These are DATA-oriented: a non-repo workspace (`isRepo:false`), a dirty tree,\n * or a pull that can't fast-forward (offline, diverged, local edits) all come\n * back as a normal REP — NOT an `error` frame. Only an unknown agent\n * (`BAD_PAYLOAD`) or an unexpected git/fs failure (`INTERNAL`) is an error.\n *\n * - `workspace/gitstatus`: the working tree. Per-file `additions`/`deletions` are\n * `git diff HEAD --numstat` counts — staged AND unstaged, i.e. what the file\n * changed vs HEAD. Optional: an untracked file has no counts, and an older\n * daemon reports none at all.\n * - `workspace/gitdiff`: unified-diff text for ONE path, bounded like\n * `workspace/read` (the daemon shrinks the slice until the JSON-escaped REP\n * fits the 256 KiB frame cap and flags `truncated`). A binary path, a path with\n * no changes and a non-repo workspace are all DATA.\n * - `workspace/gitlog`: the newest commits of the checked-out branch, each marked\n * `pushed` when the branch's upstream ref already contains it.\n *\n * The write half (`workspace/gitstage` / `gitunstage` / `gitcommit` / `gitpush`) is\n * DATA-oriented in the same way, and more strictly: nothing to stage, a commit with\n * an empty index, a daemon with no registered commit identity, a push with no\n * upstream, from a detached HEAD, or one the remote rejects are all normal REPs the\n * console renders. Stage/unstage answer with the FRESH `WorkspaceGitStatus` so the\n * panel never re-polls for the result of its own action.\n */\n/** C→D REQ: report `git status` of the agent's workspace (is it clean?). */\nexport const WorkspaceGitStatusReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional()\n});\n/** One changed path in a `git status`. `index`/`workingDir` are git's per-file XY\n * status chars (' ', 'M', 'A', 'D', 'R', 'C', 'U', '?', …). */\nexport const WorkspaceGitFile = z.object({\n path: z.string(),\n index: z.string(), // staged (X) status char\n workingDir: z.string(), // unstaged (Y) status char\n additions: z.number().int().nonnegative().optional(), // `git diff HEAD --numstat` lines added (absent ⇒ untracked / binary / older daemon)\n deletions: z.number().int().nonnegative().optional() // …and lines removed\n});\n/** The HEAD commit of the checkout. */\nexport const WorkspaceGitCommit = z.object({\n sha: z.string(), // full 40-hex commit hash\n shortSha: z.string(), // abbreviated hash (7 hex) for display\n subject: z.string(), // first line of the commit message\n committedAt: z.string() // RFC3339 committer date\n});\n/** D→C REP (corr = the req id): the working-tree status. */\nexport const WorkspaceGitStatus = z.object({\n agentId: z.string(),\n isRepo: z.boolean(), // false ⇒ from-scratch workspace (no .git) — git ops are N/A\n clean: z.boolean(), // true ⇒ no staged / unstaged / untracked changes\n branch: z.string().optional(), // current branch (absent ⇒ detached / unknown)\n tracking: z.string().optional(), // upstream ref, if the branch tracks one\n ahead: z.number().int().nonnegative().optional(), // commits ahead of upstream\n behind: z.number().int().nonnegative().optional(), // commits behind upstream\n files: z.array(WorkspaceGitFile).optional(), // changed paths (bounded; see `truncated`)\n truncated: z.boolean().optional(), // true ⇒ the `files` list was capped\n lastCommit: WorkspaceGitCommit.optional(), // HEAD commit (absent ⇒ empty repo / no commits yet)\n lastFetchAt: z.string().optional() // RFC3339 mtime of .git/FETCH_HEAD — when the repo last fetched/pulled\n});\n/** C→D REQ: unified-diff text for ONE workspace path, staged or unstaged. */\nexport const WorkspaceGitDiffReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional(),\n path: z.string().min(1).max(4096), // workspace-relative POSIX path (a directory diffs its subtree)\n staged: z.boolean().default(false) // true ⇒ index vs HEAD (`--cached`); false ⇒ worktree vs index\n});\n/** D→C REP (corr = the req id): the unified diff, or the DATA that says why there\n * is none. `diff` absent with `exists:true` and no `binary` ⇒ this path has no\n * changes in the requested scope. */\nexport const WorkspaceGitDiffResult = z.object({\n agentId: z.string(),\n path: z.string(),\n isRepo: z.boolean(), // false ⇒ from-scratch workspace (no .git) — nothing to diff\n exists: z.boolean(), // false ⇒ the path is neither changed nor present in the workspace\n diff: z.string().optional(), // unified-diff text as git emits it (bounded; see `truncated`)\n binary: z.boolean().optional(), // true ⇒ git reports a binary change, so there is no text to show\n truncated: z.boolean().optional() // true ⇒ `diff` is only the head of a bigger diff\n});\n/** Display ceilings for one `workspace/gitlog` row. 50 commits × (200 + 100)\n * characters stay under MAX_FRAME_BYTES even at JSON's 6× control-byte escape\n * blowup (50 × 300 × 6 ≈ 90 KB), so the REP can never overflow the frame. */\nexport const MAX_WORKSPACE_LOG_COMMITS = 50;\nexport const MAX_WORKSPACE_COMMIT_SUBJECT = 200;\nexport const MAX_WORKSPACE_COMMIT_AUTHOR = 100;\n/** C→D REQ: the newest commits of the workspace's checked-out branch. */\nexport const WorkspaceGitLogReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional(),\n limit: z.number().int().positive().max(MAX_WORKSPACE_LOG_COMMITS).default(20) // commits per REP\n});\n/** One commit in the log. `pushed` is reachability from the branch's upstream ref:\n * false means \"not known to be on a remote\", which is also what every commit\n * reports when the branch tracks nothing (`tracking` absent on the REP). */\nexport const WorkspaceGitLogCommit = WorkspaceGitCommit.extend({\n subject: z.string().max(MAX_WORKSPACE_COMMIT_SUBJECT), // first line of the message (display-capped)\n author: z.string().max(MAX_WORKSPACE_COMMIT_AUTHOR), // commit author name (display-capped)\n pushed: z.boolean()\n});\n/** D→C REP (corr = the req id): newest-first commits. An empty repo is DATA\n * (`commits: []`), not an error frame. */\nexport const WorkspaceGitLog = z.object({\n agentId: z.string(),\n isRepo: z.boolean(), // false ⇒ from-scratch workspace (no .git) — no log\n commits: z.array(WorkspaceGitLogCommit).max(MAX_WORKSPACE_LOG_COMMITS),\n truncated: z.boolean(), // true ⇒ more commits in this range than `limit`\n tracking: z.string().optional(), // upstream ref `pushed` was computed against (absent ⇒ tracks nothing)\n // The base ref the listing EXCLUDES, set only when the checkout sits on some other branch: the\n // commits are then `<base>..HEAD`, this branch's own work, not the repository's whole history.\n base: z.string().optional()\n});\n/** C→D REQ: force a fast-forward-only `git pull` in the agent's workspace now. */\nexport const WorkspaceGitPullReq = z.object({\n agentId: z.string().min(1) // local agent id (NOT a wire UUID)\n});\n/** D→C REP (corr = the req id): the pull outcome. A failed pull is DATA\n * (`ok:false` + `detail`), not an error frame (see the section docblock). */\nexport const WorkspaceGitPullResult = z.object({\n agentId: z.string(),\n isRepo: z.boolean(), // false ⇒ from-scratch workspace (no .git) — nothing to pull\n ok: z.boolean(), // true ⇒ pull succeeded (fast-forwarded or already up to date)\n detail: z.string().optional(), // human summary or failure reason (host paths stripped)\n changed: z.number().int().nonnegative().optional(), // files changed by the pull\n insertions: z.number().int().nonnegative().optional(),\n deletions: z.number().int().nonnegative().optional()\n});\n/** How many paths one stage/unstage REQ may carry. 500 matches the daemon's own cap on\n * `WorkspaceGitStatus.files`, so a console \"Stage all\" over a full status page is one REQ. */\nexport const MAX_WORKSPACE_STAGE_PATHS = 500;\n/** Total UTF-8 bytes across those paths — the bound that actually keeps the REQ inside the\n * 256 KiB frame cap, which 500 × 4096 could not. A path may legally contain control bytes and\n * JSON escapes each to `\\uXXXX` (6 wire bytes), so 32 KiB of paths is the worst-case ceiling\n * (pinned by a codec test). Ample for 500 ordinary paths; a bigger selection is chunked. */\nexport const MAX_WORKSPACE_STAGE_PATH_BYTES = 32 * 1024;\n/** Ceiling on one console commit message (subject + body), generated or hand-written. */\nexport const MAX_WORKSPACE_COMMIT_MESSAGE = 8_000;\nfunction stagePathBytes(paths) {\n const encoder = new TextEncoder();\n return paths.reduce((total, path) => total + encoder.encode(path).byteLength, 0);\n}\n/** C→D REQ: stage (`gitstage`) or unstage (`gitunstage`) exactly these paths. An EMPTY list is\n * a no-op that still answers with the fresh status — staging nothing is data, not a bad\n * request. Paths the checkout does not currently report as changed are skipped the same way. */\nexport const WorkspaceGitStageReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional(),\n paths: z\n .array(z.string().min(1).max(4096)) // workspace-relative POSIX paths, bounded like write/delete\n .max(MAX_WORKSPACE_STAGE_PATHS)\n .refine((paths) => stagePathBytes(paths) <= MAX_WORKSPACE_STAGE_PATH_BYTES, {\n message: `paths exceed ${MAX_WORKSPACE_STAGE_PATH_BYTES} bytes in total`\n })\n});\n/** Why a git write did not do what was asked. Present only when `ok:false`, and a closed\n * vocabulary because the console offers a different next action for each: pull before pushing,\n * stage something first, commit from the agent instead. The `detail` beside it is hand-written\n * or scrubbed of host paths, never raw git output with the workspace path in it. */\nexport const WorkspaceGitWriteReason = z.enum([\n 'not-a-repo', // from-scratch workspace (no .git) — git writes are N/A\n 'nothing-staged', // commit with an empty index diff\n 'empty-message', // commit message is blank once trimmed\n 'no-identity', // no `gitCommitIdentity` was registered, so the commit would take the host operator's\n 'detached-head', // push from a worktree with no branch checked out\n 'no-upstream', // the branch tracks nothing, so there is no ref to push to\n 'unsafe-origin', // the checkout's `origin` is not the daemon-authorized remote\n 'unsafe-config', // the checkout's local config carries a disallowed override (audit refused)\n 'diverged', // push rejected as non-fast-forward — the remote has commits this branch lacks\n 'rejected', // the remote refused the push (protected branch, hook, credentials, permissions)\n 'failed' // anything else git reported; `detail` carries the scrubbed message\n]);\n/** C→D REQ: commit the staged changes of the workspace (or session worktree). */\nexport const WorkspaceGitCommitReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional(),\n message: z.string().min(1).max(MAX_WORKSPACE_COMMIT_MESSAGE) // subject + optional body, as git receives it\n});\n/** D→C REP (corr = the req id): the commit outcome. A refusal is DATA (`ok:false` + `reason` +\n * `detail`), not an error frame. */\nexport const WorkspaceGitCommitResult = z.object({\n agentId: z.string(),\n isRepo: z.boolean(), // false ⇒ from-scratch workspace (no .git) — nothing to commit\n ok: z.boolean(), // true ⇒ a commit was created\n sha: z.string().optional(), // full 40-hex hash of the new commit (present iff ok)\n detail: z.string().optional(), // human summary or refusal reason (host paths stripped)\n reason: WorkspaceGitWriteReason.optional() // machine reason, present only when ok:false\n});\n/** C→D REQ: push the checked-out branch to the daemon-authorized remote. No refspec and no\n * force option on the wire: the daemon derives both, and a console push never forces. */\nexport const WorkspaceGitPushReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional()\n});\n/** D→C REP (corr = the req id): the push outcome. A rejection is DATA (`ok:false` + `reason` +\n * `detail`), not an error frame. A push with nothing to send is `ok:true` with `ahead:0` — the\n * requested state already holds. */\nexport const WorkspaceGitPushResult = z.object({\n agentId: z.string(),\n isRepo: z.boolean(), // false ⇒ from-scratch workspace (no .git) — nothing to push\n ok: z.boolean(), // true ⇒ the remote now has every local commit on this branch\n detail: z.string().optional(), // human summary or refusal reason (host paths stripped)\n ahead: z.number().int().nonnegative().optional(), // commits STILL ahead of the upstream (0 once pushed)\n reason: WorkspaceGitWriteReason.optional() // machine reason, present only when ok:false\n});\n/** C→D REQ: draft a commit message from the workspace's STAGED diff, on the agent's OWN runtime\n * (the CP never calls a model provider — webchat-side-panels.md §2). A bounded utility call, not\n * an agent turn: no tools, no transcript entry, no session state change. Writes nothing — the\n * reader edits the draft and commits it with `workspace/gitcommit`. It costs model tokens, so it\n * is only ever sent for an explicit press (§5.1), never prefetched. */\nexport const WorkspaceGitMessageReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id selecting that session's isolated Git worktree. */\n sessionId: z.string().min(1).optional()\n});\n/** D→C REP (corr = the req id): the drafted message. EVERY way this can fail to produce one is\n * DATA (`ok:false` + `detail`) — nothing staged, a runtime with no read-only mode, a runtime that\n * answers with prose, a timeout, a cancel. `message` is a validated conventional-commit subject\n * plus optional body, ready to put straight in the commit box. */\nexport const WorkspaceGitMessageResult = z.object({\n agentId: z.string(),\n ok: z.boolean(), // true ⇒ `message` is present and usable\n message: z.string().max(MAX_WORKSPACE_COMMIT_MESSAGE).optional(),\n detail: z.string().optional() // human explanation of a refusal (host paths stripped)\n});\n//# sourceMappingURL=workspace.js.map","import { z } from 'zod';\n/**\n * Agent background tasks (C→D REQ → REP) — the console Tasks panel's on-demand read.\n *\n * The CP stores NO task data: descriptions are model-authored strings and states live only\n * in the owning daemon's in-memory background-task lease, pulled live and proxied, never\n * persisted (body-locality — webchat-side-panels.md §2).\n *\n * Scoped per (agent, ACP session) because the lease already is: ACP session ids are\n * runtime-local, so two agents can each expose an `acp-1`\n * (background-task-aware-reclaim.md §3).\n *\n * `task/list` is the ONLY frame here. There is deliberately no `task/cancel`: the single\n * cancellation primitive an ACP runtime exposes is `session/cancel`, whose payload is\n * `{ sessionId }` — it cancels a whole prompt turn, and the only hard stop is killing the\n * agent's shared adapter process. Neither can address one background task, so a per-task\n * cancel could only report a cancellation it did not perform or silently cancel unrelated\n * work. It becomes possible when a task-addressed cancel exists upstream.\n */\n/** Machine-readable `reason` on a task `BAD_PAYLOAD` error frame's `details`, so the CP can\n * answer with a status and a code the console can branch on instead of the 503 that reads as\n * an offline daemon. Everything else about tasks is DATA: an untracked session, a session\n * with no tasks and a runtime that reports none are all normal answers. */\nexport const TaskErrorReason = z.enum([\n 'unknown-agent' // no such agent on this daemon\n]);\n/** Tasks per REP. The lease holds every live task plus a bounded settled history, so this is a\n * display ceiling rather than a pagination cursor — a panel showing 50 rows is already past\n * useful, and `truncated` says the daemon had more. */\nexport const MAX_TASK_LIST_TASKS = 50;\n/** Display ceiling for one task's description. Model-authored, so it is bounded on the wire\n * rather than trusted; the daemon truncates rather than dropping the row. */\nexport const MAX_TASK_DESCRIPTION = 500;\n/** Display ceiling for the `detail` line beside a settled task. */\nexport const MAX_TASK_DETAIL = 200;\n/**\n * What the daemon can actually know about a task, and nothing more.\n *\n * - `running` — the task is in the lease's live set, i.e. it is the thing fencing host reclaim.\n * - `done` — the task settled and no terminal edge reported a failure.\n * - `failed` — a terminal edge reported `failed` or `killed`.\n *\n * There is NO `queued`: the SDK lifecycle feed's only start signal is `task_started`, so a task\n * is either live in the lease or gone. Most settle edges (the authoritative snapshot, and\n * `task_notification`) carry no status at all, which is why `done` means \"settled without a\n * reported failure\" rather than \"reported successful\"; `detail` carries the reported status\n * when there was one.\n */\nexport const TaskState = z.enum(['running', 'done', 'failed']);\n/** C→D REQ: the background tasks of ONE ACP session of one agent. */\nexport const TaskListReq = z.object({\n agentId: z.string().min(1), // local agent id (NOT a wire UUID)\n /** ACP session id — the lease's own scope, so this is required rather than optional. */\n sessionId: z.string().min(1)\n});\n/** One background task. `subagent` is the runtime's own internal Task/subagent invocation: it\n * is carried rather than filtered out, because the same records are what fence host reclaim —\n * a panel that hid them at the SOURCE would show \"no tasks\" beside a host refusing to be\n * reclaimed. Consumers filter at RENDER. */\nexport const TaskEntry = z.object({\n id: z.string(), // runtime-local task id\n description: z.string().max(MAX_TASK_DESCRIPTION).optional(), // absent when the runtime omitted it\n state: TaskState,\n subagent: z.boolean(),\n startedAt: z.string(), // RFC3339, from the `task_started` edge\n endedAt: z.string().optional(), // RFC3339; present iff the task settled\n detail: z.string().max(MAX_TASK_DETAIL).optional() // the terminal status the runtime reported, when any\n});\n/** D→C REP (corr = the req id): live tasks newest-first, then the retained settled ones\n * newest-first. `tracked:false` means this daemon holds no lease for the session — a\n * non-Claude runtime, an adapter without the lifecycle extension, or a session that has not\n * emitted an accepted lifecycle event yet. That is a different statement from \"this session\n * has no background tasks\", and the console says so. */\nexport const TaskList = z.object({\n agentId: z.string(),\n sessionId: z.string(),\n tracked: z.boolean(),\n tasks: z.array(TaskEntry).max(MAX_TASK_LIST_TASKS),\n truncated: z.boolean() // true ⇒ the daemon held more tasks than this REP carries\n});\n//# sourceMappingURL=task.js.map","import { z } from 'zod';\nimport { SessionUsage } from './session.js';\nimport { Platform } from './route.js';\nimport { HeartbeatDuties } from './duty.js';\n/**\n * Telemetry & facts (D→C) — protocol §7.\n *\n * The dashboard's real-time source. `event/session` is the converged milestone\n * feed (NOT the message stream); `facts/daemon-runtimes` is the observed runtime\n * capability feed; `heartbeat` drives the watchdog.\n */\nexport const Heartbeat = z.object({\n load: z.object({\n cpu: z.number(), // 0..1 CPU utilization fraction (busy-time across cores) — NOT a raw load average\n mem: z.number(), // 0..1 utilization fraction\n agents: z.number().int()\n }),\n health: z.enum(['ok', 'degraded']),\n activeSessions: z.number().int(),\n degradedScopes: z.array(z.string()).default([]), // e.g. expired-lease bindings (§6)\n // Duty lease exchange (k8s daemons only; frames/duty.ts). Absent ⇒ this daemon\n // does not participate in the duty ledger and the CP-side path stays dormant.\n duties: HeartbeatDuties.optional()\n});\nconst ExternalKey = z.string().min(1).max(200);\nconst GithubId = z.string().regex(/^[1-9]\\d*$/);\n/** Immutable audience identity inherited by A2A descendants. Credential proof\n * stays on the direct root only; children inherit this tuple from their parent. */\nexport const ExternalSessionAudience = z.discriminatedUnion('provider', [\n z.object({\n provider: z.literal('slack'),\n realmKey: ExternalKey.optional(),\n resourceKind: z.literal('conversation'),\n resourceKey: ExternalKey\n }),\n z.object({\n provider: z.literal('feishu'),\n realmKey: ExternalKey.optional(),\n resourceKind: z.literal('conversation'),\n resourceKey: ExternalKey\n }),\n z.object({\n provider: z.literal('github'),\n realmKey: z.literal('github.com'),\n resourceKind: z.literal('repository'),\n // Rename-proof GitHub repository id, never owner/repo.\n resourceKey: GithubId\n })\n]);\n/** Direct-ingress audience plus the provider-specific proof the CP validates\n * before binding a durable ExternalScope. */\nexport const ExternalSessionOrigin = z.discriminatedUnion('provider', [\n ExternalSessionAudience.options[0].extend({\n integrationId: z.string().uuid().optional()\n }),\n ExternalSessionAudience.options[1].extend({\n integrationId: z.string().uuid().optional()\n }),\n ExternalSessionAudience.options[2].extend({\n hookId: z.string().uuid(),\n deliveryKey: ExternalKey,\n sourceInstallationId: GithubId,\n // Trusted webhook snapshot; display/API-routing hint only. repoId above is\n // the authorization identity and must still match the accepted HookRun.\n repoFullName: ExternalKey\n })\n]);\n/** Converged session lifecycle milestone — protocol §7.2. NOT the message stream. */\nexport const EventSession = z.object({\n sessionId: z.string(), // ACP session id (agent-assigned; a free string, NOT a wire UUID — matches usage/report)\n // Stable ACP session id of the session that spawned this one. Absent for roots.\n // Stored as metadata so the console can navigate the session family.\n parentSessionId: z.string().optional(),\n agentId: z.string().uuid(),\n launchId: z.string().uuid().optional(), // 🅰️ CP launch fence — absent for sessions created on the Slack/Discord→daemon path (no CP-initiated launch)\n phase: z.enum(['start', 'plan', 'problem', 'end']),\n // sessionKey echo — where the session lives; the CP stores it so a deep-link\n // detail page (…/sessions/:id) can show the channel without the daemon online.\n platform: Platform.optional(),\n channel: z.string().optional(),\n thread: z.string().optional(),\n link: z.string().optional(), // deep-link to detail view\n summary: z.string().optional(), // short, human-facing milestone text\n // Dashboard-list metadata snapshot. Still metadata-only: no message bodies,\n // transcript stream, attachment bytes, or tool payloads cross into the CP store.\n title: z.string().optional(),\n status: z.string().optional(),\n lastActivityAt: z.string().datetime().optional(),\n triggeredBy: z.string().optional(),\n channelName: z.string().optional(),\n triggeredByName: z.string().optional(),\n threadUrl: z.string().optional(),\n // ── visibility classification inputs (session-visibility.md §4.1) ──\n // What kind of conversation the session lives in, from the daemon's own\n // NormalizedMessage.isDm/isGroupDm. Absent (old daemon) ⇒ 'channel' behavior,\n // i.e. the CP classifies the session `org`.\n conversationKind: z.enum(['dm', 'group_dm', 'channel']).optional(),\n // DURABLE workspace/tenant scope for ownerIdentity (§2) — a Slack team id,\n // Feishu tenant key, or a minted stable per-integration scope. NOT the\n // daemon's credential-derived transport scope (that rotates with tokens).\n // Absent ⇒ the CP records no IM owner (fail closed).\n transportScope: z.string().min(1).max(200).optional(),\n // Web API launch provenance (§4.4): the correlation id the CP minted on\n // `agent/launch`, echoed back so ingest can attribute the session to the\n // launching console user. NOT the launchId fence above.\n launchCorrelationId: z.string().uuid().optional(),\n // Durable daemon-local source provenance. `local` distinguishes synthetic or\n // otherwise non-provider sessions that retain platform-shaped coordinates\n // for session-key compatibility. Absent keeps mixed-version ingest on the\n // conservative legacy path.\n sourceBindingKind: z.enum(['local', 'external']).optional(),\n // Immutable audience candidate for a supported shared input. This is\n // metadata-only: the CP validates the integration before binding a scope and\n // resolves current provider membership only on authorized read paths.\n externalOrigin: ExternalSessionOrigin.optional(),\n // Effective execution-config snapshot: what the session actually ran with\n // (per-session sticky override, else the agent's config at run time; absent ⇒\n // the runtime's own default). Recorded so the console shows what a session\n // USED, not the owning agent's config at view time. The reporting daemon is\n // NOT echoed here — the CP stamps it from the authenticated WS connection.\n runtime: z.string().optional(),\n model: z.string().optional(),\n // Runtime observation for this milestone. `null` means the runtime exposed\n // only an opaque/default model; absent is a legacy/config-only snapshot. New\n // readers prioritize this over `model`, while old readers safely ignore it.\n observedModel: z.string().nullable().optional(),\n effort: z.string().optional(), // reasoning effort level (runtime-owned vocabulary)\n fastMode: z.boolean().optional(),\n // Effective session permission preset. Usually the runtime-owned mode; Codex Auto\n // is the AgentConnect composite value that the daemon decomposes before ACP.\n permissionMode: z.string().optional(),\n outputMode: z.string().optional(), // daemon-side output verbosity (none/minimal/low/medium/high)\n // Workspace choice pinned when the logical session was created. This is\n // metadata only; it lets the console offer a link to an isolated worktree\n // without assuming the Agent's current setting still matches this session.\n workspaceIsolation: z.enum(['shared', 'session']).optional(),\n ts: z.string().datetime()\n});\n/**\n * Metadata-only transcript invalidation. Message/tool bodies remain daemon-local;\n * an authorized browser uses this signal to pull the changed rows through\n * `session/history.after`.\n */\nexport const SessionActivity = z.object({\n sessionId: z.string(),\n agentId: z.string().uuid(),\n revision: z.string().regex(/^\\d+$/),\n ts: z.string().datetime()\n});\n/** Why a daemon dropped a session's local content. Only the retention sweep\n * (#485) purges autonomously today; the vocabulary is an enum so an explicit\n * operator-initiated delete can join it without a frame revision. */\nexport const SessionPurgeReason = z.enum(['retention']);\n/**\n * Retention-GC receipt — D→C REQ, answered with the generic `ack` (#485).\n *\n * The daemon deleted these sessions' local rows (and any per-session worktree)\n * after `sessions.retention` elapsed, so their transcripts can never be pulled\n * again. The CP keeps the metadata row and MARKS it purged — that is what lets\n * the console explain an empty transcript instead of rendering it as \"this\n * session said nothing\".\n *\n * Correlated rather than fire-and-forget precisely because the local row is\n * already gone: an unacknowledged report cannot be re-derived from daemon state\n * later, so the daemon holds a durable receipt until this ACKs. Delivery is\n * therefore at-least-once and the CP applies it idempotently (a re-reported\n * session keeps its first `contentPurgedAt`).\n */\nexport const SessionPurged = z.object({\n // One agent per frame: the CP authorizes the report by checking that THIS\n // agent is placed on the reporting daemon, the same trust boundary as\n // `event/session`. A sweep spanning several agents sends several frames.\n agentId: z.string().uuid(),\n // ACP session ids (agent-assigned strings, NOT wire UUIDs). Batched because a\n // single sweep commonly expires many sessions at once; capped well under the\n // frame budget so the daemon chunks instead of overflowing the wire.\n sessionIds: z.array(z.string().min(1)).min(1).max(200),\n reason: SessionPurgeReason,\n ts: z.string().datetime()\n});\n/**\n * Per-session token-usage report — D→C EVT. The daemon meters usage from the\n * agent's ACP stream and reports the session's CUMULATIVE snapshot (latest-wins)\n * so the CP can persist it for the console's historical usage aggregates. This is\n * dashboard metadata (token counts + cost), never the message stream. Idempotent\n * by `sessionId`: re-sending the same snapshot is a no-op upsert on the CP.\n */\nexport const UsageReport = z.object({\n sessionId: z.string(), // ACP session id (agent-assigned; NOT a wire UUID)\n agentId: z.string().uuid(),\n platform: z.string().optional(), // denormalized sessionKey echo for dashboard filters\n channel: z.string().optional(),\n // The model observed for the usage delta ending at this cumulative snapshot.\n // `null` is an explicit runtime-owned default/unknown; absent is an old daemon.\n observedModel: z.string().nullable().optional(),\n lastActivityAt: z.string(), // ISO ts of the session's last activity\n usage: SessionUsage\n});\n/**\n * Observed capabilities of an installed runtime — protocol §7.3. The element\n * type of the `facts/daemon-runtimes` snapshot. As a standalone per-runtime\n * frame (`facts/runtime-profile`, upsert-only) it is DEPRECATED: current\n * daemons report the full snapshot instead; the CP keeps accepting the old\n * frame from older daemons.\n */\n/**\n * MCP transports a runtime accepts on `session/new` `mcpServers` (from the ACP\n * `initialize` response's `agentCapabilities.mcpCapabilities`). Stdio is the ACP\n * baseline every agent must accept, so only the optional transports are listed.\n */\nexport const McpTransportCapabilities = z.object({\n http: z.boolean(),\n sse: z.boolean()\n});\n/**\n * One thought-level (reasoning-effort) choice a model offers — value is the\n * wire vocabulary the runtime accepts; name/description are display metadata\n * straight from the runtime's select options (or catalog driver), when present.\n */\nexport const EffortOption = z.object({\n value: z.string(),\n name: z.string().optional(),\n description: z.string().optional()\n});\n/** One runtime permission-mode choice. The display metadata is forwarded\n * verbatim from the runtime's ACP `category: \"mode\"` select option. */\nexport const PermissionModeOption = z.object({\n value: z.string(),\n name: z.string().optional(),\n description: z.string().optional()\n});\n/**\n * Per-model capability entry of a runtime's model catalog (design doc\n * runtime-model-catalog.md). `efforts` carries the thought_level vocabulary the\n * daemon will actually offer when this model is selected (daemon-side synthetic\n * levels included): `[]` = the model has no effort selector; absent = not yet\n * discovered. `fastMode` mirrors whether the model_config fast toggle appears\n * for this model; absent = unknown.\n */\nexport const RuntimeModelCapability = z.object({\n id: z.string(), // model-selector value\n name: z.string().optional(), // display name (sent only when it differs from id)\n efforts: z.array(EffortOption).optional(),\n defaultEffort: z.string().optional(),\n fastMode: z.boolean().optional()\n});\n/**\n * A runtime's discovered model × config capability matrix. One shape shared by\n * the wire, the CP's `runtime_profile.modelCatalog` JSONB column, and the DTO —\n * no field renames between layers.\n */\nexport const RuntimeModelCatalog = z.object({\n models: z.array(RuntimeModelCapability).max(128),\n defaultModel: z.string().optional(), // resolved concrete model id (never the literal \"default\")\n permissionModes: z.array(PermissionModeOption).optional(),\n // The mode select's currentValue on a fresh probe session — the runtime's own\n // default permission mode (e.g. copilot 'agent'). Absent = not observed.\n defaultPermissionMode: z.string().optional(),\n source: z.enum(['native', 'acp']), // native = catalog driver, acp = per-model enumeration / probe seed\n observedAt: z.string().datetime()\n});\nexport const FactsRuntimeProfile = z.object({\n runtime: z.string(), // \"claude\" / \"codex\" / ...\n version: z.string(),\n models: z.array(z.string()),\n contextWindow: z.number().int().optional(),\n acpSupport: z.enum(['full', 'partial', 'none']), // gates the dual-mode decision (#1)\n // ACP protocol version the runtime negotiated at `initialize` (the number the\n // agent echoed/downgraded to). Absent for older daemons / runtimes not probed yet.\n acpProtocolVersion: z.number().int().optional(),\n toolCalling: z.boolean(),\n // MCP transports the runtime advertised at `initialize`. Absent for older\n // daemons / runtimes not probed yet (⇒ assume stdio-only).\n mcpCapabilities: McpTransportCapabilities.optional(),\n // Provenance of `models[]`: 'cached' = hydrated from the daemon's local\n // last-good catalog cache (a live probe has not confirmed it this process) —\n // capability gates (agent move / activation model checks) MUST treat it as\n // permissive, exactly like an empty list; 'probed' = confirmed by a live\n // probe. Absent ⇒ 'probed' semantics.\n modelsSource: z.enum(['cached', 'probed']).optional(),\n // The last probe was rejected with the ACP auth-required error (-32000): the\n // runtime is installed but needs an interactive login on the daemon host\n // before sessions can start. Cleared (absent) once a probe succeeds; absent\n // also for older daemons that don't report it.\n authRequired: z.boolean().optional(),\n // Discovered model × config capability matrix (last-good; survives probe\n // failures — advertisement (`models`) empties on failure, capability\n // knowledge does not). Absent = this daemon has no catalog for the runtime.\n modelCatalog: RuntimeModelCatalog.optional()\n});\n/**\n * One daemon-configured MCP server (daemon config `mcpServers`), surfaced so the\n * console can list the servers an agent may enable. Name + transport only —\n * derived directly from config; the daemon does NOT connect to the server.\n * Definitions (commands, URLs, headers) stay daemon-local.\n */\nexport const FactsMcpServer = z.object({\n name: z.string(), // config key; what AgentSpec.mcpServers references\n transport: z.enum(['stdio', 'http', 'sse'])\n});\n/**\n * Full snapshot of the daemon's installed runtimes — D→C EVT (protocol §7.3a),\n * emitted on each register and again once the background probe sweep completes\n * (with the learned `models[]`). REPLACE semantics: the CP reconciles its\n * stored runtime list for the daemon to exactly `runtimes[]`, pruning runtimes\n * that are no longer installed. Idempotent (latest-wins). Supersedes the\n * per-runtime `facts/runtime-profile` upsert.\n */\nexport const DaemonRuntimes = z.object({\n runtimes: z.array(FactsRuntimeProfile),\n // Daemon-level (not per-runtime) MCP-server list (name + transport, from\n // config) — same REPLACE semantics as `runtimes`. Default [] so older daemons\n // parse clean.\n mcpServers: z.array(FactsMcpServer).default([]),\n // Per-connection monotonic snapshot ordinal. The CP resets its stored value\n // on register and ignores snapshots whose seq is <= the stored one, so two\n // frames whose DB transactions interleave (sweep frame vs catalog frame; the\n // CP dispatches inbound frames without awaiting) cannot commit out of order.\n // Absent (older daemon) ⇒ latest-commit-wins as before.\n seq: z.number().int().optional()\n});\n/** Non-secret config update — C→D EVT, protocol §8.3 / frame #26. */\nexport const ConfigPush = z.object({\n keys: z.record(z.string(), z.unknown())\n});\n/** Auth-time upgrade result, legal before full registration. */\nexport const DaemonBootstrapResult = z.object({\n operationId: z.string(),\n status: z.enum(['installed', 'failed']),\n reason: z.string().max(500).optional()\n});\n/** Fleet: drain+exit, supervisor restarts — C→D REQ, protocol §8.3 / frame #27. */\nexport const DaemonRestart = z.object({\n reason: z.string(),\n drainFirst: z.boolean().default(true)\n});\n/** Fleet: drain+exit for version bump — C→D REQ, protocol §8.3 / frame #28. */\nexport const DaemonUpgrade = z.object({\n targetVersion: z.string(),\n drainFirst: z.boolean().default(true)\n});\n/** Reply to a fleet restart/upgrade REQ (protocol §8.3). */\nexport const DaemonControlAck = z.object({\n accepted: z.boolean(),\n willDrainUntil: z.string().datetime().optional(),\n // Why the daemon declined (`accepted:false`) — e.g. no supervisor, CLI not\n // locatable, another lifecycle op in flight (cli-daemon-split.md §7.1).\n // Optional + backward-compatible: an older daemon simply omits it.\n reason: z.string().optional()\n});\n/**\n * Generic acknowledgement for REQs whose reply is just `ack` in the frame index\n * (cron/upsert, cron/remove, agent/stop). Kept permissive but typed.\n */\nexport const Ack = z.object({\n ok: z.boolean(),\n reason: z.string().optional()\n});\n//# sourceMappingURL=telemetry.js.map","import { z } from 'zod';\n/**\n * Error model — protocol §9.\n *\n * Every REQ can be answered by an `error` REP (`corr` = request `id`). Errors\n * are typed and actionable, not free text.\n */\nexport const ErrorCode = z.enum([\n // protocol / framing\n 'UNKNOWN_FRAME',\n 'FRAME_TOO_LARGE',\n 'PROTOCOL_STATE',\n 'BAD_PAYLOAD',\n // auth / identity\n 'AUTH_FAILED',\n 'ATTESTATION_INVALID',\n // fencing / ordering\n 'STALE_EPOCH',\n 'STALE_LAUNCH',\n // delivery\n 'NO_SESSION',\n 'SCOPE_DENIED',\n // delegated MCP authority / invocation binding\n 'DELEGATION_DENIED',\n 'INVOCATION_CONFLICT',\n // secrets\n 'LEASE_EXPIRED',\n 'LEASE_DENIED',\n // generic\n 'RATE_LIMITED',\n 'CONFLICT',\n 'INTERNAL'\n]);\nexport const ErrorFrame = z.object({\n code: ErrorCode,\n message: z.string(), // human-readable, redacted of secrets\n retryable: z.boolean(),\n details: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * WebSocket close codes — protocol §9.\n *\n * `4401` requires a fresh credential before reconnecting; everything else uses\n * exponential backoff with jitter.\n */\nexport const CloseCode = {\n BAD_SUBPROTOCOL: 4400, // bad subprotocol/handshake\n AUTH_FAILED: 4401, // auth failed (don't auto-retry)\n EPOCH_CONFLICT: 4409, // epoch conflict on handshake (do full reconcile)\n UNSUPPORTED_ENCODING: 4415, // binary/unsupported encoding\n RATE_LIMITED: 4429, // rate-limited (backoff)\n SERVER_INTERNAL: 1011, // server internal\n SERVER_RESTARTING: 1012, // server restarting (reconnect with backoff)\n /** soft 256 KiB cap exceeded → ws library close (protocol §1). */\n MESSAGE_TOO_BIG: 1009\n};\n//# sourceMappingURL=error.js.map","import { z } from 'zod';\n/** Non-secret entitlement carried CP → relay → daemon after webchat verification. */\nexport const WebchatRemoteMcpEntitlement = z\n .object({\n authorityId: z.string().uuid(),\n authorityGeneration: z.number().int().positive(),\n expiresAt: z.string().datetime()\n})\n .strict();\nconst DescriptorFence = z\n .object({\n authorityId: z.string().uuid(),\n authorityGeneration: z.number().int().positive(),\n conversationId: z.string().uuid(),\n descriptorInstanceId: z.string().uuid(),\n grantRevision: z.number().int().positive()\n})\n .strict();\nexport const WebchatMcpGrantIssue = z\n .object({\n authorityId: z.string().uuid(),\n authorityGeneration: z.number().int().positive(),\n conversationId: z.string().uuid(),\n descriptorInstanceId: z.string().uuid()\n})\n .strict();\nexport const WebchatMcpGrantIssued = DescriptorFence.extend({\n grantId: z.string().uuid(),\n token: z.string().min(32),\n expiresAt: z.string().datetime(),\n mcpUrl: z.string().url()\n}).strict();\nexport const WebchatMcpGrantAccept = DescriptorFence.extend({\n grantId: z.string().uuid()\n}).strict();\nexport const WebchatMcpGrantActivate = WebchatMcpGrantAccept.extend({\n activated: z.boolean()\n}).strict();\nexport const WebchatMcpGrantRevoke = z\n .object({\n authorityId: z.string().uuid(),\n authorityGeneration: z.number().int().positive(),\n conversationId: z.string().uuid(),\n reason: z.enum(['session_closed', 'session_expired', 'agent_detached', 'feature_disabled', 'security'])\n})\n .strict();\nexport const WebchatMcpGrantRevoked = WebchatMcpGrantRevoke.pick({\n authorityId: true,\n authorityGeneration: true,\n conversationId: true\n})\n .extend({ revoked: z.boolean() })\n .strict();\n//# sourceMappingURL=remote-mcp.js.map","import { z } from 'zod';\nimport { AuthReq, AuthOk } from './frames/auth.js';\nimport { RegisterReq, RegisterOk, RelayRosterUpdate, CapabilitiesUpdate } from './frames/register.js';\nimport { CollabRoutesSnapshot } from './frames/collab.js';\nimport { RouteAssign, RouteAssignAck, RouteUpdate, Drain, DrainProgress, DrainDone } from './frames/route.js';\nimport { AgentLaunch, AgentLaunched, AgentStop, AgentUpsert, AgentRemove, AgentDetach, AgentActivate, AgentActivity, AgentScopeDenied, AgentPermissionRequestList, AgentPermissionRequestPage, AgentPermissionDecision } from './frames/agent.js';\nimport { CronUpsert, CronRemove, CronReport, CronRunNow } from './frames/cron.js';\nimport { DutyGrant, DutyRenewed, DutyRevoke, DutyRelease, DutyClaim, DutyClaimOk, DutyFetch, DutyFetchOk } from './frames/duty.js';\nimport { GithubReviewAuthorize, GithubReviewAuthorized, GithubReviewResultOk, GithubReviewResultReport, HookReport, HookStart, HookStartOk } from './frames/hook.js';\nimport { IntegrationUpsert, IntegrationRemove, IntegrationChannels, IntegrationForget, IntegrationLeave, IntegrationLeaveOk } from './frames/integration.js';\nimport { McpServerUpsert, McpServerRemove } from './frames/mcpserver.js';\nimport { MemoryConnectionUpsert, MemoryConnectionRemove, MemoryConnectionFacts } from './frames/memory-connection.js';\nimport { GitCredRequest, GitCredGrant } from './frames/gitcred.js';\nimport { SecretsRequest, SecretsGrant, SecretsRenew, SecretsRevoke, ScopeAttestation } from './frames/secrets.js';\nimport { SessionHistoryReq, SessionHistoryPage, SessionListReq, SessionListPage, SessionToolBodyReq, SessionToolBodyChunk, ChildSessionStatus, ChildSessionStatusReq, ChildSessionStatusProbe, SessionVisibilityPush, SessionVisibilityOk, SessionVisibilitySnapshot } from './frames/session.js';\nimport { ChannelAgentsReq, ChannelAgentsOk } from './frames/channel.js';\nimport { WorkspaceListReq, WorkspaceListPage, WorkspaceReadReq, WorkspaceReadContent, WorkspaceWriteReq, WorkspaceWriteOk, WorkspaceDeleteReq, WorkspaceDeleteOk, WorkspaceGitStatusReq, WorkspaceGitStatus, WorkspaceGitDiffReq, WorkspaceGitDiffResult, WorkspaceGitLogReq, WorkspaceGitLog, WorkspaceGitPullReq, WorkspaceGitPullResult, WorkspaceGitStageReq, WorkspaceGitCommitReq, WorkspaceGitCommitResult, WorkspaceGitPushReq, WorkspaceGitPushResult, WorkspaceGitMessageReq, WorkspaceGitMessageResult } from './frames/workspace.js';\nimport { TaskListReq, TaskList } from './frames/task.js';\nimport { MemoryChannelsReq, MemoryChannelsPage, MemoryListReq, MemoryListPage, MemoryReadReq, MemoryReadContent, MemoryWriteReq, MemoryWriteOk, MemoryHistoryReq, MemoryHistoryPage, MemorySurfaceReq, MemorySurfaceInfo, MemoryRecordSearchReq, MemoryRecordSearchPage, MemoryRecordListReq, MemoryRecordListPage, MemoryRecordGetReq, MemoryRecordGetResult, MemoryRecordCreateReq, MemoryRecordCreateResult, MemoryRecordUpdateReq, MemoryRecordUpdateResult, MemoryRecordDeleteReq, MemoryRecordDeleteResult, MemoryRecordHistoryReq, MemoryRecordHistoryPage, DreamStartReq, DreamState, DreamCancelReq, DreamListReq, DreamListPage, DreamGetReq, DreamAdoptReq, DreamDiscardReq, DreamFilesReq, DreamFilesPage, DreamFileReadReq, DreamFileReadContent, DreamSkillReviewReq, DreamSkillReadReq, DreamSkillContent } from './frames/memory.js';\nimport { LocalSkillsReq, LocalSkillsList } from './frames/skill.js';\nimport { KnowledgeSearchReq, KnowledgeSearchOk, KnowledgeListReq, KnowledgeListOk, OrgSkillsReq, OrgSkillsOk, OrganizationSuggestionsSyncReq, OrganizationSuggestionsSyncOk, OrganizationSuggestionReadReq, OrganizationSuggestionChunk, OrganizationSuggestionReviewReq, ManagedSkillReadReq, ManagedSkillChunk } from './frames/organization-knowledge.js';\nimport { Heartbeat, EventSession, SessionActivity, SessionPurged, UsageReport, FactsRuntimeProfile, DaemonRuntimes, ConfigPush, DaemonBootstrapResult, DaemonRestart, DaemonUpgrade, DaemonControlAck, Ack } from './frames/telemetry.js';\nimport { ErrorFrame } from './frames/error.js';\nimport { WebchatMcpGrantAccept, WebchatMcpGrantActivate, WebchatMcpGrantIssue, WebchatMcpGrantIssued, WebchatMcpGrantRevoke, WebchatMcpGrantRevoked } from './frames/remote-mcp.js';\n// webchat CONTENT frames were retired in milestone A4 — content rides the relay's rd/*\n// wire now, not the daemon↔CP control WS. The reply-payload schemas live on in\n// frames/webchat.ts (reused by rd/chat); remote-MCP grant lifecycle frames\n// remain valid on the control WebSocket.\n/**\n * The single source of truth for the wire: `type` string → payload zod schema.\n *\n * Mirrors the frame index in daemon-cp-ws-protocol.md §10 (the 29 numbered\n * frames) plus the correlated REP types named in the \"Reply\" column\n * (`route/assign/ack`, `drain/done`, and the generic `ack` replies) that also\n * travel on the wire and must be decodable.\n *\n * `ws/codec.ts` validates every inbound `payload` against `FRAME_SCHEMAS[type]`;\n * an unknown `type` → `ErrorFrame{code:\"UNKNOWN_FRAME\"}` (a REP, not a close).\n */\nexport const FRAME_SCHEMAS = {\n // ── auth / identity ──\n auth: AuthReq,\n 'auth/ok': AuthOk,\n // ── register / reconcile ──\n register: RegisterReq,\n 'register/ok': RegisterOk,\n // ── capability refresh (D→C hot update of register.capabilities) ──\n 'capabilities/update': CapabilitiesUpdate,\n // ── relay roster (C→D hot update of register/ok.relays) ──\n 'relay/roster': RelayRosterUpdate,\n // ── collaboration routing snapshot (C→D hot push; baseline in register/ok) ──\n 'collaboration/routes': CollabRoutesSnapshot,\n // ── telemetry ──\n heartbeat: Heartbeat,\n 'duty/grant': DutyGrant,\n 'duty/renewed': DutyRenewed,\n 'duty/revoke': DutyRevoke,\n 'duty/release': DutyRelease,\n 'duty/claim': DutyClaim,\n 'duty/claim/ok': DutyClaimOk,\n 'duty/fetch': DutyFetch,\n 'duty/fetch/ok': DutyFetchOk,\n // ── agent lifecycle / delivery ──\n 'agent/launch': AgentLaunch,\n 'agent/launched': AgentLaunched,\n 'agent/stop': AgentStop,\n 'agent/upsert': AgentUpsert,\n 'agent/remove': AgentRemove,\n 'agent/detach': AgentDetach,\n 'agent/activate': AgentActivate,\n 'agent/activity': AgentActivity,\n 'agent/scope-denied': AgentScopeDenied,\n 'agent/permission-requests': AgentPermissionRequestList,\n 'agent/permission-requests/page': AgentPermissionRequestPage,\n 'agent/permission-decision': AgentPermissionDecision,\n // ── routing / orchestration ──\n 'route/assign': RouteAssign,\n 'route/assign/ack': RouteAssignAck,\n 'route/update': RouteUpdate,\n 'daemon/drain': Drain,\n 'drain/progress': DrainProgress,\n 'drain/done': DrainDone,\n // ── cron ──\n 'cron/upsert': CronUpsert,\n 'cron/remove': CronRemove,\n 'cron/report': CronReport,\n 'cron/run': CronRunNow,\n // ── hooks (content fires ride rd/*; only metadata/effect control is here) ──\n 'hook/report': HookReport,\n 'hook/start': HookStart,\n 'hook/start/ok': HookStartOk,\n 'github/review-authorize': GithubReviewAuthorize,\n 'github/review-authorized': GithubReviewAuthorized,\n 'github/review-result': GithubReviewResultReport,\n 'github/review-result/ok': GithubReviewResultOk,\n // ── integrations (platform config distribution; token-bearing — never log) ──\n 'integration/upsert': IntegrationUpsert,\n 'integration/remove': IntegrationRemove,\n 'integration/channels': IntegrationChannels,\n 'integration/forget': IntegrationForget,\n 'integration/leave': IntegrationLeave,\n 'integration/leave/ok': IntegrationLeaveOk,\n // ── MCP provider registry (CP-owned defs pushed to daemons; grant-key-bearing — never log) ──\n 'mcpserver/upsert': McpServerUpsert,\n 'mcpserver/remove': McpServerRemove,\n // ── external-memory connection registry (grant-bearing; never log) ──\n 'memoryconnection/upsert': MemoryConnectionUpsert,\n 'memoryconnection/remove': MemoryConnectionRemove,\n // ── git credentials (github-app workspaces; token-bearing — never log) ──\n 'gitcred/request': GitCredRequest,\n 'gitcred/grant': GitCredGrant,\n // ── secrets ──\n 'secrets/request': SecretsRequest,\n 'secrets/grant': SecretsGrant,\n 'secrets/renew': SecretsRenew,\n 'secrets/revoke': SecretsRevoke,\n 'scope-attestation': ScopeAttestation,\n // ── webchat-scoped remote AgentConnect MCP grants ──\n 'webchat/mcp-grant/issue': WebchatMcpGrantIssue,\n 'webchat/mcp-grant/issued': WebchatMcpGrantIssued,\n 'webchat/mcp-grant/accept': WebchatMcpGrantAccept,\n 'webchat/mcp-grant/activate': WebchatMcpGrantActivate,\n 'webchat/mcp-grant/revoke': WebchatMcpGrantRevoke,\n 'webchat/mcp-grant/revoked': WebchatMcpGrantRevoked,\n // ── dashboard / facts ──\n 'event/session': EventSession,\n // Durable latest-wins metadata snapshot — D→C REQ, replied with `ack`.\n 'event/session-sync': EventSession,\n 'event/session-activity': SessionActivity,\n // Retention-GC receipt (#485) — D→C REQ, replied with the generic `ack`.\n 'event/session-purged': SessionPurged,\n 'usage/report': UsageReport,\n 'facts/runtime-profile': FactsRuntimeProfile,\n 'facts/daemon-runtimes': DaemonRuntimes,\n 'facts/memory-connections': MemoryConnectionFacts,\n // ── session read-back (console history pull) ──\n 'session/list': SessionListReq,\n 'session/list/page': SessionListPage,\n 'session/history': SessionHistoryReq,\n 'session/history/page': SessionHistoryPage,\n 'session/tool-body': SessionToolBodyReq,\n 'session/tool-body/chunk': SessionToolBodyChunk,\n // ── child-session status (session-concept §5.4). Two legs: D→C asks the CP (the placement\n // authority) about a child on another daemon; C→D forwards the lineage pair to the OWNING\n // daemon, which authorizes it. Metadata only — the CP never persists the answer.\n 'session/child-status': ChildSessionStatusReq,\n 'session/child-status/ok': ChildSessionStatus,\n 'session/child-status/probe': ChildSessionStatusProbe,\n 'session/child-status/probe/ok': ChildSessionStatus,\n // ── session visibility gate push (session-visibility.md §5.1). C→D REQs: a single\n // per-session push (reply: typed `session/visibility/ok`) and the register-time\n // snapshot replay (reply: generic `ack`). Rev-fenced in the payload — a stale rev\n // is acked `superseded`, never answered with an error frame.\n 'session/visibility': SessionVisibilityPush,\n 'session/visibility/ok': SessionVisibilityOk,\n 'session/visibility/snapshot': SessionVisibilitySnapshot,\n // ── channel agent directory (agent collaboration; D→C REQ → REP) ──\n 'channel/agents': ChannelAgentsReq,\n 'channel/agents/ok': ChannelAgentsOk,\n // ── workspace files (console live access; bytes transit, never stored) ──\n 'workspace/list': WorkspaceListReq,\n 'workspace/list/page': WorkspaceListPage,\n 'workspace/read': WorkspaceReadReq,\n 'workspace/read/content': WorkspaceReadContent,\n 'workspace/write': WorkspaceWriteReq,\n 'workspace/write/ok': WorkspaceWriteOk,\n 'workspace/delete': WorkspaceDeleteReq,\n 'workspace/delete/ok': WorkspaceDeleteOk,\n 'workspace/gitstatus': WorkspaceGitStatusReq,\n 'workspace/gitstatus/result': WorkspaceGitStatus,\n 'workspace/gitdiff': WorkspaceGitDiffReq,\n 'workspace/gitdiff/result': WorkspaceGitDiffResult,\n 'workspace/gitlog': WorkspaceGitLogReq,\n 'workspace/gitlog/result': WorkspaceGitLog,\n 'workspace/gitpull': WorkspaceGitPullReq,\n 'workspace/gitpull/result': WorkspaceGitPullResult,\n // ── workspace git writes: stage/unstage answer with the FRESH status; commit/push\n // report a refusal as DATA (`ok:false` + `reason`), never as an error frame.\n 'workspace/gitstage': WorkspaceGitStageReq,\n 'workspace/gitstage/result': WorkspaceGitStatus,\n 'workspace/gitunstage': WorkspaceGitStageReq,\n 'workspace/gitunstage/result': WorkspaceGitStatus,\n 'workspace/gitcommit': WorkspaceGitCommitReq,\n 'workspace/gitcommit/result': WorkspaceGitCommitResult,\n 'workspace/gitpush': WorkspaceGitPushReq,\n 'workspace/gitpush/result': WorkspaceGitPushResult,\n // ── AI commit message: a bounded model pass on the DAEMON's runtime, no write of any kind.\n 'workspace/gitmessage': WorkspaceGitMessageReq,\n 'workspace/gitmessage/result': WorkspaceGitMessageResult,\n // ── background tasks: a read of the daemon's in-memory lease. No cancel frame — see task.ts.\n 'task/list': TaskListReq,\n 'task/list/result': TaskList,\n 'memory/channels': MemoryChannelsReq,\n 'memory/channels/page': MemoryChannelsPage,\n 'memory/list': MemoryListReq,\n 'memory/list/page': MemoryListPage,\n 'memory/read': MemoryReadReq,\n 'memory/read/content': MemoryReadContent,\n 'memory/write': MemoryWriteReq,\n 'memory/write/ok': MemoryWriteOk,\n 'memory/history': MemoryHistoryReq,\n 'memory/history/page': MemoryHistoryPage,\n 'memory/surface': MemorySurfaceReq,\n 'memory/surface/info': MemorySurfaceInfo,\n 'memory/record/search': MemoryRecordSearchReq,\n 'memory/record/search/page': MemoryRecordSearchPage,\n 'memory/record/list': MemoryRecordListReq,\n 'memory/record/list/page': MemoryRecordListPage,\n 'memory/record/get': MemoryRecordGetReq,\n 'memory/record/get/result': MemoryRecordGetResult,\n 'memory/record/create': MemoryRecordCreateReq,\n 'memory/record/create/result': MemoryRecordCreateResult,\n 'memory/record/update': MemoryRecordUpdateReq,\n 'memory/record/update/result': MemoryRecordUpdateResult,\n 'memory/record/delete': MemoryRecordDeleteReq,\n 'memory/record/delete/result': MemoryRecordDeleteResult,\n 'memory/record/history': MemoryRecordHistoryReq,\n 'memory/record/history/page': MemoryRecordHistoryPage,\n // ── memory dreaming (managed-store consolidation jobs; REPs carry DreamState) ──\n 'memory/dream/start': DreamStartReq,\n 'memory/dream/start/ok': DreamState,\n 'memory/dream/cancel': DreamCancelReq,\n 'memory/dream/cancel/ok': DreamState,\n 'memory/dream/list': DreamListReq,\n 'memory/dream/list/page': DreamListPage,\n 'memory/dream/get': DreamGetReq,\n 'memory/dream/get/result': DreamState,\n 'memory/dream/adopt': DreamAdoptReq,\n 'memory/dream/adopt/ok': DreamState,\n 'memory/dream/discard': DreamDiscardReq,\n 'memory/dream/discard/ok': DreamState,\n 'memory/dream/files': DreamFilesReq,\n 'memory/dream/files/page': DreamFilesPage,\n 'memory/dream/file/read': DreamFileReadReq,\n 'memory/dream/file/read/content': DreamFileReadContent,\n 'memory/dream/skill/read': DreamSkillReadReq,\n 'memory/dream/skill/read/ok': DreamSkillContent,\n 'memory/dream/skill/accept': DreamSkillReviewReq,\n 'memory/dream/skill/accept/ok': DreamState,\n 'memory/dream/skill/dismiss': DreamSkillReviewReq,\n 'memory/dream/skill/dismiss/ok': DreamState,\n 'skills/local': LocalSkillsReq,\n 'skills/local/list': LocalSkillsList,\n // ── organization knowledge + managed skills ──\n 'knowledge/search': KnowledgeSearchReq,\n 'knowledge/search/ok': KnowledgeSearchOk,\n 'knowledge/list': KnowledgeListReq,\n 'knowledge/list/ok': KnowledgeListOk,\n 'skills/org': OrgSkillsReq,\n 'skills/org/ok': OrgSkillsOk,\n 'knowledge/suggestions/sync': OrganizationSuggestionsSyncReq,\n 'knowledge/suggestions/sync/ok': OrganizationSuggestionsSyncOk,\n 'knowledge/suggestion/read': OrganizationSuggestionReadReq,\n 'knowledge/suggestion/content': OrganizationSuggestionChunk,\n 'knowledge/suggestion/review': OrganizationSuggestionReviewReq,\n 'managed-skill/read': ManagedSkillReadReq,\n 'managed-skill/chunk': ManagedSkillChunk,\n // ── fleet / config ──\n 'config/push': ConfigPush,\n 'daemon/bootstrap/result': DaemonBootstrapResult,\n 'daemon/restart': DaemonRestart,\n 'daemon/upgrade': DaemonUpgrade,\n // ── generic replies ──\n 'daemon/control/ack': DaemonControlAck,\n ack: Ack,\n // ── error ──\n error: ErrorFrame\n};\n/** All frame `type` strings, as a runtime array (used by guards / tests). */\nexport const FRAME_TYPES = Object.keys(FRAME_SCHEMAS);\n/**\n * Builds the envelope schema for one frame `type` with a `type` literal and the\n * typed payload, so the discriminated union infers `payload` precisely.\n *\n * Kept as a local generic (payload pinned to `FRAME_SCHEMAS[T]`) so a\n * mispaired member — `frame('auth', FRAME_SCHEMAS['register'])` — is a compile\n * error; a bare `frameSchema` alias would accept it. The body is deliberately\n * inlined rather than delegated: `return frameSchema(type, payload)` under\n * THIS generic signature collapses every union member's `payload` to `unknown`\n * (113 × TS18046 under TS 6.0.3 / zod 4.4.3 — reproducible by making exactly\n * that substitution), while the small relay unions call `frameSchema` with\n * concrete schemas and infer fine.\n */\nfunction frame(type, payload) {\n return z.object({\n v: z.literal(1),\n id: z.string().uuid(),\n ts: z.string().datetime(),\n type: z.literal(type),\n corr: z.string().uuid().optional(),\n orgId: z.string().min(1).max(64).optional(),\n payload\n });\n}\n/**\n * `AnyFrame` — the discriminated union over `type` of every fully-validated\n * frame (envelope + typed payload). This is the runtime guard at the socket\n * edge and the precise inferred type the handlers switch on.\n */\nexport const AnyFrame = z.discriminatedUnion('type', [\n frame('auth', FRAME_SCHEMAS['auth']),\n frame('auth/ok', FRAME_SCHEMAS['auth/ok']),\n frame('register', FRAME_SCHEMAS['register']),\n frame('register/ok', FRAME_SCHEMAS['register/ok']),\n frame('capabilities/update', FRAME_SCHEMAS['capabilities/update']),\n frame('relay/roster', FRAME_SCHEMAS['relay/roster']),\n frame('collaboration/routes', FRAME_SCHEMAS['collaboration/routes']),\n frame('heartbeat', FRAME_SCHEMAS['heartbeat']),\n frame('duty/grant', FRAME_SCHEMAS['duty/grant']),\n frame('duty/renewed', FRAME_SCHEMAS['duty/renewed']),\n frame('duty/revoke', FRAME_SCHEMAS['duty/revoke']),\n frame('duty/release', FRAME_SCHEMAS['duty/release']),\n frame('duty/claim', FRAME_SCHEMAS['duty/claim']),\n frame('duty/claim/ok', FRAME_SCHEMAS['duty/claim/ok']),\n frame('duty/fetch', FRAME_SCHEMAS['duty/fetch']),\n frame('duty/fetch/ok', FRAME_SCHEMAS['duty/fetch/ok']),\n frame('agent/launch', FRAME_SCHEMAS['agent/launch']),\n frame('agent/launched', FRAME_SCHEMAS['agent/launched']),\n frame('agent/stop', FRAME_SCHEMAS['agent/stop']),\n frame('agent/upsert', FRAME_SCHEMAS['agent/upsert']),\n frame('agent/remove', FRAME_SCHEMAS['agent/remove']),\n frame('agent/detach', FRAME_SCHEMAS['agent/detach']),\n frame('agent/activate', FRAME_SCHEMAS['agent/activate']),\n frame('agent/activity', FRAME_SCHEMAS['agent/activity']),\n frame('agent/scope-denied', FRAME_SCHEMAS['agent/scope-denied']),\n frame('agent/permission-requests', FRAME_SCHEMAS['agent/permission-requests']),\n frame('agent/permission-requests/page', FRAME_SCHEMAS['agent/permission-requests/page']),\n frame('agent/permission-decision', FRAME_SCHEMAS['agent/permission-decision']),\n // ── routing and daemon control ──\n frame('route/assign', FRAME_SCHEMAS['route/assign']),\n frame('route/assign/ack', FRAME_SCHEMAS['route/assign/ack']),\n frame('route/update', FRAME_SCHEMAS['route/update']),\n frame('daemon/drain', FRAME_SCHEMAS['daemon/drain']),\n frame('drain/progress', FRAME_SCHEMAS['drain/progress']),\n frame('drain/done', FRAME_SCHEMAS['drain/done']),\n frame('cron/upsert', FRAME_SCHEMAS['cron/upsert']),\n frame('cron/remove', FRAME_SCHEMAS['cron/remove']),\n frame('cron/report', FRAME_SCHEMAS['cron/report']),\n frame('cron/run', FRAME_SCHEMAS['cron/run']),\n frame('hook/report', FRAME_SCHEMAS['hook/report']),\n frame('hook/start', FRAME_SCHEMAS['hook/start']),\n frame('hook/start/ok', FRAME_SCHEMAS['hook/start/ok']),\n frame('github/review-authorize', FRAME_SCHEMAS['github/review-authorize']),\n frame('github/review-authorized', FRAME_SCHEMAS['github/review-authorized']),\n frame('github/review-result', FRAME_SCHEMAS['github/review-result']),\n frame('github/review-result/ok', FRAME_SCHEMAS['github/review-result/ok']),\n frame('integration/upsert', FRAME_SCHEMAS['integration/upsert']),\n frame('integration/remove', FRAME_SCHEMAS['integration/remove']),\n frame('integration/channels', FRAME_SCHEMAS['integration/channels']),\n frame('integration/forget', FRAME_SCHEMAS['integration/forget']),\n frame('integration/leave', FRAME_SCHEMAS['integration/leave']),\n frame('integration/leave/ok', FRAME_SCHEMAS['integration/leave/ok']),\n frame('mcpserver/upsert', FRAME_SCHEMAS['mcpserver/upsert']),\n frame('mcpserver/remove', FRAME_SCHEMAS['mcpserver/remove']),\n frame('memoryconnection/upsert', FRAME_SCHEMAS['memoryconnection/upsert']),\n frame('memoryconnection/remove', FRAME_SCHEMAS['memoryconnection/remove']),\n frame('gitcred/request', FRAME_SCHEMAS['gitcred/request']),\n frame('gitcred/grant', FRAME_SCHEMAS['gitcred/grant']),\n frame('secrets/request', FRAME_SCHEMAS['secrets/request']),\n frame('secrets/grant', FRAME_SCHEMAS['secrets/grant']),\n frame('secrets/renew', FRAME_SCHEMAS['secrets/renew']),\n frame('secrets/revoke', FRAME_SCHEMAS['secrets/revoke']),\n frame('scope-attestation', FRAME_SCHEMAS['scope-attestation']),\n frame('webchat/mcp-grant/issue', FRAME_SCHEMAS['webchat/mcp-grant/issue']),\n frame('webchat/mcp-grant/issued', FRAME_SCHEMAS['webchat/mcp-grant/issued']),\n frame('webchat/mcp-grant/accept', FRAME_SCHEMAS['webchat/mcp-grant/accept']),\n frame('webchat/mcp-grant/activate', FRAME_SCHEMAS['webchat/mcp-grant/activate']),\n frame('webchat/mcp-grant/revoke', FRAME_SCHEMAS['webchat/mcp-grant/revoke']),\n frame('webchat/mcp-grant/revoked', FRAME_SCHEMAS['webchat/mcp-grant/revoked']),\n frame('event/session', FRAME_SCHEMAS['event/session']),\n frame('event/session-sync', FRAME_SCHEMAS['event/session-sync']),\n frame('event/session-activity', FRAME_SCHEMAS['event/session-activity']),\n frame('event/session-purged', FRAME_SCHEMAS['event/session-purged']),\n frame('usage/report', FRAME_SCHEMAS['usage/report']),\n frame('facts/runtime-profile', FRAME_SCHEMAS['facts/runtime-profile']),\n frame('facts/daemon-runtimes', FRAME_SCHEMAS['facts/daemon-runtimes']),\n frame('facts/memory-connections', FRAME_SCHEMAS['facts/memory-connections']),\n frame('session/list', FRAME_SCHEMAS['session/list']),\n frame('session/list/page', FRAME_SCHEMAS['session/list/page']),\n frame('session/history', FRAME_SCHEMAS['session/history']),\n frame('session/history/page', FRAME_SCHEMAS['session/history/page']),\n frame('session/tool-body', FRAME_SCHEMAS['session/tool-body']),\n frame('session/tool-body/chunk', FRAME_SCHEMAS['session/tool-body/chunk']),\n frame('session/child-status', FRAME_SCHEMAS['session/child-status']),\n frame('session/child-status/ok', FRAME_SCHEMAS['session/child-status/ok']),\n frame('session/child-status/probe', FRAME_SCHEMAS['session/child-status/probe']),\n frame('session/child-status/probe/ok', FRAME_SCHEMAS['session/child-status/probe/ok']),\n frame('session/visibility', FRAME_SCHEMAS['session/visibility']),\n frame('session/visibility/ok', FRAME_SCHEMAS['session/visibility/ok']),\n frame('session/visibility/snapshot', FRAME_SCHEMAS['session/visibility/snapshot']),\n frame('channel/agents', FRAME_SCHEMAS['channel/agents']),\n frame('channel/agents/ok', FRAME_SCHEMAS['channel/agents/ok']),\n frame('workspace/list', FRAME_SCHEMAS['workspace/list']),\n frame('workspace/list/page', FRAME_SCHEMAS['workspace/list/page']),\n frame('workspace/read', FRAME_SCHEMAS['workspace/read']),\n frame('workspace/read/content', FRAME_SCHEMAS['workspace/read/content']),\n frame('workspace/write', FRAME_SCHEMAS['workspace/write']),\n frame('workspace/write/ok', FRAME_SCHEMAS['workspace/write/ok']),\n frame('workspace/delete', FRAME_SCHEMAS['workspace/delete']),\n frame('workspace/delete/ok', FRAME_SCHEMAS['workspace/delete/ok']),\n frame('workspace/gitstatus', FRAME_SCHEMAS['workspace/gitstatus']),\n frame('workspace/gitstatus/result', FRAME_SCHEMAS['workspace/gitstatus/result']),\n frame('workspace/gitdiff', FRAME_SCHEMAS['workspace/gitdiff']),\n frame('workspace/gitdiff/result', FRAME_SCHEMAS['workspace/gitdiff/result']),\n frame('workspace/gitlog', FRAME_SCHEMAS['workspace/gitlog']),\n frame('workspace/gitlog/result', FRAME_SCHEMAS['workspace/gitlog/result']),\n frame('workspace/gitpull', FRAME_SCHEMAS['workspace/gitpull']),\n frame('workspace/gitpull/result', FRAME_SCHEMAS['workspace/gitpull/result']),\n frame('workspace/gitstage', FRAME_SCHEMAS['workspace/gitstage']),\n frame('workspace/gitstage/result', FRAME_SCHEMAS['workspace/gitstage/result']),\n frame('workspace/gitunstage', FRAME_SCHEMAS['workspace/gitunstage']),\n frame('workspace/gitunstage/result', FRAME_SCHEMAS['workspace/gitunstage/result']),\n frame('workspace/gitcommit', FRAME_SCHEMAS['workspace/gitcommit']),\n frame('workspace/gitcommit/result', FRAME_SCHEMAS['workspace/gitcommit/result']),\n frame('workspace/gitpush', FRAME_SCHEMAS['workspace/gitpush']),\n frame('workspace/gitpush/result', FRAME_SCHEMAS['workspace/gitpush/result']),\n frame('workspace/gitmessage', FRAME_SCHEMAS['workspace/gitmessage']),\n frame('workspace/gitmessage/result', FRAME_SCHEMAS['workspace/gitmessage/result']),\n frame('task/list', FRAME_SCHEMAS['task/list']),\n frame('task/list/result', FRAME_SCHEMAS['task/list/result']),\n frame('memory/channels', FRAME_SCHEMAS['memory/channels']),\n frame('memory/channels/page', FRAME_SCHEMAS['memory/channels/page']),\n frame('memory/list', FRAME_SCHEMAS['memory/list']),\n frame('memory/list/page', FRAME_SCHEMAS['memory/list/page']),\n frame('memory/read', FRAME_SCHEMAS['memory/read']),\n frame('memory/read/content', FRAME_SCHEMAS['memory/read/content']),\n frame('memory/write', FRAME_SCHEMAS['memory/write']),\n frame('memory/write/ok', FRAME_SCHEMAS['memory/write/ok']),\n frame('memory/history', FRAME_SCHEMAS['memory/history']),\n frame('memory/history/page', FRAME_SCHEMAS['memory/history/page']),\n frame('memory/surface', FRAME_SCHEMAS['memory/surface']),\n frame('memory/surface/info', FRAME_SCHEMAS['memory/surface/info']),\n frame('memory/record/search', FRAME_SCHEMAS['memory/record/search']),\n frame('memory/record/search/page', FRAME_SCHEMAS['memory/record/search/page']),\n frame('memory/record/list', FRAME_SCHEMAS['memory/record/list']),\n frame('memory/record/list/page', FRAME_SCHEMAS['memory/record/list/page']),\n frame('memory/record/get', FRAME_SCHEMAS['memory/record/get']),\n frame('memory/record/get/result', FRAME_SCHEMAS['memory/record/get/result']),\n frame('memory/record/create', FRAME_SCHEMAS['memory/record/create']),\n frame('memory/record/create/result', FRAME_SCHEMAS['memory/record/create/result']),\n frame('memory/record/update', FRAME_SCHEMAS['memory/record/update']),\n frame('memory/record/update/result', FRAME_SCHEMAS['memory/record/update/result']),\n frame('memory/record/delete', FRAME_SCHEMAS['memory/record/delete']),\n frame('memory/record/delete/result', FRAME_SCHEMAS['memory/record/delete/result']),\n frame('memory/record/history', FRAME_SCHEMAS['memory/record/history']),\n frame('memory/record/history/page', FRAME_SCHEMAS['memory/record/history/page']),\n frame('memory/dream/start', FRAME_SCHEMAS['memory/dream/start']),\n frame('memory/dream/start/ok', FRAME_SCHEMAS['memory/dream/start/ok']),\n frame('memory/dream/cancel', FRAME_SCHEMAS['memory/dream/cancel']),\n frame('memory/dream/cancel/ok', FRAME_SCHEMAS['memory/dream/cancel/ok']),\n frame('memory/dream/list', FRAME_SCHEMAS['memory/dream/list']),\n frame('memory/dream/list/page', FRAME_SCHEMAS['memory/dream/list/page']),\n frame('memory/dream/get', FRAME_SCHEMAS['memory/dream/get']),\n frame('memory/dream/get/result', FRAME_SCHEMAS['memory/dream/get/result']),\n frame('memory/dream/adopt', FRAME_SCHEMAS['memory/dream/adopt']),\n frame('memory/dream/adopt/ok', FRAME_SCHEMAS['memory/dream/adopt/ok']),\n frame('memory/dream/discard', FRAME_SCHEMAS['memory/dream/discard']),\n frame('memory/dream/discard/ok', FRAME_SCHEMAS['memory/dream/discard/ok']),\n frame('memory/dream/files', FRAME_SCHEMAS['memory/dream/files']),\n frame('memory/dream/files/page', FRAME_SCHEMAS['memory/dream/files/page']),\n frame('memory/dream/file/read', FRAME_SCHEMAS['memory/dream/file/read']),\n frame('memory/dream/file/read/content', FRAME_SCHEMAS['memory/dream/file/read/content']),\n frame('memory/dream/skill/read', FRAME_SCHEMAS['memory/dream/skill/read']),\n frame('memory/dream/skill/read/ok', FRAME_SCHEMAS['memory/dream/skill/read/ok']),\n frame('memory/dream/skill/accept', FRAME_SCHEMAS['memory/dream/skill/accept']),\n frame('memory/dream/skill/accept/ok', FRAME_SCHEMAS['memory/dream/skill/accept/ok']),\n frame('memory/dream/skill/dismiss', FRAME_SCHEMAS['memory/dream/skill/dismiss']),\n frame('memory/dream/skill/dismiss/ok', FRAME_SCHEMAS['memory/dream/skill/dismiss/ok']),\n frame('skills/local', FRAME_SCHEMAS['skills/local']),\n frame('skills/local/list', FRAME_SCHEMAS['skills/local/list']),\n frame('knowledge/search', FRAME_SCHEMAS['knowledge/search']),\n frame('knowledge/list', FRAME_SCHEMAS['knowledge/list']),\n frame('knowledge/list/ok', FRAME_SCHEMAS['knowledge/list/ok']),\n frame('skills/org', FRAME_SCHEMAS['skills/org']),\n frame('skills/org/ok', FRAME_SCHEMAS['skills/org/ok']),\n frame('knowledge/search/ok', FRAME_SCHEMAS['knowledge/search/ok']),\n frame('knowledge/suggestions/sync', FRAME_SCHEMAS['knowledge/suggestions/sync']),\n frame('knowledge/suggestions/sync/ok', FRAME_SCHEMAS['knowledge/suggestions/sync/ok']),\n frame('knowledge/suggestion/read', FRAME_SCHEMAS['knowledge/suggestion/read']),\n frame('knowledge/suggestion/content', FRAME_SCHEMAS['knowledge/suggestion/content']),\n frame('knowledge/suggestion/review', FRAME_SCHEMAS['knowledge/suggestion/review']),\n frame('managed-skill/read', FRAME_SCHEMAS['managed-skill/read']),\n frame('managed-skill/chunk', FRAME_SCHEMAS['managed-skill/chunk']),\n frame('config/push', FRAME_SCHEMAS['config/push']),\n frame('daemon/bootstrap/result', FRAME_SCHEMAS['daemon/bootstrap/result']),\n frame('daemon/restart', FRAME_SCHEMAS['daemon/restart']),\n frame('daemon/upgrade', FRAME_SCHEMAS['daemon/upgrade']),\n frame('daemon/control/ack', FRAME_SCHEMAS['daemon/control/ack']),\n frame('ack', FRAME_SCHEMAS['ack']),\n frame('error', FRAME_SCHEMAS['error'])\n]);\n/** Runtime guard: is `t` a known frame `type`? */\nexport function isFrameType(t) {\n return Object.prototype.hasOwnProperty.call(FRAME_SCHEMAS, t);\n}\n//# sourceMappingURL=frame.js.map","import { randomUUID } from 'node:crypto';\nimport { Envelope, NIL_UUID } from './envelope.js';\n/**\n * Generic envelope codec — the schema-map-agnostic core shared by every wire.\n *\n * The daemon↔CP wire (`codec.ts` over `FRAME_SCHEMAS`) and the two relay wires\n * (`frames/relay-cp.ts` / `frames/relay-daemon.ts` over their OWN maps) all\n * decode the same envelope shape but accept disjoint frame families — a relay\n * socket must answer a daemon↔CP frame with `UNKNOWN_FRAME`, and vice versa\n * (shared-bot-relay.md §8 \"standalone frame union, not mixed into the daemon protocol\").\n */\n/** Soft cap per frame — 256 KiB (protocol §1). Over this → FRAME_TOO_LARGE. */\nexport const MAX_FRAME_BYTES = 256 * 1024;\nconst textEncoder = new TextEncoder();\nfunction byteLength(text) {\n return textEncoder.encode(text).length;\n}\nfunction extractControlExt(json) {\n if (typeof json !== 'object' || json === null)\n return undefined;\n const o = json;\n const ext = {};\n if (typeof o.epoch === 'number')\n ext.epoch = o.epoch;\n if (typeof o.agentId === 'string')\n ext.agentId = o.agentId;\n if (typeof o.launchId === 'string')\n ext.launchId = o.launchId;\n return Object.keys(ext).length > 0 ? ext : undefined;\n}\n/**\n * Decode one wire frame against `schemas` (the wire's `type` → payload map).\n * Two-step parse: envelope first, then the per-type payload schema — an unknown\n * `type` is a typed `UNKNOWN_FRAME` failure (a REP, never a hard close).\n */\nexport function decodeEnvelopeWith(schemas, text) {\n if (byteLength(text) > MAX_FRAME_BYTES) {\n return { ok: false, id: NIL_UUID, msg: 'FRAME_TOO_LARGE' };\n }\n let json;\n try {\n json = JSON.parse(text);\n }\n catch {\n return { ok: false, id: NIL_UUID, msg: 'invalid json' };\n }\n const env = Envelope.safeParse(json);\n if (!env.success) {\n const id = typeof json === 'object' && json !== null && typeof json.id === 'string'\n ? json.id\n : NIL_UUID;\n return { ok: false, id, msg: env.error.message };\n }\n const schema = Object.hasOwn(schemas, env.data.type) ? schemas[env.data.type] : undefined;\n if (!schema) {\n return {\n ok: false,\n id: env.data.id,\n msg: 'UNKNOWN_FRAME',\n ...(env.data.corr ? { corr: env.data.corr } : {})\n };\n }\n const payload = schema.safeParse(env.data.payload);\n if (!payload.success) {\n return {\n ok: false,\n id: env.data.id,\n msg: payload.error.message,\n ...(env.data.corr ? { corr: env.data.corr } : {})\n };\n }\n const ext = extractControlExt(json);\n return {\n ok: true,\n frame: { ...env.data, payload: payload.data },\n ...(ext ? { ext } : {})\n };\n}\n/**\n * Wrap a payload in the wire envelope. Untyped core — each wire exports a typed\n * wrapper (`buildEnvelope` / `buildRelayCpFrame` / `buildRelayDaemonFrame`) that\n * pins `type` to its own union and casts the result.\n */\nexport function buildEnvelopeRaw(type, payload, opts = {}) {\n return {\n v: 1,\n id: opts.id ?? randomUUID(),\n ts: opts.ts ?? new Date().toISOString(),\n type,\n payload,\n ...(opts.corr ? { corr: opts.corr } : {}),\n ...(opts.orgId ? { orgId: opts.orgId } : {}),\n ...(opts.ext ?? {})\n };\n}\n//# sourceMappingURL=wire.js.map","import { FRAME_SCHEMAS } from './index.js';\nimport { MAX_FRAME_BYTES, buildEnvelopeRaw, decodeEnvelopeWith } from './wire.js';\n/**\n * The daemon↔CP wire codec — the `FRAME_SCHEMAS` instantiation of the generic\n * envelope codec in `wire.ts`. The relay wires (`frames/relay-*.ts`) build their\n * own instantiations over their own schema maps; the unions never mix.\n */\nexport { MAX_FRAME_BYTES };\nexport function decodeEnvelope(text) {\n return decodeEnvelopeWith(FRAME_SCHEMAS, text);\n}\nexport function buildEnvelope(type, payload, opts = {}) {\n return buildEnvelopeRaw(type, payload, opts);\n}\nexport function encode(frame) {\n return JSON.stringify(frame);\n}\n//# sourceMappingURL=codec.js.map","export class SystemClock {\n now() {\n return Date.now();\n }\n setTimeout(fn, ms) {\n return globalThis.setTimeout(fn, ms);\n }\n clearTimeout(h) {\n globalThis.clearTimeout(h);\n }\n}\nexport const systemClock = new SystemClock();\n/**\n * A deterministic Clock for unit tests: `now` only advances via {@link advance},\n * which fires every timer whose deadline has passed (in deadline order). No real\n * timers arm, so tests never race the wall clock.\n */\nexport class FakeClock {\n t = 0;\n seq = 0;\n timers = new Map();\n constructor(startMs = 0) {\n this.t = startMs;\n }\n now() {\n return this.t;\n }\n /** Armed-timer count — how a test waits for the code under test to park on a delay\n * instead of guessing from a side effect that lands earlier. */\n get pending() {\n return this.timers.size;\n }\n setTimeout(fn, ms) {\n const id = ++this.seq;\n this.timers.set(id, { at: this.t + Math.max(0, ms), fn });\n return id;\n }\n clearTimeout(h) {\n this.timers.delete(h);\n }\n /** Advance time by `ms`, firing every timer that comes due, earliest first. */\n advance(ms) {\n const until = this.t + ms;\n for (;;) {\n let next;\n for (const [id, e] of this.timers) {\n if (e.at <= until && (!next || e.at < next.at))\n next = { id, at: e.at, fn: e.fn };\n }\n if (!next)\n break;\n this.timers.delete(next.id);\n this.t = next.at;\n next.fn();\n }\n this.t = until;\n }\n}\n//# sourceMappingURL=clock.js.map","/** Transport-free representation of a typed wire `error` REP. */\nexport class WireError extends Error {\n code;\n retryable;\n details;\n constructor(code, message, retryable = false, details) {\n super(message);\n this.name = 'WireError';\n this.code = code;\n this.retryable = retryable;\n if (details)\n this.details = details;\n }\n}\nexport class ReqRep {\n clock;\n ackTimeoutMs;\n maxTries;\n pending = new Map();\n constructor(clock, ackTimeoutMs, maxTries = 5) {\n this.clock = clock;\n this.ackTimeoutMs = ackTimeoutMs;\n this.maxTries = maxTries;\n }\n request(frame, write, opts = {}) {\n const encoded = JSON.stringify(frame);\n return new Promise((resolve, reject) => {\n const entry = {\n id: frame.id,\n encoded,\n resolve,\n reject,\n tries: 1,\n maxTries: opts.maxTries ?? this.maxTries\n };\n this.pending.set(frame.id, entry);\n this.arm(entry, write, opts.ackTimeoutMs ?? this.ackTimeoutMs);\n // A dead transport must reject THIS request — never throw into the caller\n // (or, on the timer path below, crash the process as an uncaught throw).\n try {\n write(encoded);\n }\n catch (e) {\n this.fail(entry, new WireError('INTERNAL', `send failed: ${e.message}`, true));\n }\n });\n }\n arm(entry, write, ackTimeoutMs) {\n entry.timer = this.clock.setTimeout(() => {\n if (!this.pending.has(entry.id))\n return;\n if (entry.tries >= entry.maxTries) {\n this.pending.delete(entry.id);\n entry.reject(new WireError('INTERNAL', `no ack after ${entry.maxTries} tries for ${entry.id}`, true));\n return;\n }\n entry.tries += 1;\n this.arm(entry, write, ackTimeoutMs);\n try {\n write(entry.encoded);\n }\n catch (e) {\n this.fail(entry, new WireError('INTERNAL', `send failed: ${e.message}`, true));\n }\n }, ackTimeoutMs);\n }\n fail(entry, err) {\n if (!this.pending.has(entry.id))\n return;\n this.pending.delete(entry.id);\n if (entry.timer !== undefined)\n this.clock.clearTimeout(entry.timer);\n entry.reject(err);\n }\n /**\n * Settle a pending REQ from an inbound correlated frame. Returns true when\n * `frame.corr` matched a pending REQ (a REP resolves it; an `error` frame\n * rejects with a {@link WireError}), false when it correlates nothing.\n */\n settle(frame) {\n const corr = frame.corr;\n if (!corr)\n return false;\n if (frame.type === 'error') {\n const e = frame.payload;\n return this.reject(corr, new WireError(e.code, e.message, e.retryable, e.details));\n }\n const entry = this.pending.get(corr);\n if (!entry)\n return false;\n this.pending.delete(corr);\n if (entry.timer !== undefined)\n this.clock.clearTimeout(entry.timer);\n entry.resolve(frame);\n return true;\n }\n /** Reject one pending request by correlation id (e.g. a REP whose envelope is\n * valid but whose payload cannot be decoded). Returns false when nothing matches. */\n reject(corr, err) {\n const entry = this.pending.get(corr);\n if (!entry)\n return false;\n this.pending.delete(corr);\n if (entry.timer !== undefined)\n this.clock.clearTimeout(entry.timer);\n entry.reject(err);\n return true;\n }\n inflight() {\n return this.pending.size;\n }\n rejectAll(err) {\n for (const entry of this.pending.values()) {\n if (entry.timer !== undefined)\n this.clock.clearTimeout(entry.timer);\n entry.reject(err);\n }\n this.pending.clear();\n }\n}\n//# sourceMappingURL=correlator.js.map","'use strict';\n\nconst BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];\nconst hasBlob = typeof Blob !== 'undefined';\n\nif (hasBlob) BINARY_TYPES.push('blob');\n\nmodule.exports = {\n BINARY_TYPES,\n CLOSE_TIMEOUT: 30000,\n EMPTY_BUFFER: Buffer.alloc(0),\n GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',\n hasBlob,\n kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),\n kListener: Symbol('kListener'),\n kStatusCode: Symbol('status-code'),\n kWebSocket: Symbol('websocket'),\n NOOP: () => {}\n};\n","'use strict';\n\nconst { EMPTY_BUFFER } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\n\n/**\n * Merges an array of buffers into a new buffer.\n *\n * @param {Buffer[]} list The array of buffers to concat\n * @param {Number} totalLength The total length of buffers in the list\n * @return {Buffer} The resulting buffer\n * @public\n */\nfunction concat(list, totalLength) {\n if (list.length === 0) return EMPTY_BUFFER;\n if (list.length === 1) return list[0];\n\n const target = Buffer.allocUnsafe(totalLength);\n let offset = 0;\n\n for (let i = 0; i < list.length; i++) {\n const buf = list[i];\n target.set(buf, offset);\n offset += buf.length;\n }\n\n if (offset < totalLength) {\n return new FastBuffer(target.buffer, target.byteOffset, offset);\n }\n\n return target;\n}\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nfunction _mask(source, mask, output, offset, length) {\n for (let i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n}\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nfunction _unmask(buffer, mask) {\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n}\n\n/**\n * Converts a buffer to an `ArrayBuffer`.\n *\n * @param {Buffer} buf The buffer to convert\n * @return {ArrayBuffer} Converted buffer\n * @public\n */\nfunction toArrayBuffer(buf) {\n if (buf.length === buf.buffer.byteLength) {\n return buf.buffer;\n }\n\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);\n}\n\n/**\n * Converts `data` to a `Buffer`.\n *\n * @param {*} data The data to convert\n * @return {Buffer} The buffer\n * @throws {TypeError}\n * @public\n */\nfunction toBuffer(data) {\n toBuffer.readOnly = true;\n\n if (Buffer.isBuffer(data)) return data;\n\n let buf;\n\n if (data instanceof ArrayBuffer) {\n buf = new FastBuffer(data);\n } else if (ArrayBuffer.isView(data)) {\n buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);\n } else {\n buf = Buffer.from(data);\n toBuffer.readOnly = false;\n }\n\n return buf;\n}\n\nmodule.exports = {\n concat,\n mask: _mask,\n toArrayBuffer,\n toBuffer,\n unmask: _unmask\n};\n\n/* istanbul ignore else */\nif (!process.env.WS_NO_BUFFER_UTIL) {\n try {\n const bufferUtil = require('bufferutil');\n\n module.exports.mask = function (source, mask, output, offset, length) {\n if (length < 48) _mask(source, mask, output, offset, length);\n else bufferUtil.mask(source, mask, output, offset, length);\n };\n\n module.exports.unmask = function (buffer, mask) {\n if (buffer.length < 32) _unmask(buffer, mask);\n else bufferUtil.unmask(buffer, mask);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst kDone = Symbol('kDone');\nconst kRun = Symbol('kRun');\n\n/**\n * A very simple job queue with adjustable concurrency. Adapted from\n * https://github.com/STRML/async-limiter\n */\nclass Limiter {\n /**\n * Creates a new `Limiter`.\n *\n * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed\n * to run concurrently\n */\n constructor(concurrency) {\n this[kDone] = () => {\n this.pending--;\n this[kRun]();\n };\n this.concurrency = concurrency || Infinity;\n this.jobs = [];\n this.pending = 0;\n }\n\n /**\n * Adds a job to the queue.\n *\n * @param {Function} job The job to run\n * @public\n */\n add(job) {\n this.jobs.push(job);\n this[kRun]();\n }\n\n /**\n * Removes a job from the queue and runs it if possible.\n *\n * @private\n */\n [kRun]() {\n if (this.pending === this.concurrency) return;\n\n if (this.jobs.length) {\n const job = this.jobs.shift();\n\n this.pending++;\n job(this[kDone]);\n }\n }\n}\n\nmodule.exports = Limiter;\n","'use strict';\n\nconst zlib = require('zlib');\n\nconst bufferUtil = require('./buffer-util');\nconst Limiter = require('./limiter');\nconst { kStatusCode } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);\nconst kPerMessageDeflate = Symbol('permessage-deflate');\nconst kTotalLength = Symbol('total-length');\nconst kCallback = Symbol('callback');\nconst kBuffers = Symbol('buffers');\nconst kError = Symbol('error');\n\n//\n// We limit zlib concurrency, which prevents severe memory fragmentation\n// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913\n// and https://github.com/websockets/ws/issues/1202\n//\n// Intentionally global; it's the global thread pool that's an issue.\n//\nlet zlibLimiter;\n\n/**\n * permessage-deflate implementation.\n */\nclass PerMessageDeflate {\n /**\n * Creates a PerMessageDeflate instance.\n *\n * @param {Object} [options] Configuration options\n * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support\n * for, or request, a custom client window size\n * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/\n * acknowledge disabling of client context takeover\n * @param {Number} [options.concurrencyLimit=10] The number of concurrent\n * calls to zlib\n * @param {Boolean} [options.isServer=false] Create the instance in either\n * server or client mode\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the\n * use of a custom server window size\n * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept\n * disabling of server context takeover\n * @param {Number} [options.threshold=1024] Size (in bytes) below which\n * messages should not be compressed if context takeover is disabled\n * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on\n * deflate\n * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on\n * inflate\n */\n constructor(options) {\n this._options = options || {};\n this._threshold =\n this._options.threshold !== undefined ? this._options.threshold : 1024;\n this._maxPayload = this._options.maxPayload | 0;\n this._isServer = !!this._options.isServer;\n this._deflate = null;\n this._inflate = null;\n\n this.params = null;\n\n if (!zlibLimiter) {\n const concurrency =\n this._options.concurrencyLimit !== undefined\n ? this._options.concurrencyLimit\n : 10;\n zlibLimiter = new Limiter(concurrency);\n }\n }\n\n /**\n * @type {String}\n */\n static get extensionName() {\n return 'permessage-deflate';\n }\n\n /**\n * Create an extension negotiation offer.\n *\n * @return {Object} Extension parameters\n * @public\n */\n offer() {\n const params = {};\n\n if (this._options.serverNoContextTakeover) {\n params.server_no_context_takeover = true;\n }\n if (this._options.clientNoContextTakeover) {\n params.client_no_context_takeover = true;\n }\n if (this._options.serverMaxWindowBits) {\n params.server_max_window_bits = this._options.serverMaxWindowBits;\n }\n if (this._options.clientMaxWindowBits) {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n } else if (this._options.clientMaxWindowBits == null) {\n params.client_max_window_bits = true;\n }\n\n return params;\n }\n\n /**\n * Accept an extension negotiation offer/response.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Object} Accepted configuration\n * @public\n */\n accept(configurations) {\n configurations = this.normalizeParams(configurations);\n\n this.params = this._isServer\n ? this.acceptAsServer(configurations)\n : this.acceptAsClient(configurations);\n\n return this.params;\n }\n\n /**\n * Releases all resources used by the extension.\n *\n * @public\n */\n cleanup() {\n if (this._inflate) {\n this._inflate.close();\n this._inflate = null;\n }\n\n if (this._deflate) {\n const callback = this._deflate[kCallback];\n\n this._deflate.close();\n this._deflate = null;\n\n if (callback) {\n callback(\n new Error(\n 'The deflate stream was closed while data was being processed'\n )\n );\n }\n }\n }\n\n /**\n * Accept an extension negotiation offer.\n *\n * @param {Array} offers The extension negotiation offers\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsServer(offers) {\n const opts = this._options;\n const accepted = offers.find((params) => {\n if (\n (opts.serverNoContextTakeover === false &&\n params.server_no_context_takeover) ||\n (params.server_max_window_bits &&\n (opts.serverMaxWindowBits === false ||\n (typeof opts.serverMaxWindowBits === 'number' &&\n opts.serverMaxWindowBits > params.server_max_window_bits))) ||\n (typeof opts.clientMaxWindowBits === 'number' &&\n !params.client_max_window_bits)\n ) {\n return false;\n }\n\n return true;\n });\n\n if (!accepted) {\n throw new Error('None of the extension offers can be accepted');\n }\n\n if (opts.serverNoContextTakeover) {\n accepted.server_no_context_takeover = true;\n }\n if (opts.clientNoContextTakeover) {\n accepted.client_no_context_takeover = true;\n }\n if (typeof opts.serverMaxWindowBits === 'number') {\n accepted.server_max_window_bits = opts.serverMaxWindowBits;\n }\n if (typeof opts.clientMaxWindowBits === 'number') {\n accepted.client_max_window_bits = opts.clientMaxWindowBits;\n } else if (\n accepted.client_max_window_bits === true ||\n opts.clientMaxWindowBits === false\n ) {\n delete accepted.client_max_window_bits;\n }\n\n return accepted;\n }\n\n /**\n * Accept the extension negotiation response.\n *\n * @param {Array} response The extension negotiation response\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsClient(response) {\n const params = response[0];\n\n if (\n this._options.clientNoContextTakeover === false &&\n params.client_no_context_takeover\n ) {\n throw new Error('Unexpected parameter \"client_no_context_takeover\"');\n }\n\n if (!params.client_max_window_bits) {\n if (typeof this._options.clientMaxWindowBits === 'number') {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n }\n } else if (\n this._options.clientMaxWindowBits === false ||\n (typeof this._options.clientMaxWindowBits === 'number' &&\n params.client_max_window_bits > this._options.clientMaxWindowBits)\n ) {\n throw new Error(\n 'Unexpected or invalid parameter \"client_max_window_bits\"'\n );\n }\n\n return params;\n }\n\n /**\n * Normalize parameters.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Array} The offers/response with normalized parameters\n * @private\n */\n normalizeParams(configurations) {\n configurations.forEach((params) => {\n Object.keys(params).forEach((key) => {\n let value = params[key];\n\n if (value.length > 1) {\n throw new Error(`Parameter \"${key}\" must have only a single value`);\n }\n\n value = value[0];\n\n if (key === 'client_max_window_bits') {\n if (value !== true) {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (!this._isServer) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else if (key === 'server_max_window_bits') {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (\n key === 'client_no_context_takeover' ||\n key === 'server_no_context_takeover'\n ) {\n if (value !== true) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else {\n throw new Error(`Unknown parameter \"${key}\"`);\n }\n\n params[key] = value;\n });\n });\n\n return configurations;\n }\n\n /**\n * Decompress data. Concurrency limited.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n decompress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._decompress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Compress data. Concurrency limited.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n compress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._compress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Decompress data.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _decompress(data, fin, callback) {\n const endpoint = this._isServer ? 'client' : 'server';\n\n if (!this._inflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._inflate = zlib.createInflateRaw({\n ...this._options.zlibInflateOptions,\n windowBits\n });\n this._inflate[kPerMessageDeflate] = this;\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n this._inflate.on('error', inflateOnError);\n this._inflate.on('data', inflateOnData);\n }\n\n this._inflate[kCallback] = callback;\n\n this._inflate.write(data);\n if (fin) this._inflate.write(TRAILER);\n\n this._inflate.flush(() => {\n const err = this._inflate[kError];\n\n if (err) {\n this._inflate.close();\n this._inflate = null;\n callback(err);\n return;\n }\n\n const data = bufferUtil.concat(\n this._inflate[kBuffers],\n this._inflate[kTotalLength]\n );\n\n if (this._inflate._readableState.endEmitted) {\n this._inflate.close();\n this._inflate = null;\n } else {\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._inflate.reset();\n }\n }\n\n callback(null, data);\n });\n }\n\n /**\n * Compress data.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _compress(data, fin, callback) {\n const endpoint = this._isServer ? 'server' : 'client';\n\n if (!this._deflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._deflate = zlib.createDeflateRaw({\n ...this._options.zlibDeflateOptions,\n windowBits\n });\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n this._deflate.on('data', deflateOnData);\n }\n\n this._deflate[kCallback] = callback;\n\n this._deflate.write(data);\n this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {\n if (!this._deflate) {\n //\n // The deflate stream was closed while data was being processed.\n //\n return;\n }\n\n let data = bufferUtil.concat(\n this._deflate[kBuffers],\n this._deflate[kTotalLength]\n );\n\n if (fin) {\n data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);\n }\n\n //\n // Ensure that the callback will not be called again in\n // `PerMessageDeflate#cleanup()`.\n //\n this._deflate[kCallback] = null;\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._deflate.reset();\n }\n\n callback(null, data);\n });\n }\n}\n\nmodule.exports = PerMessageDeflate;\n\n/**\n * The listener of the `zlib.DeflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction deflateOnData(chunk) {\n this[kBuffers].push(chunk);\n this[kTotalLength] += chunk.length;\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction inflateOnData(chunk) {\n this[kTotalLength] += chunk.length;\n\n if (\n this[kPerMessageDeflate]._maxPayload < 1 ||\n this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload\n ) {\n this[kBuffers].push(chunk);\n return;\n }\n\n this[kError] = new RangeError('Max payload size exceeded');\n this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';\n this[kError][kStatusCode] = 1009;\n this.removeListener('data', inflateOnData);\n\n //\n // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the\n // fact that in Node.js versions prior to 13.10.0, the callback for\n // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing\n // `zlib.reset()` ensures that either the callback is invoked or an error is\n // emitted.\n //\n this.reset();\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'error'` event.\n *\n * @param {Error} err The emitted error\n * @private\n */\nfunction inflateOnError(err) {\n //\n // There is no need to call `Zlib#close()` as the handle is automatically\n // closed when an error is emitted.\n //\n this[kPerMessageDeflate]._inflate = null;\n\n if (this[kError]) {\n this[kCallback](this[kError]);\n return;\n }\n\n err[kStatusCode] = 1007;\n this[kCallback](err);\n}\n","'use strict';\n\nconst { isUtf8 } = require('buffer');\n\nconst { hasBlob } = require('./constants');\n\n//\n// Allowed token characters:\n//\n// '!', '#', '$', '%', '&', ''', '*', '+', '-',\n// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'\n//\n// tokenChars[32] === 0 // ' '\n// tokenChars[33] === 1 // '!'\n// tokenChars[34] === 0 // '\"'\n// ...\n//\n// prettier-ignore\nconst tokenChars = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31\n 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127\n];\n\n/**\n * Checks if a status code is allowed in a close frame.\n *\n * @param {Number} code The status code\n * @return {Boolean} `true` if the status code is valid, else `false`\n * @public\n */\nfunction isValidStatusCode(code) {\n return (\n (code >= 1000 &&\n code <= 1014 &&\n code !== 1004 &&\n code !== 1005 &&\n code !== 1006) ||\n (code >= 3000 && code <= 4999)\n );\n}\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction _isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0) {\n // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) {\n // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // Overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) {\n // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong\n (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) {\n // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong\n (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||\n buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Determines whether a value is a `Blob`.\n *\n * @param {*} value The value to be tested\n * @return {Boolean} `true` if `value` is a `Blob`, else `false`\n * @private\n */\nfunction isBlob(value) {\n return (\n hasBlob &&\n typeof value === 'object' &&\n typeof value.arrayBuffer === 'function' &&\n typeof value.type === 'string' &&\n typeof value.stream === 'function' &&\n (value[Symbol.toStringTag] === 'Blob' ||\n value[Symbol.toStringTag] === 'File')\n );\n}\n\nmodule.exports = {\n isBlob,\n isValidStatusCode,\n isValidUTF8: _isValidUTF8,\n tokenChars\n};\n\nif (isUtf8) {\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);\n };\n} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {\n try {\n const isValidUTF8 = require('utf-8-validate');\n\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst { Writable } = require('stream');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n kStatusCode,\n kWebSocket\n} = require('./constants');\nconst { concat, toArrayBuffer, unmask } = require('./buffer-util');\nconst { isValidStatusCode, isValidUTF8 } = require('./validation');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst GET_INFO = 0;\nconst GET_PAYLOAD_LENGTH_16 = 1;\nconst GET_PAYLOAD_LENGTH_64 = 2;\nconst GET_MASK = 3;\nconst GET_DATA = 4;\nconst INFLATING = 5;\nconst DEFER_EVENT = 6;\n\n/**\n * HyBi Receiver implementation.\n *\n * @extends Writable\n */\nclass Receiver extends Writable {\n /**\n * Creates a Receiver instance.\n *\n * @param {Object} [options] Options object\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {String} [options.binaryType=nodebuffer] The type for binary data\n * @param {Object} [options.extensions] An object containing the negotiated\n * extensions\n * @param {Boolean} [options.isServer=false] Specifies whether to operate in\n * client or server mode\n * @param {Number} [options.maxBufferedChunks=0] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=0] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n */\n constructor(options = {}) {\n super();\n\n this._allowSynchronousEvents =\n options.allowSynchronousEvents !== undefined\n ? options.allowSynchronousEvents\n : true;\n this._binaryType = options.binaryType || BINARY_TYPES[0];\n this._extensions = options.extensions || {};\n this._isServer = !!options.isServer;\n this._maxBufferedChunks = options.maxBufferedChunks | 0;\n this._maxFragments = options.maxFragments | 0;\n this._maxPayload = options.maxPayload | 0;\n this._skipUTF8Validation = !!options.skipUTF8Validation;\n this[kWebSocket] = undefined;\n\n this._bufferedBytes = 0;\n this._buffers = [];\n\n this._compressed = false;\n this._payloadLength = 0;\n this._mask = undefined;\n this._fragmented = 0;\n this._masked = false;\n this._fin = false;\n this._opcode = 0;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._numFragments = 0;\n this._fragments = [];\n\n this._errored = false;\n this._loop = false;\n this._state = GET_INFO;\n }\n\n /**\n * Implements `Writable.prototype._write()`.\n *\n * @param {Buffer} chunk The chunk of data to write\n * @param {String} encoding The character encoding of `chunk`\n * @param {Function} cb Callback\n * @private\n */\n _write(chunk, encoding, cb) {\n if (this._opcode === 0x08 && this._state == GET_INFO) return cb();\n\n if (\n this._maxBufferedChunks > 0 &&\n this._buffers.length >= this._maxBufferedChunks\n ) {\n cb(\n this.createError(\n RangeError,\n 'Too many buffered chunks',\n false,\n 1008,\n 'WS_ERR_TOO_MANY_BUFFERED_PARTS'\n )\n );\n return;\n }\n\n this._bufferedBytes += chunk.length;\n this._buffers.push(chunk);\n this.startLoop(cb);\n }\n\n /**\n * Consumes `n` bytes from the buffered data.\n *\n * @param {Number} n The number of bytes to consume\n * @return {Buffer} The consumed bytes\n * @private\n */\n consume(n) {\n this._bufferedBytes -= n;\n\n if (n === this._buffers[0].length) return this._buffers.shift();\n\n if (n < this._buffers[0].length) {\n const buf = this._buffers[0];\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n\n return new FastBuffer(buf.buffer, buf.byteOffset, n);\n }\n\n const dst = Buffer.allocUnsafe(n);\n\n do {\n const buf = this._buffers[0];\n const offset = dst.length - n;\n\n if (n >= buf.length) {\n dst.set(this._buffers.shift(), offset);\n } else {\n dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n }\n\n n -= buf.length;\n } while (n > 0);\n\n return dst;\n }\n\n /**\n * Starts the parsing loop.\n *\n * @param {Function} cb Callback\n * @private\n */\n startLoop(cb) {\n this._loop = true;\n\n do {\n switch (this._state) {\n case GET_INFO:\n this.getInfo(cb);\n break;\n case GET_PAYLOAD_LENGTH_16:\n this.getPayloadLength16(cb);\n break;\n case GET_PAYLOAD_LENGTH_64:\n this.getPayloadLength64(cb);\n break;\n case GET_MASK:\n this.getMask();\n break;\n case GET_DATA:\n this.getData(cb);\n break;\n case INFLATING:\n case DEFER_EVENT:\n this._loop = false;\n return;\n }\n } while (this._loop);\n\n if (!this._errored) cb();\n }\n\n /**\n * Reads the first two bytes of a frame.\n *\n * @param {Function} cb Callback\n * @private\n */\n getInfo(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(2);\n\n if ((buf[0] & 0x30) !== 0x00) {\n const error = this.createError(\n RangeError,\n 'RSV2 and RSV3 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_2_3'\n );\n\n cb(error);\n return;\n }\n\n const compressed = (buf[0] & 0x40) === 0x40;\n\n if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n this._fin = (buf[0] & 0x80) === 0x80;\n this._opcode = buf[0] & 0x0f;\n this._payloadLength = buf[1] & 0x7f;\n\n if (this._opcode === 0x00) {\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fragmented) {\n const error = this.createError(\n RangeError,\n 'invalid opcode 0',\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._opcode = this._fragmented;\n } else if (this._opcode === 0x01 || this._opcode === 0x02) {\n if (this._fragmented) {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._compressed = compressed;\n } else if (this._opcode > 0x07 && this._opcode < 0x0b) {\n if (!this._fin) {\n const error = this.createError(\n RangeError,\n 'FIN must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_FIN'\n );\n\n cb(error);\n return;\n }\n\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (\n this._payloadLength > 0x7d ||\n (this._opcode === 0x08 && this._payloadLength === 1)\n ) {\n const error = this.createError(\n RangeError,\n `invalid payload length ${this._payloadLength}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n } else {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fin && !this._fragmented) this._fragmented = this._opcode;\n this._masked = (buf[1] & 0x80) === 0x80;\n\n if (this._isServer) {\n if (!this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n } else if (this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n\n if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;\n else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;\n else this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+16).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength16(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n this._payloadLength = this.consume(2).readUInt16BE(0);\n this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+64).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength64(cb) {\n if (this._bufferedBytes < 8) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(8);\n const num = buf.readUInt32BE(0);\n\n //\n // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned\n // if payload length is greater than this number.\n //\n if (num > Math.pow(2, 53 - 32) - 1) {\n const error = this.createError(\n RangeError,\n 'Unsupported WebSocket frame: payload length > 2^53 - 1',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);\n this.haveLength(cb);\n }\n\n /**\n * Payload length has been read.\n *\n * @param {Function} cb Callback\n * @private\n */\n haveLength(cb) {\n if (this._payloadLength && this._opcode < 0x08) {\n this._totalPayloadLength += this._payloadLength;\n if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n }\n\n if (this._masked) this._state = GET_MASK;\n else this._state = GET_DATA;\n }\n\n /**\n * Reads mask bytes.\n *\n * @private\n */\n getMask() {\n if (this._bufferedBytes < 4) {\n this._loop = false;\n return;\n }\n\n this._mask = this.consume(4);\n this._state = GET_DATA;\n }\n\n /**\n * Reads data bytes.\n *\n * @param {Function} cb Callback\n * @private\n */\n getData(cb) {\n let data = EMPTY_BUFFER;\n\n if (this._payloadLength) {\n if (this._bufferedBytes < this._payloadLength) {\n this._loop = false;\n return;\n }\n\n data = this.consume(this._payloadLength);\n\n if (\n this._masked &&\n (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0\n ) {\n unmask(data, this._mask);\n }\n }\n\n if (this._opcode > 0x07) {\n this.controlMessage(data, cb);\n return;\n }\n\n if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {\n const error = this.createError(\n RangeError,\n 'Too many message fragments',\n false,\n 1008,\n 'WS_ERR_TOO_MANY_BUFFERED_PARTS'\n );\n\n cb(error);\n return;\n }\n\n if (this._compressed) {\n this._state = INFLATING;\n this.decompress(data, cb);\n return;\n }\n\n if (data.length) {\n //\n // This message is not compressed so its length is the sum of the payload\n // length of all fragments.\n //\n this._messageLength = this._totalPayloadLength;\n this._fragments.push(data);\n }\n\n this.dataMessage(cb);\n }\n\n /**\n * Decompresses data.\n *\n * @param {Buffer} data Compressed data\n * @param {Function} cb Callback\n * @private\n */\n decompress(data, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n perMessageDeflate.decompress(data, this._fin, (err, buf) => {\n if (err) return cb(err);\n\n if (buf.length) {\n this._messageLength += buf.length;\n if (this._messageLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._fragments.push(buf);\n }\n\n this.dataMessage(cb);\n if (this._state === GET_INFO) this.startLoop(cb);\n });\n }\n\n /**\n * Handles a data message.\n *\n * @param {Function} cb Callback\n * @private\n */\n dataMessage(cb) {\n if (!this._fin) {\n this._state = GET_INFO;\n return;\n }\n\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._numFragments = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n let data;\n\n if (this._binaryType === 'nodebuffer') {\n data = concat(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(concat(fragments, messageLength));\n } else if (this._binaryType === 'blob') {\n data = new Blob(fragments);\n } else {\n data = fragments;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit('message', data, true);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', data, true);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n } else {\n const buf = concat(fragments, messageLength);\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n if (this._state === INFLATING || this._allowSynchronousEvents) {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n }\n\n /**\n * Handles a control message.\n *\n * @param {Buffer} data Data to handle\n * @return {(Error|RangeError|undefined)} A possible error\n * @private\n */\n controlMessage(data, cb) {\n if (this._opcode === 0x08) {\n if (data.length === 0) {\n this._loop = false;\n this.emit('conclude', 1005, EMPTY_BUFFER);\n this.end();\n } else {\n const code = data.readUInt16BE(0);\n\n if (!isValidStatusCode(code)) {\n const error = this.createError(\n RangeError,\n `invalid status code ${code}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CLOSE_CODE'\n );\n\n cb(error);\n return;\n }\n\n const buf = new FastBuffer(\n data.buffer,\n data.byteOffset + 2,\n data.length - 2\n );\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n this._loop = false;\n this.emit('conclude', code, buf);\n this.end();\n }\n\n this._state = GET_INFO;\n return;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n\n /**\n * Builds an error object.\n *\n * @param {function(new:Error|RangeError)} ErrorCtor The error constructor\n * @param {String} message The error message\n * @param {Boolean} prefix Specifies whether or not to add a default prefix to\n * `message`\n * @param {Number} statusCode The status code\n * @param {String} errorCode The exposed error code\n * @return {(Error|RangeError)} The error\n * @private\n */\n createError(ErrorCtor, message, prefix, statusCode, errorCode) {\n this._loop = false;\n this._errored = true;\n\n const err = new ErrorCtor(\n prefix ? `Invalid WebSocket frame: ${message}` : message\n );\n\n Error.captureStackTrace(err, this.createError);\n err.code = errorCode;\n err[kStatusCode] = statusCode;\n return err;\n }\n}\n\nmodule.exports = Receiver;\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex\" }] */\n\n'use strict';\n\nconst { Duplex } = require('stream');\nconst { randomFillSync } = require('crypto');\nconst {\n types: { isUint8Array }\n} = require('util');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');\nconst { isBlob, isValidStatusCode } = require('./validation');\nconst { mask: applyMask, toBuffer } = require('./buffer-util');\n\nconst kByteLength = Symbol('kByteLength');\nconst maskBuffer = Buffer.alloc(4);\nconst RANDOM_POOL_SIZE = 8 * 1024;\nlet randomPool;\nlet randomPoolPointer = RANDOM_POOL_SIZE;\n\nconst DEFAULT = 0;\nconst DEFLATING = 1;\nconst GET_BLOB_DATA = 2;\n\n/**\n * HyBi Sender implementation.\n */\nclass Sender {\n /**\n * Creates a Sender instance.\n *\n * @param {Duplex} socket The connection socket\n * @param {Object} [extensions] An object containing the negotiated extensions\n * @param {Function} [generateMask] The function used to generate the masking\n * key\n */\n constructor(socket, extensions, generateMask) {\n this._extensions = extensions || {};\n\n if (generateMask) {\n this._generateMask = generateMask;\n this._maskBuffer = Buffer.alloc(4);\n }\n\n this._socket = socket;\n\n this._firstFragment = true;\n this._compress = false;\n\n this._bufferedBytes = 0;\n this._queue = [];\n this._state = DEFAULT;\n this.onerror = NOOP;\n this[kWebSocket] = undefined;\n }\n\n /**\n * Frames a piece of data according to the HyBi WebSocket protocol.\n *\n * @param {(Buffer|String)} data The data to frame\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @return {(Buffer|String)[]} The framed data\n * @public\n */\n static frame(data, options) {\n let mask;\n let merge = false;\n let offset = 2;\n let skipMasking = false;\n\n if (options.mask) {\n mask = options.maskBuffer || maskBuffer;\n\n if (options.generateMask) {\n options.generateMask(mask);\n } else {\n if (randomPoolPointer === RANDOM_POOL_SIZE) {\n /* istanbul ignore else */\n if (randomPool === undefined) {\n //\n // This is lazily initialized because server-sent frames must not\n // be masked so it may never be used.\n //\n randomPool = Buffer.alloc(RANDOM_POOL_SIZE);\n }\n\n randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);\n randomPoolPointer = 0;\n }\n\n mask[0] = randomPool[randomPoolPointer++];\n mask[1] = randomPool[randomPoolPointer++];\n mask[2] = randomPool[randomPoolPointer++];\n mask[3] = randomPool[randomPoolPointer++];\n }\n\n skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;\n offset = 6;\n }\n\n let dataLength;\n\n if (typeof data === 'string') {\n if (\n (!options.mask || skipMasking) &&\n options[kByteLength] !== undefined\n ) {\n dataLength = options[kByteLength];\n } else {\n data = Buffer.from(data);\n dataLength = data.length;\n }\n } else {\n dataLength = data.length;\n merge = options.mask && options.readOnly && !skipMasking;\n }\n\n let payloadLength = dataLength;\n\n if (dataLength >= 65536) {\n offset += 8;\n payloadLength = 127;\n } else if (dataLength > 125) {\n offset += 2;\n payloadLength = 126;\n }\n\n const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);\n\n target[0] = options.fin ? options.opcode | 0x80 : options.opcode;\n if (options.rsv1) target[0] |= 0x40;\n\n target[1] = payloadLength;\n\n if (payloadLength === 126) {\n target.writeUInt16BE(dataLength, 2);\n } else if (payloadLength === 127) {\n target[2] = target[3] = 0;\n target.writeUIntBE(dataLength, 4, 6);\n }\n\n if (!options.mask) return [target, data];\n\n target[1] |= 0x80;\n target[offset - 4] = mask[0];\n target[offset - 3] = mask[1];\n target[offset - 2] = mask[2];\n target[offset - 1] = mask[3];\n\n if (skipMasking) return [target, data];\n\n if (merge) {\n applyMask(data, mask, target, offset, dataLength);\n return [target];\n }\n\n applyMask(data, mask, data, 0, dataLength);\n return [target, data];\n }\n\n /**\n * Sends a close message to the other peer.\n *\n * @param {Number} [code] The status code component of the body\n * @param {(String|Buffer)} [data] The message component of the body\n * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n * @param {Function} [cb] Callback\n * @public\n */\n close(code, data, mask, cb) {\n let buf;\n\n if (code === undefined) {\n buf = EMPTY_BUFFER;\n } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n throw new TypeError('First argument must be a valid error code number');\n } else if (data === undefined || !data.length) {\n buf = Buffer.allocUnsafe(2);\n buf.writeUInt16BE(code, 0);\n } else {\n const length = Buffer.byteLength(data);\n\n if (length > 123) {\n throw new RangeError('The message must not be greater than 123 bytes');\n }\n\n buf = Buffer.allocUnsafe(2 + length);\n buf.writeUInt16BE(code, 0);\n\n if (typeof data === 'string') {\n buf.write(data, 2);\n } else if (isUint8Array(data)) {\n buf.set(data, 2);\n } else {\n throw new TypeError('Second argument must be a string or a Uint8Array');\n }\n }\n\n const options = {\n [kByteLength]: buf.length,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x08,\n readOnly: false,\n rsv1: false\n };\n\n if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, buf, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(buf, options), cb);\n }\n }\n\n /**\n * Sends a ping message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n ping(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x09,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a pong message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n pong(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x0a,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a data message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Object} options Options object\n * @param {Boolean} [options.binary=false] Specifies whether `data` is binary\n * or text\n * @param {Boolean} [options.compress=false] Specifies whether or not to\n * compress `data`\n * @param {Boolean} [options.fin=false] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Function} [cb] Callback\n * @public\n */\n send(data, options, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n let opcode = options.binary ? 2 : 1;\n let rsv1 = options.compress;\n\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (this._firstFragment) {\n this._firstFragment = false;\n if (\n rsv1 &&\n perMessageDeflate &&\n perMessageDeflate.params[\n perMessageDeflate._isServer\n ? 'server_no_context_takeover'\n : 'client_no_context_takeover'\n ]\n ) {\n rsv1 = byteLength >= perMessageDeflate._threshold;\n }\n this._compress = rsv1;\n } else {\n rsv1 = false;\n opcode = 0;\n }\n\n if (options.fin) this._firstFragment = true;\n\n const opts = {\n [kByteLength]: byteLength,\n fin: options.fin,\n generateMask: this._generateMask,\n mask: options.mask,\n maskBuffer: this._maskBuffer,\n opcode,\n readOnly,\n rsv1\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, this._compress, opts, cb]);\n } else {\n this.getBlobData(data, this._compress, opts, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, this._compress, opts, cb]);\n } else {\n this.dispatch(data, this._compress, opts, cb);\n }\n }\n\n /**\n * Gets the contents of a blob as binary data.\n *\n * @param {Blob} blob The blob\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * the data\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n getBlobData(blob, compress, options, cb) {\n this._bufferedBytes += options[kByteLength];\n this._state = GET_BLOB_DATA;\n\n blob\n .arrayBuffer()\n .then((arrayBuffer) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while the blob was being read'\n );\n\n //\n // `callCallbacks` is called in the next tick to ensure that errors\n // that might be thrown in the callbacks behave like errors thrown\n // outside the promise chain.\n //\n process.nextTick(callCallbacks, this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n const data = toBuffer(arrayBuffer);\n\n if (!compress) {\n this._state = DEFAULT;\n this.sendFrame(Sender.frame(data, options), cb);\n this.dequeue();\n } else {\n this.dispatch(data, compress, options, cb);\n }\n })\n .catch((err) => {\n //\n // `onError` is called in the next tick for the same reason that\n // `callCallbacks` above is.\n //\n process.nextTick(onError, this, err, cb);\n });\n }\n\n /**\n * Dispatches a message.\n *\n * @param {(Buffer|String)} data The message to send\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * `data`\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n dispatch(data, compress, options, cb) {\n if (!compress) {\n this.sendFrame(Sender.frame(data, options), cb);\n return;\n }\n\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n this._bufferedBytes += options[kByteLength];\n this._state = DEFLATING;\n perMessageDeflate.compress(data, options.fin, (_, buf) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while data was being compressed'\n );\n\n callCallbacks(this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n this._state = DEFAULT;\n options.readOnly = false;\n this.sendFrame(Sender.frame(buf, options), cb);\n this.dequeue();\n });\n }\n\n /**\n * Executes queued send operations.\n *\n * @private\n */\n dequeue() {\n while (this._state === DEFAULT && this._queue.length) {\n const params = this._queue.shift();\n\n this._bufferedBytes -= params[3][kByteLength];\n Reflect.apply(params[0], this, params.slice(1));\n }\n }\n\n /**\n * Enqueues a send operation.\n *\n * @param {Array} params Send operation parameters.\n * @private\n */\n enqueue(params) {\n this._bufferedBytes += params[3][kByteLength];\n this._queue.push(params);\n }\n\n /**\n * Sends a frame.\n *\n * @param {(Buffer | String)[]} list The frame to send\n * @param {Function} [cb] Callback\n * @private\n */\n sendFrame(list, cb) {\n if (list.length === 2) {\n this._socket.cork();\n this._socket.write(list[0]);\n this._socket.write(list[1], cb);\n this._socket.uncork();\n } else {\n this._socket.write(list[0], cb);\n }\n }\n}\n\nmodule.exports = Sender;\n\n/**\n * Calls queued callbacks with an error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error to call the callbacks with\n * @param {Function} [cb] The first callback\n * @private\n */\nfunction callCallbacks(sender, err, cb) {\n if (typeof cb === 'function') cb(err);\n\n for (let i = 0; i < sender._queue.length; i++) {\n const params = sender._queue[i];\n const callback = params[params.length - 1];\n\n if (typeof callback === 'function') callback(err);\n }\n}\n\n/**\n * Handles a `Sender` error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error\n * @param {Function} [cb] The first pending callback\n * @private\n */\nfunction onError(sender, err, cb) {\n callCallbacks(sender, err, cb);\n sender.onerror(err);\n}\n","'use strict';\n\nconst { kForOnEventAttribute, kListener } = require('./constants');\n\nconst kCode = Symbol('kCode');\nconst kData = Symbol('kData');\nconst kError = Symbol('kError');\nconst kMessage = Symbol('kMessage');\nconst kReason = Symbol('kReason');\nconst kTarget = Symbol('kTarget');\nconst kType = Symbol('kType');\nconst kWasClean = Symbol('kWasClean');\n\n/**\n * Class representing an event.\n */\nclass Event {\n /**\n * Create a new `Event`.\n *\n * @param {String} type The name of the event\n * @throws {TypeError} If the `type` argument is not specified\n */\n constructor(type) {\n this[kTarget] = null;\n this[kType] = type;\n }\n\n /**\n * @type {*}\n */\n get target() {\n return this[kTarget];\n }\n\n /**\n * @type {String}\n */\n get type() {\n return this[kType];\n }\n}\n\nObject.defineProperty(Event.prototype, 'target', { enumerable: true });\nObject.defineProperty(Event.prototype, 'type', { enumerable: true });\n\n/**\n * Class representing a close event.\n *\n * @extends Event\n */\nclass CloseEvent extends Event {\n /**\n * Create a new `CloseEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {Number} [options.code=0] The status code explaining why the\n * connection was closed\n * @param {String} [options.reason=''] A human-readable string explaining why\n * the connection was closed\n * @param {Boolean} [options.wasClean=false] Indicates whether or not the\n * connection was cleanly closed\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kCode] = options.code === undefined ? 0 : options.code;\n this[kReason] = options.reason === undefined ? '' : options.reason;\n this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;\n }\n\n /**\n * @type {Number}\n */\n get code() {\n return this[kCode];\n }\n\n /**\n * @type {String}\n */\n get reason() {\n return this[kReason];\n }\n\n /**\n * @type {Boolean}\n */\n get wasClean() {\n return this[kWasClean];\n }\n}\n\nObject.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });\n\n/**\n * Class representing an error event.\n *\n * @extends Event\n */\nclass ErrorEvent extends Event {\n /**\n * Create a new `ErrorEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.error=null] The error that generated this event\n * @param {String} [options.message=''] The error message\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kError] = options.error === undefined ? null : options.error;\n this[kMessage] = options.message === undefined ? '' : options.message;\n }\n\n /**\n * @type {*}\n */\n get error() {\n return this[kError];\n }\n\n /**\n * @type {String}\n */\n get message() {\n return this[kMessage];\n }\n}\n\nObject.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });\nObject.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });\n\n/**\n * Class representing a message event.\n *\n * @extends Event\n */\nclass MessageEvent extends Event {\n /**\n * Create a new `MessageEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.data=null] The message content\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kData] = options.data === undefined ? null : options.data;\n }\n\n /**\n * @type {*}\n */\n get data() {\n return this[kData];\n }\n}\n\nObject.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });\n\n/**\n * This provides methods for emulating the `EventTarget` interface. It's not\n * meant to be used directly.\n *\n * @mixin\n */\nconst EventTarget = {\n /**\n * Register an event listener.\n *\n * @param {String} type A string representing the event type to listen for\n * @param {(Function|Object)} handler The listener to add\n * @param {Object} [options] An options object specifies characteristics about\n * the event listener\n * @param {Boolean} [options.once=false] A `Boolean` indicating that the\n * listener should be invoked at most once after being added. If `true`,\n * the listener would be automatically removed when invoked.\n * @public\n */\n addEventListener(type, handler, options = {}) {\n for (const listener of this.listeners(type)) {\n if (\n !options[kForOnEventAttribute] &&\n listener[kListener] === handler &&\n !listener[kForOnEventAttribute]\n ) {\n return;\n }\n }\n\n let wrapper;\n\n if (type === 'message') {\n wrapper = function onMessage(data, isBinary) {\n const event = new MessageEvent('message', {\n data: isBinary ? data : data.toString()\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'close') {\n wrapper = function onClose(code, message) {\n const event = new CloseEvent('close', {\n code,\n reason: message.toString(),\n wasClean: this._closeFrameReceived && this._closeFrameSent\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'error') {\n wrapper = function onError(error) {\n const event = new ErrorEvent('error', {\n error,\n message: error.message\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'open') {\n wrapper = function onOpen() {\n const event = new Event('open');\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else {\n return;\n }\n\n wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];\n wrapper[kListener] = handler;\n\n if (options.once) {\n this.once(type, wrapper);\n } else {\n this.on(type, wrapper);\n }\n },\n\n /**\n * Remove an event listener.\n *\n * @param {String} type A string representing the event type to remove\n * @param {(Function|Object)} handler The listener to remove\n * @public\n */\n removeEventListener(type, handler) {\n for (const listener of this.listeners(type)) {\n if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {\n this.removeListener(type, listener);\n break;\n }\n }\n }\n};\n\nmodule.exports = {\n CloseEvent,\n ErrorEvent,\n Event,\n EventTarget,\n MessageEvent\n};\n\n/**\n * Call an event listener\n *\n * @param {(Function|Object)} listener The listener to call\n * @param {*} thisArg The value to use as `this`` when calling the listener\n * @param {Event} event The event to pass to the listener\n * @private\n */\nfunction callListener(listener, thisArg, event) {\n if (typeof listener === 'object' && listener.handleEvent) {\n listener.handleEvent.call(listener, event);\n } else {\n listener.call(thisArg, event);\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Adds an offer to the map of extension offers or a parameter to the map of\n * parameters.\n *\n * @param {Object} dest The map of extension offers or parameters\n * @param {String} name The extension or parameter name\n * @param {(Object|Boolean|String)} elem The extension parameters or the\n * parameter value\n * @private\n */\nfunction push(dest, name, elem) {\n if (dest[name] === undefined) dest[name] = [elem];\n else dest[name].push(elem);\n}\n\n/**\n * Parses the `Sec-WebSocket-Extensions` header into an object.\n *\n * @param {String} header The field value of the header\n * @return {Object} The parsed object\n * @public\n */\nfunction parse(header) {\n const offers = Object.create(null);\n let params = Object.create(null);\n let mustUnescape = false;\n let isEscaping = false;\n let inQuotes = false;\n let extensionName;\n let paramName;\n let start = -1;\n let code = -1;\n let end = -1;\n let i = 0;\n\n for (; i < header.length; i++) {\n code = header.charCodeAt(i);\n\n if (extensionName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n const name = header.slice(start, end);\n if (code === 0x2c) {\n push(offers, name, params);\n params = Object.create(null);\n } else {\n extensionName = name;\n }\n\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (paramName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x20 || code === 0x09) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n push(params, header.slice(start, end), true);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n start = end = -1;\n } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {\n paramName = header.slice(start, i);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else {\n //\n // The value of a quoted-string after unescaping must conform to the\n // token ABNF, so only token characters are valid.\n // Ref: https://tools.ietf.org/html/rfc6455#section-9.1\n //\n if (isEscaping) {\n if (tokenChars[code] !== 1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n if (start === -1) start = i;\n else if (!mustUnescape) mustUnescape = true;\n isEscaping = false;\n } else if (inQuotes) {\n if (tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x22 /* '\"' */ && start !== -1) {\n inQuotes = false;\n end = i;\n } else if (code === 0x5c /* '\\' */) {\n isEscaping = true;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {\n inQuotes = true;\n } else if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (start !== -1 && (code === 0x20 || code === 0x09)) {\n if (end === -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n let value = header.slice(start, end);\n if (mustUnescape) {\n value = value.replace(/\\\\/g, '');\n mustUnescape = false;\n }\n push(params, paramName, value);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n paramName = undefined;\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n }\n\n if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n if (end === -1) end = i;\n const token = header.slice(start, end);\n if (extensionName === undefined) {\n push(offers, token, params);\n } else {\n if (paramName === undefined) {\n push(params, token, true);\n } else if (mustUnescape) {\n push(params, paramName, token.replace(/\\\\/g, ''));\n } else {\n push(params, paramName, token);\n }\n push(offers, extensionName, params);\n }\n\n return offers;\n}\n\n/**\n * Builds the `Sec-WebSocket-Extensions` header field value.\n *\n * @param {Object} extensions The map of extensions and parameters to format\n * @return {String} A string representing the given object\n * @public\n */\nfunction format(extensions) {\n return Object.keys(extensions)\n .map((extension) => {\n let configurations = extensions[extension];\n if (!Array.isArray(configurations)) configurations = [configurations];\n return configurations\n .map((params) => {\n return [extension]\n .concat(\n Object.keys(params).map((k) => {\n let values = params[k];\n if (!Array.isArray(values)) values = [values];\n return values\n .map((v) => (v === true ? k : `${k}=${v}`))\n .join('; ');\n })\n )\n .join('; ');\n })\n .join(', ');\n })\n .join(', ');\n}\n\nmodule.exports = { format, parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex|Readable$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst https = require('https');\nconst http = require('http');\nconst net = require('net');\nconst tls = require('tls');\nconst { randomBytes, createHash } = require('crypto');\nconst { Duplex, Readable } = require('stream');\nconst { URL } = require('url');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst Receiver = require('./receiver');\nconst Sender = require('./sender');\nconst { isBlob } = require('./validation');\n\nconst {\n BINARY_TYPES,\n CLOSE_TIMEOUT,\n EMPTY_BUFFER,\n GUID,\n kForOnEventAttribute,\n kListener,\n kStatusCode,\n kWebSocket,\n NOOP\n} = require('./constants');\nconst {\n EventTarget: { addEventListener, removeEventListener }\n} = require('./event-target');\nconst { format, parse } = require('./extension');\nconst { toBuffer } = require('./buffer-util');\n\nconst kAborted = Symbol('kAborted');\nconst protocolVersions = [8, 13];\nconst readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];\nconst subprotocolRegex = /^[!#$%&'*+\\-.0-9A-Z^_`|a-z~]+$/;\n\n/**\n * Class representing a WebSocket.\n *\n * @extends EventEmitter\n */\nclass WebSocket extends EventEmitter {\n /**\n * Create a new `WebSocket`.\n *\n * @param {(String|URL)} address The URL to which to connect\n * @param {(String|String[])} [protocols] The subprotocols\n * @param {Object} [options] Connection options\n */\n constructor(address, protocols, options) {\n super();\n\n this._binaryType = BINARY_TYPES[0];\n this._closeCode = 1006;\n this._closeFrameReceived = false;\n this._closeFrameSent = false;\n this._closeMessage = EMPTY_BUFFER;\n this._closeTimer = null;\n this._errorEmitted = false;\n this._extensions = {};\n this._paused = false;\n this._protocol = '';\n this._readyState = WebSocket.CONNECTING;\n this._receiver = null;\n this._sender = null;\n this._socket = null;\n\n if (address !== null) {\n this._bufferedAmount = 0;\n this._isServer = false;\n this._redirects = 0;\n\n if (protocols === undefined) {\n protocols = [];\n } else if (!Array.isArray(protocols)) {\n if (typeof protocols === 'object' && protocols !== null) {\n options = protocols;\n protocols = [];\n } else {\n protocols = [protocols];\n }\n }\n\n initAsClient(this, address, protocols, options);\n } else {\n this._autoPong = options.autoPong;\n this._closeTimeout = options.closeTimeout;\n this._isServer = true;\n }\n }\n\n /**\n * For historical reasons, the custom \"nodebuffer\" type is used by the default\n * instead of \"blob\".\n *\n * @type {String}\n */\n get binaryType() {\n return this._binaryType;\n }\n\n set binaryType(type) {\n if (!BINARY_TYPES.includes(type)) return;\n\n this._binaryType = type;\n\n //\n // Allow to change `binaryType` on the fly.\n //\n if (this._receiver) this._receiver._binaryType = type;\n }\n\n /**\n * @type {Number}\n */\n get bufferedAmount() {\n if (!this._socket) return this._bufferedAmount;\n\n return this._socket._writableState.length + this._sender._bufferedBytes;\n }\n\n /**\n * @type {String}\n */\n get extensions() {\n return Object.keys(this._extensions).join();\n }\n\n /**\n * @type {Boolean}\n */\n get isPaused() {\n return this._paused;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onclose() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onerror() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onopen() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onmessage() {\n return null;\n }\n\n /**\n * @type {String}\n */\n get protocol() {\n return this._protocol;\n }\n\n /**\n * @type {Number}\n */\n get readyState() {\n return this._readyState;\n }\n\n /**\n * @type {String}\n */\n get url() {\n return this._url;\n }\n\n /**\n * Set up the socket and the internal resources.\n *\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Object} options Options object\n * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.maxBufferedChunks=0] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=0] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=0] The maximum allowed message size\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\n setSocket(socket, head, options) {\n const receiver = new Receiver({\n allowSynchronousEvents: options.allowSynchronousEvents,\n binaryType: this.binaryType,\n extensions: this._extensions,\n isServer: this._isServer,\n maxBufferedChunks: options.maxBufferedChunks,\n maxFragments: options.maxFragments,\n maxPayload: options.maxPayload,\n skipUTF8Validation: options.skipUTF8Validation\n });\n\n const sender = new Sender(socket, this._extensions, options.generateMask);\n\n this._receiver = receiver;\n this._sender = sender;\n this._socket = socket;\n\n receiver[kWebSocket] = this;\n sender[kWebSocket] = this;\n socket[kWebSocket] = this;\n\n receiver.on('conclude', receiverOnConclude);\n receiver.on('drain', receiverOnDrain);\n receiver.on('error', receiverOnError);\n receiver.on('message', receiverOnMessage);\n receiver.on('ping', receiverOnPing);\n receiver.on('pong', receiverOnPong);\n\n sender.onerror = senderOnError;\n\n //\n // These methods may not be available if `socket` is just a `Duplex`.\n //\n if (socket.setTimeout) socket.setTimeout(0);\n if (socket.setNoDelay) socket.setNoDelay();\n\n if (head.length > 0) socket.unshift(head);\n\n socket.on('close', socketOnClose);\n socket.on('data', socketOnData);\n socket.on('end', socketOnEnd);\n socket.on('error', socketOnError);\n\n this._readyState = WebSocket.OPEN;\n this.emit('open');\n }\n\n /**\n * Emit the `'close'` event.\n *\n * @private\n */\n emitClose() {\n if (!this._socket) {\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n return;\n }\n\n if (this._extensions[PerMessageDeflate.extensionName]) {\n this._extensions[PerMessageDeflate.extensionName].cleanup();\n }\n\n this._receiver.removeAllListeners();\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n }\n\n /**\n * Start a closing handshake.\n *\n * +----------+ +-----------+ +----------+\n * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -\n * | +----------+ +-----------+ +----------+ |\n * +----------+ +-----------+ |\n * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING\n * +----------+ +-----------+ |\n * | | | +---+ |\n * +------------------------+-->|fin| - - - -\n * | +---+ | +---+\n * - - - - -|fin|<---------------------+\n * +---+\n *\n * @param {Number} [code] Status code explaining why the connection is closing\n * @param {(String|Buffer)} [data] The reason why the connection is\n * closing\n * @public\n */\n close(code, data) {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this.readyState === WebSocket.CLOSING) {\n if (\n this._closeFrameSent &&\n (this._closeFrameReceived || this._receiver._writableState.errorEmitted)\n ) {\n this._socket.end();\n }\n\n return;\n }\n\n this._readyState = WebSocket.CLOSING;\n this._sender.close(code, data, !this._isServer, (err) => {\n //\n // This error is handled by the `'error'` listener on the socket. We only\n // want to know if the close frame has been sent here.\n //\n if (err) return;\n\n this._closeFrameSent = true;\n\n if (\n this._closeFrameReceived ||\n this._receiver._writableState.errorEmitted\n ) {\n this._socket.end();\n }\n });\n\n setCloseTimer(this);\n }\n\n /**\n * Pause the socket.\n *\n * @public\n */\n pause() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = true;\n this._socket.pause();\n }\n\n /**\n * Send a ping.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the ping is sent\n * @public\n */\n ping(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.ping(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Send a pong.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the pong is sent\n * @public\n */\n pong(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.pong(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Resume the socket.\n *\n * @public\n */\n resume() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = false;\n if (!this._receiver._writableState.needDrain) this._socket.resume();\n }\n\n /**\n * Send a data message.\n *\n * @param {*} data The message to send\n * @param {Object} [options] Options object\n * @param {Boolean} [options.binary] Specifies whether `data` is binary or\n * text\n * @param {Boolean} [options.compress] Specifies whether or not to compress\n * `data`\n * @param {Boolean} [options.fin=true] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when data is written out\n * @public\n */\n send(data, options, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n const opts = {\n binary: typeof data !== 'string',\n mask: !this._isServer,\n compress: true,\n fin: true,\n ...options\n };\n\n if (!this._extensions[PerMessageDeflate.extensionName]) {\n opts.compress = false;\n }\n\n this._sender.send(data || EMPTY_BUFFER, opts, cb);\n }\n\n /**\n * Forcibly close the connection.\n *\n * @public\n */\n terminate() {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this._socket) {\n this._readyState = WebSocket.CLOSING;\n this._socket.destroy();\n }\n }\n}\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n[\n 'binaryType',\n 'bufferedAmount',\n 'extensions',\n 'isPaused',\n 'protocol',\n 'readyState',\n 'url'\n].forEach((property) => {\n Object.defineProperty(WebSocket.prototype, property, { enumerable: true });\n});\n\n//\n// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.\n// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface\n//\n['open', 'error', 'close', 'message'].forEach((method) => {\n Object.defineProperty(WebSocket.prototype, `on${method}`, {\n enumerable: true,\n get() {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) return listener[kListener];\n }\n\n return null;\n },\n set(handler) {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) {\n this.removeListener(method, listener);\n break;\n }\n }\n\n if (typeof handler !== 'function') return;\n\n this.addEventListener(method, handler, {\n [kForOnEventAttribute]: true\n });\n }\n });\n});\n\nWebSocket.prototype.addEventListener = addEventListener;\nWebSocket.prototype.removeEventListener = removeEventListener;\n\nmodule.exports = WebSocket;\n\n/**\n * Initialize a WebSocket client.\n *\n * @param {WebSocket} websocket The client to initialize\n * @param {(String|URL)} address The URL to which to connect\n * @param {Array} protocols The subprotocols\n * @param {Object} [options] Connection options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any\n * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple\n * times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait\n * for the closing handshake to finish after `websocket.close()` is called\n * @param {Function} [options.finishRequest] A function which can be used to\n * customize the headers of each http request before it is sent\n * @param {Boolean} [options.followRedirects=false] Whether or not to follow\n * redirects\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the\n * handshake request\n * @param {Number} [options.maxBufferedChunks=262144] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=16384] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Number} [options.maxRedirects=10] The maximum number of redirects\n * allowed\n * @param {String} [options.origin] Value of the `Origin` or\n * `Sec-WebSocket-Origin` header\n * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable\n * permessage-deflate\n * @param {Number} [options.protocolVersion=13] Value of the\n * `Sec-WebSocket-Version` header\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\nfunction initAsClient(websocket, address, protocols, options) {\n const opts = {\n allowSynchronousEvents: true,\n autoPong: true,\n closeTimeout: CLOSE_TIMEOUT,\n protocolVersion: protocolVersions[1],\n maxBufferedChunks: 256 * 1024,\n maxFragments: 16 * 1024,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: true,\n followRedirects: false,\n maxRedirects: 10,\n ...options,\n socketPath: undefined,\n hostname: undefined,\n protocol: undefined,\n timeout: undefined,\n method: 'GET',\n host: undefined,\n path: undefined,\n port: undefined\n };\n\n websocket._autoPong = opts.autoPong;\n websocket._closeTimeout = opts.closeTimeout;\n\n if (!protocolVersions.includes(opts.protocolVersion)) {\n throw new RangeError(\n `Unsupported protocol version: ${opts.protocolVersion} ` +\n `(supported versions: ${protocolVersions.join(', ')})`\n );\n }\n\n let parsedUrl;\n\n if (address instanceof URL) {\n parsedUrl = address;\n } else {\n try {\n parsedUrl = new URL(address);\n } catch {\n throw new SyntaxError(`Invalid URL: ${address}`);\n }\n }\n\n if (parsedUrl.protocol === 'http:') {\n parsedUrl.protocol = 'ws:';\n } else if (parsedUrl.protocol === 'https:') {\n parsedUrl.protocol = 'wss:';\n }\n\n websocket._url = parsedUrl.href;\n\n const isSecure = parsedUrl.protocol === 'wss:';\n const isIpcUrl = parsedUrl.protocol === 'ws+unix:';\n let invalidUrlMessage;\n\n if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {\n invalidUrlMessage =\n 'The URL\\'s protocol must be one of \"ws:\", \"wss:\", ' +\n '\"http:\", \"https:\", or \"ws+unix:\"';\n } else if (isIpcUrl && !parsedUrl.pathname) {\n invalidUrlMessage = \"The URL's pathname is empty\";\n } else if (parsedUrl.hash) {\n invalidUrlMessage = 'The URL contains a fragment identifier';\n }\n\n if (invalidUrlMessage) {\n const err = new SyntaxError(invalidUrlMessage);\n\n if (websocket._redirects === 0) {\n throw err;\n } else {\n emitErrorAndClose(websocket, err);\n return;\n }\n }\n\n const defaultPort = isSecure ? 443 : 80;\n const key = randomBytes(16).toString('base64');\n const request = isSecure ? https.request : http.request;\n const protocolSet = new Set();\n let perMessageDeflate;\n\n opts.createConnection =\n opts.createConnection || (isSecure ? tlsConnect : netConnect);\n opts.defaultPort = opts.defaultPort || defaultPort;\n opts.port = parsedUrl.port || defaultPort;\n opts.host = parsedUrl.hostname.startsWith('[')\n ? parsedUrl.hostname.slice(1, -1)\n : parsedUrl.hostname;\n opts.headers = {\n ...opts.headers,\n 'Sec-WebSocket-Version': opts.protocolVersion,\n 'Sec-WebSocket-Key': key,\n Connection: 'Upgrade',\n Upgrade: 'websocket'\n };\n opts.path = parsedUrl.pathname + parsedUrl.search;\n opts.timeout = opts.handshakeTimeout;\n\n if (opts.perMessageDeflate) {\n perMessageDeflate = new PerMessageDeflate({\n ...opts.perMessageDeflate,\n isServer: false,\n maxPayload: opts.maxPayload\n });\n opts.headers['Sec-WebSocket-Extensions'] = format({\n [PerMessageDeflate.extensionName]: perMessageDeflate.offer()\n });\n }\n if (protocols.length) {\n for (const protocol of protocols) {\n if (\n typeof protocol !== 'string' ||\n !subprotocolRegex.test(protocol) ||\n protocolSet.has(protocol)\n ) {\n throw new SyntaxError(\n 'An invalid or duplicated subprotocol was specified'\n );\n }\n\n protocolSet.add(protocol);\n }\n\n opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');\n }\n if (opts.origin) {\n if (opts.protocolVersion < 13) {\n opts.headers['Sec-WebSocket-Origin'] = opts.origin;\n } else {\n opts.headers.Origin = opts.origin;\n }\n }\n if (parsedUrl.username || parsedUrl.password) {\n opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;\n }\n\n if (isIpcUrl) {\n const parts = opts.path.split(':');\n\n opts.socketPath = parts[0];\n opts.path = parts[1];\n }\n\n let req;\n\n if (opts.followRedirects) {\n if (websocket._redirects === 0) {\n websocket._originalIpc = isIpcUrl;\n websocket._originalSecure = isSecure;\n websocket._originalHostOrSocketPath = isIpcUrl\n ? opts.socketPath\n : parsedUrl.host;\n\n const headers = options && options.headers;\n\n //\n // Shallow copy the user provided options so that headers can be changed\n // without mutating the original object.\n //\n options = { ...options, headers: {} };\n\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n options.headers[key.toLowerCase()] = value;\n }\n }\n } else if (websocket.listenerCount('redirect') === 0) {\n const isSameHost = isIpcUrl\n ? websocket._originalIpc\n ? opts.socketPath === websocket._originalHostOrSocketPath\n : false\n : websocket._originalIpc\n ? false\n : parsedUrl.host === websocket._originalHostOrSocketPath;\n\n if (!isSameHost || (websocket._originalSecure && !isSecure)) {\n //\n // Match curl 7.77.0 behavior and drop the following headers. These\n // headers are also dropped when following a redirect to a subdomain.\n //\n delete opts.headers.authorization;\n delete opts.headers.cookie;\n\n if (!isSameHost) delete opts.headers.host;\n\n opts.auth = undefined;\n }\n }\n\n //\n // Match curl 7.77.0 behavior and make the first `Authorization` header win.\n // If the `Authorization` header is set, then there is nothing to do as it\n // will take precedence.\n //\n if (opts.auth && !options.headers.authorization) {\n options.headers.authorization =\n 'Basic ' + Buffer.from(opts.auth).toString('base64');\n }\n\n req = websocket._req = request(opts);\n\n if (websocket._redirects) {\n //\n // Unlike what is done for the `'upgrade'` event, no early exit is\n // triggered here if the user calls `websocket.close()` or\n // `websocket.terminate()` from a listener of the `'redirect'` event. This\n // is because the user can also call `request.destroy()` with an error\n // before calling `websocket.close()` or `websocket.terminate()` and this\n // would result in an error being emitted on the `request` object with no\n // `'error'` event listeners attached.\n //\n websocket.emit('redirect', websocket.url, req);\n }\n } else {\n req = websocket._req = request(opts);\n }\n\n if (opts.timeout) {\n req.on('timeout', () => {\n abortHandshake(websocket, req, 'Opening handshake has timed out');\n });\n }\n\n req.on('error', (err) => {\n if (req === null || req[kAborted]) return;\n\n req = websocket._req = null;\n emitErrorAndClose(websocket, err);\n });\n\n req.on('response', (res) => {\n const location = res.headers.location;\n const statusCode = res.statusCode;\n\n if (\n location &&\n opts.followRedirects &&\n statusCode >= 300 &&\n statusCode < 400\n ) {\n if (++websocket._redirects > opts.maxRedirects) {\n abortHandshake(websocket, req, 'Maximum redirects exceeded');\n return;\n }\n\n req.abort();\n\n let addr;\n\n try {\n addr = new URL(location, address);\n } catch (e) {\n const err = new SyntaxError(`Invalid URL: ${location}`);\n emitErrorAndClose(websocket, err);\n return;\n }\n\n initAsClient(websocket, addr, protocols, options);\n } else if (!websocket.emit('unexpected-response', req, res)) {\n abortHandshake(\n websocket,\n req,\n `Unexpected server response: ${res.statusCode}`\n );\n }\n });\n\n req.on('upgrade', (res, socket, head) => {\n websocket.emit('upgrade', res);\n\n //\n // The user may have closed the connection from a listener of the\n // `'upgrade'` event.\n //\n if (websocket.readyState !== WebSocket.CONNECTING) return;\n\n req = websocket._req = null;\n\n const upgrade = res.headers.upgrade;\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n abortHandshake(websocket, socket, 'Invalid Upgrade header');\n return;\n }\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n if (res.headers['sec-websocket-accept'] !== digest) {\n abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');\n return;\n }\n\n const serverProt = res.headers['sec-websocket-protocol'];\n let protError;\n\n if (serverProt !== undefined) {\n if (!protocolSet.size) {\n protError = 'Server sent a subprotocol but none was requested';\n } else if (!protocolSet.has(serverProt)) {\n protError = 'Server sent an invalid subprotocol';\n }\n } else if (protocolSet.size) {\n protError = 'Server sent no subprotocol';\n }\n\n if (protError) {\n abortHandshake(websocket, socket, protError);\n return;\n }\n\n if (serverProt) websocket._protocol = serverProt;\n\n const secWebSocketExtensions = res.headers['sec-websocket-extensions'];\n\n if (secWebSocketExtensions !== undefined) {\n if (!perMessageDeflate) {\n const message =\n 'Server sent a Sec-WebSocket-Extensions header but no extension ' +\n 'was requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n let extensions;\n\n try {\n extensions = parse(secWebSocketExtensions);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n const extensionNames = Object.keys(extensions);\n\n if (\n extensionNames.length !== 1 ||\n extensionNames[0] !== PerMessageDeflate.extensionName\n ) {\n const message = 'Server indicated an extension that was not requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n try {\n perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n websocket._extensions[PerMessageDeflate.extensionName] =\n perMessageDeflate;\n }\n\n websocket.setSocket(socket, head, {\n allowSynchronousEvents: opts.allowSynchronousEvents,\n generateMask: opts.generateMask,\n maxBufferedChunks: opts.maxBufferedChunks,\n maxFragments: opts.maxFragments,\n maxPayload: opts.maxPayload,\n skipUTF8Validation: opts.skipUTF8Validation\n });\n });\n\n if (opts.finishRequest) {\n opts.finishRequest(req, websocket);\n } else {\n req.end();\n }\n}\n\n/**\n * Emit the `'error'` and `'close'` events.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {Error} The error to emit\n * @private\n */\nfunction emitErrorAndClose(websocket, err) {\n websocket._readyState = WebSocket.CLOSING;\n //\n // The following assignment is practically useless and is done only for\n // consistency.\n //\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n websocket.emitClose();\n}\n\n/**\n * Create a `net.Socket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {net.Socket} The newly created socket used to start the connection\n * @private\n */\nfunction netConnect(options) {\n options.path = options.socketPath;\n return net.connect(options);\n}\n\n/**\n * Create a `tls.TLSSocket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {tls.TLSSocket} The newly created socket used to start the connection\n * @private\n */\nfunction tlsConnect(options) {\n options.path = undefined;\n\n if (!options.servername && options.servername !== '') {\n options.servername = net.isIP(options.host) ? '' : options.host;\n }\n\n return tls.connect(options);\n}\n\n/**\n * Abort the handshake and emit an error.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to\n * abort or the socket to destroy\n * @param {String} message The error message\n * @private\n */\nfunction abortHandshake(websocket, stream, message) {\n websocket._readyState = WebSocket.CLOSING;\n\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshake);\n\n if (stream.setHeader) {\n stream[kAborted] = true;\n stream.abort();\n\n if (stream.socket && !stream.socket.destroyed) {\n //\n // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if\n // called after the request completed. See\n // https://github.com/websockets/ws/issues/1869.\n //\n stream.socket.destroy();\n }\n\n process.nextTick(emitErrorAndClose, websocket, err);\n } else {\n stream.destroy(err);\n stream.once('error', websocket.emit.bind(websocket, 'error'));\n stream.once('close', websocket.emitClose.bind(websocket));\n }\n}\n\n/**\n * Handle cases where the `ping()`, `pong()`, or `send()` methods are called\n * when the `readyState` attribute is `CLOSING` or `CLOSED`.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {*} [data] The data to send\n * @param {Function} [cb] Callback\n * @private\n */\nfunction sendAfterClose(websocket, data, cb) {\n if (data) {\n const length = isBlob(data) ? data.size : toBuffer(data).length;\n\n //\n // The `_bufferedAmount` property is used only when the peer is a client and\n // the opening handshake fails. Under these circumstances, in fact, the\n // `setSocket()` method is not called, so the `_socket` and `_sender`\n // properties are set to `null`.\n //\n if (websocket._socket) websocket._sender._bufferedBytes += length;\n else websocket._bufferedAmount += length;\n }\n\n if (cb) {\n const err = new Error(\n `WebSocket is not open: readyState ${websocket.readyState} ` +\n `(${readyStates[websocket.readyState]})`\n );\n process.nextTick(cb, err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'conclude'` event.\n *\n * @param {Number} code The status code\n * @param {Buffer} reason The reason for closing\n * @private\n */\nfunction receiverOnConclude(code, reason) {\n const websocket = this[kWebSocket];\n\n websocket._closeFrameReceived = true;\n websocket._closeMessage = reason;\n websocket._closeCode = code;\n\n if (websocket._socket[kWebSocket] === undefined) return;\n\n websocket._socket.removeListener('data', socketOnData);\n process.nextTick(resume, websocket._socket);\n\n if (code === 1005) websocket.close();\n else websocket.close(code, reason);\n}\n\n/**\n * The listener of the `Receiver` `'drain'` event.\n *\n * @private\n */\nfunction receiverOnDrain() {\n const websocket = this[kWebSocket];\n\n if (!websocket.isPaused) websocket._socket.resume();\n}\n\n/**\n * The listener of the `Receiver` `'error'` event.\n *\n * @param {(RangeError|Error)} err The emitted error\n * @private\n */\nfunction receiverOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket._socket[kWebSocket] !== undefined) {\n websocket._socket.removeListener('data', socketOnData);\n\n //\n // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See\n // https://github.com/websockets/ws/issues/1940.\n //\n process.nextTick(resume, websocket._socket);\n\n websocket.close(err[kStatusCode]);\n }\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'finish'` event.\n *\n * @private\n */\nfunction receiverOnFinish() {\n this[kWebSocket].emitClose();\n}\n\n/**\n * The listener of the `Receiver` `'message'` event.\n *\n * @param {Buffer|ArrayBuffer|Buffer[])} data The message\n * @param {Boolean} isBinary Specifies whether the message is binary or not\n * @private\n */\nfunction receiverOnMessage(data, isBinary) {\n this[kWebSocket].emit('message', data, isBinary);\n}\n\n/**\n * The listener of the `Receiver` `'ping'` event.\n *\n * @param {Buffer} data The data included in the ping frame\n * @private\n */\nfunction receiverOnPing(data) {\n const websocket = this[kWebSocket];\n\n if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);\n websocket.emit('ping', data);\n}\n\n/**\n * The listener of the `Receiver` `'pong'` event.\n *\n * @param {Buffer} data The data included in the pong frame\n * @private\n */\nfunction receiverOnPong(data) {\n this[kWebSocket].emit('pong', data);\n}\n\n/**\n * Resume a readable stream\n *\n * @param {Readable} stream The readable stream\n * @private\n */\nfunction resume(stream) {\n stream.resume();\n}\n\n/**\n * The `Sender` error event handler.\n *\n * @param {Error} The error\n * @private\n */\nfunction senderOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket.readyState === WebSocket.CLOSED) return;\n if (websocket.readyState === WebSocket.OPEN) {\n websocket._readyState = WebSocket.CLOSING;\n setCloseTimer(websocket);\n }\n\n //\n // `socket.end()` is used instead of `socket.destroy()` to allow the other\n // peer to finish sending queued data. There is no need to set a timer here\n // because `CLOSING` means that it is already set or not needed.\n //\n this._socket.end();\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * Set a timer to destroy the underlying raw socket of a WebSocket.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @private\n */\nfunction setCloseTimer(websocket) {\n websocket._closeTimer = setTimeout(\n websocket._socket.destroy.bind(websocket._socket),\n websocket._closeTimeout\n );\n}\n\n/**\n * The listener of the socket `'close'` event.\n *\n * @private\n */\nfunction socketOnClose() {\n const websocket = this[kWebSocket];\n\n this.removeListener('close', socketOnClose);\n this.removeListener('data', socketOnData);\n this.removeListener('end', socketOnEnd);\n\n websocket._readyState = WebSocket.CLOSING;\n\n //\n // The close frame might not have been received or the `'end'` event emitted,\n // for example, if the socket was destroyed due to an error. Ensure that the\n // `receiver` stream is closed after writing any remaining buffered data to\n // it. If the readable side of the socket is in flowing mode then there is no\n // buffered data as everything has been already written. If instead, the\n // socket is paused, any possible buffered data will be read as a single\n // chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n this._readableState.length !== 0\n ) {\n const chunk = this.read(this._readableState.length);\n\n websocket._receiver.write(chunk);\n }\n\n websocket._receiver.end();\n\n this[kWebSocket] = undefined;\n\n clearTimeout(websocket._closeTimer);\n\n if (\n websocket._receiver._writableState.finished ||\n websocket._receiver._writableState.errorEmitted\n ) {\n websocket.emitClose();\n } else {\n websocket._receiver.on('error', receiverOnFinish);\n websocket._receiver.on('finish', receiverOnFinish);\n }\n}\n\n/**\n * The listener of the socket `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction socketOnData(chunk) {\n if (!this[kWebSocket]._receiver.write(chunk)) {\n this.pause();\n }\n}\n\n/**\n * The listener of the socket `'end'` event.\n *\n * @private\n */\nfunction socketOnEnd() {\n const websocket = this[kWebSocket];\n\n websocket._readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}\n\n/**\n * The listener of the socket `'error'` event.\n *\n * @private\n */\nfunction socketOnError() {\n const websocket = this[kWebSocket];\n\n this.removeListener('error', socketOnError);\n this.on('error', NOOP);\n\n if (websocket) {\n websocket._readyState = WebSocket.CLOSING;\n this.destroy();\n }\n}\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^WebSocket$\" }] */\n'use strict';\n\nconst WebSocket = require('./websocket');\nconst { Duplex } = require('stream');\n\n/**\n * Emits the `'close'` event on a stream.\n *\n * @param {Duplex} stream The stream.\n * @private\n */\nfunction emitClose(stream) {\n stream.emit('close');\n}\n\n/**\n * The listener of the `'end'` event.\n *\n * @private\n */\nfunction duplexOnEnd() {\n if (!this.destroyed && this._writableState.finished) {\n this.destroy();\n }\n}\n\n/**\n * The listener of the `'error'` event.\n *\n * @param {Error} err The error\n * @private\n */\nfunction duplexOnError(err) {\n this.removeListener('error', duplexOnError);\n this.destroy();\n if (this.listenerCount('error') === 0) {\n // Do not suppress the throwing behavior.\n this.emit('error', err);\n }\n}\n\n/**\n * Wraps a `WebSocket` in a duplex stream.\n *\n * @param {WebSocket} ws The `WebSocket` to wrap\n * @param {Object} [options] The options for the `Duplex` constructor\n * @return {Duplex} The duplex stream\n * @public\n */\nfunction createWebSocketStream(ws, options) {\n let terminateOnDestroy = true;\n\n const duplex = new Duplex({\n ...options,\n autoDestroy: false,\n emitClose: false,\n objectMode: false,\n writableObjectMode: false\n });\n\n ws.on('message', function message(msg, isBinary) {\n const data =\n !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;\n\n if (!duplex.push(data)) ws.pause();\n });\n\n ws.once('error', function error(err) {\n if (duplex.destroyed) return;\n\n // Prevent `ws.terminate()` from being called by `duplex._destroy()`.\n //\n // - If the `'error'` event is emitted before the `'open'` event, then\n // `ws.terminate()` is a noop as no socket is assigned.\n // - Otherwise, the error is re-emitted by the listener of the `'error'`\n // event of the `Receiver` object. The listener already closes the\n // connection by calling `ws.close()`. This allows a close frame to be\n // sent to the other peer. If `ws.terminate()` is called right after this,\n // then the close frame might not be sent.\n terminateOnDestroy = false;\n duplex.destroy(err);\n });\n\n ws.once('close', function close() {\n if (duplex.destroyed) return;\n\n duplex.push(null);\n });\n\n duplex._destroy = function (err, callback) {\n if (ws.readyState === ws.CLOSED) {\n callback(err);\n process.nextTick(emitClose, duplex);\n return;\n }\n\n let called = false;\n\n ws.once('error', function error(err) {\n called = true;\n callback(err);\n });\n\n ws.once('close', function close() {\n if (!called) callback(err);\n process.nextTick(emitClose, duplex);\n });\n\n if (terminateOnDestroy) ws.terminate();\n };\n\n duplex._final = function (callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._final(callback);\n });\n return;\n }\n\n // If the value of the `_socket` property is `null` it means that `ws` is a\n // client websocket and the handshake failed. In fact, when this happens, a\n // socket is never assigned to the websocket. Wait for the `'error'` event\n // that will be emitted by the websocket.\n if (ws._socket === null) return;\n\n if (ws._socket._writableState.finished) {\n callback();\n if (duplex._readableState.endEmitted) duplex.destroy();\n } else {\n ws._socket.once('finish', function finish() {\n // `duplex` is not destroyed here because the `'end'` event will be\n // emitted on `duplex` after this `'finish'` event. The EOF signaling\n // `null` chunk is, in fact, pushed when the websocket emits `'close'`.\n callback();\n });\n ws.close();\n }\n };\n\n duplex._read = function () {\n if (ws.isPaused) ws.resume();\n };\n\n duplex._write = function (chunk, encoding, callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._write(chunk, encoding, callback);\n });\n return;\n }\n\n ws.send(chunk, callback);\n };\n\n duplex.on('end', duplexOnEnd);\n duplex.on('error', duplexOnError);\n return duplex;\n}\n\nmodule.exports = createWebSocketStream;\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.\n *\n * @param {String} header The field value of the header\n * @return {Set} The subprotocol names\n * @public\n */\nfunction parse(header) {\n const protocols = new Set();\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (i; i < header.length; i++) {\n const code = header.charCodeAt(i);\n\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n\n const protocol = header.slice(start, end);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n\n if (start === -1 || end !== -1) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n const protocol = header.slice(start, i);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n return protocols;\n}\n\nmodule.exports = { parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst http = require('http');\nconst { Duplex } = require('stream');\nconst { createHash } = require('crypto');\n\nconst extension = require('./extension');\nconst PerMessageDeflate = require('./permessage-deflate');\nconst subprotocol = require('./subprotocol');\nconst WebSocket = require('./websocket');\nconst { CLOSE_TIMEOUT, GUID, kWebSocket } = require('./constants');\n\nconst keyRegex = /^[+/0-9A-Za-z]{22}==$/;\n\nconst RUNNING = 0;\nconst CLOSING = 1;\nconst CLOSED = 2;\n\n/**\n * Class representing a WebSocket server.\n *\n * @extends EventEmitter\n */\nclass WebSocketServer extends EventEmitter {\n /**\n * Create a `WebSocketServer` instance.\n *\n * @param {Object} options Configuration options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.backlog=511] The maximum length of the queue of\n * pending connections\n * @param {Boolean} [options.clientTracking=true] Specifies whether or not to\n * track clients\n * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to\n * wait for the closing handshake to finish after `websocket.close()` is\n * called\n * @param {Function} [options.handleProtocols] A hook to handle protocols\n * @param {String} [options.host] The hostname where to bind the server\n * @param {Number} [options.maxBufferedChunks=262144] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=16384] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Boolean} [options.noServer=false] Enable no server mode\n * @param {String} [options.path] Accept only connections matching this path\n * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable\n * permessage-deflate\n * @param {Number} [options.port] The port where to bind the server\n * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S\n * server to use\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @param {Function} [options.verifyClient] A hook to reject connections\n * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`\n * class to use. It must be the `WebSocket` class or class that extends it\n * @param {Function} [callback] A listener for the `listening` event\n */\n constructor(options, callback) {\n super();\n\n options = {\n allowSynchronousEvents: true,\n autoPong: true,\n maxBufferedChunks: 256 * 1024,\n maxFragments: 16 * 1024,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: false,\n handleProtocols: null,\n clientTracking: true,\n closeTimeout: CLOSE_TIMEOUT,\n verifyClient: null,\n noServer: false,\n backlog: null, // use default (511 as implemented in net.js)\n server: null,\n host: null,\n path: null,\n port: null,\n WebSocket,\n ...options\n };\n\n if (\n (options.port == null && !options.server && !options.noServer) ||\n (options.port != null && (options.server || options.noServer)) ||\n (options.server && options.noServer)\n ) {\n throw new TypeError(\n 'One and only one of the \"port\", \"server\", or \"noServer\" options ' +\n 'must be specified'\n );\n }\n\n if (options.port != null) {\n this._server = http.createServer((req, res) => {\n const body = http.STATUS_CODES[426];\n\n res.writeHead(426, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain'\n });\n res.end(body);\n });\n this._server.listen(\n options.port,\n options.host,\n options.backlog,\n callback\n );\n } else if (options.server) {\n this._server = options.server;\n }\n\n if (this._server) {\n const emitConnection = this.emit.bind(this, 'connection');\n\n this._removeListeners = addListeners(this._server, {\n listening: this.emit.bind(this, 'listening'),\n error: this.emit.bind(this, 'error'),\n upgrade: (req, socket, head) => {\n this.handleUpgrade(req, socket, head, emitConnection);\n }\n });\n }\n\n if (options.perMessageDeflate === true) options.perMessageDeflate = {};\n if (options.clientTracking) {\n this.clients = new Set();\n this._shouldEmitClose = false;\n }\n\n this.options = options;\n this._state = RUNNING;\n }\n\n /**\n * Returns the bound address, the address family name, and port of the server\n * as reported by the operating system if listening on an IP socket.\n * If the server is listening on a pipe or UNIX domain socket, the name is\n * returned as a string.\n *\n * @return {(Object|String|null)} The address of the server\n * @public\n */\n address() {\n if (this.options.noServer) {\n throw new Error('The server is operating in \"noServer\" mode');\n }\n\n if (!this._server) return null;\n return this._server.address();\n }\n\n /**\n * Stop the server from accepting new connections and emit the `'close'` event\n * when all existing connections are closed.\n *\n * @param {Function} [cb] A one-time listener for the `'close'` event\n * @public\n */\n close(cb) {\n if (this._state === CLOSED) {\n if (cb) {\n this.once('close', () => {\n cb(new Error('The server is not running'));\n });\n }\n\n process.nextTick(emitClose, this);\n return;\n }\n\n if (cb) this.once('close', cb);\n\n if (this._state === CLOSING) return;\n this._state = CLOSING;\n\n if (this.options.noServer || this.options.server) {\n if (this._server) {\n this._removeListeners();\n this._removeListeners = this._server = null;\n }\n\n if (this.clients) {\n if (!this.clients.size) {\n process.nextTick(emitClose, this);\n } else {\n this._shouldEmitClose = true;\n }\n } else {\n process.nextTick(emitClose, this);\n }\n } else {\n const server = this._server;\n\n this._removeListeners();\n this._removeListeners = this._server = null;\n\n //\n // The HTTP/S server was created internally. Close it, and rely on its\n // `'close'` event.\n //\n server.close(() => {\n emitClose(this);\n });\n }\n }\n\n /**\n * See if a given request should be handled by this server instance.\n *\n * @param {http.IncomingMessage} req Request object to inspect\n * @return {Boolean} `true` if the request is valid, else `false`\n * @public\n */\n shouldHandle(req) {\n if (this.options.path) {\n const index = req.url.indexOf('?');\n const pathname = index !== -1 ? req.url.slice(0, index) : req.url;\n\n if (pathname !== this.options.path) return false;\n }\n\n return true;\n }\n\n /**\n * Handle a HTTP Upgrade request.\n *\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @public\n */\n handleUpgrade(req, socket, head, cb) {\n socket.on('error', socketOnError);\n\n const key = req.headers['sec-websocket-key'];\n const upgrade = req.headers.upgrade;\n const version = +req.headers['sec-websocket-version'];\n\n if (req.method !== 'GET') {\n const message = 'Invalid HTTP method';\n abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);\n return;\n }\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n const message = 'Invalid Upgrade header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (key === undefined || !keyRegex.test(key)) {\n const message = 'Missing or invalid Sec-WebSocket-Key header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (version !== 13 && version !== 8) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {\n 'Sec-WebSocket-Version': '13, 8'\n });\n return;\n }\n\n if (!this.shouldHandle(req)) {\n abortHandshake(socket, 400);\n return;\n }\n\n const secWebSocketProtocol = req.headers['sec-websocket-protocol'];\n let protocols = new Set();\n\n if (secWebSocketProtocol !== undefined) {\n try {\n protocols = subprotocol.parse(secWebSocketProtocol);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Protocol header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n const secWebSocketExtensions = req.headers['sec-websocket-extensions'];\n const extensions = {};\n\n if (\n this.options.perMessageDeflate &&\n secWebSocketExtensions !== undefined\n ) {\n const perMessageDeflate = new PerMessageDeflate({\n ...this.options.perMessageDeflate,\n isServer: true,\n maxPayload: this.options.maxPayload\n });\n\n try {\n const offers = extension.parse(secWebSocketExtensions);\n\n if (offers[PerMessageDeflate.extensionName]) {\n perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);\n extensions[PerMessageDeflate.extensionName] = perMessageDeflate;\n }\n } catch (err) {\n const message =\n 'Invalid or unacceptable Sec-WebSocket-Extensions header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n //\n // Optionally call external client verification handler.\n //\n if (this.options.verifyClient) {\n const info = {\n origin:\n req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],\n secure: !!(req.socket.authorized || req.socket.encrypted),\n req\n };\n\n if (this.options.verifyClient.length === 2) {\n this.options.verifyClient(info, (verified, code, message, headers) => {\n if (!verified) {\n return abortHandshake(socket, code || 401, message, headers);\n }\n\n this.completeUpgrade(\n extensions,\n key,\n protocols,\n req,\n socket,\n head,\n cb\n );\n });\n return;\n }\n\n if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);\n }\n\n this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);\n }\n\n /**\n * Upgrade the connection to WebSocket.\n *\n * @param {Object} extensions The accepted extensions\n * @param {String} key The value of the `Sec-WebSocket-Key` header\n * @param {Set} protocols The subprotocols\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @throws {Error} If called more than once with the same socket\n * @private\n */\n completeUpgrade(extensions, key, protocols, req, socket, head, cb) {\n //\n // Destroy the socket if the client has already sent a FIN packet.\n //\n if (!socket.readable || !socket.writable) return socket.destroy();\n\n if (socket[kWebSocket]) {\n throw new Error(\n 'server.handleUpgrade() was called more than once with the same ' +\n 'socket, possibly due to a misconfiguration'\n );\n }\n\n if (this._state > RUNNING) return abortHandshake(socket, 503);\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n const headers = [\n 'HTTP/1.1 101 Switching Protocols',\n 'Upgrade: websocket',\n 'Connection: Upgrade',\n `Sec-WebSocket-Accept: ${digest}`\n ];\n\n const ws = new this.options.WebSocket(null, undefined, this.options);\n\n if (protocols.size) {\n //\n // Optionally call external protocol selection handler.\n //\n const protocol = this.options.handleProtocols\n ? this.options.handleProtocols(protocols, req)\n : protocols.values().next().value;\n\n if (protocol) {\n headers.push(`Sec-WebSocket-Protocol: ${protocol}`);\n ws._protocol = protocol;\n }\n }\n\n if (extensions[PerMessageDeflate.extensionName]) {\n const params = extensions[PerMessageDeflate.extensionName].params;\n const value = extension.format({\n [PerMessageDeflate.extensionName]: [params]\n });\n headers.push(`Sec-WebSocket-Extensions: ${value}`);\n ws._extensions = extensions;\n }\n\n //\n // Allow external modification/inspection of handshake headers.\n //\n this.emit('headers', headers, req);\n\n socket.write(headers.concat('\\r\\n').join('\\r\\n'));\n socket.removeListener('error', socketOnError);\n\n ws.setSocket(socket, head, {\n allowSynchronousEvents: this.options.allowSynchronousEvents,\n maxBufferedChunks: this.options.maxBufferedChunks,\n maxFragments: this.options.maxFragments,\n maxPayload: this.options.maxPayload,\n skipUTF8Validation: this.options.skipUTF8Validation\n });\n\n if (this.clients) {\n this.clients.add(ws);\n ws.on('close', () => {\n this.clients.delete(ws);\n\n if (this._shouldEmitClose && !this.clients.size) {\n process.nextTick(emitClose, this);\n }\n });\n }\n\n cb(ws, req);\n }\n}\n\nmodule.exports = WebSocketServer;\n\n/**\n * Add event listeners on an `EventEmitter` using a map of <event, listener>\n * pairs.\n *\n * @param {EventEmitter} server The event emitter\n * @param {Object.<String, Function>} map The listeners to add\n * @return {Function} A function that will remove the added listeners when\n * called\n * @private\n */\nfunction addListeners(server, map) {\n for (const event of Object.keys(map)) server.on(event, map[event]);\n\n return function removeListeners() {\n for (const event of Object.keys(map)) {\n server.removeListener(event, map[event]);\n }\n };\n}\n\n/**\n * Emit a `'close'` event on an `EventEmitter`.\n *\n * @param {EventEmitter} server The event emitter\n * @private\n */\nfunction emitClose(server) {\n server._state = CLOSED;\n server.emit('close');\n}\n\n/**\n * Handle socket errors.\n *\n * @private\n */\nfunction socketOnError() {\n this.destroy();\n}\n\n/**\n * Close the connection when preconditions are not fulfilled.\n *\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} [message] The HTTP response body\n * @param {Object} [headers] Additional HTTP response headers\n * @private\n */\nfunction abortHandshake(socket, code, message, headers) {\n //\n // The socket is writable unless the user destroyed or ended it before calling\n // `server.handleUpgrade()` or in the `verifyClient` function, which is a user\n // error. Handling this does not make much sense as the worst that can happen\n // is that some of the data written by the user might be discarded due to the\n // call to `socket.end()` below, which triggers an `'error'` event that in\n // turn causes the socket to be destroyed.\n //\n message = message || http.STATUS_CODES[code];\n headers = {\n Connection: 'close',\n 'Content-Type': 'text/html',\n 'Content-Length': Buffer.byteLength(message),\n ...headers\n };\n\n socket.once('finish', socket.destroy);\n\n socket.end(\n `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\\r\\n` +\n Object.keys(headers)\n .map((h) => `${h}: ${headers[h]}`)\n .join('\\r\\n') +\n '\\r\\n\\r\\n' +\n message\n );\n}\n\n/**\n * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least\n * one listener for it, otherwise call `abortHandshake()`.\n *\n * @param {WebSocketServer} server The WebSocket server\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} message The HTTP response body\n * @param {Object} [headers] The HTTP response headers\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(\n server,\n req,\n socket,\n code,\n message,\n headers\n) {\n if (server.listenerCount('wsClientError')) {\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);\n\n server.emit('wsClientError', err, socket, req);\n } else {\n abortHandshake(socket, code, message, headers);\n }\n}\n","import createWebSocketStream from './lib/stream.js';\nimport extension from './lib/extension.js';\nimport PerMessageDeflate from './lib/permessage-deflate.js';\nimport Receiver from './lib/receiver.js';\nimport Sender from './lib/sender.js';\nimport subprotocol from './lib/subprotocol.js';\nimport WebSocket from './lib/websocket.js';\nimport WebSocketServer from './lib/websocket-server.js';\n\nexport {\n createWebSocketStream,\n extension,\n PerMessageDeflate,\n Receiver,\n Sender,\n subprotocol,\n WebSocket,\n WebSocketServer\n};\n\nexport default WebSocket;\n","/**\n * Dial-out WS transport seam — the no-real-socket boundary a client FSM depends\n * on, so tests inject a fake. {@link ClientTransport} is the production impl: it\n * DIALS OUT (the daemon/relay connects to its peer, never the reverse), resolves\n * once the socket is open, and arms a receive-idle watchdog to detect a half-open\n * peer. Wire-agnostic: the subprotocol and dial path are passed in, so the same\n * transport serves the daemon↔CP, relay↔CP, and relay↔daemon wires.\n */\nimport WebSocket from 'ws';\nimport { MAX_FRAME_BYTES } from '@agentconnect.md/protocol';\n// ws has NO default handshake timeout: against a black-holing host a dial can\n// hang past the OS connect timeout (or forever if TCP connects but the 101 never\n// arrives), stalling the reconnect loop on one attempt.\nconst DEFAULT_HANDSHAKE_TIMEOUT_MS = 10_000;\n// rx-idle watchdog: self-ping this often, and terminate if nothing has arrived\n// from the peer for IDLE_MS. The heartbeat is send-only, so a half-open socket\n// (peer gone without a FIN) is otherwise invisible until the OS TCP timeout\n// (~minutes). The peer auto-pongs, so the self-ping alone refreshes liveness.\nconst DEFAULT_SELF_PING_MS = 15_000;\nconst DEFAULT_RX_IDLE_MS = 45_000;\n/**\n * Arm a receive-idle watchdog on an open socket: every `selfPingMs` send a ping\n * (the peer auto-pongs, which counts as inbound), and if NOTHING has arrived for\n * `idleMs`, `terminate()` the socket — routing a dead half-open connection into\n * the normal `close` → reconnect path. Any inbound frame (message/ping/pong)\n * resets the idle clock. Cleared on `close`. Kept off the FSM's injected Clock so\n * it never perturbs the fake-clock client tests.\n */\nexport function armRxWatchdog(ws, opts) {\n const now = opts.now ?? (() => Date.now());\n const setIv = opts.setInterval ?? ((fn, ms) => globalThis.setInterval(fn, ms));\n const clearIv = opts.clearInterval ?? ((h) => globalThis.clearInterval(h));\n let lastRx = now();\n const touch = () => {\n lastRx = now();\n };\n ws.on('message', touch);\n ws.on('ping', touch);\n ws.on('pong', touch);\n const timer = setIv(() => {\n if (now() - lastRx > opts.idleMs) {\n ws.terminate();\n return;\n }\n if (ws.readyState === ws.OPEN)\n ws.ping();\n }, opts.selfPingMs);\n if (typeof timer.unref === 'function')\n timer.unref();\n ws.on('close', () => clearIv(timer));\n}\nexport class ClientTransport {\n ws;\n get subprotocol() {\n return this.ws.protocol;\n }\n constructor(ws, selfPingMs, idleMs) {\n this.ws = ws;\n // Detect a half-open peer socket (gone without a FIN) and force a reconnect,\n // instead of silently queueing heartbeats until the OS TCP timeout.\n armRxWatchdog(ws, { selfPingMs, idleMs });\n }\n /**\n * Dial `<url normalized to end in opts.path>` with `opts.subprotocol`.\n * Resolves once the socket is open; rejects on any error before open\n * (refused, bad handshake/subprotocol → HTTP 400).\n */\n static dial(url, opts) {\n const wsUrl = url.endsWith(opts.path) ? url : url.replace(/\\/+$/, '') + opts.path;\n const selfPingMs = opts.selfPingMs ?? DEFAULT_SELF_PING_MS;\n const idleMs = opts.idleMs ?? DEFAULT_RX_IDLE_MS;\n return new Promise((resolve, reject) => {\n const ws = new WebSocket(wsUrl, [opts.subprotocol], {\n maxPayload: MAX_FRAME_BYTES,\n handshakeTimeout: opts.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS\n });\n const onPreOpenError = (err) => {\n ws.removeAllListeners();\n reject(err);\n };\n ws.once('error', onPreOpenError);\n ws.once('open', () => {\n ws.removeListener('error', onPreOpenError);\n // Post-open socket errors (ETIMEDOUT on a half-open connection after the\n // peer dies without a FIN, an oversized frame, a mid-stream reset) MUST\n // NOT surface as an unhandled 'error' event — that crashes the process\n // (only unhandledRejection is trapped). Fold them into the close path:\n // terminate() emits 'close', and the client FSM reconnects from there.\n ws.on('error', () => ws.terminate());\n resolve(new ClientTransport(ws, selfPingMs, idleMs));\n });\n });\n }\n send(text) {\n this.ws.send(text);\n }\n onMessage(cb) {\n this.ws.on('message', (data, isBinary) => {\n if (isBinary)\n return; // JSON text frames only (protocol §1)\n cb(typeof data === 'string' ? data : String(data));\n });\n }\n onClose(cb) {\n this.ws.on('close', (code, reason) => cb(code, reason.toString()));\n }\n close(code, reason) {\n this.ws.close(code, reason);\n }\n}\n//# sourceMappingURL=ws-client-transport.js.map","import { spawn } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { cliEntryPointer } from '../paths.js'\n\nexport interface UpgradeLog {\n info(message: string): void\n error(message: string): void\n}\n\n/** Resolve the stable CLI entry that owns the daemon version store. */\nexport function readCliEntry(root: string): string | undefined {\n try {\n const entry = readFileSync(cliEntryPointer(root), 'utf8').trim()\n return entry && existsSync(entry) ? entry : undefined\n } catch {\n return undefined\n }\n}\n\n/** Install and atomically activate one CP-selected daemon version. */\nexport async function runCliUpgrade(\n cliEntry: string,\n targetVersion: string,\n root: string,\n log: UpgradeLog\n): Promise<boolean> {\n log.info(`cp: installing daemon ${targetVersion} via ${cliEntry}`)\n return await new Promise<boolean>((resolve) => {\n const child = spawn(process.execPath, [cliEntry, 'upgrade', '--to', targetVersion, '--root', root], {\n stdio: 'inherit'\n })\n child.on('exit', (code) => {\n if (code === 0) log.info(`cp: daemon ${targetVersion} installed and activated`)\n else log.error(`cp: CLI upgrade exited ${code ?? 'via signal'}`)\n resolve(code === 0)\n })\n child.on('error', (err) => {\n log.error(`cp: could not launch CLI upgrade: ${err.message}`)\n resolve(false)\n })\n })\n}\n"],"x_google_ignoreList":[15,16,17,18,19,20,21,22,23,24,25,26,27,28],"mappings":";;;;;;;;;;;;;;;;;;AAUA,MAAa,WAAWA,OAAS;CAC7B,GAAGC,QAAU,CAAC;CACd,IAAIC,OAAS,CAAC,CAAC,KAAK;CACpB,IAAIA,OAAS,CAAC,CAAC,SAAS;CACxB,MAAMA,OAAS;CACf,MAAMA,OAAS,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS;CACjC,OAAOA,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,SAAS;CAC1C,SAASC,QAAU;AACvB,CAAC;AASyBH,OAAS;CAC/B,OAAOI,OAAS,CAAC,CAAC,IAAI;CACtB,SAASF,OAAS,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS;CACpC,UAAUA,OAAS,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS;AACzC,CAAC;;AAED,MAAa,WAAW;;;;;;;;AAQxB,SAAgB,YAAY,MAAM,SAAS;CACvC,OAAOF,OAAS;EACZ,GAAGC,QAAU,CAAC;EACd,IAAIC,OAAS,CAAC,CAAC,KAAK;EACpB,IAAIA,OAAS,CAAC,CAAC,SAAS;EACxB,MAAMD,QAAU,IAAI;EACpB,MAAMC,OAAS,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS;EACjC,OAAOA,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,SAAS;EAC1C;CACJ,CAAC;AACL;;;;;;;;;;AC3CA,MAAa,UAAUG,OAAS;CAI5B,QAAQC,OAAS,CAAC,CAAC,SAAS;CAI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