dsh-interconnect 0.11.23 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +164 -27
- package/assets/dsh-interconnect.md +60 -24
- package/dsh.plugin.json +1 -1
- package/lib/index.js +28 -13
- package/lib/interconnect/index.js +28 -13
- package/lib/interconnect/index.js.map +3 -3
- package/lib/tool-interconnect/index.js +106 -27
- package/lib/tool-interconnect/index.js.map +3 -3
- package/lib/types/interconnect/index.d.ts +32 -6
- package/lib/types/interconnect/index.d.ts.map +1 -1
- package/lib/types/interconnect/types.d.ts +57 -18
- package/lib/types/interconnect/types.d.ts.map +1 -1
- package/lib/types/tool-interconnect/index.d.ts +1 -1
- package/lib/types/tool-interconnect/index.d.ts.map +1 -1
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../src/interconnect/index.ts", "
|
|
4
|
-
"sourcesContent": ["/**\n * Cross-instance message handoff service: the inbound half owns one WebSocket\n * upgrade route on the host webserver and delivers authenticated messages into\n * live sessions; the outbound half dials the same route on peer instances.\n *\n * Transport is deliberately NOT the Connection RPC channel: that registry's\n * handler sees only `(endpoint, payload, signal)` and the trust fence is the\n * DNS-rebinding `trustedHosts` check, neither of which carries the shared-key\n * `Authorization` header this service authenticates on. Owning a plain\n * upgrade route keeps bearer-token auth at the boundary where the header is\n * readable and fails closed when the token is unconfigured.\n * @module dsh-interconnect\n */\n\nimport { Context, Service, LoggerService } from '@deepseek-ai/cordis'\nimport { createHash, randomUUID, timingSafeEqual as constantTimeEqual } from 'node:crypto'\nimport type { IncomingMessage } from 'node:http'\nimport type { Duplex } from 'node:stream'\nimport type { WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'\nimport { credentialRef } from '@deepseek-ai/dsh-credentials'\n// The Host's resolver reports a subagent-owned session as a Remote failure, and\n// that code is the only ownership signal a cold session carries.\nimport { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol'\nimport { boundContextSummary, createUserMessage } from '@deepseek-ai/dsh-llm'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\n// Loads the `RemoteErrorDetailsMap` augmentation that declares `session/agent-busy`,\n// the code the Host raises when a resume hits a subagent-owned session. Type-only:\n// no runtime dependency, and this subpath exists in every host revision in use.\nimport type {} from '@deepseek-ai/dsh-api-session-controller/types'\nimport type { Session } from '@deepseek-ai/dsh-session'\nimport type { SubagentRunEndInfo } from '@deepseek-ai/dsh-subagent'\nimport z from '@deepseek-ai/schemastery'\nimport WebSocket, { WebSocketServer } from 'ws'\nimport type { RawData } from 'ws'\nimport {\n type Config,\n type DeliveryMode,\n type EventNotification,\n type EventPayload,\n type LinkFrame,\n type LinkMessage,\n type ListResult,\n type PingResult,\n type QueryMessage,\n type ReplyRequest,\n type SendPayload,\n type SendResult,\n type SendRequest,\n type SendFailure,\n type SenderIdentity,\n type InterconnectSessionSummary,\n} from './types.ts'\n\n/**\n * Mirror of the Host's subagent-ownership predicate. The Host keeps that rule in\n * `@deepseek-ai/dsh-api-session-controller`, whose package root exports it only\n * from the revision this plugin's merge introduces \u2014 the hosts this package is\n * installed on still resolve the older root, so importing it would fail at load.\n * The body is copied verbatim from the Host; keep it in sync if the Host changes\n * the rule, because this is a safety fence.\n * @param ctx - host context carrying the live agent registry.\n * @param session - attached or live session whose ownership is tested.\n * @param agent - live agent when one exists for the session.\n * @returns whether subagent routing owns the session identity.\n */\nfunction isSessionOwnedBySubagent(\n ctx: Context,\n session: Pick<Session, 'header'>,\n agent: Agent | undefined,\n): boolean {\n if (session.header.origin === 'subagent') return true\n const parentId = session.header.parentSession\n if (parentId === undefined || agent === undefined) return false\n const parent = ctx.agents.get(parentId)\n return parent !== undefined && ctx.agents.isOwnedBy(agent.id, parent)\n}\n\n/** Exhaustiveness guard for closed unions. */\nfunction assertNever(value: never): never {\n throw new Error(`interconnect: unhandled variant ${JSON.stringify(value)}`)\n}\n\nexport type * from './types.ts'\n\n/**\n * Credential reference holding the shared auth token. Both halves of a link\n * must resolve the same value: inbound requests are rejected unless their\n * `Authorization: Bearer <token>` matches this secret, and outbound requests\n * send it. An unconfigured token fails closed on the inbound side.\n */\nexport const INTERCONNECT_TOKEN_REF = 'DSH_INTERCONNECT_TOKEN'\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n interconnect: InterconnectService\n }\n interface Events {\n /**\n * A remote peer instance pushed one authenticated lifecycle notification\n * into this instance. Payload is the exact {@link EventNotification} that\n * crossed the wire; listeners run when the frame arrives, and a listener\n * that throws or rejects is logged rather than propagated to the link.\n * @mode parallel\n * @param notification - the serialized lifecycle fact that crossed the wire.\n * @param peer - the sender's self-reported instance id.\n */\n 'interconnect/event'(notification: EventNotification, peer: string): void\n }\n}\n\nconst PLUGIN_SOURCE = 'dsh-interconnect'\n\n/** Maximum inbound link-frame size in bytes; larger frames are dropped as protocol violations. */\nconst MAX_LINK_FRAME_BYTES = 1024 * 1024\n/** Instance id a composition that omits `instanceId` runs under. */\nconst DEFAULT_INSTANCE_ID = 'dsh'\n/** Outbound request timeout a composition that omits `requestTimeoutMs` runs with. */\nconst DEFAULT_REQUEST_TIMEOUT_MS = 10_000\n/** Handshake window for an outbound dial; a CONNECTING socket past this is terminated and re-dialed. */\nconst LINK_HANDSHAKE_TIMEOUT_MS = 10_000\n/** WebSocket upgrade pathname owning the persistent peer link. */\nconst LINK_CHANNEL = '/interconnect/link'\n/**\n * Longest `instanceId` a deployment may configure. Every frame this instance\n * writes carries it (the `hello` announcement, answers, and results), so an\n * unbounded id would fail the first write against the link cap instead of\n * failing the load.\n */\nconst MAX_INSTANCE_ID_CHARS = 256\n/**\n * Longest request id one inbound frame may carry. Every answer repeats the\n * peer's `reqId`, so an unbounded id would decide the size of the frame this\n * instance writes back; the ids this plugin generates are about 40 characters.\n */\nconst MAX_REQUEST_ID_CHARS = 256\n/**\n * Maximum session rows one `list` answer carries, so a very large live set\n * still answers with a bounded number of targets. A consumer that renders the\n * answer can compare a full page against this bound to tell a complete listing\n * from a truncated one.\n */\nexport const MAX_LISTED_SESSIONS = 100\n\n/**\n * Whether one encoded link frame fits the cap both link halves enforce. An\n * over-cap write makes the receiving ws close the link, so a frame whose size\n * this instance already knows is refused before anything is written.\n */\nconst frameFitsLink = (frame: LinkFrame): boolean =>\n Buffer.byteLength(JSON.stringify(frame), 'utf8') <= MAX_LINK_FRAME_BYTES\n/** Serialized size of one row inside a frame's `sessions` array: UTF-8 bytes plus its separating comma. */\nconst rowBytes = (row: InterconnectSessionSummary): number =>\n Buffer.byteLength(JSON.stringify(row), 'utf8') + 1\n\n/** Wire union for the discriminated EventNotification fact carried by an `event` frame. */\nconst notificationSchema = z.union([\n z.object({ kind: z.const('agent/created').required(), sessionId: z.string().required() }),\n z.object({ kind: z.const('agent/disposed').required(), sessionId: z.string().required() }),\n z.object({ kind: z.const('agent/status').required(), sessionId: z.string().required(), status: z.union([z.const('idle'), z.const('running')]).required() }),\n z.object({ kind: z.const('session/created').required(), sessionId: z.string().required(), parentSessionId: z.string() }),\n z.object({ kind: z.const('session/disposed').required(), sessionId: z.string().required() }),\n z.object({ kind: z.const('subagent/end').required(), provider: z.string().required(), childSessionId: z.string().required(), stopReason: z.string().required() }),\n])\n\n/**\n * Wire shape of an address-free {@link SenderIdentity}. Fields stay optional\n * so an absent `sender` key (schemastery resolves it to an empty object)\n * still passes; `deliver()` treats a partial identity as no sender.\n */\nconst senderSchema = z.object({ instanceId: z.string(), sessionId: z.string() })\n\n/**\n * Wire shape of the ping answer. Validated against the KIND of query the\n * caller asked, not only the frame union: the union's branches merge their\n * unknown keys, so a `list`-shaped payload would otherwise satisfy a `ping`\n * request.\n */\nconst pingResultSchema = z.object({ pong: z.const(true).required(), instance: z.string().required() })\n\n/**\n * Wire shape of the live-session list. Every row must carry a `sessionId`\n * string: the consumer builds its tool result by reading that field, so an\n * unvalidated row would throw instead of reading as an unreachable peer.\n */\nconst listResultSchema = z.object({\n instance: z.string().required(),\n sessions: z.array(z.object({\n sessionId: z.string().required(),\n title: z.string().required(false),\n status: z.string().required(false),\n })).required(),\n})\n\n/**\n * Drop the explicit `null` values of one decoded frame. Schemastery accepts\n * `null` for a field that is not required and keeps it in the parsed result,\n * while every declared field on these frames is present-or-absent only: a peer\n * whose JSON writer emits `null` for a value it has none of would otherwise\n * hand a `null` title, status, or delivery to the tool output schemas, which\n * accept the field's own type and reject the whole result.\n * @param value - decoded frame, or any nested value of one.\n * @returns the value with every `null`-valued object key removed.\n */\nconst withoutNullFields = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(item => withoutNullFields(item))\n if (value === null || typeof value !== 'object') return value\n return Object.fromEntries(Object.entries(value as Record<string, unknown>)\n .filter(([, field]) => field !== null)\n .map(([key, field]) => [key, withoutNullFields(field)]))\n}\n\n/**\n * Project one decoded `msg-result` payload onto the fields its discriminant\n * branch declares. Schemastery's union keeps the keys of every branch it\n * considered, so a failing answer still carries the `delivery` a peer sent\n * beside it and a successful one carries a stray `reason` or an unknown key;\n * the tool output schemas accept only the branch's own string fields, so\n * nothing else may leave this service. `delivered` selects the branch and the\n * schema has already validated the fields that branch declares.\n * @param result - decoded `msg-result` payload.\n * @returns the payload restricted to its branch's fields.\n */\nconst projectMsgResult = (result: SendResult): SendResult =>\n result.delivered\n ? { delivered: true, instance: result.instance, ...(result.delivery === undefined ? {} : { delivery: result.delivery }) }\n : { delivered: false, instance: result.instance, reason: result.reason }\n\n/**\n * Decode one `query-result` payload against the schema for the request kind\n * that asked for it. `z.resolve` rejects with a `ValidationError` on a\n * mismatch, so the parse is contained here instead of throwing out of the frame\n * handler; the frame schema requires the `result` field, so a payload that\n * reaches this function is an object. The projections below read the fields the\n * schema validated, and schemastery types every optional field as `null`-capable,\n * so each field is read through the wire view its kind declares.\n * @param schema - the answer schema for the request kind.\n * @param result - the decoded `query-result` payload.\n * @returns the parsed payload's fields, or undefined when it does not match.\n */\nconst parseQueryResult = (\n schema: Parameters<typeof z.resolve>[1],\n result: unknown,\n): Record<string, unknown> | undefined => {\n try {\n const [parsed] = z.resolve(result, schema, {}) as [Record<string, unknown>]\n return parsed\n } catch {\n return undefined\n }\n}\n\n/**\n * Project one decoded `ping` answer onto its declared fields. Schemastery keeps\n * the keys of every union branch it considered, so an answer must not carry the\n * `sessions` rows or any other key this kind does not declare.\n * @param result - the decoded `query-result` payload.\n * @returns the answer as a {@link PingResult}, or undefined on a mismatch.\n */\nconst projectPingResult = (result: unknown): PingResult | undefined => {\n const parsed = parseQueryResult(pingResultSchema, result)\n return parsed === undefined ? undefined : { pong: true, instance: parsed.instance as string }\n}\n\n/**\n * Project one decoded `list` answer onto its declared fields, rows included,\n * for the same reason {@link projectPingResult} exists.\n * @param result - the decoded `query-result` payload.\n * @returns the answer as a {@link ListResult}, or undefined on a mismatch.\n */\nconst projectListResult = (result: unknown): ListResult | undefined => {\n const parsed = parseQueryResult(listResultSchema, result)\n if (parsed === undefined) return undefined\n const rows = parsed.sessions as Array<Record<string, unknown>>\n return {\n instance: parsed.instance as string,\n sessions: rows.map((row): InterconnectSessionSummary => ({\n sessionId: row.sessionId as string,\n ...(row.title === undefined || row.title === null ? {} : { title: row.title as string }),\n ...(row.status === undefined || row.status === null ? {} : { status: row.status as string }),\n })),\n }\n}\n\n/** Wire shape of one `query-result`: the ping answer, the live-session list, or the event-query ack. */\nconst queryResultSchema = z.union([\n pingResultSchema,\n listResultSchema,\n z.object({ accepted: z.const(true).required() }),\n])\n\n/** Wire shape of a `send` message carried by a `msg` link frame. */\nconst messageSchema = z.object({\n kind: z.const('send').required(),\n sessionId: z.string().required(),\n text: z.string().required(),\n sender: senderSchema,\n delivery: z.union([z.const('followup'), z.const('steer'), z.const('inject')]),\n resume: z.boolean(),\n})\n\n/** Wire union for the discovery query carried by a `query` link frame. */\nconst querySchema = z.union([\n z.object({ kind: z.const('ping').required() }),\n z.object({ kind: z.const('list').required() }),\n z.object({ kind: z.const('event').required(), notification: notificationSchema.required() }),\n])\n\n/**\n * Wire union of one `send` answer: the success branch carries the mode the\n * receiver used, and the failure branches carry only the reasons a receiver can\n * answer with \u2014 the local-only reasons (`message-too-large`, `no-sender-known`)\n * are produced locally and never cross the link.\n */\nconst msgResultSchema = z.union([\n z.object({ delivered: z.const(true).required(), instance: z.string().required(), delivery: z.union([z.const('followup'), z.const('steer'), z.const('inject')]) }),\n z.object({ delivered: z.const(false).required(), instance: z.string().required(), reason: z.union([\n z.const('session-not-live'),\n z.const('unreachable'),\n z.const('resume-refused'),\n z.const('resume-failed'),\n z.const('session-owned-by-subagent'),\n ]).required() }),\n])\n\n/** Wire union for one WebSocket link text frame. */\nconst linkFrameSchema = z.union([\n z.object({ type: z.const('hello').required(), sender: z.string().required() }),\n z.object({ type: z.const('event').required(), notification: notificationSchema.required() }),\n z.object({ type: z.const('msg').required(), reqId: z.string().max(MAX_REQUEST_ID_CHARS).required(), message: messageSchema.required() }),\n z.object({ type: z.const('msg-result').required(), reqId: z.string().max(MAX_REQUEST_ID_CHARS).required(), result: msgResultSchema.required() }),\n z.object({ type: z.const('query').required(), reqId: z.string().max(MAX_REQUEST_ID_CHARS).required(), query: querySchema.required() }),\n z.object({ type: z.const('query-result').required(), reqId: z.string().max(MAX_REQUEST_ID_CHARS).required(), result: queryResultSchema.required() }),\n])\n\n/**\n * Live cross-instance handoff service, registered as `ctx.interconnect`.\n * Requires the live agent registry and the credential store; the webserver is\n * optional \u2014 with one, the service accepts inbound links on\n * `/interconnect/link`; without one it still dials configured peers and\n * delivers over those outbound links. Activation is availability-driven like\n * every other host service.\n */\nexport class InterconnectService extends Service {\n static inject = ['agents', 'credentials']\n static Config: z<Config> = z.object({\n instanceId: z.string().max(MAX_INSTANCE_ID_CHARS).default(DEFAULT_INSTANCE_ID),\n requestTimeoutMs: z.natural().max(60000).default(DEFAULT_REQUEST_TIMEOUT_MS),\n peers: z.dict(z.string()).default({}),\n delivery: z.union([z.const('followup'), z.const('steer'), z.const('inject')]).default('followup'),\n allowResume: z.boolean().default(true),\n })\n\n private readonly instanceId: string\n private readonly requestTimeoutMs: number\n private readonly delivery: DeliveryMode\n private readonly allowResume: boolean\n private readonly server = new WebSocketServer({ noServer: true, maxPayload: MAX_LINK_FRAME_BYTES })\n private readonly sockets = new Set<WebSocket>()\n /** Outbound peer links keyed by the peer's `instanceId`. */\n private readonly linkStates = new Map<string, LinkState>()\n private heartbeatTimer: NodeJS.Timeout | undefined\n /** Peer identity each live socket announced via its `hello` frame, if any. */\n private readonly peerOf = new WeakMap<WebSocket, string>()\n /** Configured peer an outbound dial owns a socket for; absent on inbound sockets. */\n private readonly dialedPeerOf = new WeakMap<WebSocket, string>()\n /** Dialed sockets already reported as announcing an id other than their configured key. */\n private readonly mismatchWarned = new WeakSet<WebSocket>()\n /** Sender each local session last received a send from, keyed by local session id. */\n private readonly senders = new Map<string, SenderIdentity>()\n /** In-flight frames sent over a peer link, keyed by `reqId`, awaiting a correlated result. */\n private readonly pendingMessages = new Map<string, MutablePendingMessage>()\n private reqIdCounter = 0\n /** Set when the service fiber unwinds; guards late inbound deliveries against driving disposed agents. */\n private disposed = false\n\n constructor(ctx: Context, config: Config) {\n super(ctx, 'interconnect')\n /* v8 ignore next 1 -- the Config schema applies its instanceId default before the constructor runs. */\n this.instanceId = config.instanceId ?? DEFAULT_INSTANCE_ID\n /* v8 ignore next 1 -- the Config schema applies its requestTimeoutMs default before the constructor runs. */\n this.requestTimeoutMs = config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS\n /* v8 ignore next 1 -- the Config schema applies its delivery default before the constructor runs. */\n this.delivery = config.delivery ?? 'followup'\n /* v8 ignore next 1 -- the Config schema applies its allowResume default before the constructor runs. */\n this.allowResume = config.allowResume ?? true\n // Validate every peer origin before dialing any of them: the same URL\n // construction dial() uses, so a malformed origin fails the load before a\n // socket or reconnect loop exists to leak (misconfiguration fails loud).\n /* v8 ignore next 2 -- the Config schema applies its peers default before the constructor runs. */\n for (const origin of Object.values(config.peers ?? {})) {\n linkUrl(trimBase(origin))\n }\n // Link every configured peer at activation: all delivery is over these\n // persistent links, and addressing is by instanceId through them.\n /* v8 ignore next 1 -- the Config schema applies its peers default before the constructor runs. */\n for (const [peerInstanceId, origin] of Object.entries(config.peers ?? {})) {\n this.link(peerInstanceId, origin)\n }\n\n const upgrade: WebUpgradeRoute = {\n path: LINK_CHANNEL,\n handler: (req, socket, head) => {\n // `handleUpgrade` handles its own refusals; this catch keeps an\n // unexpected failure from becoming an unhandled rejection behind a\n // client left waiting on an open socket.\n void this.handleUpgrade(req, socket, head).catch((error: unknown) => {\n this.ctx.logger.warn(`interconnect: upgrade failed: ${error instanceof Error ? error.message : String(error)}`)\n socket.destroy()\n })\n },\n }\n // The webserver is optional: without one the service still dials peers and\n // delivers over those outbound links (outbound-only mode). Registering the\n // inbound route through a waiting inject fiber instead of a constructor\n // `ctx.get` means composition order cannot leave the route unregistered \u2014\n // the fiber activates whenever a webserver is available, and headless\n // profiles simply never get one.\n ctx.inject(['webServer'], (webCtx) => {\n webCtx.effect(() => webCtx.webServer.registerUpgrade(upgrade), 'interconnect: /interconnect/link websocket')\n })\n\n // Liveness sweep: terminate sockets that stopped answering protocol pings.\n // Deleting the CURRENT element of a `Set` while iterating is safe: Set\n // iterators traverse live in insertion order, and a delete of an already\n // visited element is a no-op for the traversal. `socket.terminate()` from\n // `ws` fires its `close` handler asynchronously, so the `close` handler's\n // own `this.sockets.delete(socket)` cannot run mid-iteration either\n // (measured against the real `ws`). Neither delete removes a not-yet-visited\n // element, so nothing is skipped.\n // This timer is created before its cleanup effect below, so it could leak if\n // any statement between here and that effect threw. The only statements in\n // that window are `ctx.on(...)` registrations, and Cordis's `ctx.on` does not\n // throw for any of the event names used here (verified against a real\n // Context), so the window is not reachable. The teardown effect clears the\n // timer when the fiber unwinds.\n // Protocol constants, not deployment tunables: the heartbeat cadence is\n // fixed by the link-layer liveness contract and the backoff schedule by the\n // reconnect policy, so both stay hardcoded like the frame vocabulary.\n this.heartbeatTimer = setInterval(() => {\n for (const socket of this.sockets) {\n // A socket that closed between sweeps must not reach ping(): ws\n // throws synchronously when ping() is called on a non-OPEN socket.\n if (socket.readyState !== WebSocket.OPEN) {\n this.sockets.delete(socket)\n continue\n }\n if ((socket as WebSocket & { isAlive?: boolean }).isAlive === false) {\n socket.terminate()\n this.sockets.delete(socket)\n continue\n }\n ;(socket as WebSocket & { isAlive?: boolean }).isAlive = false\n socket.ping()\n }\n }, 30000)\n\n ctx.on('agent/status', ({ agent, status }) => {\n this.fanout({ kind: 'agent/status', sessionId: String(agent.session.id), status })\n })\n ctx.on('agent/created', ({ agent }) => {\n this.fanout({ kind: 'agent/created', sessionId: String(agent.session.id) })\n })\n ctx.on('agent/disposed', ({ agent }) => {\n this.fanout({ kind: 'agent/disposed', sessionId: String(agent.session.id) })\n })\n ctx.on('session/created', (session: Session) => {\n const parentSessionId = session.header.parentSession === undefined\n ? undefined\n : String(session.header.parentSession)\n this.fanout({\n kind: 'session/created',\n sessionId: String(session.id),\n ...(parentSessionId === undefined ? {} : { parentSessionId }),\n })\n })\n ctx.on('session/disposed', (session: Session) => {\n this.senders.delete(String(session.id))\n this.fanout({ kind: 'session/disposed', sessionId: String(session.id) })\n })\n ctx.on('subagent/end', (info: SubagentRunEndInfo) => {\n // Only in-process children are this instance's own work; remote provider\n // runs settle through a different, non-local path.\n if (!info.local) return\n this.fanout({\n kind: 'subagent/end',\n provider: info.provider,\n childSessionId: String(info.id),\n stopReason: info.stopReason,\n })\n })\n\n // Terminate every live socket, outbound dial loop, and the no-server\n // acceptor when the service fiber unwinds.\n ctx.effect(() => () => {\n /* v8 ignore next 1 -- the constructor sets the interval before registering this teardown effect, so dispose always observes it. */\n if (this.heartbeatTimer !== undefined) clearInterval(this.heartbeatTimer)\n for (const state of this.linkStates.values()) state.close()\n this.linkStates.clear()\n for (const socket of this.sockets) socket.terminate()\n this.sockets.clear()\n this.server.close()\n // Settle every in-flight request as unreachable: without this their\n // timers keep the process alive until they fire, and a late `*-result`\n // could resolve a pending that outlived its caller.\n for (const pending of this.pendingMessages.values()) {\n clearTimeout(pending.timer)\n pending.resolve?.(undefined)\n }\n this.pendingMessages.clear()\n this.disposed = true\n }, 'interconnect: websocket teardown')\n }\n\n /**\n * This instance's identity to attach to outbound messages. Always present:\n * it needs no address, only this instance's id and the calling session.\n * @param sessionId - the local session that is sending, used as the reply target.\n * @returns this instance's address-free identity for the calling session.\n */\n selfSender(sessionId: string): SenderIdentity {\n return { instanceId: this.instanceId, sessionId }\n }\n\n /**\n * Deliver one text message to a live session on a peer instance.\n * @param request - the peer instance id, target session, text, and optional delivery/resume overrides.\n * @returns the peer's answer, an unreachable result when no link answers, or a local\n * `message-too-large` result when the encoded frame would exceed the link cap.\n */\n async send(request: SendRequest): Promise<SendResult> {\n const payload: SendPayload = {\n sessionId: request.sessionId,\n text: request.text,\n ...(request.sender === undefined ? {} : { sender: request.sender }),\n ...(request.delivery === undefined ? {} : { delivery: request.delivery }),\n ...(request.resume === undefined ? {} : { resume: request.resume }),\n }\n try {\n const result = await this.msgRequest(request.instanceId, 'send', payload)\n return result ?? { delivered: false, instance: request.instanceId, reason: 'unreachable' }\n } catch {\n return { delivered: false, instance: request.instanceId, reason: 'unreachable' }\n }\n }\n\n /**\n * Deliver one text message back to the peer that a local session last\n * received a send from. `sessionId` names the LOCAL replying session; the\n * outbound target is the `sender` that session recorded, addressed through\n * this instance's own link to the sender's instance.\n * @param request - the LOCAL replying session id, the reply text, and optional delivery/resume overrides.\n * @returns the recalled sender's answer, an unreachable result when no link answers, or a\n * local `message-too-large` result when the encoded frame would exceed the link cap; a\n * local session that recorded no sender answers `no-sender-known` instead.\n */\n async reply(request: ReplyRequest): Promise<SendResult> {\n const sender = this.senders.get(request.sessionId)\n if (sender === undefined) {\n return { delivered: false, instance: this.instanceId, reason: 'no-sender-known' }\n }\n const payload: SendPayload = {\n sessionId: sender.sessionId,\n text: request.text,\n ...(request.delivery === undefined ? {} : { delivery: request.delivery }),\n ...(request.resume === undefined ? {} : { resume: request.resume }),\n // Attribute the reply to this instance so the peer, in turn, can reply\n // back \u2014 chaining the conversation.\n sender: this.selfSender(request.sessionId),\n }\n try {\n const result = await this.msgRequest(sender.instanceId, 'send', payload)\n return result ?? { delivered: false, instance: sender.instanceId, reason: 'unreachable' }\n } catch {\n return { delivered: false, instance: sender.instanceId, reason: 'unreachable' }\n }\n }\n\n /**\n * Probe a peer instance for liveness and identity over its persistent link.\n * Returns the peer identity when reachable, or undefined when the link is\n * not up or no answer arrives.\n * @param instanceId - the peer's `instanceId` as configured under {@link Config.peers}.\n * @returns the peer's identity, or undefined when the link is not up or no answer arrives.\n */\n async ping(instanceId: string): Promise<PingResult | undefined> {\n return this.queryRequest(instanceId, { kind: 'ping' }) as Promise<PingResult | undefined>\n }\n\n /**\n * List a peer instance's live sessions over its persistent link. Undefined on\n * transport failure, matching `ping`.\n * @param instanceId - the peer's `instanceId` as configured under {@link Config.peers}.\n * @returns the peer's live session rows, or undefined on transport failure.\n */\n async list(instanceId: string): Promise<ListResult | undefined> {\n return this.queryRequest(instanceId, { kind: 'list' }) as Promise<ListResult | undefined>\n }\n\n /**\n * Send a `msg` frame over the live link to a peer and resolve with its\n * correlated `msg-result`. Undefined when the peer has no live link here\n * (not configured, or the link is down) \u2014 sends can only address configured+\n * connected peers by design \u2014 and a `message-too-large` result when the\n * encoded frame would not fit the link.\n */\n private async msgRequest(\n instanceId: string,\n kind: LinkMessage['kind'],\n payload: SendPayload,\n ): Promise<SendResult | undefined> {\n const state = this.linkStates.get(instanceId)\n if (state === undefined || !state.writable()) return undefined\n const reqId = `m${++this.reqIdCounter}-${randomUUID()}`\n const frame: LinkFrame = {\n type: 'msg',\n reqId,\n message: {\n kind,\n sessionId: payload.sessionId,\n text: payload.text,\n ...(payload.sender === undefined ? {} : { sender: payload.sender }),\n ...(payload.delivery === undefined ? {} : { delivery: payload.delivery }),\n ...(payload.resume === undefined ? {} : { resume: payload.resume }),\n },\n }\n // Refuse an over-cap frame locally: the peer's ws would close the link on\n // receiving it, and the caller would read a transport failure for a message\n // that could never have fit.\n if (!frameFitsLink(frame)) {\n return { delivered: false, instance: instanceId, reason: 'message-too-large' }\n }\n return this.waitForResult(reqId, 'msg', (failure) => {\n const wrote = state.sendFrame(frame)\n /* v8 ignore next 1 -- writable() and sendFrame read the same socket.readyState synchronously, so this guard is unreachable. */\n if (!wrote) failure(new Error(`interconnect: peer link to ${instanceId} closed while sending`))\n }) as Promise<SendResult | undefined>\n }\n\n /** Send a `query` frame over the live link to a peer and resolve its result. */\n private async queryRequest(instanceId: string, query: { kind: 'ping' } | { kind: 'list' }): Promise<unknown> {\n const state = this.linkStates.get(instanceId)\n if (state === undefined || !state.writable()) return undefined\n const reqId = `q${++this.reqIdCounter}-${randomUUID()}`\n // Validate the answer against the KIND of query this request asked, not\n // just the frame union: a peer answering a `list` with a ping-shaped\n // result would otherwise crash the tool on `result.sessions.map`. An\n // answer that fails its kind's shape is treated as no answer at all.\n const accept = query.kind === 'ping' ? projectPingResult : projectListResult\n try {\n return await this.waitForResult(reqId, 'query', (failure) => {\n const wrote = state.sendFrame({ type: 'query', reqId, query })\n /* v8 ignore next 1 -- writable() and sendFrame read the same socket.readyState synchronously. */\n if (!wrote) failure(new Error(`interconnect: peer link to ${instanceId} closed while querying`))\n }, accept)\n } catch {\n // A peer that never answers must read as transport failure, matching the\n // public JSDoc: `ping`/`list` return undefined when no answer arrives.\n return undefined\n }\n }\n\n /** Settle a `reqId` frame against its `*-result`, timing out at `requestTimeoutMs`. */\n private waitForResult(\n reqId: string,\n kind: 'msg' | 'query',\n send: (failure: (error: unknown) => void) => void,\n accept?: (result: unknown) => unknown,\n ): Promise<unknown> {\n return new Promise<unknown>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.pendingMessages.delete(reqId)\n reject(new Error(`interconnect: no result for ${reqId} within ${this.requestTimeoutMs}ms`))\n }, this.requestTimeoutMs)\n const settle = (result: unknown): void => {\n clearTimeout(timer)\n this.pendingMessages.delete(reqId)\n resolve(result)\n }\n // Only a query pending carries a projector; a `msg-result` is projected by\n // `projectMsgResult` at its own settle site.\n this.pendingMessages.set(reqId, kind === 'query'\n ? { timer, kind, accept: accept as (result: unknown) => unknown, resolve: settle }\n : { timer, kind, resolve: settle })\n /* v8 ignore start -- the failure callback is gated by the writable() check; the timeout rejects instead. */\n send((error: unknown) => {\n clearTimeout(timer)\n this.pendingMessages.delete(reqId)\n reject(error instanceof Error ? error : new Error(String(error)))\n })\n /* v8 ignore stop */\n })\n }\n\n /**\n * Dial one configured peer route. Activation calls this once per\n * `Config.peers` entry; the resulting state owns reconnection for the life of\n * the service fiber.\n * @param instanceId - the peer's `instanceId`.\n * @param origin - receiver origin this instance dials, e.g. `http://127.0.0.1:13080`.\n */\n private link(instanceId: string, origin: string): void {\n const state = new LinkState(\n (socket) => { this.attachDialedSocket(socket, instanceId) },\n this.ctx.logger,\n () => this.resolveToken(),\n instanceId,\n trimBase(origin),\n )\n this.linkStates.set(instanceId, state)\n state.dial()\n }\n\n /** Push one serialized lifecycle fact out to every linked peer over WS. */\n private fanout(notification: EventNotification): void {\n this.broadcast(notification)\n }\n\n /**\n * Push one fact over every live WebSocket link, dropping closed sockets.\n *\n * A bidirectional pair owns two sockets to the same peer (this instance's\n * dialed link plus the peer's inbound one), so one event must leave over one\n * of them. Which one is decided by local ownership, not by the peer: a dialed\n * socket is a configured peer's link and always sends. An inbound socket is\n * skipped only when this instance has an open dialed link configured under\n * the id that socket itself announced, so a self-reported announcement can\n * never silence another peer's link; with no such dialed link every inbound\n * socket receives the event. A peer listed under a key other than the id it\n * announces is warned about once per link, because then its own inbound\n * socket is not attributable and the peer receives each event twice.\n *\n * That holds once a peer's announcement has been seen. Between this\n * instance's dialed link opening and the peer's `hello` arriving on its\n * inbound socket, the inbound socket is not yet attributable, so an event\n * emitted in that window leaves over both sockets and reaches that peer\n * twice. The duplicate is transient and never a dropped event.\n */\n private broadcast(notification: EventNotification): void {\n if (this.sockets.size === 0) return\n const frame: LinkFrame = { type: 'event', notification }\n const encoded = JSON.stringify(frame)\n const covered = new Set<string>()\n for (const socket of this.sockets) {\n if (socket.readyState !== WebSocket.OPEN) {\n this.sockets.delete(socket)\n continue\n }\n const dialedPeer = this.dialedPeerOf.get(socket)\n if (dialedPeer !== undefined) covered.add(dialedPeer)\n }\n for (const socket of this.sockets) {\n if (this.dialedPeerOf.get(socket) === undefined) {\n const announced = this.peerOf.get(socket)\n if (announced !== undefined && covered.has(announced)) continue\n }\n socket.send(encoded)\n }\n }\n\n /**\n * Dispatch one inbound `msg` frame: deliver a `send`/`reply` and answer the\n * correlated `msg-result` on the same socket. Errors are surfaced as the\n * result so a throwing handler cannot escape the socket's message callback.\n */\n private async handleMsgFrame(socket: WebSocket, reqId: string, message: LinkMessage): Promise<void> {\n // Only `send` arrives over the wire: `reply` originates locally (the tool\n // calls `reply()` which sends a regular `send` frame to the recalled\n // sender). A remote `reply` frame would relay arbitrary text through this\n // instance's sender map, so the schema does not admit it.\n const result = await this.deliver({\n sessionId: message.sessionId,\n text: message.text,\n /* v8 ignore next 1 -- schemastery resolves an absent optional `sender` to an empty object, never undefined. */\n ...(message.sender === undefined ? {} : { sender: message.sender }),\n ...(message.delivery === undefined ? {} : { delivery: message.delivery }),\n ...(message.resume === undefined ? {} : { resume: message.resume }),\n })\n this.sendFrame(socket, { type: 'msg-result', reqId, result })\n }\n\n /** Dispatch one inbound `query` frame (ping/list/event) and answer on the socket. */\n private handleQueryFrame(socket: WebSocket, reqId: string, query: QueryMessage): void {\n let result: unknown\n if (query.kind === 'ping') {\n result = { pong: true, instance: this.instanceId }\n } else if (query.kind === 'list') {\n result = this.listSessions(this.listRowsBudgetBytes(reqId))\n } else {\n const payload: EventPayload = {\n sender: this.peerOf.get(socket) ?? 'unknown-peer',\n notification: query.notification,\n }\n this.receiveEvent(payload)\n result = { accepted: true }\n }\n this.sendFrame(socket, { type: 'query-result', reqId, result })\n }\n\n /**\n * Surface one remote notification to local listeners and the log.\n *\n * `ctx.parallel` is used instead of `ctx.emit`: `emit` maps listeners without\n * awaiting them, so a listener that returns a rejected promise would surface\n * as an unhandled rejection, while `parallel` settles every listener and\n * aggregates their failures.\n */\n private receiveEvent(eventPayload: EventPayload): void {\n const { notification, sender } = eventPayload\n this.ctx.logger.info(`interconnect: remote event ${notification.kind} from ${sender}`)\n // A listener failure is the listener's bug and must not take down the link\n // or this process, so the aggregate is logged instead of rethrown.\n void this.ctx.parallel('interconnect/event', notification, sender).catch((error: unknown) => {\n // `parallel` aggregates the rejected listeners into an AggregateError\n // whose own message is empty, so the reasons carry the diagnostic.\n /* v8 ignore next 1 -- `parallel` rejects only with the AggregateError it builds from listener results. */\n const reasons = error instanceof AggregateError ? error.errors : [error]\n const detail = reasons\n .map(reason => (reason instanceof Error ? reason.message : String(reason)))\n .join('; ')\n this.ctx.logger.warn(`interconnect: listener for a ${notification.kind} event from ${sender} threw: ${detail}`)\n })\n }\n\n /**\n * Bytes one `list` answer may spend on its `sessions` rows: the frame cap\n * minus the serialized envelope that answer will carry. The envelope holds\n * the peer-supplied `reqId` and this instance's own id, so it is measured per\n * answer instead of reserved with a fixed constant. Both ids are bounded\n * ({@link MAX_REQUEST_ID_CHARS} and {@link MAX_INSTANCE_ID_CHARS} characters),\n * so the envelope always fits and the budget is always positive.\n * @param reqId - the request id the answer has to echo.\n * @returns the byte budget for the rows.\n */\n private listRowsBudgetBytes(reqId: string): number {\n const envelope: LinkFrame = {\n type: 'query-result',\n reqId,\n result: { sessions: [], instance: this.instanceId },\n }\n return MAX_LINK_FRAME_BYTES - Buffer.byteLength(JSON.stringify(envelope), 'utf8')\n }\n\n /**\n * Summarize the live local sessions so a sender can discover valid targets\n * instead of having to know a session id already. Only live agents are listed\n * because `send` can reach exactly those. The answer stops at\n * {@link MAX_LISTED_SESSIONS} rows or at the row budget the answer's own\n * envelope leaves, whichever comes first: that budget is what keeps the\n * complete `query-result` frame inside the link's cap, because a title's\n * length comes from the session-title projection's own bound rather than\n * from anything this listing controls. A title that does not fit the\n * remaining budget is dropped so its target stays listed; a row that does not\n * fit even untitled ends the listing, which keeps the answer a prefix of the\n * registration order instead of a set with gaps.\n *\n * Title and status are best-effort: the title projection is an optional\n * service, and a receiver without it still returns the ids. A projection that\n * throws degrades that one row rather than failing the whole listing, which\n * matches how the Host's own session listing treats its projection column.\n * @param rowBudgetBytes - bytes the `sessions` rows may occupy, envelope excluded.\n * @returns the bounded listing.\n */\n private listSessions(rowBudgetBytes: number): ListResult {\n // `agents.list()` includes subagent children; a row this instance would\n // refuse to deliver to must not be advertised as a target, or the listing\n // contradicts `send`.\n const reachable = this.ctx.agents.list()\n .filter(agent => !isSessionOwnedBySubagent(this.ctx, agent.session, agent))\n const sessions: InterconnectSessionSummary[] = []\n let used = 0\n for (const agent of reachable.slice(0, MAX_LISTED_SESSIONS)) {\n const row = this.sessionRow(agent)\n const sized = used + rowBytes(row)\n if (sized > rowBudgetBytes) {\n // A title is best-effort: a row whose title does not fit keeps its\n // target and drops the title before it drops out of the listing.\n const untitled = {\n sessionId: row.sessionId,\n ...(row.status === undefined ? {} : { status: row.status }),\n }\n const untitledSized = used + rowBytes(untitled)\n // A row that does not fit even untitled ends the listing: adding a\n // shorter later row would report the set out of order.\n if (untitledSized > rowBudgetBytes) break\n sessions.push(untitled)\n used = untitledSized\n continue\n }\n sessions.push(row)\n used = sized\n }\n return { sessions, instance: this.instanceId }\n }\n\n /** One listing row for a live agent; the title projection is best-effort. */\n private sessionRow(agent: Agent): InterconnectSessionSummary {\n let title: string | undefined\n try {\n const snapshot = this.ctx.get('sessionProjections')?.snapshot(agent.session)\n const value = snapshot?.values.title\n if (typeof value === 'string' && value !== '') title = value\n } catch {\n // A failing projection must not hide a reachable session.\n title = undefined\n }\n return {\n sessionId: agent.id,\n ...(title === undefined ? {} : { title }),\n ...(typeof agent.status === 'string' ? { status: agent.status } : {}),\n }\n }\n\n /**\n * Resolve a session that is not currently live, when the sender asked to wake\n * it. Returns the agent, or the reason it stays undelivered.\n *\n * The resume is delegated to the Host's configured `agent` lookup rather than\n * calling `ctx.agents.resume()` here, and that is the whole point: a handle\n * from `resume()` is owned by the CALLING context, so resuming on this\n * plugin's fiber would tear the session down again the moment the plugin\n * unloads (measured: the same call through the root context leaves it alive).\n * The Host's resolver owns it instead, and it also composes the preset the\n * session recorded \u2014 so a woken agent comes back with the toolset its history\n * was produced under, not an empty one.\n */\n private async wake(payload: SendPayload): Promise<{ agent: Agent } | { reason: SendFailure }> {\n if (payload.resume !== true) return { reason: 'session-not-live' }\n if (!this.allowResume) return { reason: 'resume-refused' }\n // Optional by design: a deployment without the Host's lookup (headless, or\n // a profile with no api-proxy) degrades to the plain not-live answer rather\n // than failing the call.\n const lookup = this.ctx.get('typert')?.lookups.get('agent')\n if (lookup === undefined) return { reason: 'session-not-live' }\n try {\n const resolved = await lookup.resolve(payload.sessionId)\n // `undefined` is not a failed wake: the base `agent` provider is a plain\n // registry read, so a deployment without the Host's resuming resolver\n // answers undefined for every id that is not already live. Reporting\n // `resume-failed` there would send the caller chasing a wake that was\n // never possible, when the honest answer is that nothing is live here.\n if (resolved === undefined || resolved === null) return { reason: 'session-not-live' }\n return { agent: resolved as Agent }\n } catch (error) {\n // A refusing resolver is an expected outcome, not a fault of this\n // instance: the id may not exist, or a subagent owner may hold it.\n this.ctx.logger.info(\n `interconnect: resume refused for ${payload.sessionId}: ${error instanceof Error ? error.message : String(error)}`,\n )\n // A subagent-owned session is the one refusal with a different answer for\n // the caller: it exists, and its parent is the address that can deliver\n // to it. The Host reports that cause as `session/agent-busy`, and for a\n // cold session nothing local carries the ownership header, so the code is\n // the only signal available here.\n if (remoteErrorOf(error)?.code === 'session/agent-busy') {\n return { reason: 'session-owned-by-subagent' }\n }\n return { reason: 'resume-failed' }\n }\n }\n\n /**\n * Deliver one message to a live local session, waking a persisted one only\n * when the sender asked and this receiver allows it.\n */\n private async deliver(payload: SendPayload): Promise<SendResult> {\n // A delivery that outlived the service fiber (an inbound frame already in\n // flight when the plugin unloaded) must not drive a disposed agent.\n if (this.disposed) return { delivered: false, instance: this.instanceId, reason: 'unreachable' }\n let agent = this.ctx.agents.get(payload.sessionId as Agent['id'])\n if (agent === undefined) {\n const woken = await this.wake(payload)\n // The fiber may have unwound while the wake resolution was in flight;\n // re-check before touching a woken agent. oxlint's flow analysis treats\n // the two `disposed` reads as the same value, but `await` is a yield\n // point at which the teardown effect can run.\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- the service can dispose during the wake await\n if (this.disposed) return { delivered: false, instance: this.instanceId, reason: 'unreachable' }\n if ('reason' in woken) {\n return { delivered: false, instance: this.instanceId, reason: woken.reason }\n }\n agent = woken.agent\n }\n // Fence the live-hit path too, exactly as the Host does before handing out a\n // live agent: a session reserved to subagent routing is delivered to by its\n // parent, and splicing into its inbox from here would race that parent. The\n // wake path needs no separate check because the Host's resolver applies the\n // same fence internally.\n if (isSessionOwnedBySubagent(this.ctx, agent.session, agent)) {\n return { delivered: false, instance: this.instanceId, reason: 'session-owned-by-subagent' }\n }\n // Remember who sent this message so the receiving session can reply later.\n // `source` never reaches the model, so recording the sender here only sets\n // up reply attribution; the model-facing `content` stays exactly the text\n // that crossed the wire. An absent sender resolves to `{}` under schematery,\n // so test for a real identity rather than `undefined`.\n // The wire shape is untrusted here: a peer may send a partial identity,\n // so validate both fields at runtime before recording a reply target.\n const sender = ((): SenderIdentity | undefined => {\n const candidate: unknown = payload.sender\n if (typeof candidate !== 'object' || candidate === null) return undefined\n const record = candidate as Record<string, unknown>\n if (typeof record.instanceId !== 'string' || typeof record.sessionId !== 'string') return undefined\n return { instanceId: record.instanceId, sessionId: record.sessionId }\n })()\n // Attribute the message to this plugin, not to the human operator: the\n // receiving agent must be able to tell a cross-instance handoff from text\n // its own user typed. The summary names the sender when one was carried, so\n // a GUI/archive can show where the handoff came from without touching the\n // model-facing content.\n const message = createUserMessage({\n source: {\n kind: 'plugin',\n plugin: PLUGIN_SOURCE,\n form: 'notice',\n summary: boundContextSummary(\n sender === undefined\n ? `interconnect handoff delivered on instance ${this.instanceId}`\n : `interconnect handoff from ${sender.instanceId} (session ${sender.sessionId}) delivered on instance ${this.instanceId}`,\n ),\n },\n content: [{ type: 'text', text: payload.text }],\n })\n // The sender may override the mode per message, because urgency belongs to\n // one message rather than to the link; an absent override leaves the\n // receiver's configured default in force. The switch is exhaustive over\n // DeliveryMode so adding a mode fails the type check here instead of\n // silently falling through to `followup`.\n const mode: DeliveryMode = payload.delivery ?? this.delivery\n switch (mode) {\n case 'steer':\n agent.steer(message)\n break\n case 'inject':\n agent.inject(message)\n break\n case 'followup':\n agent.followup(message)\n break\n /* v8 ignore next -- closed-union exhaustiveness guard */\n default:\n assertNever(mode)\n }\n // Record the reply target only after the message committed: a delivery that\n // threw leaves no sender behind, so a later reply cannot target a session\n // whose handoff never landed. A message that carries NO sender (an old peer,\n // or an anonymous relay) clears any earlier mapping, so a reply cannot go\n // back to a stale sender from a previous handoff.\n if (sender !== undefined) {\n this.senders.set(payload.sessionId, sender)\n } else {\n this.senders.delete(payload.sessionId)\n }\n return { delivered: true, instance: this.instanceId, delivery: mode }\n }\n\n private async resolveToken(): Promise<string | undefined> {\n const credential = await this.ctx.credentials.resolve(credentialRef(INTERCONNECT_TOKEN_REF))\n return credential === undefined || credential.value.length === 0 ? undefined : credential.value\n }\n\n /**\n * Answer one refused upgrade and close its socket. `socket.end()` alone only\n * half-closes the connection: a client that keeps its own writing side open\n * (a socket created with `allowHalfOpen`) leaves the connection live, and a\n * refused socket never enters the link pool, so nothing else would reap it.\n * @param socket - the refused upgrade socket.\n * @param response - the complete HTTP response sent to the client.\n */\n private refuseUpgrade(socket: Duplex, response: string): void {\n socket.end(response, () => { socket.destroy() })\n }\n\n /** Inbound WebSocket upgrade: authenticate the bearer header, then accept. */\n private async handleUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): Promise<void> {\n let token: string | undefined\n try {\n token = await this.resolveToken()\n } catch (error) {\n // Fail closed and end the socket: the caller invokes this as\n // `void handleUpgrade(...)`, so letting the rejection escape would both\n // leave this client hanging on an open socket and surface as an unhandled\n // rejection.\n this.ctx.logger.warn(`interconnect: upgrade token read failed: ${error instanceof Error ? error.message : String(error)}`)\n this.refuseUpgrade(socket, 'HTTP/1.1 403 Forbidden\\r\\nConnection: close\\r\\nContent-Length: 9\\r\\n\\r\\nforbidden')\n return\n }\n if (token === undefined) {\n this.refuseUpgrade(socket, 'HTTP/1.1 403 Forbidden\\r\\nConnection: close\\r\\nContent-Length: 9\\r\\n\\r\\nforbidden')\n return\n }\n // The token read is an await, so the service can be torn down (or the\n // webserver route withdrawn) before it settles. Accepting here would add a\n // socket to a pool the teardown already cleared, with no owner left to\n // close it or answer its heartbeat.\n if (this.disposed) {\n this.refuseUpgrade(socket, 'HTTP/1.1 503 Service Unavailable\\r\\nConnection: close\\r\\nContent-Length: 11\\r\\n\\r\\nunavailable')\n return\n }\n const expected = `Bearer ${token}`\n const header = req.headers.authorization\n if (header === undefined || !timingSafeEqual(header, expected)) {\n this.refuseUpgrade(socket, 'HTTP/1.1 401 Unauthorized\\r\\nConnection: close\\r\\nContent-Length: 12\\r\\n\\r\\nunauthorized')\n return\n }\n this.server.handleUpgrade(req, socket, head, (websocket) => {\n this.attachSocket(websocket)\n })\n }\n\n /**\n * Install frame + liveness handling on one outbound socket the dial owns for\n * a configured peer, recording that local ownership before anything else can\n * observe the socket.\n * @param websocket - the dialed socket.\n * @param peerInstanceId - the configured peer this instance dials.\n */\n private attachDialedSocket(websocket: WebSocket, peerInstanceId: string): void {\n this.dialedPeerOf.set(websocket, peerInstanceId)\n this.attachSocket(websocket)\n }\n\n /**\n * Install frame + liveness handling on one socket and add it to the live\n * pool. Used by both the server half (accepted upgrade) and the client half\n * (outbound dial), so a single socket carries events both directions. Not a\n * model-facing entry point; the outbound dial reaches it through a private\n * closure.\n * @param websocket - the accepted or dialed socket to install handlers on.\n */\n private attachSocket(websocket: WebSocket): void {\n this.sockets.add(websocket)\n ;(websocket as WebSocket & { isAlive: boolean }).isAlive = true\n websocket.on('pong', () => {\n ;(websocket as WebSocket & { isAlive: boolean }).isAlive = true\n })\n websocket.on('message', (data: RawData, isBinary: boolean) => {\n // ws flags the frame opcode: binary frames are a protocol violation (the\n // link vocabulary is JSON text), so drop them before parsing.\n if (isBinary) return\n this.handleFrame(websocket, data)\n })\n websocket.on('close', () => {\n this.sockets.delete(websocket)\n this.peerOf.delete(websocket)\n })\n websocket.on('error', () => {\n this.sockets.delete(websocket)\n })\n // Announce this instance's identity so the dialer can attribute pushes.\n websocket.send(JSON.stringify({ type: 'hello', sender: this.instanceId } satisfies LinkFrame))\n }\n\n /** Parse and route one inbound link frame, attributing events to the socket's announced peer. */\n private handleFrame(socket: WebSocket, data: RawData | string): void {\n // Cap inbound frames well below ws's 100 MiB default: a link frame is at\n // most one small message plus metadata, so a larger frame is a hostile or\n // broken peer, not a legitimate handoff.\n const byteLength = typeof data === 'string'\n ? Buffer.byteLength(data)\n : Array.isArray(data)\n ? data.reduce((total, part) => total + part.byteLength, 0)\n : data.byteLength\n if (byteLength > MAX_LINK_FRAME_BYTES) {\n this.ctx.logger.warn('interconnect: dropping oversized link frame')\n return\n }\n // Text frames arrive as Buffers over real sockets (ws flags the opcode\n // separately); the other RawData arms cover alternate binaryType\n // deliveries and the string arm the direct test seams.\n const text = typeof data === 'string'\n ? data\n : Array.isArray(data)\n ? Buffer.concat(data).toString('utf8')\n : Buffer.isBuffer(data)\n ? data.toString('utf8')\n : Buffer.from(data).toString('utf8')\n let parsed: unknown\n try {\n parsed = withoutNullFields(z.resolve(JSON.parse(text), linkFrameSchema, {})[0])\n } catch {\n this.ctx.logger.warn('interconnect: dropping malformed link frame')\n return\n }\n // schemastery passes a JSON `null` through a union untouched; reject it\n // like any other malformed frame instead of dereferencing null below.\n if (parsed === null || typeof parsed !== 'object') {\n this.ctx.logger.warn('interconnect: dropping malformed link frame')\n return\n }\n const frame = parsed as LinkFrame\n if (frame.type === 'hello') {\n this.peerOf.set(socket, frame.sender)\n const dialedPeer = this.dialedPeerOf.get(socket)\n if (dialedPeer !== undefined && dialedPeer !== frame.sender && !this.mismatchWarned.has(socket)) {\n this.mismatchWarned.add(socket)\n this.ctx.logger.warn(\n `interconnect: peer configured as ${dialedPeer} announces ${frame.sender}; list a peer under the instanceId it announces, or the duplicate inbound link is not recognised`,\n )\n }\n return\n }\n if (frame.type === 'event') {\n // `receiveEvent` reports listener failures itself, synchronously or not,\n // so this socket's synchronous `message` handler cannot be reached by a\n // remote peer's event through a local listener.\n this.receiveEvent({ sender: this.peerOf.get(socket) ?? 'unknown-peer', notification: frame.notification })\n return\n }\n if (frame.type === 'msg-result') {\n const pending = this.pendingMessages.get(frame.reqId)\n // A `msg-result` settles only a `msg` request: a query awaiting its\n // `query-result` must never be resolved by a mis-typed frame. The\n // result shape is already enforced by the frame schema; msg requests\n // carry no per-kind accept gate.\n if (pending !== undefined && pending.kind === 'msg') {\n ;pending.resolve?.(projectMsgResult(frame.result))\n }\n return\n }\n if (frame.type === 'query-result') {\n const pending = this.pendingMessages.get(frame.reqId)\n // Only a result that satisfies the pending request's own shape settles\n // it, and the projecting accept returns what settles: anything else is\n // dropped and the request times out as unreachable.\n if (pending !== undefined && pending.kind === 'query') {\n const answer = pending.accept(frame.result)\n if (answer !== undefined) pending.resolve?.(answer)\n }\n return\n }\n if (frame.type === 'msg') {\n void Promise.resolve().then(async () => {\n await this.handleMsgFrame(socket, frame.reqId, frame.message)\n }).catch((error: unknown) => {\n this.ctx.logger.warn(`interconnect: msg ${frame.reqId} handler threw: ${error instanceof Error ? error.message : String(error)}`)\n void this.sendFrame(socket, {\n type: 'msg-result',\n reqId: frame.reqId,\n result: { delivered: false, instance: this.instanceId, reason: 'unreachable' },\n })\n })\n return\n }\n // `query`: an inbound discovery/event request. Answer asynchronously and\n // never let a throw escape the socket's synchronous message callback.\n void Promise.resolve().then(() => {\n this.handleQueryFrame(socket, frame.reqId, frame.query)\n }).catch((error: unknown) => {\n this.ctx.logger.warn(`interconnect: query ${frame.reqId} handler threw: ${error instanceof Error ? error.message : String(error)}`)\n })\n }\n\n /** Write one frame to a socket, returning false when the socket cannot take it. */\n private sendFrame(socket: WebSocket, frame: LinkFrame): boolean {\n if (socket.readyState !== WebSocket.OPEN) return false\n socket.send(JSON.stringify(frame))\n return true\n }\n}\n\n/**\n * One in-flight request awaiting its `*-result` frame. `waitForResult`\n * installs the timer and settle callbacks; `handleFrame` settles the matching\n * entry when the result arrives.\n */\ninterface PendingMessage {\n readonly timer: ReturnType<typeof setTimeout>\n}\n/** A pending that awaits a `msg-result` frame. */\ninterface PendingMsg extends PendingMessage {\n kind: 'msg'\n resolve?: (result: unknown) => void\n}\n/** A pending that awaits a `query-result` frame, gated by its request kind's projector. */\ninterface PendingQuery extends PendingMessage {\n kind: 'query'\n resolve?: (result: unknown) => void\n /** Kind gate and projector: returns the answer to settle with, or undefined to drop the frame. */\n accept: (result: unknown) => unknown\n}\n/** One pending request: a `msg` outcome is projected at its settle site, a `query` outcome by its own projector. */\ntype MutablePendingMessage = PendingMsg | PendingQuery\n\n/**\n * One dialed socket together with the handlers that dial registered on it, so\n * close can remove exactly those by reference and leave the pool-cleanup\n * handlers attachSocket added in place.\n */\ninterface DialedSocket {\n socket: WebSocket\n open: () => void\n close: () => void\n error: () => void\n}\n\n/**\n * One outbound WebSocket peer link: dials, re-dials with backoff after an\n * unexpected drop, and joins the service's live socket pool once open, so\n * local events fan out over the link and the peer's pushes come back in.\n */\nclass LinkState {\n private dialed: DialedSocket | undefined\n private closed = false\n private retry = 0\n private reconnectTimer: ReturnType<typeof setTimeout> | undefined\n private warnedNoToken = false\n\n /** Receiver origin this link dials. */\n readonly peer: string\n readonly instanceId: string\n\n constructor(\n private readonly attachSocket: (socket: WebSocket) => void,\n private readonly logger: LoggerService,\n private readonly resolveToken: () => Promise<string | undefined>,\n instanceId: string,\n origin: string,\n ) {\n this.instanceId = instanceId\n this.peer = origin\n }\n\n /** Open the socket; reconnect is scheduled by the close handler. */\n dial(): void {\n /* v8 ignore next 1 -- close() removes the link state from the map before any later dial can observe it. */\n if (this.closed) return\n let url: URL\n try {\n url = linkUrl(this.peer)\n } catch {\n // The constructor pre-validates configured origins, so a malformed one\n // here can only come from a deployment whose config bypassed validation;\n // it degrades to a down link rather than a thrown dial.\n this.logger.warn(`interconnect: invalid peer origin ${this.peer}; link to ${this.instanceId} stays down`)\n return\n }\n void this.resolveToken().then((token) => {\n if (token === undefined) {\n // Warn once, then keep retrying on the reconnect backoff: a credential\n // injected after this service activated must bring the link up without\n // a restart. The dial re-resolves the token on every retry.\n if (!this.warnedNoToken) {\n this.warnedNoToken = true\n this.logger.warn(`interconnect: no shared token configured; peer ${this.instanceId} link stays down, retrying until one is set`)\n }\n if (this.closed) return\n this.scheduleReconnect()\n return\n }\n if (this.closed) return\n const socket = new WebSocket(url, {\n headers: { authorization: `Bearer ${token}` },\n maxPayload: MAX_LINK_FRAME_BYTES,\n // A peer that accepts TCP but never completes the upgrade would leave\n // the socket in CONNECTING forever: no open (so no heartbeat) and no\n // close (so no reconnect). ws aborts the connection past the handshake\n // window, so its own error+close fire and the close handler schedules\n // a reconnect \u2014 and ws owns the timer, so nothing leaks on teardown.\n handshakeTimeout: LINK_HANDSHAKE_TIMEOUT_MS,\n })\n const onOpen = (): void => {\n this.retry = 0\n // Same handler as the server half: adds to the live pool and announces\n // this instance's identity over the now-open link.\n this.attachSocket(socket)\n }\n const onClose = (): void => {\n /* v8 ignore next 1 -- close() strips this listener before terminating, so the guard is only reachable on real drops. */\n if (this.closed) return\n this.scheduleReconnect()\n }\n const onError = (): void => {\n // close follows; reconnect is scheduled there.\n }\n this.dialed = { socket, open: onOpen, close: onClose, error: onError }\n socket.once('open', onOpen)\n socket.once('close', onClose)\n socket.on('error', onError)\n }).catch(() => {\n // A rejecting token read must not become an unhandled rejection, and must\n // not silently end the dial loop either: without this the link would stay\n // down until the process restarted, since no socket was ever created and\n // so no `close` will arrive to schedule the retry.\n if (this.closed) return\n this.scheduleReconnect()\n })\n }\n\n /** Whether this link currently holds an open socket that can carry frames. */\n writable(): boolean {\n const dialed = this.dialed\n return dialed !== undefined && dialed.socket.readyState === WebSocket.OPEN\n }\n\n /** Write one frame over this link's outbound socket; false when not open. */\n sendFrame(frame: LinkFrame): boolean {\n const dialed = this.dialed\n /* v8 ignore next 1 -- callers gate on writable(), which reads the same readyState synchronously; this guard is unreachable. */\n if (dialed === undefined || dialed.socket.readyState !== WebSocket.OPEN) return false\n dialed.socket.send(JSON.stringify(frame))\n return true\n }\n\n close(): void {\n this.closed = true\n if (this.reconnectTimer !== undefined) clearTimeout(this.reconnectTimer)\n const dialed = this.dialed\n if (dialed === undefined) return\n // Remove only the dial handlers: the attachSocket pool-cleanup handlers\n // must stay so the pool does not retain the terminated socket.\n dialed.socket.removeListener('open', dialed.open)\n dialed.socket.removeListener('close', dialed.close)\n dialed.socket.removeListener('error', dialed.error)\n // A CONNECTING socket emits 'error' asynchronously on terminate; keep a\n // listener so the event cannot escape as an uncaughtException. Callers\n // delete this link's state from the map themselves.\n /* v8 ignore next 1 -- a CONNECTING terminate error is timing-dependent and does not fire in tests. */\n dialed.socket.on('error', () => {})\n dialed.socket.terminate()\n }\n\n private scheduleReconnect(): void {\n /* v8 ignore next 1 -- the 30s cap binds only after five consecutive reconnect failures (~31s of wall time). */\n const delay = Math.min(30000, 1000 * 2 ** this.retry)\n this.retry += 1\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = undefined\n this.dial()\n }, delay)\n }\n}\n\n/**\n * Constant-time comparison of two strings. Each side is digest-normalized\n * first, so the buffers passed to `timingSafeEqual` always match in length:\n * a malformed multi-byte Authorization header cannot reach the crypto layer\n * with a mismatched length, and the comparison leaks no length information.\n */\nfunction timingSafeEqual(a: string, b: string): boolean {\n return constantTimeEqual(createHash('sha256').update(a, 'utf8').digest(), createHash('sha256').update(b, 'utf8').digest())\n}\n\n/**\n * Map one HTTP(S) peer origin to the WebSocket URL of its link route. Only\n * the plain-HTTP schemes are rewritten to their WebSocket equivalents; an\n * explicit `wss:` (or `ws:`) origin keeps its scheme, so a TLS peer link is\n * never downgraded to plaintext. Any other scheme (ftp:, file:, ...) is\n * rejected so a misconfigured origin fails loudly instead of feeding\n * `new WebSocket` a URL it cannot dial.\n * @param origin - peer origin as configured, e.g. `http://127.0.0.1:13080`.\n * @returns the link URL, e.g. `ws://127.0.0.1:13080/interconnect/link`.\n * @throws TypeError when the origin is not a valid absolute URL or maps to a\n * non-WebSocket protocol.\n */\nexport function linkUrl(origin: string): URL {\n const url = new URL(LINK_CHANNEL, origin)\n if (url.protocol === 'http:') url.protocol = 'ws:'\n else if (url.protocol === 'https:') url.protocol = 'wss:'\n if (url.protocol !== 'ws:' && url.protocol !== 'wss:') {\n throw new TypeError(`interconnect: unsupported peer origin protocol ${url.protocol}`)\n }\n return url\n}\n\nfunction trimBase(baseUrl: string): string {\n return baseUrl.replace(/\\/+$/, '')\n}\n\nexport default InterconnectService\n", "/** String/symbol keyed dictionary type. */\nexport type Dict<T = any, K extends string | symbol = string> = { [key in K]: T }\n/** Safely read `T[K]`, returning `never` when `K` is not a key of `T`. */\nexport type Get<T extends {}, K> = K extends keyof T ? T[K] : never\n/** Conditional extraction helper with a configurable return type. */\nexport type Extract<S, T, U = S> = S extends T ? U : never\n/** Accept a value or an array, unless the value is already an array type. */\nexport type MaybeArray<T> = [T] extends [unknown[]] ? T : T | T[]\n/** Wrap a value in `Promise`, preserving the resolved type of existing promises. */\nexport type Promisify<T> = Promise<T extends Promise<infer S> ? S : T>\n/** Accept a value or promise unless the value type is already promise-like. */\nexport type Awaitable<T> = [T] extends [Promise<unknown>] ? T : T | Promise<T>\n/** Convert a union type to an intersection type. */\nexport type Intersect<U> = (U extends any ? (arg: U) => void : never) extends ((arg: infer I) => void) ? I : never\n\n/** No-op callback returning `undefined` at runtime and `any` at type level. */\nexport function noop(): any {}\n\n/** Return true when a value is `null` or `undefined`. */\nexport function isNullable(value: any): value is null | undefined | void {\n return value === null || value === undefined\n}\n\n/** Return true when a value is neither `null` nor `undefined`. */\nexport function isNonNullable<T>(value: T): value is NonNullable<T> {\n return !isNullable(value)\n}\n\n/** Return true for non-array object values. */\nexport function isPlainObject(data: any) {\n return data && typeof data === 'object' && !Array.isArray(data)\n}\n\n/** Filter object entries with a key type guard. */\nexport function filterKeys<T, K extends string, U extends K>(object: Dict<T, K>, filter: (key: K, value: T) => key is U): Dict<T, U>\n/** Filter object entries with a boolean predicate. */\nexport function filterKeys<T, K extends string>(object: Dict<T, K>, filter: (key: K, value: T) => boolean): Dict<T, K>\n/** Filter object entries and return a new object. */\nexport function filterKeys(object: {}, filter: (key: string, value: any) => boolean) {\n return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)))\n}\n\n/** Map object values while preserving the original key set. */\nexport function mapValues<U, T, K extends string>(object: Dict<T, K>, transform: (value: T, key: K) => U) {\n return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, (transform as any)(value, key)])) as Dict<U, K>\n}\n\n/** Alias for `mapValues`. */\nexport { mapValues as valueMap }\n\n/** Pick selected keys from an object, optionally including `undefined` values. */\nexport function pick<T extends object, K extends keyof T>(source: T, keys?: Iterable<K>, forced?: boolean) {\n if (!keys) return { ...source }\n const result = {} as Pick<T, K>\n for (const key of keys) {\n if (forced || source[key] !== undefined) result[key] = source[key]\n }\n return result\n}\n\n/** Omit selected keys from a shallow object copy. */\nexport function omit<T, K extends keyof T>(source: T, keys?: Iterable<K>) {\n if (!keys) return { ...source }\n const result = { ...source } as Omit<T, K>\n for (const key of keys) {\n Reflect.deleteProperty(result, key)\n }\n return result\n}\n\n/** Define a non-enumerable writable property with a typed key. */\nexport function defineProperty<T, K extends keyof T>(object: T, key: K, value: T[K]): T\n/** Define a non-enumerable writable property with an arbitrary key. */\nexport function defineProperty<T, K extends keyof any>(object: T, key: K, value: any): T\n/** Define a non-enumerable writable property and return the object. */\nexport function defineProperty<T, K extends keyof any>(object: T, key: K, value: any) {\n return Object.defineProperty(object, key, { writable: true, value, enumerable: false })\n}\n", "import { isNullable } from './misc.ts'\n\ntype GlobalConstructorNames = keyof {\n [K in keyof typeof globalThis as typeof globalThis[K] extends abstract new (...args: any) => any ? K : never]: K\n}\n\n/** Create a predicate for a global constructor name. */\nexport function is<K extends GlobalConstructorNames>(type: K): (value: any) => value is InstanceType<typeof globalThis[K]>\n/** Test whether a value matches a global constructor name. */\nexport function is<K extends GlobalConstructorNames>(type: K, value: any): value is InstanceType<typeof globalThis[K]>\n/** Test values using `instanceof` with a `toStringTag` fallback. */\nexport function is<K extends GlobalConstructorNames>(type: K, value?: any): any {\n if (arguments.length === 1) return (value: any) => is(type, value)\n return type in globalThis && value instanceof (globalThis[type] as any)\n || Object.prototype.toString.call(value).slice(8, -1) === type\n}\n\nfunction isArrayBufferLike(value: any): value is ArrayBufferLike {\n return is('ArrayBuffer', value) || is('SharedArrayBuffer', value)\n}\n\nfunction isArrayBufferSource(value: any): value is Binary.Source {\n return isArrayBufferLike(value) || ArrayBuffer.isView(value)\n}\n\n/** Binary source detection and base64/hex conversion helpers. */\nexport namespace Binary {\n export type Source<T extends ArrayBufferLike = ArrayBufferLike> = T | ArrayBufferView<T>\n\n export const is = isArrayBufferLike\n export const isSource = isArrayBufferSource\n\n export function fromSource<T extends ArrayBufferLike>(source: Source<T>): T {\n if (ArrayBuffer.isView(source)) {\n // https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer#answer-31394257\n return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength) as T\n } else {\n return source\n }\n }\n\n export function toBase64(source: Source) {\n source = fromSource(source)\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(source).toString('base64')\n }\n let binary = ''\n const bytes = new Uint8Array(source)\n for (let i = 0; i < bytes.byteLength; i++) {\n binary += String.fromCharCode(bytes[i])\n }\n return btoa(binary)\n }\n\n export function fromBase64(source: string) {\n if (typeof Buffer !== 'undefined') return fromSource(Buffer.from(source, 'base64'))\n return Uint8Array.from(atob(source), c => c.charCodeAt(0))\n }\n\n export function toHex(source: Source) {\n source = fromSource(source)\n if (typeof Buffer !== 'undefined') return Buffer.from(source).toString('hex')\n return Array.from(new Uint8Array(source), byte => byte.toString(16).padStart(2, '0')).join('')\n }\n\n export function fromHex(source: string) {\n if (typeof Buffer !== 'undefined') return fromSource(Buffer.from(source, 'hex'))\n const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1)\n const buffer: number[] = []\n for (let i = 0; i < hex.length; i += 2) {\n buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16))\n }\n return Uint8Array.from(buffer).buffer\n }\n}\n\n/** Decode a base64 string into binary data. */\nexport const base64ToArrayBuffer = Binary.fromBase64\n/** Encode binary data as base64. */\nexport const arrayBufferToBase64 = Binary.toBase64\n/** Decode a hex string into binary data. */\nexport const hexToArrayBuffer = Binary.fromHex\n/** Encode binary data as hex. */\nexport const arrayBufferToHex = Binary.toHex\n\n/** Deep-clone common JavaScript values while preserving prototypes. */\nexport function clone<T>(source: T): T\n/** Deep-clone common JavaScript values while preserving prototypes and cycles. */\nexport function clone(source: any, refs = new Map<any, any>()) {\n if (!source || typeof source !== 'object') return source\n if (is('Date', source)) return new Date(source.valueOf())\n if (is('RegExp', source)) return new RegExp(source.source, source.flags)\n if (isArrayBufferLike(source)) return source.slice(0)\n if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength)\n const cached = refs.get(source)\n if (cached) return cached\n if (Array.isArray(source)) {\n const result: any[] = []\n refs.set(source, result)\n source.forEach((value, index) => {\n result[index] = Reflect.apply(clone, null, [value, refs])\n })\n return result\n }\n const result = Object.create(Object.getPrototypeOf(source))\n refs.set(source, result)\n for (const key of Reflect.ownKeys(source)) {\n const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) }\n if ('value' in descriptor) {\n descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs])\n }\n Reflect.defineProperty(result, key, descriptor)\n }\n return result\n}\n\n/** Deeply compare arrays, dates, regexps, buffers, and plain object fields. */\nexport function deepEqual(a: any, b: any, strict?: boolean): boolean {\n if (a === b) return true\n if (!strict && isNullable(a) && isNullable(b)) return true\n if (typeof a !== typeof b) return false\n if (typeof a !== 'object') return false\n if (!a || !b) return false\n\n function check<T>(test: (x: any) => x is T, then: (a: T, b: T) => boolean) {\n return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : undefined\n }\n\n return check(Array.isArray, (a, b) => a.length === b.length && a.every((item, index) => deepEqual(item, b[index])))\n ?? check(is('Date'), (a, b) => a.valueOf() === b.valueOf())\n ?? check(is('RegExp'), (a, b) => a.source === b.source && a.flags === b.flags)\n ?? check(isArrayBufferLike, (a, b) => {\n if (a.byteLength !== b.byteLength) return false\n const viewA = new Uint8Array(a)\n const viewB = new Uint8Array(b)\n for (let i = 0; i < viewA.length; i++) {\n if (viewA[i] !== viewB[i]) return false\n }\n return true\n })\n ?? Object.keys({ ...a, ...b }).every(key => deepEqual(a[key], b[key], strict))\n}\n", "/** Time constants plus parsing and formatting helpers. */\nexport namespace Time {\n export const millisecond = 1\n export const second = 1000\n export const minute = second * 60\n export const hour = minute * 60\n export const day = hour * 24\n export const week = day * 7\n\n let timezoneOffset = new Date().getTimezoneOffset()\n\n export function setTimezoneOffset(offset: number) {\n timezoneOffset = offset\n }\n\n export function getTimezoneOffset() {\n return timezoneOffset\n }\n\n export function getDateNumber(date: number | Date = new Date(), offset?: number) {\n if (typeof date === 'number') date = new Date(date)\n if (offset === undefined) offset = timezoneOffset\n return Math.floor((date.valueOf() / minute - offset) / 1440)\n }\n\n export function fromDateNumber(value: number, offset?: number) {\n const date = new Date(value * day)\n if (offset === undefined) offset = timezoneOffset\n return new Date(+date + offset * minute)\n }\n\n const numeric = /\\d+(?:\\.\\d+)?/.source\n const timeRegExp = new RegExp(`^${[\n 'w(?:eek(?:s)?)?',\n 'd(?:ay(?:s)?)?',\n 'h(?:our(?:s)?)?',\n 'm(?:in(?:ute)?(?:s)?)?',\n 's(?:ec(?:ond)?(?:s)?)?',\n ].map(unit => `(${numeric}${unit})?`).join('')}$`)\n\n export function parseTime(source: string) {\n const capture = timeRegExp.exec(source)\n if (!capture) return 0\n return (parseFloat(capture[1]) * week || 0)\n + (parseFloat(capture[2]) * day || 0)\n + (parseFloat(capture[3]) * hour || 0)\n + (parseFloat(capture[4]) * minute || 0)\n + (parseFloat(capture[5]) * second || 0)\n }\n\n export function parseDate(date: string) {\n const parsed = parseTime(date)\n if (parsed) {\n date = Date.now() + parsed as any\n } else if (/^\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) {\n date = `${new Date().toLocaleDateString()}-${date}`\n } else if (/^\\d{1,2}-\\d{1,2}-\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) {\n date = `${new Date().getFullYear()}-${date}`\n }\n return date ? new Date(date) : new Date()\n }\n\n export function format(ms: number) {\n const abs = Math.abs(ms)\n if (abs >= day - hour / 2) {\n return Math.round(ms / day) + 'd'\n } else if (abs >= hour - minute / 2) {\n return Math.round(ms / hour) + 'h'\n } else if (abs >= minute - second / 2) {\n return Math.round(ms / minute) + 'm'\n } else if (abs >= second) {\n return Math.round(ms / second) + 's'\n }\n return ms + 'ms'\n }\n\n export function toDigits(source: number, length = 2) {\n return source.toString().padStart(length, '0')\n }\n\n export function template(template: string, time = new Date()) {\n return template\n .replace('yyyy', time.getFullYear().toString())\n .replace('yy', time.getFullYear().toString().slice(2))\n .replace('MM', toDigits(time.getMonth() + 1))\n .replace('dd', toDigits(time.getDate()))\n .replace('hh', toDigits(time.getHours()))\n .replace('mm', toDigits(time.getMinutes()))\n .replace('ss', toDigits(time.getSeconds()))\n .replace('SSS', toDigits(time.getMilliseconds(), 3))\n }\n}\n", "import { Binary, clone, deepEqual, filterKeys, isNullable, isPlainObject, pick, valueMap } from \"@deepseek-ai/cosmokit\";\n//#region lib/types/index.js\nconst kSchema = Symbol.for(\"schemastery\");\nconst kValidationError = Symbol.for(\"ValidationError\");\nglobalThis.__schemastery_index__ ??= 0;\nglobalThis.__schemastery_refs__ = void 0;\nvar ValidationError = class extends TypeError {\n\toptions;\n\tname = \"ValidationError\";\n\tconstructor(message, options) {\n\t\tlet prefix = \"$\";\n\t\tfor (const segment of options.path || []) if (typeof segment === \"string\") prefix += \".\" + segment;\n\t\telse if (typeof segment === \"number\") prefix += \"[\" + segment + \"]\";\n\t\telse if (typeof segment === \"symbol\") prefix += `[Symbol(${segment.toString()})]`;\n\t\tif (prefix.startsWith(\".\")) prefix = prefix.slice(1);\n\t\tsuper((prefix === \"$\" ? \"\" : `${prefix} `) + message);\n\t\tthis.options = options;\n\t}\n\tstatic is(error) {\n\t\treturn !!error?.[kValidationError];\n\t}\n};\nObject.defineProperty(ValidationError.prototype, kValidationError, { value: true });\nconst Schema = function(options) {\n\tconst schema = function(data, options = {}) {\n\t\treturn Schema.resolve(data, schema, options)[0];\n\t};\n\tif (options.refs) {\n\t\tconst refs = valueMap(options.refs, (options) => new Schema(options));\n\t\tconst getRef = (uid) => refs[uid];\n\t\tfor (const key in refs) {\n\t\t\tconst options = refs[key];\n\t\t\toptions.sKey = getRef(options.sKey);\n\t\t\toptions.inner = getRef(options.inner);\n\t\t\toptions.list = options.list && options.list.map(getRef);\n\t\t\toptions.dict = options.dict && valueMap(options.dict, getRef);\n\t\t}\n\t\treturn refs[options.uid];\n\t}\n\tObject.assign(schema, options);\n\tif (typeof schema.callback === \"string\") try {\n\t\tschema.callback = new Function(\"return \" + schema.callback)();\n\t} catch {}\n\tObject.defineProperty(schema, \"uid\", { value: globalThis.__schemastery_index__++ });\n\tObject.setPrototypeOf(schema, Schema.prototype);\n\tschema.meta ||= {};\n\tschema.toString = schema.toString.bind(schema);\n\treturn schema;\n};\nSchema.prototype = Object.create(Function.prototype);\nSchema.prototype[kSchema] = true;\nObject.defineProperty(Schema.prototype, \"~standard\", { get() {\n\treturn {\n\t\tversion: 1,\n\t\tvendor: \"schemastery\",\n\t\tvalidate: (value) => {\n\t\t\ttry {\n\t\t\t\treturn { value: Schema.resolve(value, this, {})[0] };\n\t\t\t} catch (error) {\n\t\t\t\tif (ValidationError.is(error)) return { issues: [{\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tpath: error.options.path\n\t\t\t\t}] };\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t};\n} });\nSchema.ValidationError = ValidationError;\nSchema.prototype.toJSON = function toJSON() {\n\tif (globalThis.__schemastery_refs__) {\n\t\tglobalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));\n\t\treturn this.uid;\n\t}\n\tglobalThis.__schemastery_refs__ = { [this.uid]: { ...this } };\n\tglobalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));\n\tconst result = {\n\t\tuid: this.uid,\n\t\trefs: globalThis.__schemastery_refs__\n\t};\n\tglobalThis.__schemastery_refs__ = void 0;\n\treturn result;\n};\nSchema.prototype.set = function set(key, value) {\n\tthis.dict[key] = value;\n\treturn this;\n};\nSchema.prototype.push = function push(value) {\n\tthis.list.push(value);\n\treturn this;\n};\nfunction mergeDesc(original, messages) {\n\tconst result = typeof original === \"string\" ? { \"\": original } : { ...original };\n\tfor (const locale in messages) {\n\t\tconst value = messages[locale];\n\t\tif (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;\n\t\telse if (typeof value === \"string\") result[locale] = value;\n\t}\n\treturn result;\n}\nfunction getInner(value) {\n\treturn value?.$value ?? value?.$inner;\n}\nfunction extractKeys(data) {\n\treturn filterKeys(data ?? {}, (key) => !key.startsWith(\"$\"));\n}\nSchema.prototype.i18n = function i18n(messages) {\n\tconst schema = Schema(this);\n\tconst desc = mergeDesc(schema.meta.description, messages);\n\tif (Object.keys(desc).length) schema.meta.description = desc;\n\tif (schema.dict) schema.dict = valueMap(schema.dict, (inner, key) => {\n\t\treturn inner.i18n(valueMap(messages, (data) => getInner(data)?.[key] ?? data?.[key]));\n\t});\n\tif (schema.list) schema.list = schema.list.map((inner, index) => {\n\t\treturn inner.i18n(valueMap(messages, (data = {}) => {\n\t\t\tif (Array.isArray(getInner(data))) return getInner(data)[index];\n\t\t\tif (Array.isArray(data)) return data[index];\n\t\t\treturn extractKeys(data);\n\t\t}));\n\t});\n\tif (schema.inner) schema.inner = schema.inner.i18n(valueMap(messages, (data) => {\n\t\tif (getInner(data)) return getInner(data);\n\t\treturn extractKeys(data);\n\t}));\n\tif (schema.sKey) schema.sKey = schema.sKey.i18n(valueMap(messages, (data) => data?.$key));\n\treturn schema;\n};\nSchema.prototype.extra = function extra(key, value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"required\",\n\t\"disabled\",\n\t\"collapse\",\n\t\"hidden\",\n\t\"loose\"\n]) Object.assign(Schema.prototype, { [key](value = true) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nSchema.prototype.deprecated = function deprecated() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"deprecated\",\n\t\ttype: \"danger\"\n\t});\n\treturn schema;\n};\nSchema.prototype.experimental = function experimental() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"experimental\",\n\t\ttype: \"warning\"\n\t});\n\treturn schema;\n};\nSchema.prototype.pattern = function pattern(regexp) {\n\tconst schema = Schema(this);\n\tconst pattern = pick(regexp, [\"source\", \"flags\"]);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\tpattern\n\t};\n\treturn schema;\n};\nSchema.prototype.simplify = function simplify(value) {\n\tif (deepEqual(value, this.meta.default, this.type === \"dict\")) return null;\n\tif (isNullable(value)) return value;\n\tif (this.type === \"object\" || this.type === \"dict\") {\n\t\tconst result = {};\n\t\tfor (const key in value) {\n\t\t\tconst item = (this.type === \"object\" ? this.dict[key] : this.inner)?.simplify(value[key]);\n\t\t\tif (this.type === \"dict\" || !isNullable(item)) result[key] = item;\n\t\t}\n\t\tif (deepEqual(result, this.meta.default, this.type === \"dict\")) return null;\n\t\treturn result;\n\t} else if (this.type === \"array\" || this.type === \"tuple\") {\n\t\tconst result = [];\n\t\tvalue.forEach((value, index) => {\n\t\t\tconst schema = this.type === \"array\" ? this.inner : this.list[index];\n\t\t\tconst item = schema ? schema.simplify(value) : value;\n\t\t\tresult.push(item);\n\t\t});\n\t\treturn result;\n\t} else if (this.type === \"intersect\") {\n\t\tconst result = {};\n\t\tfor (const item of this.list) Object.assign(result, item.simplify(value));\n\t\treturn result;\n\t} else if (this.type === \"union\") for (const schema of this.list) try {\n\t\tSchema.resolve(value, schema, {});\n\t\treturn schema.simplify(value);\n\t} catch {}\n\treturn value;\n};\nSchema.prototype.toString = function toString(inline) {\n\treturn formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;\n};\nSchema.prototype.role = function role(role, extra) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\trole,\n\t\textra\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"default\",\n\t\"link\",\n\t\"comment\",\n\t\"description\",\n\t\"max\",\n\t\"min\",\n\t\"step\"\n]) Object.assign(Schema.prototype, { [key](value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nconst resolvers = {};\nSchema.extend = function extend(type, resolve) {\n\tresolvers[type] = resolve;\n};\nSchema.resolve = function resolve(data, schema, options = {}, strict = false) {\n\tif (!schema) return [data];\n\tif (options.ignore?.(data, schema)) return [data];\n\tif (isNullable(data) && schema.type !== \"lazy\") {\n\t\tif (schema.meta.required) throw new ValidationError(`missing required value`, options);\n\t\tlet current = schema;\n\t\tlet fallback = schema.meta.default;\n\t\twhile (current?.type === \"intersect\" && isNullable(fallback)) {\n\t\t\tcurrent = current.list[0];\n\t\t\tfallback = current?.meta.default;\n\t\t}\n\t\tif (isNullable(fallback)) return [data];\n\t\tdata = clone(fallback);\n\t}\n\tconst callback = resolvers[schema.type];\n\tif (!callback) throw new ValidationError(`unsupported type \"${schema.type}\"`, options);\n\ttry {\n\t\treturn callback(data, schema, options, strict);\n\t} catch (error) {\n\t\tif (!schema.meta.loose) throw error;\n\t\treturn [schema.meta.default];\n\t}\n};\nSchema.from = function from(source) {\n\tif (isNullable(source)) return Schema.any();\n\telse if ([\n\t\t\"string\",\n\t\t\"number\",\n\t\t\"boolean\"\n\t].includes(typeof source)) return Schema.const(source).required();\n\telse if (source[kSchema]) return source;\n\telse if (typeof source === \"function\") switch (source) {\n\t\tcase String: return Schema.string().required();\n\t\tcase Number: return Schema.number().required();\n\t\tcase Boolean: return Schema.boolean().required();\n\t\tcase Function: return Schema.function().required();\n\t\tdefault: return Schema.is(source).required();\n\t}\n\telse throw new TypeError(`cannot infer schema from ${source}`);\n};\nSchema.lazy = function lazy(builder) {\n\tconst toJSON = () => {\n\t\tif (!schema.inner[kSchema]) {\n\t\t\tschema.inner = schema.builder();\n\t\t\tschema.inner.meta = {\n\t\t\t\t...schema.meta,\n\t\t\t\t...schema.inner.meta\n\t\t\t};\n\t\t}\n\t\treturn schema.inner.toJSON();\n\t};\n\tconst schema = new Schema({\n\t\ttype: \"lazy\",\n\t\tbuilder,\n\t\tinner: { toJSON }\n\t});\n\treturn schema;\n};\nSchema.natural = function natural() {\n\treturn Schema.number().step(1).min(0);\n};\nSchema.percent = function percent() {\n\treturn Schema.number().step(.01).min(0).max(1).role(\"slider\");\n};\nSchema.date = function date() {\n\treturn Schema.union([Schema.is(Date), Schema.transform(Schema.string().role(\"datetime\"), (value, options) => {\n\t\tconst date = new Date(value);\n\t\tif (isNaN(+date)) throw new ValidationError(`invalid date \"${value}\"`, options);\n\t\treturn date;\n\t}, true)]);\n};\nSchema.regExp = function regExp(flag = \"\") {\n\treturn Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role(\"regexp\", { flag }), (value, options) => {\n\t\ttry {\n\t\t\treturn new RegExp(value, flag);\n\t\t} catch (e) {\n\t\t\tthrow new ValidationError(e.message, options);\n\t\t}\n\t}, true)]);\n};\nSchema.arrayBuffer = function arrayBuffer(encoding) {\n\treturn Schema.union([\n\t\tSchema.is(ArrayBuffer),\n\t\tSchema.is(SharedArrayBuffer),\n\t\tSchema.transform(Schema.any(), (value, options) => {\n\t\t\tif (Binary.isSource(value)) return Binary.fromSource(value);\n\t\t\tthrow new ValidationError(`expected ArrayBufferSource but got ${value}`, options);\n\t\t}, true),\n\t\t...encoding ? [Schema.transform(Schema.string(), (value, options) => {\n\t\t\ttry {\n\t\t\t\treturn encoding === \"base64\" ? Binary.fromBase64(value) : Binary.fromHex(value);\n\t\t\t} catch (e) {\n\t\t\t\tthrow new ValidationError(e.message, options);\n\t\t\t}\n\t\t}, true)] : []\n\t]);\n};\nSchema.extend(\"lazy\", (data, schema, options, strict) => {\n\tif (!schema.inner[kSchema]) {\n\t\tschema.inner = schema.builder();\n\t\tschema.inner.meta = {\n\t\t\t...schema.meta,\n\t\t\t...schema.inner.meta\n\t\t};\n\t}\n\treturn Schema.resolve(data, schema.inner, options, strict);\n});\nSchema.extend(\"any\", (data) => {\n\treturn [data];\n});\nSchema.extend(\"never\", (data, _, options) => {\n\tthrow new ValidationError(`expected nullable but got ${data}`, options);\n});\nSchema.extend(\"const\", (data, { value }, options) => {\n\tif (deepEqual(data, value)) return [value];\n\tthrow new ValidationError(`expected ${value} but got ${data}`, options);\n});\nfunction checkWithinRange(data, meta, description, options, skipMin = false) {\n\tconst { max = Infinity, min = -Infinity } = meta;\n\tif (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);\n\tif (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);\n}\nSchema.extend(\"string\", (data, { meta }, options) => {\n\tif (typeof data !== \"string\") throw new ValidationError(`expected string but got ${data}`, options);\n\tif (meta.pattern) {\n\t\tconst regexp = new RegExp(meta.pattern.source, meta.pattern.flags);\n\t\tif (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);\n\t}\n\tcheckWithinRange(data.length, meta, \"string length\", options);\n\treturn [data];\n});\nfunction decimalShift(data, digits) {\n\tconst str = data.toString();\n\tif (str.includes(\"e\")) return data * Math.pow(10, digits);\n\tconst index = str.indexOf(\".\");\n\tif (index === -1) return data * Math.pow(10, digits);\n\tconst frac = str.slice(index + 1);\n\tconst integer = str.slice(0, index);\n\tif (frac.length <= digits) return +(integer + frac.padEnd(digits, \"0\"));\n\treturn +(integer + frac.slice(0, digits) + \".\" + frac.slice(digits));\n}\nfunction isMultipleOf(data, min, step) {\n\tstep = Math.abs(step);\n\tif (!/^\\d+\\.\\d+$/.test(step.toString())) return (data - min) % step === 0;\n\tconst index = step.toString().indexOf(\".\");\n\tconst digits = step.toString().slice(index + 1).length;\n\treturn Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;\n}\nSchema.extend(\"number\", (data, { meta }, options) => {\n\tif (typeof data !== \"number\") throw new ValidationError(`expected number but got ${data}`, options);\n\tcheckWithinRange(data, meta, \"number\", options);\n\tconst { step } = meta;\n\tif (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);\n\treturn [data];\n});\nSchema.extend(\"boolean\", (data, _, options) => {\n\tif (typeof data === \"boolean\") return [data];\n\tthrow new ValidationError(`expected boolean but got ${data}`, options);\n});\nSchema.extend(\"bitset\", (data, { bits, meta }, options) => {\n\tlet value = 0, keys = [];\n\tif (typeof data === \"number\") {\n\t\tvalue = data;\n\t\tfor (const key in bits) if (data & bits[key]) keys.push(key);\n\t} else if (Array.isArray(data)) {\n\t\tkeys = data;\n\t\tfor (const key of keys) {\n\t\t\tif (typeof key !== \"string\") throw new ValidationError(`expected string but got ${key}`, options);\n\t\t\tif (key in bits) value |= bits[key];\n\t\t}\n\t} else throw new ValidationError(`expected number or array but got ${data}`, options);\n\tif (value === meta.default) return [value];\n\treturn [value, keys];\n});\nSchema.extend(\"function\", (data, _, options) => {\n\tif (typeof data === \"function\") return [data];\n\tthrow new ValidationError(`expected function but got ${data}`, options);\n});\nSchema.extend(\"is\", (data, { constructor }, options) => {\n\tif (typeof constructor === \"function\") {\n\t\tif (data instanceof constructor) return [data];\n\t\tthrow new ValidationError(`expected ${constructor.name} but got ${data}`, options);\n\t} else {\n\t\tif (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t\tlet prototype = Object.getPrototypeOf(data);\n\t\twhile (prototype) {\n\t\t\tif (prototype.constructor?.name === constructor) return [data];\n\t\t\tprototype = Object.getPrototypeOf(prototype);\n\t\t}\n\t\tthrow new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t}\n});\nfunction property(data, key, schema, options) {\n\ttry {\n\t\tconst [value, adapted] = Schema.resolve(data[key], schema, {\n\t\t\t...options,\n\t\t\tpath: [...options.path || [], key]\n\t\t});\n\t\tif (adapted !== void 0) data[key] = adapted;\n\t\treturn value;\n\t} catch (e) {\n\t\tif (!options?.autofix) throw e;\n\t\tdelete data[key];\n\t\treturn schema.meta.default;\n\t}\n}\nSchema.extend(\"array\", (data, { inner, meta }, options) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tcheckWithinRange(data.length, meta, \"array length\", options, !isNullable(inner.meta.default));\n\treturn [data.map((_, index) => property(data, index, inner, options))];\n});\nSchema.extend(\"dict\", (data, { inner, sKey }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in data) {\n\t\tlet rKey;\n\t\ttry {\n\t\t\trKey = Schema.resolve(key, sKey, options)[0];\n\t\t} catch (error) {\n\t\t\tif (strict) continue;\n\t\t\tthrow error;\n\t\t}\n\t\tresult[rKey] = property(data, key, inner, options);\n\t\tdata[rKey] = data[key];\n\t\tif (key !== rKey) delete data[key];\n\t}\n\treturn [result];\n});\nSchema.extend(\"tuple\", (data, { list }, options, strict) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tconst result = list.map((inner, index) => property(data, index, inner, options));\n\tif (strict) return [result];\n\tresult.push(...data.slice(list.length));\n\treturn [result];\n});\nfunction merge(result, data) {\n\tfor (const key in data) {\n\t\tif (key in result) continue;\n\t\tresult[key] = data[key];\n\t}\n}\nSchema.extend(\"object\", (data, { dict }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in dict) {\n\t\tconst value = property(data, key, dict[key], options);\n\t\tif (!isNullable(value) || key in data) result[key] = value;\n\t}\n\tif (!strict) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"union\", (data, { list, toString }, options, strict) => {\n\tconst messages = [];\n\tfor (const inner of list) try {\n\t\treturn Schema.resolve(data, inner, options, strict);\n\t} catch (error) {\n\t\tmessages.push(error);\n\t}\n\tthrow new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n});\nSchema.extend(\"intersect\", (data, { list, toString }, options, strict) => {\n\tif (!list.length) return [data];\n\tlet result;\n\tfor (const inner of list) {\n\t\tconst value = Schema.resolve(data, inner, options, true)[0];\n\t\tif (isNullable(value)) continue;\n\t\tif (isNullable(result)) result = value;\n\t\telse if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t\telse if (typeof value === \"object\") merge(result ??= {}, value);\n\t\telse if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t}\n\tif (!strict && isPlainObject(data)) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"transform\", (data, { inner, callback, preserve }, options) => {\n\tconst [result, adapted = data] = Schema.resolve(data, inner, options, true);\n\tif (preserve) return [callback(result)];\n\telse return [callback(result), callback(adapted)];\n});\nconst formatters = {};\nfunction defineMethod(name, keys, format) {\n\tformatters[name] = format;\n\tObject.assign(Schema, { [name](...args) {\n\t\tconst schema = new Schema({ type: name });\n\t\tkeys.forEach((key, index) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase \"sKey\":\n\t\t\t\t\tschema.sKey = args[index] ?? Schema.string();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"inner\":\n\t\t\t\t\tschema.inner = Schema.from(args[index]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"list\":\n\t\t\t\t\tschema.list = args[index].map(Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"dict\":\n\t\t\t\t\tschema.dict = valueMap(args[index], Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"bits\":\n\t\t\t\t\tschema.bits = {};\n\t\t\t\t\tfor (const key in args[index]) {\n\t\t\t\t\t\tif (typeof args[index][key] !== \"number\") continue;\n\t\t\t\t\t\tschema.bits[key] = args[index][key];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"callback\": {\n\t\t\t\t\tconst callback = schema.callback = args[index];\n\t\t\t\t\tcallback[\"toJSON\"] ||= () => callback.toString();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"constructor\": {\n\t\t\t\t\tconst constructor = schema.constructor = args[index];\n\t\t\t\t\tif (typeof constructor === \"function\") constructor[\"toJSON\"] ||= () => constructor[\"name\"];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: schema[key] = args[index];\n\t\t\t}\n\t\t});\n\t\tif (name === \"object\" || name === \"dict\") schema.meta.default = {};\n\t\telse if (name === \"array\" || name === \"tuple\") schema.meta.default = [];\n\t\telse if (name === \"bitset\") schema.meta.default = 0;\n\t\treturn schema;\n\t} });\n}\ndefineMethod(\"is\", [\"constructor\"], ({ constructor }) => {\n\tif (typeof constructor === \"function\") return constructor.name;\n\telse return constructor;\n});\ndefineMethod(\"any\", [], () => \"any\");\ndefineMethod(\"never\", [], () => \"never\");\ndefineMethod(\"const\", [\"value\"], ({ value }) => typeof value === \"string\" ? JSON.stringify(value) : value);\ndefineMethod(\"string\", [], () => \"string\");\ndefineMethod(\"number\", [], () => \"number\");\ndefineMethod(\"boolean\", [], () => \"boolean\");\ndefineMethod(\"bitset\", [\"bits\"], () => \"bitset\");\ndefineMethod(\"function\", [], () => \"function\");\ndefineMethod(\"array\", [\"inner\"], ({ inner }) => `${inner.toString(true)}[]`);\ndefineMethod(\"dict\", [\"inner\", \"sKey\"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);\ndefineMethod(\"tuple\", [\"list\"], ({ list }) => `[${list.map((inner) => inner.toString()).join(\", \")}]`);\ndefineMethod(\"object\", [\"dict\"], ({ dict }) => {\n\tif (Object.keys(dict).length === 0) return \"{}\";\n\treturn `{ ${Object.entries(dict).map(([key, inner]) => {\n\t\treturn `${key}${inner.meta.required ? \"\" : \"?\"}: ${inner.toString()}`;\n\t}).join(\", \")} }`;\n});\ndefineMethod(\"union\", [\"list\"], ({ list }, inline) => {\n\tconst result = list.map(({ toString: format }) => format()).join(\" | \");\n\treturn inline ? `(${result})` : result;\n});\ndefineMethod(\"intersect\", [\"list\"], ({ list }) => {\n\treturn `${list.map((inner) => inner.toString(true)).join(\" & \")}`;\n});\ndefineMethod(\"transform\", [\n\t\"inner\",\n\t\"callback\",\n\t\"preserve\"\n], ({ inner }, isInner) => inner.toString(isInner));\n//#endregion\nexport { Schema as default };\n"],
|
|
5
|
-
"mappings": ";AAcA,SAAkB,eAA8B;AAChD,SAAS,YAAY,YAAY,mBAAmB,yBAAyB;AAI7E,SAAS,qBAAqB;AAG9B,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB,yBAAyB;;;ACJhD,SAAS,WAAW,OAA8C;AACvE,SAAO,UAAU,QAAQ,UAAU;AACrC;AAQO,SAAS,cAAc,MAAW;AACvC,SAAO,QAAQ,OAAO,SAAS,YAAY,CAAC,MAAM,QAAQ,IAAI;AAChE;AAOO,SAAS,WAAW,QAAY,QAA8C;AACnF,SAAO,OAAO,YAAY,OAAO,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,gBAAQ;",
|
|
3
|
+
"sources": ["../../src/interconnect/index.ts", "../../../dsh-wt-ic-merge/vendor/cosmokit/src/misc.ts", "../../../dsh-wt-ic-merge/vendor/cosmokit/src/types.ts", "../../../dsh-wt-ic-merge/vendor/cosmokit/src/time.ts", "../../../dsh-wt-ic-merge/vendor/schemastery/lib/index.mjs"],
|
|
4
|
+
"sourcesContent": ["/**\n * Cross-instance message handoff service: the inbound half owns one WebSocket\n * upgrade route on the host webserver and delivers authenticated messages into\n * live sessions; the outbound half dials the same route on peer instances.\n *\n * Transport is deliberately NOT the Connection RPC channel: that registry's\n * handler sees only `(endpoint, payload, signal)` and the trust fence is the\n * DNS-rebinding `trustedHosts` check, neither of which carries the shared-key\n * `Authorization` header this service authenticates on. Owning a plain\n * upgrade route keeps bearer-token auth at the boundary where the header is\n * readable and fails closed when the token is unconfigured.\n * @module dsh-interconnect\n */\n\nimport { Context, Service, LoggerService } from '@deepseek-ai/cordis'\nimport { createHash, randomUUID, timingSafeEqual as constantTimeEqual } from 'node:crypto'\nimport type { IncomingMessage } from 'node:http'\nimport type { Duplex } from 'node:stream'\nimport type { WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'\nimport { credentialRef } from '@deepseek-ai/dsh-credentials'\n// The Host's resolver reports a subagent-owned session as a Remote failure, and\n// that code is the only ownership signal a cold session carries.\nimport { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol'\nimport { boundContextSummary, createUserMessage } from '@deepseek-ai/dsh-llm'\nimport type { ContextFormed } from '@deepseek-ai/dsh-llm'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\n// Loads the `RemoteErrorDetailsMap` augmentation that declares `session/agent-busy`,\n// the code the Host raises when a resume hits a subagent-owned session. Type-only:\n// no runtime dependency, and this subpath exists in every host revision in use.\nimport type {} from '@deepseek-ai/dsh-api-session-controller/types'\nimport type { Session } from '@deepseek-ai/dsh-session'\nimport type { SubagentRunEndInfo } from '@deepseek-ai/dsh-subagent'\nimport z from '@deepseek-ai/schemastery'\nimport WebSocket, { WebSocketServer } from 'ws'\nimport type { RawData } from 'ws'\nimport {\n type Config,\n type DeliveryMode,\n type EventNotification,\n type EventPayload,\n type LinkFrame,\n type LinkMessage,\n type ListResult,\n type PeerStatus,\n type PingResult,\n type QueryMessage,\n type ReplyRequest,\n type SendPayload,\n type SendResult,\n type SendRequest,\n type SendFailure,\n type SenderIdentity,\n type InterconnectSessionSummary,\n} from './types.ts'\n\n/**\n * Mirror of the Host's subagent-ownership predicate. The Host keeps that rule in\n * `@deepseek-ai/dsh-api-session-controller`, whose package root exports it only\n * from the revision this plugin's merge introduces \u2014 the hosts this package is\n * installed on still resolve the older root, so importing it would fail at load.\n * The body is copied verbatim from the Host; keep it in sync if the Host changes\n * the rule, because this is a safety fence.\n * @param ctx - host context carrying the live agent registry.\n * @param session - attached or live session whose ownership is tested.\n * @param agent - live agent when one exists for the session.\n * @returns whether subagent routing owns the session identity.\n */\nfunction isSessionOwnedBySubagent(\n ctx: Context,\n session: Pick<Session, 'header'>,\n agent: Agent | undefined,\n): boolean {\n if (session.header.origin === 'subagent') return true\n const parentId = session.header.parentSession\n if (parentId === undefined || agent === undefined) return false\n const parent = ctx.agents.get(parentId)\n return parent !== undefined && ctx.agents.isOwnedBy(agent.id, parent)\n}\n\n/** Exhaustiveness guard for closed unions. */\nfunction assertNever(value: never): never {\n throw new Error(`interconnect: unhandled variant ${JSON.stringify(value)}`)\n}\n\nexport type * from './types.ts'\n\n/**\n * Credential reference holding the shared auth token. Both halves of a link\n * must resolve the same value: inbound requests are rejected unless their\n * `Authorization: Bearer <token>` matches this secret, and outbound requests\n * send it. An unconfigured token fails closed on the inbound side.\n */\nexport const INTERCONNECT_TOKEN_REF = 'DSH_INTERCONNECT_TOKEN'\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n interconnect: InterconnectService\n }\n interface Events {\n /**\n * A remote peer instance pushed one authenticated lifecycle notification\n * into this instance. Payload is the exact {@link EventNotification} that\n * crossed the wire; listeners run when the frame arrives, and a listener\n * that throws or rejects is logged rather than propagated to the link.\n * @mode parallel\n * @param notification - the serialized lifecycle fact that crossed the wire.\n * @param peer - the sender's self-reported instance id.\n */\n 'interconnect/event'(notification: EventNotification, peer: string): void\n }\n}\n\ndeclare module '@deepseek-ai/dsh-llm' {\n interface MessageSourceMap {\n /**\n * Attribution of a handoff this plugin delivered. Session format V4 refuses\n * the retired `{ kind: 'plugin', plugin }` wrapper, so the producer kind\n * stands alone: the name is exactly what the harness's V3-to-V4 migration\n * writes for this plugin's already-persisted handoffs (`plugin:` plus the\n * original plugin name), keeping migrated rows and rows written from now on\n * under one producer identity.\n */\n 'plugin:dsh-interconnect': { readonly kind: 'plugin:dsh-interconnect' } & ContextFormed\n }\n}\n\n/** Maximum inbound link-frame size in bytes; larger frames are dropped as protocol violations. */\nconst MAX_LINK_FRAME_BYTES = 1024 * 1024\n/** Instance id a composition that omits `instanceId` runs under. */\nconst DEFAULT_INSTANCE_ID = 'dsh'\n/** Outbound request timeout a composition that omits `requestTimeoutMs` runs with. */\nconst DEFAULT_REQUEST_TIMEOUT_MS = 10_000\n/** Handshake window for an outbound dial; a CONNECTING socket past this is terminated and re-dialed. */\nconst LINK_HANDSHAKE_TIMEOUT_MS = 10_000\n/** WebSocket upgrade pathname owning the persistent peer link. */\nconst LINK_CHANNEL = '/interconnect/link'\n/**\n * Longest `instanceId` a deployment may configure. Every frame this instance\n * writes carries it (the `hello` announcement, answers, and results), so an\n * unbounded id would fail the first write against the link cap instead of\n * failing the load.\n */\nconst MAX_INSTANCE_ID_CHARS = 256\n/**\n * Longest request id one inbound frame may carry. Every answer repeats the\n * peer's `reqId`, so an unbounded id would decide the size of the frame this\n * instance writes back; the ids this plugin generates are about 40 characters.\n */\nconst MAX_REQUEST_ID_CHARS = 256\n/**\n * Maximum session rows one `list` answer carries, so a very large live set\n * still answers with a bounded number of targets. A consumer that renders the\n * answer can compare a full page against this bound to tell a complete listing\n * from a truncated one.\n */\nexport const MAX_LISTED_SESSIONS = 100\n\n/**\n * Whether one encoded link frame fits the cap both link halves enforce. An\n * over-cap write makes the receiving ws close the link, so a frame whose size\n * this instance already knows is refused before anything is written.\n */\nconst frameFitsLink = (frame: LinkFrame): boolean =>\n Buffer.byteLength(JSON.stringify(frame), 'utf8') <= MAX_LINK_FRAME_BYTES\n/** Serialized size of one row inside a frame's `sessions` array: UTF-8 bytes plus its separating comma. */\nconst rowBytes = (row: InterconnectSessionSummary): number =>\n Buffer.byteLength(JSON.stringify(row), 'utf8') + 1\n\n/** Wire union for the discriminated EventNotification fact carried by an `event` frame. */\nconst notificationSchema = z.union([\n z.object({ kind: z.const('agent/created').required(), sessionId: z.string().required() }),\n z.object({ kind: z.const('agent/disposed').required(), sessionId: z.string().required() }),\n z.object({ kind: z.const('agent/status').required(), sessionId: z.string().required(), status: z.union([z.const('idle'), z.const('running')]).required() }),\n z.object({ kind: z.const('session/created').required(), sessionId: z.string().required(), parentSessionId: z.string() }),\n z.object({ kind: z.const('session/disposed').required(), sessionId: z.string().required() }),\n z.object({ kind: z.const('subagent/end').required(), provider: z.string().required(), childSessionId: z.string().required(), stopReason: z.string().required() }),\n])\n\n/**\n * Wire shape of an address-free {@link SenderIdentity}. Fields stay optional\n * so an absent `sender` key (schemastery resolves it to an empty object)\n * still passes; `deliver()` treats a partial identity as no sender.\n */\nconst senderSchema = z.object({ instanceId: z.string(), sessionId: z.string() })\n\n/**\n * Wire shape of the ping answer. Validated against the KIND of query the\n * caller asked, not only the frame union: the union's branches merge their\n * unknown keys, so a `list`-shaped payload would otherwise satisfy a `ping`\n * request.\n */\nconst pingResultSchema = z.object({ pong: z.const(true).required(), instance: z.string().required() })\n\n/**\n * Wire shape of the live-session list. Every row must carry a `sessionId`\n * string: the consumer builds its tool result by reading that field, so an\n * unvalidated row would throw instead of reading as an unreachable peer.\n */\nconst listResultSchema = z.object({\n instance: z.string().required(),\n sessions: z.array(z.object({\n sessionId: z.string().required(),\n title: z.string().required(false),\n status: z.string().required(false),\n })).required(),\n})\n\n/**\n * Drop the explicit `null` values of one decoded frame. Schemastery accepts\n * `null` for a field that is not required and keeps it in the parsed result,\n * while every declared field on these frames is present-or-absent only: a peer\n * whose JSON writer emits `null` for a value it has none of would otherwise\n * hand a `null` title, status, or delivery to the tool output schemas, which\n * accept the field's own type and reject the whole result.\n * @param value - decoded frame, or any nested value of one.\n * @returns the value with every `null`-valued object key removed.\n */\nconst withoutNullFields = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(item => withoutNullFields(item))\n if (value === null || typeof value !== 'object') return value\n return Object.fromEntries(Object.entries(value as Record<string, unknown>)\n .filter(([, field]) => field !== null)\n .map(([key, field]) => [key, withoutNullFields(field)]))\n}\n\n/**\n * Project one decoded `msg-result` payload onto the fields its discriminant\n * branch declares. Schemastery's union keeps the keys of every branch it\n * considered, so a failing answer still carries the `delivery` a peer sent\n * beside it and a successful one carries a stray `reason` or an unknown key;\n * the tool output schemas accept only the branch's own string fields, so\n * nothing else may leave this service. `delivered` selects the branch and the\n * schema has already validated the fields that branch declares.\n * @param result - decoded `msg-result` payload.\n * @returns the payload restricted to its branch's fields.\n */\nconst projectMsgResult = (result: SendResult): SendResult =>\n result.delivered\n ? { delivered: true, instance: result.instance, ...(result.delivery === undefined ? {} : { delivery: result.delivery }) }\n : { delivered: false, instance: result.instance, reason: result.reason }\n\n/**\n * Decode one `query-result` payload against the schema for the request kind\n * that asked for it. `z.resolve` rejects with a `ValidationError` on a\n * mismatch, so the parse is contained here instead of throwing out of the frame\n * handler; the frame schema requires the `result` field, so a payload that\n * reaches this function is an object. The projections below read the fields the\n * schema validated, and schemastery types every optional field as `null`-capable,\n * so each field is read through the wire view its kind declares.\n * @param schema - the answer schema for the request kind.\n * @param result - the decoded `query-result` payload.\n * @returns the parsed payload's fields, or undefined when it does not match.\n */\nconst parseQueryResult = (\n schema: Parameters<typeof z.resolve>[1],\n result: unknown,\n): Record<string, unknown> | undefined => {\n try {\n const [parsed] = z.resolve(result, schema, {}) as [Record<string, unknown>]\n return parsed\n } catch {\n return undefined\n }\n}\n\n/**\n * Project one decoded `ping` answer onto its declared fields. Schemastery keeps\n * the keys of every union branch it considered, so an answer must not carry the\n * `sessions` rows or any other key this kind does not declare.\n * @param result - the decoded `query-result` payload.\n * @returns the answer as a {@link PingResult}, or undefined on a mismatch.\n */\nconst projectPingResult = (result: unknown): PingResult | undefined => {\n const parsed = parseQueryResult(pingResultSchema, result)\n return parsed === undefined ? undefined : { pong: true, instance: parsed.instance as string }\n}\n\n/**\n * Project one decoded `list` answer onto its declared fields, rows included,\n * for the same reason {@link projectPingResult} exists.\n * @param result - the decoded `query-result` payload.\n * @returns the answer as a {@link ListResult}, or undefined on a mismatch.\n */\nconst projectListResult = (result: unknown): ListResult | undefined => {\n const parsed = parseQueryResult(listResultSchema, result)\n if (parsed === undefined) return undefined\n const rows = parsed.sessions as Array<Record<string, unknown>>\n return {\n instance: parsed.instance as string,\n sessions: rows.map((row): InterconnectSessionSummary => ({\n sessionId: row.sessionId as string,\n ...(row.title === undefined || row.title === null ? {} : { title: row.title as string }),\n ...(row.status === undefined || row.status === null ? {} : { status: row.status as string }),\n })),\n }\n}\n\n/** Wire shape of one `query-result`: the ping answer, the live-session list, or the event-query ack. */\nconst queryResultSchema = z.union([\n pingResultSchema,\n listResultSchema,\n z.object({ accepted: z.const(true).required() }),\n])\n\n/** Wire shape of a `send` message carried by a `msg` link frame. */\nconst messageSchema = z.object({\n kind: z.const('send').required(),\n sessionId: z.string().required(),\n text: z.string().required(),\n sender: senderSchema,\n delivery: z.union([z.const('followup'), z.const('steer'), z.const('inject')]),\n resume: z.boolean(),\n})\n\n/** Wire union for the discovery query carried by a `query` link frame. */\nconst querySchema = z.union([\n z.object({ kind: z.const('ping').required() }),\n z.object({ kind: z.const('list').required() }),\n z.object({ kind: z.const('event').required(), notification: notificationSchema.required() }),\n])\n\n/**\n * Wire union of one `send` answer: the success branch carries the mode the\n * receiver used, and the failure branches carry only the reasons a receiver can\n * answer with \u2014 the local-only reasons (`message-too-large`, `no-sender-known`)\n * are produced locally and never cross the link.\n */\nconst msgResultSchema = z.union([\n z.object({ delivered: z.const(true).required(), instance: z.string().required(), delivery: z.union([z.const('followup'), z.const('steer'), z.const('inject')]) }),\n z.object({ delivered: z.const(false).required(), instance: z.string().required(), reason: z.union([\n z.const('session-not-live'),\n z.const('unreachable'),\n z.const('resume-refused'),\n z.const('resume-failed'),\n z.const('session-owned-by-subagent'),\n ]).required() }),\n])\n\n/** Wire union for one WebSocket link text frame. */\nconst linkFrameSchema = z.union([\n z.object({ type: z.const('hello').required(), sender: z.string().required() }),\n z.object({ type: z.const('event').required(), notification: notificationSchema.required() }),\n z.object({ type: z.const('msg').required(), reqId: z.string().max(MAX_REQUEST_ID_CHARS).required(), message: messageSchema.required() }),\n z.object({ type: z.const('msg-result').required(), reqId: z.string().max(MAX_REQUEST_ID_CHARS).required(), result: msgResultSchema.required() }),\n z.object({ type: z.const('query').required(), reqId: z.string().max(MAX_REQUEST_ID_CHARS).required(), query: querySchema.required() }),\n z.object({ type: z.const('query-result').required(), reqId: z.string().max(MAX_REQUEST_ID_CHARS).required(), result: queryResultSchema.required() }),\n])\n\n/**\n * Live cross-instance handoff service, registered as `ctx.interconnect`.\n * Requires the live agent registry and the credential store; the webserver is\n * optional \u2014 with one, the service accepts inbound links on\n * `/interconnect/link`; without one it still dials configured peers and\n * delivers over those outbound links. Activation is availability-driven like\n * every other host service.\n */\nexport class InterconnectService extends Service {\n static inject = ['agents', 'credentials']\n static Config: z<Config> = z.object({\n instanceId: z.string().max(MAX_INSTANCE_ID_CHARS).default(DEFAULT_INSTANCE_ID),\n requestTimeoutMs: z.natural().max(60000).default(DEFAULT_REQUEST_TIMEOUT_MS),\n peers: z.dict(z.string()).default({}),\n delivery: z.union([z.const('followup'), z.const('steer'), z.const('inject')]).default('followup'),\n allowResume: z.boolean().default(true),\n })\n\n private readonly instanceId: string\n private readonly requestTimeoutMs: number\n private readonly delivery: DeliveryMode\n private readonly allowResume: boolean\n private readonly server = new WebSocketServer({ noServer: true, maxPayload: MAX_LINK_FRAME_BYTES })\n private readonly sockets = new Set<WebSocket>()\n /** Outbound peer links keyed by the peer's `instanceId`. */\n private readonly linkStates = new Map<string, LinkState>()\n private heartbeatTimer: NodeJS.Timeout | undefined\n /** Peer identity each live socket announced via its `hello` frame, if any. */\n private readonly peerOf = new WeakMap<WebSocket, string>()\n /** Configured peer an outbound dial owns a socket for; absent on inbound sockets. */\n private readonly dialedPeerOf = new WeakMap<WebSocket, string>()\n /** Dialed sockets already reported as announcing an id other than their configured key. */\n private readonly mismatchWarned = new WeakSet<WebSocket>()\n /** Sender each local session last received a send from, keyed by local session id. */\n private readonly senders = new Map<string, SenderIdentity>()\n /** In-flight frames sent over a peer link, keyed by `reqId`, awaiting a correlated result. */\n private readonly pendingMessages = new Map<string, MutablePendingMessage>()\n private reqIdCounter = 0\n /** Set when the service fiber unwinds; guards late inbound deliveries against driving disposed agents. */\n private disposed = false\n\n constructor(ctx: Context, config: Config) {\n super(ctx, 'interconnect')\n /* v8 ignore next 1 -- the Config schema applies its instanceId default before the constructor runs. */\n this.instanceId = config.instanceId ?? DEFAULT_INSTANCE_ID\n /* v8 ignore next 1 -- the Config schema applies its requestTimeoutMs default before the constructor runs. */\n this.requestTimeoutMs = config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS\n /* v8 ignore next 1 -- the Config schema applies its delivery default before the constructor runs. */\n this.delivery = config.delivery ?? 'followup'\n /* v8 ignore next 1 -- the Config schema applies its allowResume default before the constructor runs. */\n this.allowResume = config.allowResume ?? true\n // Validate every peer origin before dialing any of them: the same URL\n // construction dial() uses, so a malformed origin fails the load before a\n // socket or reconnect loop exists to leak (misconfiguration fails loud).\n /* v8 ignore next 2 -- the Config schema applies its peers default before the constructor runs. */\n for (const origin of Object.values(config.peers ?? {})) {\n linkUrl(trimBase(origin))\n }\n // Link every configured peer at activation: all delivery is over these\n // persistent links, and addressing is by instanceId through them.\n /* v8 ignore next 1 -- the Config schema applies its peers default before the constructor runs. */\n for (const [peerInstanceId, origin] of Object.entries(config.peers ?? {})) {\n this.link(peerInstanceId, origin)\n }\n\n const upgrade: WebUpgradeRoute = {\n path: LINK_CHANNEL,\n handler: (req, socket, head) => {\n // `handleUpgrade` handles its own refusals; this catch keeps an\n // unexpected failure from becoming an unhandled rejection behind a\n // client left waiting on an open socket.\n void this.handleUpgrade(req, socket, head).catch((error: unknown) => {\n this.ctx.logger.warn(`interconnect: upgrade failed: ${error instanceof Error ? error.message : String(error)}`)\n socket.destroy()\n })\n },\n }\n // The webserver is optional: without one the service still dials peers and\n // delivers over those outbound links (outbound-only mode). Registering the\n // inbound route through a waiting inject fiber instead of a constructor\n // `ctx.get` means composition order cannot leave the route unregistered \u2014\n // the fiber activates whenever a webserver is available, and headless\n // profiles simply never get one.\n ctx.inject(['webServer'], (webCtx) => {\n webCtx.effect(() => webCtx.webServer.registerUpgrade(upgrade), 'interconnect: /interconnect/link websocket')\n })\n\n // Liveness sweep: terminate sockets that stopped answering protocol pings.\n // Deleting the CURRENT element of a `Set` while iterating is safe: Set\n // iterators traverse live in insertion order, and a delete of an already\n // visited element is a no-op for the traversal. `socket.terminate()` from\n // `ws` fires its `close` handler asynchronously, so the `close` handler's\n // own `this.sockets.delete(socket)` cannot run mid-iteration either\n // (measured against the real `ws`). Neither delete removes a not-yet-visited\n // element, so nothing is skipped.\n // This timer is created before its cleanup effect below, so it could leak if\n // any statement between here and that effect threw. The only statements in\n // that window are `ctx.on(...)` registrations, and Cordis's `ctx.on` does not\n // throw for any of the event names used here (verified against a real\n // Context), so the window is not reachable. The teardown effect clears the\n // timer when the fiber unwinds.\n // Protocol constants, not deployment tunables: the heartbeat cadence is\n // fixed by the link-layer liveness contract and the backoff schedule by the\n // reconnect policy, so both stay hardcoded like the frame vocabulary.\n this.heartbeatTimer = setInterval(() => {\n for (const socket of this.sockets) {\n // A socket that closed between sweeps must not reach ping(): ws\n // throws synchronously when ping() is called on a non-OPEN socket.\n if (socket.readyState !== WebSocket.OPEN) {\n this.sockets.delete(socket)\n continue\n }\n if ((socket as WebSocket & { isAlive?: boolean }).isAlive === false) {\n socket.terminate()\n this.sockets.delete(socket)\n continue\n }\n ;(socket as WebSocket & { isAlive?: boolean }).isAlive = false\n socket.ping()\n }\n }, 30000)\n\n ctx.on('agent/status', ({ agent, status }) => {\n this.fanout({ kind: 'agent/status', sessionId: String(agent.session.id), status })\n })\n ctx.on('agent/created', ({ agent }) => {\n this.fanout({ kind: 'agent/created', sessionId: String(agent.session.id) })\n })\n ctx.on('agent/disposed', ({ agent }) => {\n this.fanout({ kind: 'agent/disposed', sessionId: String(agent.session.id) })\n })\n ctx.on('session/created', (session: Session) => {\n const parentSessionId = session.header.parentSession === undefined\n ? undefined\n : String(session.header.parentSession)\n this.fanout({\n kind: 'session/created',\n sessionId: String(session.id),\n ...(parentSessionId === undefined ? {} : { parentSessionId }),\n })\n })\n ctx.on('session/disposed', (session: Session) => {\n this.senders.delete(String(session.id))\n this.fanout({ kind: 'session/disposed', sessionId: String(session.id) })\n })\n ctx.on('subagent/end', (info: SubagentRunEndInfo) => {\n // Only in-process children are this instance's own work; remote provider\n // runs settle through a different, non-local path.\n if (!info.local) return\n this.fanout({\n kind: 'subagent/end',\n provider: info.provider,\n childSessionId: String(info.id),\n stopReason: info.stopReason,\n })\n })\n\n // Terminate every live socket, outbound dial loop, and the no-server\n // acceptor when the service fiber unwinds.\n ctx.effect(() => () => {\n /* v8 ignore next 1 -- the constructor sets the interval before registering this teardown effect, so dispose always observes it. */\n if (this.heartbeatTimer !== undefined) clearInterval(this.heartbeatTimer)\n for (const state of this.linkStates.values()) state.close()\n this.linkStates.clear()\n for (const socket of this.sockets) socket.terminate()\n this.sockets.clear()\n this.server.close()\n // Settle every in-flight request as unreachable: without this their\n // timers keep the process alive until they fire, and a late `*-result`\n // could resolve a pending that outlived its caller.\n for (const pending of this.pendingMessages.values()) {\n clearTimeout(pending.timer)\n pending.resolve?.(undefined)\n }\n this.pendingMessages.clear()\n this.disposed = true\n }, 'interconnect: websocket teardown')\n }\n\n /**\n * This instance's identity to attach to outbound messages. Always present:\n * it needs no address, only this instance's id and the calling session.\n * @param sessionId - the local session that is sending, used as the reply target.\n * @returns this instance's address-free identity for the calling session.\n */\n selfSender(sessionId: string): SenderIdentity {\n return { instanceId: this.instanceId, sessionId }\n }\n\n /**\n * Deliver one text message to a live session on a peer instance.\n * @param request - the peer instance id, target session, text, and optional delivery/resume overrides.\n * @returns the peer's answer, an unreachable result when no link answers, or a local\n * `message-too-large` result when the encoded frame would exceed the link cap.\n */\n async send(request: SendRequest): Promise<SendResult> {\n const payload: SendPayload = {\n sessionId: request.sessionId,\n text: request.text,\n ...(request.sender === undefined ? {} : { sender: request.sender }),\n ...(request.delivery === undefined ? {} : { delivery: request.delivery }),\n ...(request.resume === undefined ? {} : { resume: request.resume }),\n }\n try {\n const result = await this.msgRequest(request.instanceId, 'send', payload)\n return result ?? { delivered: false, instance: request.instanceId, reason: 'unreachable' }\n } catch {\n return { delivered: false, instance: request.instanceId, reason: 'unreachable' }\n }\n }\n\n /**\n * Deliver one text message back to the peer that a local session last\n * received a send from. `sessionId` names the LOCAL replying session; the\n * outbound target is the `sender` that session recorded, addressed through\n * this instance's own link to the sender's instance.\n * @param request - the LOCAL replying session id, the reply text, and optional delivery/resume overrides.\n * @returns the recalled sender's answer, an unreachable result when no link answers, or a\n * local `message-too-large` result when the encoded frame would exceed the link cap; a\n * local session that recorded no sender answers `no-sender-known` instead.\n */\n async reply(request: ReplyRequest): Promise<SendResult> {\n const sender = this.senders.get(request.sessionId)\n if (sender === undefined) {\n return { delivered: false, instance: this.instanceId, reason: 'no-sender-known' }\n }\n const payload: SendPayload = {\n sessionId: sender.sessionId,\n text: request.text,\n ...(request.delivery === undefined ? {} : { delivery: request.delivery }),\n ...(request.resume === undefined ? {} : { resume: request.resume }),\n // Attribute the reply to this instance so the peer, in turn, can reply\n // back \u2014 chaining the conversation.\n sender: this.selfSender(request.sessionId),\n }\n try {\n const result = await this.msgRequest(sender.instanceId, 'send', payload)\n return result ?? { delivered: false, instance: sender.instanceId, reason: 'unreachable' }\n } catch {\n return { delivered: false, instance: sender.instanceId, reason: 'unreachable' }\n }\n }\n\n /**\n * Probe a peer instance for liveness and identity over its persistent link.\n * Returns the peer identity when reachable, or undefined when the link is\n * not up or no answer arrives.\n * @param instanceId - the peer's `instanceId` as configured under {@link Config.peers}.\n * @returns the peer's identity, or undefined when there is no usable answer.\n */\n async ping(instanceId: string): Promise<PingResult | undefined> {\n return this.queryRequest(instanceId, { kind: 'ping' }) as Promise<PingResult | undefined>\n }\n\n /**\n * List a peer instance's live sessions over its persistent link. Undefined on\n * transport failure, matching `ping`.\n * @param instanceId - the peer's `instanceId` as configured under {@link Config.peers}.\n * @returns the peer's live session rows, or undefined on transport failure.\n */\n async list(instanceId: string): Promise<ListResult | undefined> {\n return this.queryRequest(instanceId, { kind: 'list' }) as Promise<ListResult | undefined>\n }\n\n /**\n * The peers this instance configures, each with the current state of the link\n * it dials, in configuration order. This is how a caller tells an id this\n * instance cannot reach at all (`peer-not-configured`) from one whose link is\n * merely down (`unreachable`), which the bare `undefined` of `ping`/`list`\n * cannot express. A configured peer whose link is `down` is still a valid\n * target: its reconnect runs on its own backoff, so it may answer later.\n * @returns one row per configured peer.\n */\n peers(): readonly PeerStatus[] {\n return [...this.linkStates].map(([instanceId, state]) => ({\n instanceId,\n origin: state.peer,\n link: state.writable() ? 'up' : 'down',\n }))\n }\n\n /**\n * Send a `msg` frame over the live link to a peer and resolve with its\n * correlated `msg-result`. A `peer-not-configured` result when this instance\n * configures no route for that id, undefined when the route exists but its\n * link is down, and a `message-too-large` result when the encoded frame would\n * not fit the link.\n */\n private async msgRequest(\n instanceId: string,\n kind: LinkMessage['kind'],\n payload: SendPayload,\n ): Promise<SendResult | undefined> {\n const state = this.linkStates.get(instanceId)\n // No route for this id: nothing is dialed and nothing ever will be, so the\n // only fix is adding it to Config.peers. That is a different answer from a\n // configured link that is temporarily down, which the caller may retry.\n if (state === undefined) return { delivered: false, instance: instanceId, reason: 'peer-not-configured' }\n if (!state.writable()) return undefined\n const reqId = `m${++this.reqIdCounter}-${randomUUID()}`\n const frame: LinkFrame = {\n type: 'msg',\n reqId,\n message: {\n kind,\n sessionId: payload.sessionId,\n text: payload.text,\n ...(payload.sender === undefined ? {} : { sender: payload.sender }),\n ...(payload.delivery === undefined ? {} : { delivery: payload.delivery }),\n ...(payload.resume === undefined ? {} : { resume: payload.resume }),\n },\n }\n // Refuse an over-cap frame locally: the peer's ws would close the link on\n // receiving it, and the caller would read a transport failure for a message\n // that could never have fit.\n if (!frameFitsLink(frame)) {\n return { delivered: false, instance: instanceId, reason: 'message-too-large' }\n }\n return this.waitForResult(reqId, 'msg', (failure) => {\n const wrote = state.sendFrame(frame)\n /* v8 ignore next 1 -- writable() and sendFrame read the same socket.readyState synchronously, so this guard is unreachable. */\n if (!wrote) failure(new Error(`interconnect: peer link to ${instanceId} closed while sending`))\n }) as Promise<SendResult | undefined>\n }\n\n /** Send a `query` frame over the live link to a peer and resolve its result. */\n private async queryRequest(instanceId: string, query: { kind: 'ping' } | { kind: 'list' }): Promise<unknown> {\n const state = this.linkStates.get(instanceId)\n if (state === undefined || !state.writable()) return undefined\n const reqId = `q${++this.reqIdCounter}-${randomUUID()}`\n // Validate the answer against the KIND of query this request asked, not\n // just the frame union: a peer answering a `list` with a ping-shaped\n // result would otherwise crash the tool on `result.sessions.map`. An\n // answer that fails its kind's shape is treated as no answer at all.\n const accept = query.kind === 'ping' ? projectPingResult : projectListResult\n try {\n return await this.waitForResult(reqId, 'query', (failure) => {\n const wrote = state.sendFrame({ type: 'query', reqId, query })\n /* v8 ignore next 1 -- writable() and sendFrame read the same socket.readyState synchronously. */\n if (!wrote) failure(new Error(`interconnect: peer link to ${instanceId} closed while querying`))\n }, accept)\n } catch {\n // A peer that never answers must read as transport failure, matching the\n // public JSDoc: `ping`/`list` return undefined when no answer arrives.\n return undefined\n }\n }\n\n /** Settle a `reqId` frame against its `*-result`, timing out at `requestTimeoutMs`. */\n private waitForResult(\n reqId: string,\n kind: 'msg' | 'query',\n send: (failure: (error: unknown) => void) => void,\n accept?: (result: unknown) => unknown,\n ): Promise<unknown> {\n return new Promise<unknown>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.pendingMessages.delete(reqId)\n reject(new Error(`interconnect: no result for ${reqId} within ${this.requestTimeoutMs}ms`))\n }, this.requestTimeoutMs)\n const settle = (result: unknown): void => {\n clearTimeout(timer)\n this.pendingMessages.delete(reqId)\n resolve(result)\n }\n // Only a query pending carries a projector; a `msg-result` is projected by\n // `projectMsgResult` at its own settle site.\n this.pendingMessages.set(reqId, kind === 'query'\n ? { timer, kind, accept: accept as (result: unknown) => unknown, resolve: settle }\n : { timer, kind, resolve: settle })\n /* v8 ignore start -- the failure callback is gated by the writable() check; the timeout rejects instead. */\n send((error: unknown) => {\n clearTimeout(timer)\n this.pendingMessages.delete(reqId)\n reject(error instanceof Error ? error : new Error(String(error)))\n })\n /* v8 ignore stop */\n })\n }\n\n /**\n * Dial one configured peer route. Activation calls this once per\n * `Config.peers` entry; the resulting state owns reconnection for the life of\n * the service fiber.\n * @param instanceId - the peer's `instanceId`.\n * @param origin - receiver origin this instance dials, e.g. `http://127.0.0.1:13080`.\n */\n private link(instanceId: string, origin: string): void {\n const state = new LinkState(\n (socket) => { this.attachDialedSocket(socket, instanceId) },\n this.ctx.logger,\n () => this.resolveToken(),\n instanceId,\n trimBase(origin),\n )\n this.linkStates.set(instanceId, state)\n state.dial()\n }\n\n /** Push one serialized lifecycle fact out to every linked peer over WS. */\n private fanout(notification: EventNotification): void {\n this.broadcast(notification)\n }\n\n /**\n * Push one fact over every live WebSocket link, dropping closed sockets.\n *\n * A bidirectional pair owns two sockets to the same peer (this instance's\n * dialed link plus the peer's inbound one), so one event must leave over one\n * of them. Which one is decided by local ownership, not by the peer: a dialed\n * socket is a configured peer's link and always sends. An inbound socket is\n * skipped only when this instance has an open dialed link configured under\n * the id that socket itself announced, so a self-reported announcement can\n * never silence another peer's link; with no such dialed link every inbound\n * socket receives the event. A peer listed under a key other than the id it\n * announces is warned about once per link, because then its own inbound\n * socket is not attributable and the peer receives each event twice.\n *\n * That holds once a peer's announcement has been seen. Between this\n * instance's dialed link opening and the peer's `hello` arriving on its\n * inbound socket, the inbound socket is not yet attributable, so an event\n * emitted in that window leaves over both sockets and reaches that peer\n * twice. The duplicate is transient and never a dropped event.\n */\n private broadcast(notification: EventNotification): void {\n if (this.sockets.size === 0) return\n const frame: LinkFrame = { type: 'event', notification }\n const encoded = JSON.stringify(frame)\n const covered = new Set<string>()\n for (const socket of this.sockets) {\n if (socket.readyState !== WebSocket.OPEN) {\n this.sockets.delete(socket)\n continue\n }\n const dialedPeer = this.dialedPeerOf.get(socket)\n if (dialedPeer !== undefined) covered.add(dialedPeer)\n }\n for (const socket of this.sockets) {\n if (this.dialedPeerOf.get(socket) === undefined) {\n const announced = this.peerOf.get(socket)\n if (announced !== undefined && covered.has(announced)) continue\n }\n socket.send(encoded)\n }\n }\n\n /**\n * Dispatch one inbound `msg` frame: deliver a `send`/`reply` and answer the\n * correlated `msg-result` on the same socket. Errors are surfaced as the\n * result so a throwing handler cannot escape the socket's message callback.\n */\n private async handleMsgFrame(socket: WebSocket, reqId: string, message: LinkMessage): Promise<void> {\n // Only `send` arrives over the wire: `reply` originates locally (the tool\n // calls `reply()` which sends a regular `send` frame to the recalled\n // sender). A remote `reply` frame would relay arbitrary text through this\n // instance's sender map, so the schema does not admit it.\n const result = await this.deliver({\n sessionId: message.sessionId,\n text: message.text,\n /* v8 ignore next 1 -- schemastery resolves an absent optional `sender` to an empty object, never undefined. */\n ...(message.sender === undefined ? {} : { sender: message.sender }),\n ...(message.delivery === undefined ? {} : { delivery: message.delivery }),\n ...(message.resume === undefined ? {} : { resume: message.resume }),\n })\n this.sendFrame(socket, { type: 'msg-result', reqId, result })\n }\n\n /** Dispatch one inbound `query` frame (ping/list/event) and answer on the socket. */\n private handleQueryFrame(socket: WebSocket, reqId: string, query: QueryMessage): void {\n let result: unknown\n if (query.kind === 'ping') {\n result = { pong: true, instance: this.instanceId }\n } else if (query.kind === 'list') {\n result = this.listSessions(this.listRowsBudgetBytes(reqId))\n } else {\n const payload: EventPayload = {\n sender: this.peerOf.get(socket) ?? 'unknown-peer',\n notification: query.notification,\n }\n this.receiveEvent(payload)\n result = { accepted: true }\n }\n this.sendFrame(socket, { type: 'query-result', reqId, result })\n }\n\n /**\n * Surface one remote notification to local listeners and the log.\n *\n * `ctx.parallel` is used instead of `ctx.emit`: `emit` maps listeners without\n * awaiting them, so a listener that returns a rejected promise would surface\n * as an unhandled rejection, while `parallel` settles every listener and\n * aggregates their failures.\n */\n private receiveEvent(eventPayload: EventPayload): void {\n const { notification, sender } = eventPayload\n this.ctx.logger.info(`interconnect: remote event ${notification.kind} from ${sender}`)\n // A listener failure is the listener's bug and must not take down the link\n // or this process, so the aggregate is logged instead of rethrown.\n void this.ctx.parallel('interconnect/event', notification, sender).catch((error: unknown) => {\n // `parallel` aggregates the rejected listeners into an AggregateError\n // whose own message is empty, so the reasons carry the diagnostic.\n /* v8 ignore next 1 -- `parallel` rejects only with the AggregateError it builds from listener results. */\n const reasons = error instanceof AggregateError ? error.errors : [error]\n const detail = reasons\n .map(reason => (reason instanceof Error ? reason.message : String(reason)))\n .join('; ')\n this.ctx.logger.warn(`interconnect: listener for a ${notification.kind} event from ${sender} threw: ${detail}`)\n })\n }\n\n /**\n * Bytes one `list` answer may spend on its `sessions` rows: the frame cap\n * minus the serialized envelope that answer will carry. The envelope holds\n * the peer-supplied `reqId` and this instance's own id, so it is measured per\n * answer instead of reserved with a fixed constant. Both ids are bounded\n * ({@link MAX_REQUEST_ID_CHARS} and {@link MAX_INSTANCE_ID_CHARS} characters),\n * so the envelope always fits and the budget is always positive.\n * @param reqId - the request id the answer has to echo.\n * @returns the byte budget for the rows.\n */\n private listRowsBudgetBytes(reqId: string): number {\n const envelope: LinkFrame = {\n type: 'query-result',\n reqId,\n result: { sessions: [], instance: this.instanceId },\n }\n return MAX_LINK_FRAME_BYTES - Buffer.byteLength(JSON.stringify(envelope), 'utf8')\n }\n\n /**\n * Summarize the live local sessions so a sender can discover valid targets\n * instead of having to know a session id already. Only live agents are listed\n * because `send` can reach exactly those. The answer stops at\n * {@link MAX_LISTED_SESSIONS} rows or at the row budget the answer's own\n * envelope leaves, whichever comes first: that budget is what keeps the\n * complete `query-result` frame inside the link's cap, because a title's\n * length comes from the session-title projection's own bound rather than\n * from anything this listing controls. A title that does not fit the\n * remaining budget is dropped so its target stays listed; a row that does not\n * fit even untitled ends the listing, which keeps the answer a prefix of the\n * registration order instead of a set with gaps.\n *\n * Title and status are best-effort: the title projection is an optional\n * service, and a receiver without it still returns the ids. A projection that\n * throws degrades that one row rather than failing the whole listing, which\n * matches how the Host's own session listing treats its projection column.\n * @param rowBudgetBytes - bytes the `sessions` rows may occupy, envelope excluded.\n * @returns the bounded listing.\n */\n private listSessions(rowBudgetBytes: number): ListResult {\n // `agents.list()` includes subagent children; a row this instance would\n // refuse to deliver to must not be advertised as a target, or the listing\n // contradicts `send`.\n const reachable = this.ctx.agents.list()\n .filter(agent => !isSessionOwnedBySubagent(this.ctx, agent.session, agent))\n const sessions: InterconnectSessionSummary[] = []\n let used = 0\n for (const agent of reachable.slice(0, MAX_LISTED_SESSIONS)) {\n const row = this.sessionRow(agent)\n const sized = used + rowBytes(row)\n if (sized > rowBudgetBytes) {\n // A title is best-effort: a row whose title does not fit keeps its\n // target and drops the title before it drops out of the listing.\n const untitled = {\n sessionId: row.sessionId,\n ...(row.status === undefined ? {} : { status: row.status }),\n }\n const untitledSized = used + rowBytes(untitled)\n // A row that does not fit even untitled ends the listing: adding a\n // shorter later row would report the set out of order.\n if (untitledSized > rowBudgetBytes) break\n sessions.push(untitled)\n used = untitledSized\n continue\n }\n sessions.push(row)\n used = sized\n }\n return { sessions, instance: this.instanceId }\n }\n\n /** One listing row for a live agent; the title projection is best-effort. */\n private sessionRow(agent: Agent): InterconnectSessionSummary {\n let title: string | undefined\n try {\n const snapshot = this.ctx.get('sessionProjections')?.snapshot(agent.session)\n const value = snapshot?.values.title\n if (typeof value === 'string' && value !== '') title = value\n } catch {\n // A failing projection must not hide a reachable session.\n title = undefined\n }\n return {\n sessionId: agent.id,\n ...(title === undefined ? {} : { title }),\n ...(typeof agent.status === 'string' ? { status: agent.status } : {}),\n }\n }\n\n /**\n * Resolve a session that is not currently live, when the sender asked to wake\n * it. Returns the agent, or the reason it stays undelivered.\n *\n * The resume is delegated to the Host's configured `agent` lookup rather than\n * calling `ctx.agents.resume()` here, and that is the whole point: a handle\n * from `resume()` is owned by the CALLING context, so resuming on this\n * plugin's fiber would tear the session down again the moment the plugin\n * unloads (measured: the same call through the root context leaves it alive).\n * The Host's resolver owns it instead, and it also composes the preset the\n * session recorded \u2014 so a woken agent comes back with the toolset its history\n * was produced under, not an empty one.\n */\n private async wake(payload: SendPayload): Promise<{ agent: Agent } | { reason: SendFailure }> {\n if (payload.resume !== true) return { reason: 'session-not-live' }\n if (!this.allowResume) return { reason: 'resume-refused' }\n // Optional by design: a deployment without the Host's lookup (headless, or\n // a profile with no api-proxy) degrades to the plain not-live answer rather\n // than failing the call.\n const lookup = this.ctx.get('typert')?.lookups.get('agent')\n if (lookup === undefined) return { reason: 'session-not-live' }\n try {\n const resolved = await lookup.resolve(payload.sessionId)\n // `undefined` is not a failed wake: the base `agent` provider is a plain\n // registry read, so a deployment without the Host's resuming resolver\n // answers undefined for every id that is not already live. Reporting\n // `resume-failed` there would send the caller chasing a wake that was\n // never possible, when the honest answer is that nothing is live here.\n if (resolved === undefined || resolved === null) return { reason: 'session-not-live' }\n return { agent: resolved as Agent }\n } catch (error) {\n // A refusing resolver is an expected outcome, not a fault of this\n // instance: the id may not exist, or a subagent owner may hold it.\n this.ctx.logger.info(\n `interconnect: resume refused for ${payload.sessionId}: ${error instanceof Error ? error.message : String(error)}`,\n )\n // A subagent-owned session is the one refusal with a different answer for\n // the caller: it exists, and its parent is the address that can deliver\n // to it. The Host reports that cause as `session/agent-busy`, and for a\n // cold session nothing local carries the ownership header, so the code is\n // the only signal available here.\n if (remoteErrorOf(error)?.code === 'session/agent-busy') {\n return { reason: 'session-owned-by-subagent' }\n }\n return { reason: 'resume-failed' }\n }\n }\n\n /**\n * Deliver one message to a live local session, waking a persisted one only\n * when the sender asked and this receiver allows it.\n */\n private async deliver(payload: SendPayload): Promise<SendResult> {\n // A delivery that outlived the service fiber (an inbound frame already in\n // flight when the plugin unloaded) must not drive a disposed agent.\n if (this.disposed) return { delivered: false, instance: this.instanceId, reason: 'unreachable' }\n let agent = this.ctx.agents.get(payload.sessionId as Agent['id'])\n if (agent === undefined) {\n const woken = await this.wake(payload)\n // The fiber may have unwound while the wake resolution was in flight;\n // re-check before touching a woken agent. oxlint's flow analysis treats\n // the two `disposed` reads as the same value, but `await` is a yield\n // point at which the teardown effect can run.\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- the service can dispose during the wake await\n if (this.disposed) return { delivered: false, instance: this.instanceId, reason: 'unreachable' }\n if ('reason' in woken) {\n return { delivered: false, instance: this.instanceId, reason: woken.reason }\n }\n agent = woken.agent\n }\n // One guard covers both paths below: the live hit, exactly as the Host fences\n // it before handing out an agent, and a session this call just woke. A\n // session reserved to subagent routing is delivered to by its parent, so\n // splicing into its inbox here would race that parent.\n if (isSessionOwnedBySubagent(this.ctx, agent.session, agent)) {\n return { delivered: false, instance: this.instanceId, reason: 'session-owned-by-subagent' }\n }\n // Remember who sent this message so the receiving session can reply later.\n // `source` never reaches the model, so recording the sender here only sets\n // up reply attribution; the model-facing `content` stays exactly the text\n // that crossed the wire. An absent sender resolves to `{}` under schematery,\n // so test for a real identity rather than `undefined`.\n // The wire shape is untrusted here: a peer may send a partial identity,\n // so validate both fields at runtime before recording a reply target.\n const sender = ((): SenderIdentity | undefined => {\n const candidate: unknown = payload.sender\n if (typeof candidate !== 'object' || candidate === null) return undefined\n const record = candidate as Record<string, unknown>\n if (typeof record.instanceId !== 'string' || typeof record.sessionId !== 'string') return undefined\n return { instanceId: record.instanceId, sessionId: record.sessionId }\n })()\n // Attribute the message to this plugin, not to the human operator: the\n // receiving agent must be able to tell a cross-instance handoff from text\n // its own user typed. The summary names the sender when one was carried, so\n // a GUI/archive can show where the handoff came from without touching the\n // model-facing content.\n const message = createUserMessage({\n source: {\n kind: 'plugin:dsh-interconnect',\n form: 'notice',\n summary: boundContextSummary(\n sender === undefined\n ? `interconnect handoff delivered on instance ${this.instanceId}`\n : `interconnect handoff from ${sender.instanceId} (session ${sender.sessionId}) delivered on instance ${this.instanceId}`,\n ),\n },\n content: [{ type: 'text', text: payload.text }],\n })\n // The sender may override the mode per message, because urgency belongs to\n // one message rather than to the link; an absent override leaves the\n // receiver's configured default in force. The switch is exhaustive over\n // DeliveryMode so adding a mode fails the type check here instead of\n // silently falling through to `followup`.\n const mode: DeliveryMode = payload.delivery ?? this.delivery\n switch (mode) {\n case 'steer':\n agent.steer(message)\n break\n case 'inject':\n agent.inject(message)\n break\n case 'followup':\n agent.followup(message)\n break\n /* v8 ignore next -- closed-union exhaustiveness guard */\n default:\n assertNever(mode)\n }\n // Record the reply target only after the message committed: a delivery that\n // threw leaves no sender behind, so a later reply cannot target a session\n // whose handoff never landed. A message that carries NO sender (an old peer,\n // or an anonymous relay) clears any earlier mapping, so a reply cannot go\n // back to a stale sender from a previous handoff.\n if (sender !== undefined) {\n this.senders.set(payload.sessionId, sender)\n } else {\n this.senders.delete(payload.sessionId)\n }\n return { delivered: true, instance: this.instanceId, delivery: mode }\n }\n\n private async resolveToken(): Promise<string | undefined> {\n const credential = await this.ctx.credentials.resolve(credentialRef(INTERCONNECT_TOKEN_REF))\n return credential === undefined || credential.value.length === 0 ? undefined : credential.value\n }\n\n /**\n * Answer one refused upgrade and close its socket. `socket.end()` alone only\n * half-closes the connection: a client that keeps its own writing side open\n * (a socket created with `allowHalfOpen`) leaves the connection live, and a\n * refused socket never enters the link pool, so nothing else would reap it.\n * @param socket - the refused upgrade socket.\n * @param response - the complete HTTP response sent to the client.\n */\n private refuseUpgrade(socket: Duplex, response: string): void {\n socket.end(response, () => { socket.destroy() })\n }\n\n /** Inbound WebSocket upgrade: authenticate the bearer header, then accept. */\n private async handleUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): Promise<void> {\n let token: string | undefined\n try {\n token = await this.resolveToken()\n } catch (error) {\n // Fail closed and end the socket: the caller invokes this as\n // `void handleUpgrade(...)`, so letting the rejection escape would both\n // leave this client hanging on an open socket and surface as an unhandled\n // rejection.\n this.ctx.logger.warn(`interconnect: upgrade token read failed: ${error instanceof Error ? error.message : String(error)}`)\n this.refuseUpgrade(socket, 'HTTP/1.1 403 Forbidden\\r\\nConnection: close\\r\\nContent-Length: 9\\r\\n\\r\\nforbidden')\n return\n }\n if (token === undefined) {\n this.refuseUpgrade(socket, 'HTTP/1.1 403 Forbidden\\r\\nConnection: close\\r\\nContent-Length: 9\\r\\n\\r\\nforbidden')\n return\n }\n // The token read is an await, so the service can be torn down (or the\n // webserver route withdrawn) before it settles. Accepting here would add a\n // socket to a pool the teardown already cleared, with no owner left to\n // close it or answer its heartbeat.\n if (this.disposed) {\n this.refuseUpgrade(socket, 'HTTP/1.1 503 Service Unavailable\\r\\nConnection: close\\r\\nContent-Length: 11\\r\\n\\r\\nunavailable')\n return\n }\n const expected = `Bearer ${token}`\n const header = req.headers.authorization\n if (header === undefined || !timingSafeEqual(header, expected)) {\n this.refuseUpgrade(socket, 'HTTP/1.1 401 Unauthorized\\r\\nConnection: close\\r\\nContent-Length: 12\\r\\n\\r\\nunauthorized')\n return\n }\n this.server.handleUpgrade(req, socket, head, (websocket) => {\n this.attachSocket(websocket)\n })\n }\n\n /**\n * Install frame + liveness handling on one outbound socket the dial owns for\n * a configured peer, recording that local ownership before anything else can\n * observe the socket.\n * @param websocket - the dialed socket.\n * @param peerInstanceId - the configured peer this instance dials.\n */\n private attachDialedSocket(websocket: WebSocket, peerInstanceId: string): void {\n this.dialedPeerOf.set(websocket, peerInstanceId)\n this.attachSocket(websocket)\n }\n\n /**\n * Install frame + liveness handling on one socket and add it to the live\n * pool. Used by both the server half (accepted upgrade) and the client half\n * (outbound dial), so a single socket carries events both directions. Not a\n * model-facing entry point; the outbound dial reaches it through a private\n * closure.\n * @param websocket - the accepted or dialed socket to install handlers on.\n */\n private attachSocket(websocket: WebSocket): void {\n this.sockets.add(websocket)\n ;(websocket as WebSocket & { isAlive: boolean }).isAlive = true\n websocket.on('pong', () => {\n ;(websocket as WebSocket & { isAlive: boolean }).isAlive = true\n })\n websocket.on('message', (data: RawData, isBinary: boolean) => {\n // ws flags the frame opcode: binary frames are a protocol violation (the\n // link vocabulary is JSON text), so drop them before parsing.\n if (isBinary) return\n this.handleFrame(websocket, data)\n })\n websocket.on('close', () => {\n this.sockets.delete(websocket)\n this.peerOf.delete(websocket)\n })\n websocket.on('error', () => {\n this.sockets.delete(websocket)\n })\n // Announce this instance's identity so the dialer can attribute pushes.\n websocket.send(JSON.stringify({ type: 'hello', sender: this.instanceId } satisfies LinkFrame))\n }\n\n /** Parse and route one inbound link frame, attributing events to the socket's announced peer. */\n private handleFrame(socket: WebSocket, data: RawData | string): void {\n // Cap inbound frames well below ws's 100 MiB default: a link frame is at\n // most one small message plus metadata, so a larger frame is a hostile or\n // broken peer, not a legitimate handoff.\n const byteLength = typeof data === 'string'\n ? Buffer.byteLength(data)\n : Array.isArray(data)\n ? data.reduce((total, part) => total + part.byteLength, 0)\n : data.byteLength\n if (byteLength > MAX_LINK_FRAME_BYTES) {\n this.ctx.logger.warn('interconnect: dropping oversized link frame')\n return\n }\n // Text frames arrive as Buffers over real sockets (ws flags the opcode\n // separately); the other RawData arms cover alternate binaryType\n // deliveries and the string arm the direct test seams.\n const text = typeof data === 'string'\n ? data\n : Array.isArray(data)\n ? Buffer.concat(data).toString('utf8')\n : Buffer.isBuffer(data)\n ? data.toString('utf8')\n : Buffer.from(data).toString('utf8')\n let parsed: unknown\n try {\n parsed = withoutNullFields(z.resolve(JSON.parse(text), linkFrameSchema, {})[0])\n } catch {\n this.ctx.logger.warn('interconnect: dropping malformed link frame')\n return\n }\n // schemastery passes a JSON `null` through a union untouched; reject it\n // like any other malformed frame instead of dereferencing null below.\n if (parsed === null || typeof parsed !== 'object') {\n this.ctx.logger.warn('interconnect: dropping malformed link frame')\n return\n }\n const frame = parsed as LinkFrame\n if (frame.type === 'hello') {\n this.peerOf.set(socket, frame.sender)\n const dialedPeer = this.dialedPeerOf.get(socket)\n if (dialedPeer !== undefined && dialedPeer !== frame.sender && !this.mismatchWarned.has(socket)) {\n this.mismatchWarned.add(socket)\n this.ctx.logger.warn(\n `interconnect: peer configured as ${dialedPeer} announces ${frame.sender}; list a peer under the instanceId it announces, or the duplicate inbound link is not recognised`,\n )\n }\n return\n }\n if (frame.type === 'event') {\n // `receiveEvent` reports listener failures itself, synchronously or not,\n // so this socket's synchronous `message` handler cannot be reached by a\n // remote peer's event through a local listener.\n this.receiveEvent({ sender: this.peerOf.get(socket) ?? 'unknown-peer', notification: frame.notification })\n return\n }\n if (frame.type === 'msg-result') {\n const pending = this.pendingMessages.get(frame.reqId)\n // A `msg-result` settles only a `msg` request: a query awaiting its\n // `query-result` must never be resolved by a mis-typed frame. The\n // result shape is already enforced by the frame schema; msg requests\n // carry no per-kind accept gate.\n if (pending !== undefined && pending.kind === 'msg') {\n ;pending.resolve?.(projectMsgResult(frame.result))\n }\n return\n }\n if (frame.type === 'query-result') {\n const pending = this.pendingMessages.get(frame.reqId)\n // Only a result that satisfies the pending request's own shape settles\n // it, and the projecting accept returns what settles: anything else is\n // dropped and the request times out as unreachable.\n if (pending !== undefined && pending.kind === 'query') {\n const answer = pending.accept(frame.result)\n if (answer !== undefined) pending.resolve?.(answer)\n }\n return\n }\n if (frame.type === 'msg') {\n void Promise.resolve().then(async () => {\n await this.handleMsgFrame(socket, frame.reqId, frame.message)\n }).catch((error: unknown) => {\n this.ctx.logger.warn(`interconnect: msg ${frame.reqId} handler threw: ${error instanceof Error ? error.message : String(error)}`)\n void this.sendFrame(socket, {\n type: 'msg-result',\n reqId: frame.reqId,\n result: { delivered: false, instance: this.instanceId, reason: 'unreachable' },\n })\n })\n return\n }\n // `query`: an inbound discovery/event request. Answer asynchronously and\n // never let a throw escape the socket's synchronous message callback.\n void Promise.resolve().then(() => {\n this.handleQueryFrame(socket, frame.reqId, frame.query)\n }).catch((error: unknown) => {\n this.ctx.logger.warn(`interconnect: query ${frame.reqId} handler threw: ${error instanceof Error ? error.message : String(error)}`)\n })\n }\n\n /** Write one frame to a socket, returning false when the socket cannot take it. */\n private sendFrame(socket: WebSocket, frame: LinkFrame): boolean {\n if (socket.readyState !== WebSocket.OPEN) return false\n socket.send(JSON.stringify(frame))\n return true\n }\n}\n\n/**\n * One in-flight request awaiting its `*-result` frame. `waitForResult`\n * installs the timer and settle callbacks; `handleFrame` settles the matching\n * entry when the result arrives.\n */\ninterface PendingMessage {\n readonly timer: ReturnType<typeof setTimeout>\n}\n/** A pending that awaits a `msg-result` frame. */\ninterface PendingMsg extends PendingMessage {\n kind: 'msg'\n resolve?: (result: unknown) => void\n}\n/** A pending that awaits a `query-result` frame, gated by its request kind's projector. */\ninterface PendingQuery extends PendingMessage {\n kind: 'query'\n resolve?: (result: unknown) => void\n /** Kind gate and projector: returns the answer to settle with, or undefined to drop the frame. */\n accept: (result: unknown) => unknown\n}\n/** One pending request: a `msg` outcome is projected at its settle site, a `query` outcome by its own projector. */\ntype MutablePendingMessage = PendingMsg | PendingQuery\n\n/**\n * One dialed socket together with the handlers that dial registered on it, so\n * close can remove exactly those by reference and leave the pool-cleanup\n * handlers attachSocket added in place.\n */\ninterface DialedSocket {\n socket: WebSocket\n open: () => void\n close: () => void\n error: () => void\n}\n\n/**\n * One outbound WebSocket peer link: dials, re-dials with backoff after an\n * unexpected drop, and joins the service's live socket pool once open, so\n * local events fan out over the link and the peer's pushes come back in.\n */\nclass LinkState {\n private dialed: DialedSocket | undefined\n private closed = false\n private retry = 0\n private reconnectTimer: ReturnType<typeof setTimeout> | undefined\n private warnedNoToken = false\n\n /** Receiver origin this link dials. */\n readonly peer: string\n readonly instanceId: string\n\n constructor(\n private readonly attachSocket: (socket: WebSocket) => void,\n private readonly logger: LoggerService,\n private readonly resolveToken: () => Promise<string | undefined>,\n instanceId: string,\n origin: string,\n ) {\n this.instanceId = instanceId\n this.peer = origin\n }\n\n /** Open the socket; reconnect is scheduled by the close handler. */\n dial(): void {\n /* v8 ignore next 1 -- close() removes the link state from the map before any later dial can observe it. */\n if (this.closed) return\n let url: URL\n try {\n url = linkUrl(this.peer)\n } catch {\n // The constructor pre-validates configured origins, so a malformed one\n // here can only come from a deployment whose config bypassed validation;\n // it degrades to a down link rather than a thrown dial.\n this.logger.warn(`interconnect: invalid peer origin ${this.peer}; link to ${this.instanceId} stays down`)\n return\n }\n void this.resolveToken().then((token) => {\n if (token === undefined) {\n // Warn once, then keep retrying on the reconnect backoff: a credential\n // injected after this service activated must bring the link up without\n // a restart. The dial re-resolves the token on every retry.\n if (!this.warnedNoToken) {\n this.warnedNoToken = true\n this.logger.warn(`interconnect: no shared token configured; peer ${this.instanceId} link stays down, retrying until one is set`)\n }\n if (this.closed) return\n this.scheduleReconnect()\n return\n }\n if (this.closed) return\n const socket = new WebSocket(url, {\n headers: { authorization: `Bearer ${token}` },\n maxPayload: MAX_LINK_FRAME_BYTES,\n // A peer that accepts TCP but never completes the upgrade would leave\n // the socket in CONNECTING forever: no open (so no heartbeat) and no\n // close (so no reconnect). ws aborts the connection past the handshake\n // window, so its own error+close fire and the close handler schedules\n // a reconnect \u2014 and ws owns the timer, so nothing leaks on teardown.\n handshakeTimeout: LINK_HANDSHAKE_TIMEOUT_MS,\n })\n const onOpen = (): void => {\n this.retry = 0\n // Same handler as the server half: adds to the live pool and announces\n // this instance's identity over the now-open link.\n this.attachSocket(socket)\n }\n const onClose = (): void => {\n /* v8 ignore next 1 -- close() strips this listener before terminating, so the guard is only reachable on real drops. */\n if (this.closed) return\n this.scheduleReconnect()\n }\n const onError = (): void => {\n // close follows; reconnect is scheduled there.\n }\n this.dialed = { socket, open: onOpen, close: onClose, error: onError }\n socket.once('open', onOpen)\n socket.once('close', onClose)\n socket.on('error', onError)\n }).catch(() => {\n // A rejecting token read must not become an unhandled rejection, and must\n // not silently end the dial loop either: without this the link would stay\n // down until the process restarted, since no socket was ever created and\n // so no `close` will arrive to schedule the retry.\n if (this.closed) return\n this.scheduleReconnect()\n })\n }\n\n /** Whether this link currently holds an open socket that can carry frames. */\n writable(): boolean {\n const dialed = this.dialed\n return dialed !== undefined && dialed.socket.readyState === WebSocket.OPEN\n }\n\n /** Write one frame over this link's outbound socket; false when not open. */\n sendFrame(frame: LinkFrame): boolean {\n const dialed = this.dialed\n /* v8 ignore next 1 -- callers gate on writable(), which reads the same readyState synchronously; this guard is unreachable. */\n if (dialed === undefined || dialed.socket.readyState !== WebSocket.OPEN) return false\n dialed.socket.send(JSON.stringify(frame))\n return true\n }\n\n close(): void {\n this.closed = true\n if (this.reconnectTimer !== undefined) clearTimeout(this.reconnectTimer)\n const dialed = this.dialed\n if (dialed === undefined) return\n // Remove only the dial handlers: the attachSocket pool-cleanup handlers\n // must stay so the pool does not retain the terminated socket.\n dialed.socket.removeListener('open', dialed.open)\n dialed.socket.removeListener('close', dialed.close)\n dialed.socket.removeListener('error', dialed.error)\n // A CONNECTING socket emits 'error' asynchronously on terminate; keep a\n // listener so the event cannot escape as an uncaughtException. Callers\n // delete this link's state from the map themselves.\n /* v8 ignore next 1 -- a CONNECTING terminate error is timing-dependent and does not fire in tests. */\n dialed.socket.on('error', () => {})\n dialed.socket.terminate()\n }\n\n private scheduleReconnect(): void {\n /* v8 ignore next 1 -- the 30s cap binds only after five consecutive reconnect failures (~31s of wall time). */\n const delay = Math.min(30000, 1000 * 2 ** this.retry)\n this.retry += 1\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = undefined\n this.dial()\n }, delay)\n }\n}\n\n/**\n * Constant-time comparison of two strings. Each side is digest-normalized\n * first, so the buffers passed to `timingSafeEqual` always match in length:\n * a malformed multi-byte Authorization header cannot reach the crypto layer\n * with a mismatched length, and the comparison leaks no length information.\n */\nfunction timingSafeEqual(a: string, b: string): boolean {\n return constantTimeEqual(createHash('sha256').update(a, 'utf8').digest(), createHash('sha256').update(b, 'utf8').digest())\n}\n\n/**\n * Map one HTTP(S) peer origin to the WebSocket URL of its link route. Only\n * the plain-HTTP schemes are rewritten to their WebSocket equivalents; an\n * explicit `wss:` (or `ws:`) origin keeps its scheme, so a TLS peer link is\n * never downgraded to plaintext. Any other scheme (ftp:, file:, ...) is\n * rejected so a misconfigured origin fails loudly instead of feeding\n * `new WebSocket` a URL it cannot dial.\n * @param origin - peer origin as configured, e.g. `http://127.0.0.1:13080`.\n * @returns the link URL, e.g. `ws://127.0.0.1:13080/interconnect/link`.\n * @throws TypeError when the origin is not a valid absolute URL or maps to a\n * non-WebSocket protocol.\n */\nexport function linkUrl(origin: string): URL {\n const url = new URL(LINK_CHANNEL, origin)\n if (url.protocol === 'http:') url.protocol = 'ws:'\n else if (url.protocol === 'https:') url.protocol = 'wss:'\n if (url.protocol !== 'ws:' && url.protocol !== 'wss:') {\n throw new TypeError(`interconnect: unsupported peer origin protocol ${url.protocol}`)\n }\n return url\n}\n\nfunction trimBase(baseUrl: string): string {\n return baseUrl.replace(/\\/+$/, '')\n}\n\nexport default InterconnectService\n", "/** String/symbol keyed dictionary type. */\nexport type Dict<T = any, K extends string | symbol = string> = { [key in K]: T }\n/** Safely read `T[K]`, returning `never` when `K` is not a key of `T`. */\nexport type Get<T extends {}, K> = K extends keyof T ? T[K] : never\n/** Conditional extraction helper with a configurable return type. */\nexport type Extract<S, T, U = S> = S extends T ? U : never\n/** Accept a value or an array, unless the value is already an array type. */\nexport type MaybeArray<T> = [T] extends [unknown[]] ? T : T | T[]\n/** Wrap a value in `Promise`, preserving the resolved type of existing promises. */\nexport type Promisify<T> = Promise<T extends Promise<infer S> ? S : T>\n/** Accept a value or promise unless the value type is already promise-like. */\nexport type Awaitable<T> = [T] extends [Promise<unknown>] ? T : T | Promise<T>\n/** Convert a union type to an intersection type. */\nexport type Intersect<U> = (U extends any ? (arg: U) => void : never) extends ((arg: infer I) => void) ? I : never\n\n/** No-op callback returning `undefined` at runtime and `any` at type level. */\nexport function noop(): any {}\n\n/** Return true when a value is `null` or `undefined`. */\nexport function isNullable(value: any): value is null | undefined | void {\n return value === null || value === undefined\n}\n\n/** Return true when a value is neither `null` nor `undefined`. */\nexport function isNonNullable<T>(value: T): value is NonNullable<T> {\n return !isNullable(value)\n}\n\n/** Return true for non-array object values. */\nexport function isPlainObject(data: any) {\n return data && typeof data === 'object' && !Array.isArray(data)\n}\n\n/** Filter object entries with a key type guard. */\nexport function filterKeys<T, K extends string, U extends K>(object: Dict<T, K>, filter: (key: K, value: T) => key is U): Dict<T, U>\n/** Filter object entries with a boolean predicate. */\nexport function filterKeys<T, K extends string>(object: Dict<T, K>, filter: (key: K, value: T) => boolean): Dict<T, K>\n/** Filter object entries and return a new object. */\nexport function filterKeys(object: {}, filter: (key: string, value: any) => boolean) {\n return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)))\n}\n\n/** Map object values while preserving the original key set. */\nexport function mapValues<U, T, K extends string>(object: Dict<T, K>, transform: (value: T, key: K) => U) {\n return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, (transform as any)(value, key)])) as Dict<U, K>\n}\n\n/** Alias for `mapValues`. */\nexport { mapValues as valueMap }\n\n/** Pick selected keys from an object, optionally including `undefined` values. */\nexport function pick<T extends object, K extends keyof T>(source: T, keys?: Iterable<K>, forced?: boolean) {\n if (!keys) return { ...source }\n const result = {} as Pick<T, K>\n for (const key of keys) {\n if (forced || source[key] !== undefined) result[key] = source[key]\n }\n return result\n}\n\n/** Omit selected keys from a shallow object copy. */\nexport function omit<T, K extends keyof T>(source: T, keys?: Iterable<K>) {\n if (!keys) return { ...source }\n const result = { ...source } as Omit<T, K>\n for (const key of keys) {\n Reflect.deleteProperty(result, key)\n }\n return result\n}\n\n/** Define a non-enumerable writable property with a typed key. */\nexport function defineProperty<T, K extends keyof T>(object: T, key: K, value: T[K]): T\n/** Define a non-enumerable writable property with an arbitrary key. */\nexport function defineProperty<T, K extends keyof any>(object: T, key: K, value: any): T\n/** Define a non-enumerable writable property and return the object. */\nexport function defineProperty<T, K extends keyof any>(object: T, key: K, value: any) {\n return Object.defineProperty(object, key, { writable: true, value, enumerable: false })\n}\n", "import { isNullable } from './misc.ts'\n\ntype GlobalConstructorNames = keyof {\n [K in keyof typeof globalThis as typeof globalThis[K] extends abstract new (...args: any) => any ? K : never]: K\n}\n\n/** Create a predicate for a global constructor name. */\nexport function is<K extends GlobalConstructorNames>(type: K): (value: any) => value is InstanceType<typeof globalThis[K]>\n/** Test whether a value matches a global constructor name. */\nexport function is<K extends GlobalConstructorNames>(type: K, value: any): value is InstanceType<typeof globalThis[K]>\n/** Test values using `instanceof` with a `toStringTag` fallback. */\nexport function is<K extends GlobalConstructorNames>(type: K, value?: any): any {\n if (arguments.length === 1) return (value: any) => is(type, value)\n return type in globalThis && value instanceof (globalThis[type] as any)\n || Object.prototype.toString.call(value).slice(8, -1) === type\n}\n\nfunction isArrayBufferLike(value: any): value is ArrayBufferLike {\n return is('ArrayBuffer', value) || is('SharedArrayBuffer', value)\n}\n\nfunction isArrayBufferSource(value: any): value is Binary.Source {\n return isArrayBufferLike(value) || ArrayBuffer.isView(value)\n}\n\n/** Binary source detection and base64/hex conversion helpers. */\nexport namespace Binary {\n export type Source<T extends ArrayBufferLike = ArrayBufferLike> = T | ArrayBufferView<T>\n\n export const is = isArrayBufferLike\n export const isSource = isArrayBufferSource\n\n export function fromSource<T extends ArrayBufferLike>(source: Source<T>): T {\n if (ArrayBuffer.isView(source)) {\n // https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer#answer-31394257\n return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength) as T\n } else {\n return source\n }\n }\n\n export function toBase64(source: Source) {\n source = fromSource(source)\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(source).toString('base64')\n }\n let binary = ''\n const bytes = new Uint8Array(source)\n for (let i = 0; i < bytes.byteLength; i++) {\n binary += String.fromCharCode(bytes[i])\n }\n return btoa(binary)\n }\n\n export function fromBase64(source: string) {\n if (typeof Buffer !== 'undefined') return fromSource(Buffer.from(source, 'base64'))\n return Uint8Array.from(atob(source), c => c.charCodeAt(0))\n }\n\n export function toHex(source: Source) {\n source = fromSource(source)\n if (typeof Buffer !== 'undefined') return Buffer.from(source).toString('hex')\n return Array.from(new Uint8Array(source), byte => byte.toString(16).padStart(2, '0')).join('')\n }\n\n export function fromHex(source: string) {\n if (typeof Buffer !== 'undefined') return fromSource(Buffer.from(source, 'hex'))\n const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1)\n const buffer: number[] = []\n for (let i = 0; i < hex.length; i += 2) {\n buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16))\n }\n return Uint8Array.from(buffer).buffer\n }\n}\n\n/** Decode a base64 string into binary data. */\nexport const base64ToArrayBuffer = Binary.fromBase64\n/** Encode binary data as base64. */\nexport const arrayBufferToBase64 = Binary.toBase64\n/** Decode a hex string into binary data. */\nexport const hexToArrayBuffer = Binary.fromHex\n/** Encode binary data as hex. */\nexport const arrayBufferToHex = Binary.toHex\n\n/** Deep-clone common JavaScript values while preserving prototypes. */\nexport function clone<T>(source: T): T\n/** Deep-clone common JavaScript values while preserving prototypes and cycles. */\nexport function clone(source: any, refs = new Map<any, any>()) {\n if (!source || typeof source !== 'object') return source\n if (is('Date', source)) return new Date(source.valueOf())\n if (is('RegExp', source)) return new RegExp(source.source, source.flags)\n if (isArrayBufferLike(source)) return source.slice(0)\n if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength)\n const cached = refs.get(source)\n if (cached) return cached\n if (Array.isArray(source)) {\n const result: any[] = []\n refs.set(source, result)\n source.forEach((value, index) => {\n result[index] = Reflect.apply(clone, null, [value, refs])\n })\n return result\n }\n const result = Object.create(Object.getPrototypeOf(source))\n refs.set(source, result)\n for (const key of Reflect.ownKeys(source)) {\n const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) }\n if ('value' in descriptor) {\n descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs])\n }\n Reflect.defineProperty(result, key, descriptor)\n }\n return result\n}\n\n/** Deeply compare arrays, dates, regexps, buffers, and plain object fields. */\nexport function deepEqual(a: any, b: any, strict?: boolean): boolean {\n if (a === b) return true\n if (!strict && isNullable(a) && isNullable(b)) return true\n if (typeof a !== typeof b) return false\n if (typeof a !== 'object') return false\n if (!a || !b) return false\n\n function check<T>(test: (x: any) => x is T, then: (a: T, b: T) => boolean) {\n return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : undefined\n }\n\n return check(Array.isArray, (a, b) => a.length === b.length && a.every((item, index) => deepEqual(item, b[index])))\n ?? check(is('Date'), (a, b) => a.valueOf() === b.valueOf())\n ?? check(is('RegExp'), (a, b) => a.source === b.source && a.flags === b.flags)\n ?? check(isArrayBufferLike, (a, b) => {\n if (a.byteLength !== b.byteLength) return false\n const viewA = new Uint8Array(a)\n const viewB = new Uint8Array(b)\n for (let i = 0; i < viewA.length; i++) {\n if (viewA[i] !== viewB[i]) return false\n }\n return true\n })\n ?? Object.keys({ ...a, ...b }).every(key => deepEqual(a[key], b[key], strict))\n}\n", "/** Time constants plus parsing and formatting helpers. */\nexport namespace Time {\n export const millisecond = 1\n export const second = 1000\n export const minute = second * 60\n export const hour = minute * 60\n export const day = hour * 24\n export const week = day * 7\n\n let timezoneOffset = new Date().getTimezoneOffset()\n\n export function setTimezoneOffset(offset: number) {\n timezoneOffset = offset\n }\n\n export function getTimezoneOffset() {\n return timezoneOffset\n }\n\n export function getDateNumber(date: number | Date = new Date(), offset?: number) {\n if (typeof date === 'number') date = new Date(date)\n if (offset === undefined) offset = timezoneOffset\n return Math.floor((date.valueOf() / minute - offset) / 1440)\n }\n\n export function fromDateNumber(value: number, offset?: number) {\n const date = new Date(value * day)\n if (offset === undefined) offset = timezoneOffset\n return new Date(+date + offset * minute)\n }\n\n const numeric = /\\d+(?:\\.\\d+)?/.source\n const timeRegExp = new RegExp(`^${[\n 'w(?:eek(?:s)?)?',\n 'd(?:ay(?:s)?)?',\n 'h(?:our(?:s)?)?',\n 'm(?:in(?:ute)?(?:s)?)?',\n 's(?:ec(?:ond)?(?:s)?)?',\n ].map(unit => `(${numeric}${unit})?`).join('')}$`)\n\n export function parseTime(source: string) {\n const capture = timeRegExp.exec(source)\n if (!capture) return 0\n return (parseFloat(capture[1]) * week || 0)\n + (parseFloat(capture[2]) * day || 0)\n + (parseFloat(capture[3]) * hour || 0)\n + (parseFloat(capture[4]) * minute || 0)\n + (parseFloat(capture[5]) * second || 0)\n }\n\n export function parseDate(date: string) {\n const parsed = parseTime(date)\n if (parsed) {\n date = Date.now() + parsed as any\n } else if (/^\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) {\n date = `${new Date().toLocaleDateString()}-${date}`\n } else if (/^\\d{1,2}-\\d{1,2}-\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) {\n date = `${new Date().getFullYear()}-${date}`\n }\n return date ? new Date(date) : new Date()\n }\n\n export function format(ms: number) {\n const abs = Math.abs(ms)\n if (abs >= day - hour / 2) {\n return Math.round(ms / day) + 'd'\n } else if (abs >= hour - minute / 2) {\n return Math.round(ms / hour) + 'h'\n } else if (abs >= minute - second / 2) {\n return Math.round(ms / minute) + 'm'\n } else if (abs >= second) {\n return Math.round(ms / second) + 's'\n }\n return ms + 'ms'\n }\n\n export function toDigits(source: number, length = 2) {\n return source.toString().padStart(length, '0')\n }\n\n export function template(template: string, time = new Date()) {\n return template\n .replace('yyyy', time.getFullYear().toString())\n .replace('yy', time.getFullYear().toString().slice(2))\n .replace('MM', toDigits(time.getMonth() + 1))\n .replace('dd', toDigits(time.getDate()))\n .replace('hh', toDigits(time.getHours()))\n .replace('mm', toDigits(time.getMinutes()))\n .replace('ss', toDigits(time.getSeconds()))\n .replace('SSS', toDigits(time.getMilliseconds(), 3))\n }\n}\n", "import { Binary, clone, deepEqual, filterKeys, isNullable, isPlainObject, pick, valueMap } from \"@deepseek-ai/cosmokit\";\n//#region lib/types/index.js\nconst kSchema = Symbol.for(\"schemastery\");\nconst kValidationError = Symbol.for(\"ValidationError\");\nglobalThis.__schemastery_index__ ??= 0;\nglobalThis.__schemastery_refs__ = void 0;\nvar ValidationError = class extends TypeError {\n\toptions;\n\tname = \"ValidationError\";\n\tconstructor(message, options) {\n\t\tlet prefix = \"$\";\n\t\tfor (const segment of options.path || []) if (typeof segment === \"string\") prefix += \".\" + segment;\n\t\telse if (typeof segment === \"number\") prefix += \"[\" + segment + \"]\";\n\t\telse if (typeof segment === \"symbol\") prefix += `[Symbol(${segment.toString()})]`;\n\t\tif (prefix.startsWith(\".\")) prefix = prefix.slice(1);\n\t\tsuper((prefix === \"$\" ? \"\" : `${prefix} `) + message);\n\t\tthis.options = options;\n\t}\n\tstatic is(error) {\n\t\treturn !!error?.[kValidationError];\n\t}\n};\nObject.defineProperty(ValidationError.prototype, kValidationError, { value: true });\nconst Schema = function(options) {\n\tconst schema = function(data, options = {}) {\n\t\treturn Schema.resolve(data, schema, options)[0];\n\t};\n\tif (options.refs) {\n\t\tconst refs = valueMap(options.refs, (options) => new Schema(options));\n\t\tconst getRef = (uid) => refs[uid];\n\t\tfor (const key in refs) {\n\t\t\tconst options = refs[key];\n\t\t\toptions.sKey = getRef(options.sKey);\n\t\t\toptions.inner = getRef(options.inner);\n\t\t\toptions.list = options.list && options.list.map(getRef);\n\t\t\toptions.dict = options.dict && valueMap(options.dict, getRef);\n\t\t}\n\t\treturn refs[options.uid];\n\t}\n\tObject.assign(schema, options);\n\tif (typeof schema.callback === \"string\") try {\n\t\tschema.callback = new Function(\"return \" + schema.callback)();\n\t} catch {}\n\tObject.defineProperty(schema, \"uid\", { value: globalThis.__schemastery_index__++ });\n\tObject.setPrototypeOf(schema, Schema.prototype);\n\tschema.meta ||= {};\n\tschema.toString = schema.toString.bind(schema);\n\treturn schema;\n};\nSchema.prototype = Object.create(Function.prototype);\nSchema.prototype[kSchema] = true;\nObject.defineProperty(Schema.prototype, \"~standard\", { get() {\n\treturn {\n\t\tversion: 1,\n\t\tvendor: \"schemastery\",\n\t\tvalidate: (value) => {\n\t\t\ttry {\n\t\t\t\treturn { value: Schema.resolve(value, this, {})[0] };\n\t\t\t} catch (error) {\n\t\t\t\tif (ValidationError.is(error)) return { issues: [{\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tpath: error.options.path\n\t\t\t\t}] };\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t};\n} });\nSchema.ValidationError = ValidationError;\nSchema.prototype.toJSON = function toJSON() {\n\tif (globalThis.__schemastery_refs__) {\n\t\tglobalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));\n\t\treturn this.uid;\n\t}\n\tglobalThis.__schemastery_refs__ = { [this.uid]: { ...this } };\n\tglobalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));\n\tconst result = {\n\t\tuid: this.uid,\n\t\trefs: globalThis.__schemastery_refs__\n\t};\n\tglobalThis.__schemastery_refs__ = void 0;\n\treturn result;\n};\nSchema.prototype.set = function set(key, value) {\n\tthis.dict[key] = value;\n\treturn this;\n};\nSchema.prototype.push = function push(value) {\n\tthis.list.push(value);\n\treturn this;\n};\nfunction mergeDesc(original, messages) {\n\tconst result = typeof original === \"string\" ? { \"\": original } : { ...original };\n\tfor (const locale in messages) {\n\t\tconst value = messages[locale];\n\t\tif (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;\n\t\telse if (typeof value === \"string\") result[locale] = value;\n\t}\n\treturn result;\n}\nfunction getInner(value) {\n\treturn value?.$value ?? value?.$inner;\n}\nfunction extractKeys(data) {\n\treturn filterKeys(data ?? {}, (key) => !key.startsWith(\"$\"));\n}\nSchema.prototype.i18n = function i18n(messages) {\n\tconst schema = Schema(this);\n\tconst desc = mergeDesc(schema.meta.description, messages);\n\tif (Object.keys(desc).length) schema.meta.description = desc;\n\tif (schema.dict) schema.dict = valueMap(schema.dict, (inner, key) => {\n\t\treturn inner.i18n(valueMap(messages, (data) => getInner(data)?.[key] ?? data?.[key]));\n\t});\n\tif (schema.list) schema.list = schema.list.map((inner, index) => {\n\t\treturn inner.i18n(valueMap(messages, (data = {}) => {\n\t\t\tif (Array.isArray(getInner(data))) return getInner(data)[index];\n\t\t\tif (Array.isArray(data)) return data[index];\n\t\t\treturn extractKeys(data);\n\t\t}));\n\t});\n\tif (schema.inner) schema.inner = schema.inner.i18n(valueMap(messages, (data) => {\n\t\tif (getInner(data)) return getInner(data);\n\t\treturn extractKeys(data);\n\t}));\n\tif (schema.sKey) schema.sKey = schema.sKey.i18n(valueMap(messages, (data) => data?.$key));\n\treturn schema;\n};\nSchema.prototype.extra = function extra(key, value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"required\",\n\t\"disabled\",\n\t\"collapse\",\n\t\"hidden\",\n\t\"loose\"\n]) Object.assign(Schema.prototype, { [key](value = true) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nSchema.prototype.deprecated = function deprecated() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"deprecated\",\n\t\ttype: \"danger\"\n\t});\n\treturn schema;\n};\nSchema.prototype.experimental = function experimental() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"experimental\",\n\t\ttype: \"warning\"\n\t});\n\treturn schema;\n};\nSchema.prototype.pattern = function pattern(regexp) {\n\tconst schema = Schema(this);\n\tconst pattern = pick(regexp, [\"source\", \"flags\"]);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\tpattern\n\t};\n\treturn schema;\n};\nSchema.prototype.simplify = function simplify(value) {\n\tif (deepEqual(value, this.meta.default, this.type === \"dict\")) return null;\n\tif (isNullable(value)) return value;\n\tif (this.type === \"object\" || this.type === \"dict\") {\n\t\tconst result = {};\n\t\tfor (const key in value) {\n\t\t\tconst item = (this.type === \"object\" ? this.dict[key] : this.inner)?.simplify(value[key]);\n\t\t\tif (this.type === \"dict\" || !isNullable(item)) result[key] = item;\n\t\t}\n\t\tif (deepEqual(result, this.meta.default, this.type === \"dict\")) return null;\n\t\treturn result;\n\t} else if (this.type === \"array\" || this.type === \"tuple\") {\n\t\tconst result = [];\n\t\tvalue.forEach((value, index) => {\n\t\t\tconst schema = this.type === \"array\" ? this.inner : this.list[index];\n\t\t\tconst item = schema ? schema.simplify(value) : value;\n\t\t\tresult.push(item);\n\t\t});\n\t\treturn result;\n\t} else if (this.type === \"intersect\") {\n\t\tconst result = {};\n\t\tfor (const item of this.list) Object.assign(result, item.simplify(value));\n\t\treturn result;\n\t} else if (this.type === \"union\") for (const schema of this.list) try {\n\t\tSchema.resolve(value, schema, {});\n\t\treturn schema.simplify(value);\n\t} catch {}\n\treturn value;\n};\nSchema.prototype.toString = function toString(inline) {\n\treturn formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;\n};\nSchema.prototype.role = function role(role, extra) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\trole,\n\t\textra\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"default\",\n\t\"link\",\n\t\"comment\",\n\t\"description\",\n\t\"max\",\n\t\"min\",\n\t\"step\"\n]) Object.assign(Schema.prototype, { [key](value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nconst resolvers = {};\nSchema.extend = function extend(type, resolve) {\n\tresolvers[type] = resolve;\n};\nSchema.resolve = function resolve(data, schema, options = {}, strict = false) {\n\tif (!schema) return [data];\n\tif (options.ignore?.(data, schema)) return [data];\n\tif (isNullable(data) && schema.type !== \"lazy\") {\n\t\tif (schema.meta.required) throw new ValidationError(`missing required value`, options);\n\t\tlet current = schema;\n\t\tlet fallback = schema.meta.default;\n\t\twhile (current?.type === \"intersect\" && isNullable(fallback)) {\n\t\t\tcurrent = current.list[0];\n\t\t\tfallback = current?.meta.default;\n\t\t}\n\t\tif (isNullable(fallback)) return [data];\n\t\tdata = clone(fallback);\n\t}\n\tconst callback = resolvers[schema.type];\n\tif (!callback) throw new ValidationError(`unsupported type \"${schema.type}\"`, options);\n\ttry {\n\t\treturn callback(data, schema, options, strict);\n\t} catch (error) {\n\t\tif (!schema.meta.loose) throw error;\n\t\treturn [schema.meta.default];\n\t}\n};\nSchema.from = function from(source) {\n\tif (isNullable(source)) return Schema.any();\n\telse if ([\n\t\t\"string\",\n\t\t\"number\",\n\t\t\"boolean\"\n\t].includes(typeof source)) return Schema.const(source).required();\n\telse if (source[kSchema]) return source;\n\telse if (typeof source === \"function\") switch (source) {\n\t\tcase String: return Schema.string().required();\n\t\tcase Number: return Schema.number().required();\n\t\tcase Boolean: return Schema.boolean().required();\n\t\tcase Function: return Schema.function().required();\n\t\tdefault: return Schema.is(source).required();\n\t}\n\telse throw new TypeError(`cannot infer schema from ${source}`);\n};\nSchema.lazy = function lazy(builder) {\n\tconst toJSON = () => {\n\t\tif (!schema.inner[kSchema]) {\n\t\t\tschema.inner = schema.builder();\n\t\t\tschema.inner.meta = {\n\t\t\t\t...schema.meta,\n\t\t\t\t...schema.inner.meta\n\t\t\t};\n\t\t}\n\t\treturn schema.inner.toJSON();\n\t};\n\tconst schema = new Schema({\n\t\ttype: \"lazy\",\n\t\tbuilder,\n\t\tinner: { toJSON }\n\t});\n\treturn schema;\n};\nSchema.natural = function natural() {\n\treturn Schema.number().step(1).min(0);\n};\nSchema.percent = function percent() {\n\treturn Schema.number().step(.01).min(0).max(1).role(\"slider\");\n};\nSchema.date = function date() {\n\treturn Schema.union([Schema.is(Date), Schema.transform(Schema.string().role(\"datetime\"), (value, options) => {\n\t\tconst date = new Date(value);\n\t\tif (isNaN(+date)) throw new ValidationError(`invalid date \"${value}\"`, options);\n\t\treturn date;\n\t}, true)]);\n};\nSchema.regExp = function regExp(flag = \"\") {\n\treturn Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role(\"regexp\", { flag }), (value, options) => {\n\t\ttry {\n\t\t\treturn new RegExp(value, flag);\n\t\t} catch (e) {\n\t\t\tthrow new ValidationError(e.message, options);\n\t\t}\n\t}, true)]);\n};\nSchema.arrayBuffer = function arrayBuffer(encoding) {\n\treturn Schema.union([\n\t\tSchema.is(ArrayBuffer),\n\t\tSchema.is(SharedArrayBuffer),\n\t\tSchema.transform(Schema.any(), (value, options) => {\n\t\t\tif (Binary.isSource(value)) return Binary.fromSource(value);\n\t\t\tthrow new ValidationError(`expected ArrayBufferSource but got ${value}`, options);\n\t\t}, true),\n\t\t...encoding ? [Schema.transform(Schema.string(), (value, options) => {\n\t\t\ttry {\n\t\t\t\treturn encoding === \"base64\" ? Binary.fromBase64(value) : Binary.fromHex(value);\n\t\t\t} catch (e) {\n\t\t\t\tthrow new ValidationError(e.message, options);\n\t\t\t}\n\t\t}, true)] : []\n\t]);\n};\nSchema.extend(\"lazy\", (data, schema, options, strict) => {\n\tif (!schema.inner[kSchema]) {\n\t\tschema.inner = schema.builder();\n\t\tschema.inner.meta = {\n\t\t\t...schema.meta,\n\t\t\t...schema.inner.meta\n\t\t};\n\t}\n\treturn Schema.resolve(data, schema.inner, options, strict);\n});\nSchema.extend(\"any\", (data) => {\n\treturn [data];\n});\nSchema.extend(\"never\", (data, _, options) => {\n\tthrow new ValidationError(`expected nullable but got ${data}`, options);\n});\nSchema.extend(\"const\", (data, { value }, options) => {\n\tif (deepEqual(data, value)) return [value];\n\tthrow new ValidationError(`expected ${value} but got ${data}`, options);\n});\nfunction checkWithinRange(data, meta, description, options, skipMin = false) {\n\tconst { max = Infinity, min = -Infinity } = meta;\n\tif (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);\n\tif (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);\n}\nSchema.extend(\"string\", (data, { meta }, options) => {\n\tif (typeof data !== \"string\") throw new ValidationError(`expected string but got ${data}`, options);\n\tif (meta.pattern) {\n\t\tconst regexp = new RegExp(meta.pattern.source, meta.pattern.flags);\n\t\tif (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);\n\t}\n\tcheckWithinRange(data.length, meta, \"string length\", options);\n\treturn [data];\n});\nfunction decimalShift(data, digits) {\n\tconst str = data.toString();\n\tif (str.includes(\"e\")) return data * Math.pow(10, digits);\n\tconst index = str.indexOf(\".\");\n\tif (index === -1) return data * Math.pow(10, digits);\n\tconst frac = str.slice(index + 1);\n\tconst integer = str.slice(0, index);\n\tif (frac.length <= digits) return +(integer + frac.padEnd(digits, \"0\"));\n\treturn +(integer + frac.slice(0, digits) + \".\" + frac.slice(digits));\n}\nfunction isMultipleOf(data, min, step) {\n\tstep = Math.abs(step);\n\tif (!/^\\d+\\.\\d+$/.test(step.toString())) return (data - min) % step === 0;\n\tconst index = step.toString().indexOf(\".\");\n\tconst digits = step.toString().slice(index + 1).length;\n\treturn Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;\n}\nSchema.extend(\"number\", (data, { meta }, options) => {\n\tif (typeof data !== \"number\") throw new ValidationError(`expected number but got ${data}`, options);\n\tcheckWithinRange(data, meta, \"number\", options);\n\tconst { step } = meta;\n\tif (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);\n\treturn [data];\n});\nSchema.extend(\"boolean\", (data, _, options) => {\n\tif (typeof data === \"boolean\") return [data];\n\tthrow new ValidationError(`expected boolean but got ${data}`, options);\n});\nSchema.extend(\"bitset\", (data, { bits, meta }, options) => {\n\tlet value = 0, keys = [];\n\tif (typeof data === \"number\") {\n\t\tvalue = data;\n\t\tfor (const key in bits) if (data & bits[key]) keys.push(key);\n\t} else if (Array.isArray(data)) {\n\t\tkeys = data;\n\t\tfor (const key of keys) {\n\t\t\tif (typeof key !== \"string\") throw new ValidationError(`expected string but got ${key}`, options);\n\t\t\tif (key in bits) value |= bits[key];\n\t\t}\n\t} else throw new ValidationError(`expected number or array but got ${data}`, options);\n\tif (value === meta.default) return [value];\n\treturn [value, keys];\n});\nSchema.extend(\"function\", (data, _, options) => {\n\tif (typeof data === \"function\") return [data];\n\tthrow new ValidationError(`expected function but got ${data}`, options);\n});\nSchema.extend(\"is\", (data, { constructor }, options) => {\n\tif (typeof constructor === \"function\") {\n\t\tif (data instanceof constructor) return [data];\n\t\tthrow new ValidationError(`expected ${constructor.name} but got ${data}`, options);\n\t} else {\n\t\tif (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t\tlet prototype = Object.getPrototypeOf(data);\n\t\twhile (prototype) {\n\t\t\tif (prototype.constructor?.name === constructor) return [data];\n\t\t\tprototype = Object.getPrototypeOf(prototype);\n\t\t}\n\t\tthrow new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t}\n});\nfunction property(data, key, schema, options) {\n\ttry {\n\t\tconst [value, adapted] = Schema.resolve(data[key], schema, {\n\t\t\t...options,\n\t\t\tpath: [...options.path || [], key]\n\t\t});\n\t\tif (adapted !== void 0) data[key] = adapted;\n\t\treturn value;\n\t} catch (e) {\n\t\tif (!options?.autofix) throw e;\n\t\tdelete data[key];\n\t\treturn schema.meta.default;\n\t}\n}\nSchema.extend(\"array\", (data, { inner, meta }, options) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tcheckWithinRange(data.length, meta, \"array length\", options, !isNullable(inner.meta.default));\n\treturn [data.map((_, index) => property(data, index, inner, options))];\n});\nSchema.extend(\"dict\", (data, { inner, sKey }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in data) {\n\t\tlet rKey;\n\t\ttry {\n\t\t\trKey = Schema.resolve(key, sKey, options)[0];\n\t\t} catch (error) {\n\t\t\tif (strict) continue;\n\t\t\tthrow error;\n\t\t}\n\t\tresult[rKey] = property(data, key, inner, options);\n\t\tdata[rKey] = data[key];\n\t\tif (key !== rKey) delete data[key];\n\t}\n\treturn [result];\n});\nSchema.extend(\"tuple\", (data, { list }, options, strict) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tconst result = list.map((inner, index) => property(data, index, inner, options));\n\tif (strict) return [result];\n\tresult.push(...data.slice(list.length));\n\treturn [result];\n});\nfunction merge(result, data) {\n\tfor (const key in data) {\n\t\tif (key in result) continue;\n\t\tresult[key] = data[key];\n\t}\n}\nSchema.extend(\"object\", (data, { dict }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in dict) {\n\t\tconst value = property(data, key, dict[key], options);\n\t\tif (!isNullable(value) || key in data) result[key] = value;\n\t}\n\tif (!strict) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"union\", (data, { list, toString }, options, strict) => {\n\tconst messages = [];\n\tfor (const inner of list) try {\n\t\treturn Schema.resolve(data, inner, options, strict);\n\t} catch (error) {\n\t\tmessages.push(error);\n\t}\n\tthrow new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n});\nSchema.extend(\"intersect\", (data, { list, toString }, options, strict) => {\n\tif (!list.length) return [data];\n\tlet result;\n\tfor (const inner of list) {\n\t\tconst value = Schema.resolve(data, inner, options, true)[0];\n\t\tif (isNullable(value)) continue;\n\t\tif (isNullable(result)) result = value;\n\t\telse if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t\telse if (typeof value === \"object\") merge(result ??= {}, value);\n\t\telse if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t}\n\tif (!strict && isPlainObject(data)) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"transform\", (data, { inner, callback, preserve }, options) => {\n\tconst [result, adapted = data] = Schema.resolve(data, inner, options, true);\n\tif (preserve) return [callback(result)];\n\telse return [callback(result), callback(adapted)];\n});\nconst formatters = {};\nfunction defineMethod(name, keys, format) {\n\tformatters[name] = format;\n\tObject.assign(Schema, { [name](...args) {\n\t\tconst schema = new Schema({ type: name });\n\t\tkeys.forEach((key, index) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase \"sKey\":\n\t\t\t\t\tschema.sKey = args[index] ?? Schema.string();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"inner\":\n\t\t\t\t\tschema.inner = Schema.from(args[index]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"list\":\n\t\t\t\t\tschema.list = args[index].map(Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"dict\":\n\t\t\t\t\tschema.dict = valueMap(args[index], Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"bits\":\n\t\t\t\t\tschema.bits = {};\n\t\t\t\t\tfor (const key in args[index]) {\n\t\t\t\t\t\tif (typeof args[index][key] !== \"number\") continue;\n\t\t\t\t\t\tschema.bits[key] = args[index][key];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"callback\": {\n\t\t\t\t\tconst callback = schema.callback = args[index];\n\t\t\t\t\tcallback[\"toJSON\"] ||= () => callback.toString();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"constructor\": {\n\t\t\t\t\tconst constructor = schema.constructor = args[index];\n\t\t\t\t\tif (typeof constructor === \"function\") constructor[\"toJSON\"] ||= () => constructor[\"name\"];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: schema[key] = args[index];\n\t\t\t}\n\t\t});\n\t\tif (name === \"object\" || name === \"dict\") schema.meta.default = {};\n\t\telse if (name === \"array\" || name === \"tuple\") schema.meta.default = [];\n\t\telse if (name === \"bitset\") schema.meta.default = 0;\n\t\treturn schema;\n\t} });\n}\ndefineMethod(\"is\", [\"constructor\"], ({ constructor }) => {\n\tif (typeof constructor === \"function\") return constructor.name;\n\telse return constructor;\n});\ndefineMethod(\"any\", [], () => \"any\");\ndefineMethod(\"never\", [], () => \"never\");\ndefineMethod(\"const\", [\"value\"], ({ value }) => typeof value === \"string\" ? JSON.stringify(value) : value);\ndefineMethod(\"string\", [], () => \"string\");\ndefineMethod(\"number\", [], () => \"number\");\ndefineMethod(\"boolean\", [], () => \"boolean\");\ndefineMethod(\"bitset\", [\"bits\"], () => \"bitset\");\ndefineMethod(\"function\", [], () => \"function\");\ndefineMethod(\"array\", [\"inner\"], ({ inner }) => `${inner.toString(true)}[]`);\ndefineMethod(\"dict\", [\"inner\", \"sKey\"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);\ndefineMethod(\"tuple\", [\"list\"], ({ list }) => `[${list.map((inner) => inner.toString()).join(\", \")}]`);\ndefineMethod(\"object\", [\"dict\"], ({ dict }) => {\n\tif (Object.keys(dict).length === 0) return \"{}\";\n\treturn `{ ${Object.entries(dict).map(([key, inner]) => {\n\t\treturn `${key}${inner.meta.required ? \"\" : \"?\"}: ${inner.toString()}`;\n\t}).join(\", \")} }`;\n});\ndefineMethod(\"union\", [\"list\"], ({ list }, inline) => {\n\tconst result = list.map(({ toString: format }) => format()).join(\" | \");\n\treturn inline ? `(${result})` : result;\n});\ndefineMethod(\"intersect\", [\"list\"], ({ list }) => {\n\treturn `${list.map((inner) => inner.toString(true)).join(\" & \")}`;\n});\ndefineMethod(\"transform\", [\n\t\"inner\",\n\t\"callback\",\n\t\"preserve\"\n], ({ inner }, isInner) => inner.toString(isInner));\n//#endregion\nexport { Schema as default };\n"],
|
|
5
|
+
"mappings": ";AAcA,SAAkB,eAA8B;AACh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;AACrC,WAAK,iBAAiB;AACtB,WAAK,KAAK;AAAA,IACZ,GAAG,KAAK;AAAA,EACV;AACF;AAQA,SAAS,gBAAgB,GAAW,GAAoB;AACtD,SAAO,kBAAkB,WAAW,QAAQ,EAAE,OAAO,GAAG,MAAM,EAAE,OAAO,GAAG,WAAW,QAAQ,EAAE,OAAO,GAAG,MAAM,EAAE,OAAO,CAAC;AAC3H;AAcO,SAAS,QAAQ,QAAqB;AAC3C,QAAM,MAAM,IAAI,IAAI,cAAc,MAAM;AACxC,MAAI,IAAI,aAAa,QAAS,KAAI,WAAW;AAAA,WACpC,IAAI,aAAa,SAAU,KAAI,WAAW;AACnD,MAAI,IAAI,aAAa,SAAS,IAAI,aAAa,QAAQ;AACrD,UAAM,IAAI,UAAU,kDAAkD,IAAI,QAAQ,EAAE;AAAA,EACtF;AACA,SAAO;AACT;AAEA,SAAS,SAAS,SAAyB;AACzC,SAAO,QAAQ,QAAQ,QAAQ,EAAE;AACnC;AAEA,IAAO,gBAAQ;",
|
|
6
6
|
"names": ["value", "Binary", "result", "a", "b", "Time", "date", "template", "options", "pattern", "value", "extra", "resolve", "toJSON", "date", "toString", "key", "resolve"]
|
|
7
7
|
}
|