dsh-interconnect 0.1.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/LICENSE +21 -0
- package/README.md +63 -0
- package/cordis.patch.yml +12 -0
- package/dsh.plugin.json +9 -0
- package/lib/index.js +1342 -0
- package/lib/interconnect/index.js +1343 -0
- package/lib/interconnect/index.js.map +7 -0
- package/lib/interconnect/invariant.js +25 -0
- package/lib/interconnect/invariant.js.map +7 -0
- package/lib/tool-interconnect/index.js +84 -0
- package/lib/tool-interconnect/index.js.map +7 -0
- package/lib/tool-interconnect/invariant.js +13 -0
- package/lib/tool-interconnect/invariant.js.map +7 -0
- package/lib/types/index.d.ts +9 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/interconnect/index.d.ts +106 -0
- package/lib/types/interconnect/index.d.ts.map +1 -0
- package/lib/types/interconnect/invariant.d.ts +16 -0
- package/lib/types/interconnect/invariant.d.ts.map +1 -0
- package/lib/types/interconnect/types.d.ts +132 -0
- package/lib/types/interconnect/types.d.ts.map +1 -0
- package/lib/types/tool-interconnect/index.d.ts +21 -0
- package/lib/types/tool-interconnect/index.d.ts.map +1 -0
- package/lib/types/tool-interconnect/invariant.d.ts +16 -0
- package/lib/types/tool-interconnect/invariant.d.ts.map +1 -0
- package/package.json +76 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/interconnect/index.ts", "../../../.dsh/source/staging-20260807T143236Z/vendor/cosmokit/src/misc.ts", "../../../.dsh/source/staging-20260807T143236Z/vendor/cosmokit/src/types.ts", "../../../.dsh/source/staging-20260807T143236Z/vendor/cosmokit/src/time.ts", "../../../.dsh/source/staging-20260807T143236Z/vendor/schemastery/lib/index.mjs", "../../src/interconnect/types.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Cross-instance message handoff service: inbound half owns one HTTP route on\n * the host webserver and delivers authenticated messages into live sessions;\n * outbound half POSTs the same wire shape to a peer instance.\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 HTTP\n * route keeps bearer-token auth at the boundary where the header is readable\n * and fails closed when the token is unconfigured.\n * @module @deepseek-ai/dsh-interconnect\n */\n\nimport { Context, Service } from '@deepseek-ai/cordis'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Duplex } from 'node:stream'\nimport type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'\nimport {\n clientRequestSchema,\n serverResponseSchema,\n RpcId,\n type RpcError,\n} from '@deepseek-ai/dsh-host-apiproxy/api'\nimport { credentialRef } from '@deepseek-ai/dsh-credentials'\nimport { createUserMessage } from '@deepseek-ai/dsh-llm'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\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 INTERCONNECT_CHANNEL,\n INTERCONNECT_TOKEN_REF,\n type Config,\n type EventNotification,\n type EventPayload,\n type LinkFrame,\n type PingResult,\n type SendPayload,\n type SendResult,\n type SendRequest,\n type WebSocketLinkHandle,\n} from './types.ts'\n\nexport type * from './types.ts'\nexport { INTERCONNECT_CHANNEL, INTERCONNECT_TOKEN_REF } from './types.ts'\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 may react but must not block the HTTP ack.\n */\n 'interconnect/event'(notification: EventNotification, peer: string): void\n }\n}\n\nconst INVALID_REQUEST_RPC_ID = RpcId('invalid-request')\n/** Headroom for the request body so a malicious sender cannot pin the process. */\nconst MAX_REQUEST_BODY_BYTES = 1024 * 1024\n\n/** WebSocket upgrade pathname owning the persistent peer link. */\nconst LINK_CHANNEL = '/interconnect/link'\n\n/** Wire union for the discriminated EventNotification fact (shared by HTTP and WS). */\nconst notificationSchema = z.union([\n z.object({ kind: z.const('agent/created'), sessionId: z.string() }),\n z.object({ kind: z.const('agent/disposed'), sessionId: z.string() }),\n z.object({ kind: z.const('agent/status'), sessionId: z.string(), status: z.union([z.const('idle'), z.const('running')]) }),\n z.object({ kind: z.const('session/created'), sessionId: z.string(), parentSessionId: z.string() }),\n z.object({ kind: z.const('session/disposed'), sessionId: z.string() }),\n z.object({ kind: z.const('subagent/end'), provider: z.string(), childSessionId: z.string(), stopReason: z.string() }),\n])\n\n/** Wire union for one WebSocket link text frame. */\nconst linkFrameSchema = z.union([\n z.object({ type: z.const('hello'), sender: z.string() }),\n z.object({ type: z.const('event'), notification: notificationSchema }),\n])\n\n/** Wire union the send endpoint expects inside the ClientRequest payload slot. */\nconst sendPayloadSchema = z.object({\n sessionId: z.string(),\n text: z.string(),\n})\n\n/** Wire union the event endpoint expects \u2014 sender identity wrapping a discriminated fact. */\nconst eventPayloadSchema = z.object({\n sender: z.string(),\n notification: notificationSchema,\n})\n\n/**\n * Live cross-instance handoff service, registered as `ctx.interconnect`.\n * Requires the host webserver, the live agent registry, and the credential\n * store; activation is availability-driven like every other host service.\n */\nexport class InterconnectService extends Service {\n static inject = ['webServer', 'agents', 'credentials']\n static Config: z<Config> = z.object({\n instanceId: z.string().default('dsh'),\n requestTimeoutMs: z.natural().max(60000).default(10000),\n peers: z.array(z.string()).default([]),\n delivery: z.union([z.const('followup'), z.const('inject')]).default('followup'),\n })\n\n private readonly instanceId: string\n private readonly requestTimeoutMs: number\n private readonly delivery: 'followup' | 'inject'\n private readonly peers = new Set<string>()\n private readonly subscriptions: (() => void)[] = []\n private readonly server = new WebSocketServer({ noServer: true })\n private readonly sockets = new Set<WebSocket>()\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\n constructor(ctx: Context, config: Config) {\n super(ctx, 'interconnect')\n this.instanceId = config.instanceId\n this.requestTimeoutMs = config.requestTimeoutMs\n this.delivery = config.delivery ?? 'followup'\n for (const peer of config.peers ?? []) this.peers.add(trimBase(peer))\n\n const route: WebRoute = {\n kind: 'prefix',\n path: INTERCONNECT_CHANNEL,\n handler: (req, res) => this.handle(req, res),\n }\n ctx.effect(() => ctx.webServer.register(route), 'interconnect: /interconnect route')\n\n const upgrade: WebUpgradeRoute = {\n path: LINK_CHANNEL,\n handler: (req, socket, head) => { void this.handleUpgrade(req, socket, head) },\n }\n ctx.effect(() => ctx.webServer.registerUpgrade(upgrade), 'interconnect: /interconnect/link websocket')\n\n // Liveness sweep: terminate sockets that stopped answering protocol pings.\n this.heartbeatTimer = setInterval(() => {\n for (const socket of this.sockets) {\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 this.subscriptions.push(ctx.on('agent/status', ({ agent, status }) => {\n this.fanout({ kind: 'agent/status', sessionId: String(agent.session.id), status })\n }))\n this.subscriptions.push(ctx.on('agent/created', ({ agent }) => {\n this.fanout({ kind: 'agent/created', sessionId: String(agent.session.id) })\n }))\n this.subscriptions.push(ctx.on('agent/disposed', ({ agent }) => {\n this.fanout({ kind: 'agent/disposed', sessionId: String(agent.session.id) })\n }))\n this.subscriptions.push(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 this.subscriptions.push(ctx.on('session/disposed', (session: Session) => {\n this.fanout({ kind: 'session/disposed', sessionId: String(session.id) })\n }))\n this.subscriptions.push(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 // Clean up the event listeners with the service fiber.\n ctx.effect(() => () => {\n for (const dispose of this.subscriptions.splice(0)) dispose()\n }, 'interconnect: event subscriptions')\n\n // Terminate every live socket, outbound dial loop, and the no-server\n // acceptor when the service fiber unwinds.\n ctx.effect(() => () => {\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 }, 'interconnect: websocket teardown')\n }\n\n async send(request: SendRequest): Promise<SendResult> {\n const payload: SendPayload = { sessionId: request.sessionId, text: request.text }\n const result = await this.post<SendResult>(request.baseUrl, 'send', payload)\n return result ?? { delivered: false, instance: this.instanceId }\n }\n\n async ping(baseUrl: string): Promise<PingResult | undefined> {\n return this.post<PingResult>(baseUrl, 'ping', {})\n }\n\n /**\n * Add a peer origin to the event fan-out set at runtime. Returns a disposer\n * that removes it. Duplicate origins are idempotent.\n * @param peer - receiver origin, e.g. `http://127.0.0.1:3080`.\n * @returns disposer removing the peer from the fan-out set.\n */\n subscribe(peer: string): () => void {\n const trimmed = trimBase(peer)\n this.peers.add(trimmed)\n return () => { this.peers.delete(trimmed) }\n }\n\n /** Remove a peer origin from the event fan-out set. */\n unsubscribe(peer: string): void {\n this.peers.delete(trimBase(peer))\n }\n\n /**\n * Open (and, on drop, re-open) a persistent WebSocket link to a peer. Local\n * events stream over the link in real time, and events the peer pushes are\n * surfaced as `interconnect/event`. Repeating for the same peer returns the\n * existing handle.\n * @param peer - receiver origin, e.g. `http://127.0.0.1:3080` (dialed as `ws:`).\n * @returns a handle closing the link and cancelling reconnection.\n */\n link(peer: string): WebSocketLinkHandle {\n const trimmed = trimBase(peer)\n const existing = this.linkStates.get(trimmed)\n if (existing !== undefined) return existing\n const state = new LinkState(this, trimmed)\n this.linkStates.set(trimmed, state)\n state.dial()\n return state\n }\n\n /** Remove a closed outbound link's state so a later `link` re-dials fresh. */\n forgetLink(peer: string): void {\n this.linkStates.delete(peer)\n }\n\n /** Fan one serialized lifecycle fact out to every registered peer, fire-and-forget. */\n private fanout(notification: EventNotification): void {\n const payload: EventPayload = { sender: this.instanceId, notification }\n for (const peer of this.peers) {\n void this.post(peer, 'event', payload)\n }\n this.broadcast(notification)\n }\n\n /** Push one fact over every live WebSocket link, dropping closed sockets. */\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 for (const socket of this.sockets) {\n if (socket.readyState !== WebSocket.OPEN) {\n this.sockets.delete(socket)\n continue\n }\n socket.send(encoded)\n }\n }\n\n /** Inbound route handler: bearer auth first, then envelope dispatch. */\n private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const token = await this.resolveToken()\n if (token === undefined) {\n res.writeHead(403)\n res.end('forbidden')\n return\n }\n const expected = `Bearer ${token}`\n const header = req.headers.authorization\n // Timing-safe compare so an attacker cannot siphon the token by timing.\n if (header === undefined || !timingSafeEqual(header, expected)) {\n res.writeHead(401)\n res.end('unauthorized')\n return\n }\n await this.dispatch(req, res)\n }\n\n /** Parse the ClientRequest envelope and route to the named endpoint. */\n private async dispatch(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const pathname = new URL(req.url ?? '/', 'http://dsh.internal').pathname\n const endpoint = endpointFromPath(INTERCONNECT_CHANNEL, pathname)\n if (req.method !== 'POST' || endpoint === undefined) {\n res.writeHead(404)\n res.end('not found')\n return\n }\n\n const mediaType = (req.headers['content-type'] ?? '').split(';', 1)[0]?.trim().toLowerCase()\n if (mediaType !== 'application/json') {\n res.writeHead(415)\n res.end('content type must be application/json')\n return\n }\n\n const body = await readBody(req)\n if (body === undefined) {\n res.writeHead(413)\n res.end('body too large')\n return\n }\n\n let envelope: { rpcId: unknown; method: unknown; payload: unknown }\n try {\n envelope = JSON.parse(body) as { rpcId: unknown; method: unknown; payload: unknown }\n } catch {\n res.writeHead(400)\n res.end('body is not JSON')\n return\n }\n\n const parsed = clientRequestSchema.safeParse(envelope)\n const rpcId = typeof envelope.rpcId === 'string' ? RpcId(envelope.rpcId) : INVALID_REQUEST_RPC_ID\n if (!parsed.success) {\n writeError(res, rpcId, {\n code: 'bad-request',\n message: 'invalid client-request message',\n details: { issues: parsed.error.issues },\n })\n return\n }\n if (parsed.data.method !== endpoint) {\n writeError(res, rpcId, {\n code: 'bad-request',\n message: `method ${JSON.stringify(parsed.data.method)} does not match endpoint ${JSON.stringify(endpoint)}`,\n details: { issues: [] },\n })\n return\n }\n\n try {\n const value = this.runEndpoint(endpoint, parsed.data.payload)\n writeFull(res, rpcId, { ok: true, value })\n } catch (error) {\n if (error instanceof UnknownEndpointError) {\n res.writeHead(404)\n res.end('not found')\n return\n }\n this.ctx.logger.warn(error instanceof Error ? error : new Error(String(error)))\n writeError(res, rpcId, {\n code: 'internal',\n message: error instanceof Error ? error.message : String(error),\n details: {},\n })\n }\n }\n\n /** Dispatch one authenticated business call. */\n private runEndpoint(endpoint: string, payload: unknown): unknown {\n if (endpoint === 'ping') {\n return { pong: true, instance: this.instanceId }\n }\n if (endpoint === 'send') {\n let parsed: SendPayload\n try {\n parsed = z.resolve(payload, sendPayloadSchema, {})[0] as SendPayload\n } catch (error) {\n throw new Error(`send payload invalid: ${error instanceof Error ? error.message : String(error)}`)\n }\n return this.deliver(parsed)\n }\n if (endpoint === 'event') {\n let eventPayload: EventPayload\n try {\n eventPayload = z.resolve(payload, eventPayloadSchema, {})[0] as EventPayload\n } catch (error) {\n throw new Error(`event payload invalid: ${error instanceof Error ? error.message : String(error)}`)\n }\n this.receiveEvent(eventPayload)\n return { accepted: true }\n }\n throw new UnknownEndpointError(endpoint)\n }\n\n /** Surface one remote notification to local listeners and the log. */\n private receiveEvent(eventPayload: EventPayload): void {\n this.ctx.logger.info(`interconnect: remote event ${eventPayload.notification.kind} from ${eventPayload.sender}`)\n this.ctx.emit('interconnect/event', eventPayload.notification, eventPayload.sender)\n }\n\n /** Deliver one message to a live local session, if it exists. */\n private deliver(payload: SendPayload): SendResult {\n const agent = this.ctx.agents.get(payload.sessionId as Agent['id'])\n if (agent === undefined) {\n return { delivered: false, instance: this.instanceId }\n }\n const message = createUserMessage({\n source: { kind: 'user' },\n content: [{ type: 'text', text: payload.text }],\n })\n if (this.delivery === 'inject') {\n agent.inject(message)\n } else {\n agent.followup(message)\n }\n return { delivered: true, instance: this.instanceId }\n }\n\n /** POST one business call to a peer instance; undefined on transport/auth failure. */\n private async post<T>(baseUrl: string, endpoint: string, payload: unknown): Promise<T | undefined> {\n const token = await this.resolveToken()\n if (token === undefined) return undefined\n const url = `${trimBase(baseUrl)}${INTERCONNECT_CHANNEL}/${endpoint}`\n const envelope = {\n type: 'client-request',\n rpcId: crypto.randomUUID(),\n method: endpoint,\n payload,\n }\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(envelope),\n signal: AbortSignal.timeout(this.requestTimeoutMs),\n })\n if (!response.ok) return undefined\n const body = (await response.json()) as { result?: { ok?: boolean; value?: unknown } }\n if (body.result?.ok !== true) return undefined\n return body.result.value as T\n } catch (error) {\n this.ctx.logger.warn(`interconnect: ${endpoint} to ${baseUrl} failed: ${error instanceof Error ? error.message : String(error)}`)\n return undefined\n }\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 /** Resolve the shared token for an outbound dial (same source as inbound). */\n resolveTokenForDial(): Promise<string | undefined> {\n return this.resolveToken()\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 const token = await this.resolveToken()\n if (token === undefined) {\n socket.end('HTTP/1.1 403 Forbidden\\r\\nConnection: close\\r\\nContent-Length: 9\\r\\n\\r\\nforbidden')\n return\n }\n const expected = `Bearer ${token}`\n const header = req.headers.authorization\n if (header === undefined || !timingSafeEqual(header, expected)) {\n socket.end('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 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.\n */\n 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) => {\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): void {\n if (Array.isArray(data)) return // binary frames are a protocol violation; ignore\n const text = Buffer.isBuffer(data) ? data.toString('utf8') : Buffer.from(data).toString('utf8')\n let frame: LinkFrame\n try {\n frame = z.resolve(JSON.parse(text), linkFrameSchema, {})[0] as LinkFrame\n } catch {\n this.ctx.logger.warn('interconnect: dropping malformed link frame')\n return\n }\n if (frame.type === 'hello') {\n this.peerOf.set(socket, frame.sender)\n return\n }\n const sender = this.peerOf.get(socket) ?? 'unknown-peer'\n this.receiveEvent({ sender, notification: frame.notification })\n }\n}\n\n/** Thrown for an endpoint this channel does not own; mapped to HTTP 404. */\nclass UnknownEndpointError extends Error {\n constructor(endpoint: string) {\n super(`unknown interconnect endpoint ${JSON.stringify(endpoint)}`)\n this.name = 'UnknownEndpointError'\n }\n}\n\n/**\n * One outbound WebSocket peer link: dials, re-dials with backoff after an\n * unexpected drop, and pushes local events over the live socket. The owning\n * service streams events via {@link InterconnectService.broadcast} only to\n * sockets it accepted; this dialer keeps its own socket OUT of that set and\n * instead subscribes to local events through the service's fan-out via a\n * dedicated route below.\n */\nclass LinkState implements WebSocketLinkHandle {\n private socket: WebSocket | undefined\n private closed = false\n private retry = 0\n private reconnectTimer: ReturnType<typeof setTimeout> | undefined\n\n readonly peer: string\n\n constructor(\n private readonly owner: InterconnectService,\n peer: string,\n ) {\n this.peer = peer\n }\n\n /** Open the socket; reconnect is scheduled by the close handler. */\n dial(): void {\n if (this.closed) return\n const url = new URL('/interconnect/link', this.peer)\n url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'\n void this.owner.resolveTokenForDial().then((token) => {\n if (token === undefined || this.closed) return\n const socket = new WebSocket(url, {\n headers: { authorization: `Bearer ${token}` },\n })\n this.socket = socket\n socket.once('open', () => {\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.owner.attachSocket(socket)\n })\n socket.once('close', () => {\n if (this.closed) return\n this.scheduleReconnect()\n })\n socket.on('error', () => {\n // close follows; reconnect is scheduled there.\n })\n })\n }\n\n close(): void {\n this.closed = true\n this.owner.forgetLink(this.peer)\n if (this.reconnectTimer !== undefined) clearTimeout(this.reconnectTimer)\n const socket = this.socket\n if (socket !== undefined) {\n socket.removeAllListeners()\n socket.terminate()\n }\n }\n\n private scheduleReconnect(): void {\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\nfunction endpointFromPath(channel: string, pathname: string): string | undefined {\n if (!pathname.startsWith(`${channel}/`)) return undefined\n return pathname.slice(channel.length + 1)\n}\n\n/** Read a request body up to the cap; undefined when it exceeds the cap. */\nasync function readBody(req: IncomingMessage): Promise<string | undefined> {\n let size = 0\n const chunks: Buffer[] = []\n for await (const chunk of req) {\n const buffer = chunk as Buffer\n size += buffer.byteLength\n if (size > MAX_REQUEST_BODY_BYTES) return undefined\n chunks.push(buffer)\n }\n return Buffer.concat(chunks).toString()\n}\n\n/** Constant-time string comparison over the ASCII-encoded lengths. */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i += 1) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n }\n return diff === 0\n}\n\nfunction trimBase(baseUrl: string): string {\n return baseUrl.replace(/\\/+$/, '')\n}\n\nfunction writeFull(\n res: ServerResponse,\n rpcId: unknown,\n result: { ok: true; value?: unknown } | { ok: false; error: RpcError },\n): void {\n const body = serverResponseSchema.parse({\n type: 'server-response',\n rpcId,\n result,\n })\n res.writeHead(200, { 'content-type': 'application/json' })\n res.end(JSON.stringify(body))\n}\n\nfunction writeError(res: ServerResponse, rpcId: unknown, error: RpcError): void {\n writeFull(res, rpcId, { ok: false, error })\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", "/**\n * Wire contracts for `@deepseek-ai/dsh-interconnect`.\n * The transport reuses the Connection RPC envelope (`ClientRequest` /\n * `ServerResponse` from `@deepseek-ai/dsh-host-apiproxy/api`); this module\n * defines only the business payloads that ride inside that envelope.\n * @module @deepseek-ai/dsh-interconnect\n */\n\n/**\n * Logical HTTP route prefix this service owns. Requests reach endpoints as\n * `<baseURL>/interconnect/<endpoint>`.\n */\nexport const INTERCONNECT_CHANNEL = '/interconnect'\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\n/**\n * Business payload for the `send` endpoint: deliver one text message to one\n * live session of the receiving instance.\n */\nexport interface SendPayload {\n /** Target session id on the receiving instance. */\n readonly sessionId: string\n /** Message text delivered to the peer session's inbox. */\n readonly text: string\n}\n\n/** Business result of a `send` endpoint call. */\nexport interface SendResult {\n /** True when the target session is live on the receiving instance and the message was delivered. */\n readonly delivered: boolean\n /** Echoed receiver instance id (diagnostic; never trusted for routing). */\n readonly instance: string\n}\n\n/** Business result of a `ping` endpoint call. */\nexport interface PingResult {\n /** Always true for an authenticated, live receiver. */\n readonly pong: true\n /** The receiving instance's self-reported id. */\n readonly instance: string\n}\n\n/** Outbound delivery request: receiver origin plus a `send` business payload. */\nexport interface SendRequest {\n /** Receiver origin, e.g. `http://127.0.0.1:3080`. */\n readonly baseUrl: string\n readonly sessionId: string\n readonly text: string\n}\n\n/**\n * One serializable lifecycle fact pushed from an emitting instance to its\n * peers. `kind` discriminates the union; the remaining fields are the compact\n * facts extractable from the source event without serializing live objects.\n */\nexport type EventNotification =\n | { readonly kind: 'agent/created'; readonly sessionId: string }\n | { readonly kind: 'agent/disposed'; readonly sessionId: string }\n | { readonly kind: 'agent/status'; readonly sessionId: string; readonly status: 'idle' | 'running' }\n | { readonly kind: 'session/created'; readonly sessionId: string; readonly parentSessionId?: string }\n | { readonly kind: 'session/disposed'; readonly sessionId: string }\n | { readonly kind: 'subagent/end'; readonly provider: string; readonly childSessionId: string; readonly stopReason: string }\n\n/**\n * Wire payload for the `event` endpoint: the pushed fact plus the emitting\n * instance's self-reported id, so a many-upstream receiver can attribute it.\n */\nexport interface EventPayload {\n /** Emitting instance's self-reported id. */\n readonly sender: string\n /** The serialized lifecycle fact. */\n readonly notification: EventNotification\n}\n\n/**\n * One text frame exchanged over a persistent WebSocket peer link. `hello`\n * opens a link with the dialing side's identity; `event` pushes one\n * notification in either direction. Native ws ping/pong carries the heartbeat,\n * so no application-level keepalive frame exists.\n */\nexport type LinkFrame =\n | { readonly type: 'hello'; readonly sender: string }\n | { readonly type: 'event'; readonly notification: EventNotification }\n\n/**\n * Handle to one established outbound WebSocket peer link. `close` tears the\n * socket down and cancels reconnection; `peer` records the dialed receiver.\n */\nexport interface WebSocketLinkHandle {\n /** The dialed peer origin. */\n readonly peer: string\n /** Terminate the socket and stop reconnect attempts. */\n close(): void\n}\n\n/** Service config bound by the Composition loader. */\nexport interface Config {\n /** Self-reported id of this instance, echoed in ping/send results for diagnostics. */\n readonly instanceId: string\n /** Request timeout for outbound deliveries, in milliseconds. */\n readonly requestTimeoutMs: number\n /**\n * Peer instance origins to fan local events out to at startup. A runtime\n * `subscribe` can extend the set without restart; an unset list fans nothing\n * out until a peer subscribes.\n */\n readonly peers?: string[]\n /**\n * How an inbound `send` message reaches its target session.\n * - `followup` wakes the target agent into a new turn carrying the message.\n * - `inject` seeds model-facing context without waking the agent (it is\n * claimed at the next step boundary, and may miss a step already claimed).\n */\n readonly delivery?: 'followup' | 'inject'\n}\n"],
|
|
5
|
+
"mappings": ";AAcA,SAAkB,eAAe;AAIjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,qBAAqB;AAC9B,SAAS,yBAAyB;;;ACN3B,SAAS,WAAW,OAA8C;AACvE,SAAO,UAAU,QAAQ,UAAU;AACrC;AAQO,SAAS,cAAc,MAA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,MAAI,CAAC,SAAS,WAAW,GAAG,OAAO,GAAG,EAAG,QAAO;AAChD,SAAO,SAAS,MAAM,QAAQ,SAAS,CAAC;AAC1C;AAGA,eAAe,SAAS,KAAmD;AACzE,MAAI,OAAO;AACX,QAAM,SAAmB,CAAC;AAC1B,mBAAiB,SAAS,KAAK;AAC7B,UAAM,SAAS;AACf,YAAQ,OAAO;AACf,QAAI,OAAO,uBAAwB,QAAO;AAC1C,WAAO,KAAK,MAAM;AAAA,EACpB;AACA,SAAO,OAAO,OAAO,MAAM,EAAE,SAAS;AACxC;AAGA,SAAS,gBAAgB,GAAW,GAAoB;AACtD,MAAI,EAAE,WAAW,EAAE,OAAQ,QAAO;AAClC,MAAI,OAAO;AACX,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK,GAAG;AACpC,YAAQ,EAAE,WAAW,CAAC,IAAI,EAAE,WAAW,CAAC;AAAA,EAC1C;AACA,SAAO,SAAS;AAClB;AAEA,SAAS,SAAS,SAAyB;AACzC,SAAO,QAAQ,QAAQ,QAAQ,EAAE;AACnC;AAEA,SAAS,UACP,KACA,OACA,QACM;AACN,QAAM,OAAO,qBAAqB,MAAM;AAAA,IACtC,MAAM;AAAA,IACN;AAAA,IACA;AAAA,EACF,CAAC;AACD,MAAI,UAAU,KAAK,EAAE,gBAAgB,mBAAmB,CAAC;AACzD,MAAI,IAAI,KAAK,UAAU,IAAI,CAAC;AAC9B;AAEA,SAAS,WAAW,KAAqB,OAAgB,OAAuB;AAC9E,YAAU,KAAK,OAAO,EAAE,IAAI,OAAO,MAAM,CAAC;AAC5C;AAEA,IAAO,gBAAQ;",
|
|
6
|
+
"names": ["value", "Binary", "result", "a", "b", "Time", "date", "template", "options", "pattern", "value", "extra", "resolve", "toJSON", "date", "toString", "key"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// src/interconnect/invariant.ts
|
|
2
|
+
var PACKAGE_NAME = "@deepseek-ai/dsh-interconnect";
|
|
3
|
+
var name = "interconnect-invariant";
|
|
4
|
+
var inject = ["invariants"];
|
|
5
|
+
var install = (ctx, fail) => {
|
|
6
|
+
ctx.on("internal/plugin", () => {
|
|
7
|
+
const server = ctx.get("webServer");
|
|
8
|
+
if (server === void 0) return;
|
|
9
|
+
const probe = { kind: "exact", path: "/__dsh_interconnect_invariant_probe__", handler: () => {
|
|
10
|
+
} };
|
|
11
|
+
try {
|
|
12
|
+
server.register(probe)();
|
|
13
|
+
server.register(probe)();
|
|
14
|
+
} catch {
|
|
15
|
+
fail("interconnect route disposer left a route registered \u2014 route table and fiber lifecycle diverged");
|
|
16
|
+
}
|
|
17
|
+
}, { global: true });
|
|
18
|
+
};
|
|
19
|
+
var apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
|
|
20
|
+
export {
|
|
21
|
+
apply,
|
|
22
|
+
inject,
|
|
23
|
+
name
|
|
24
|
+
};
|
|
25
|
+
//# sourceMappingURL=invariant.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/interconnect/invariant.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Package-owned invariant companion for `@deepseek-ai/dsh-interconnect`.\n * @module @deepseek-ai/dsh-interconnect/invariant\n */\n\n/* jscpd:ignore-start */\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'\n\nconst PACKAGE_NAME = '@deepseek-ai/dsh-interconnect'\n\n/** Cordis companion plugin name. */\nexport const name = 'interconnect-invariant'\n/** Service required before the companion can register. */\nexport const inject = ['invariants']\n\n/**\n * Owned relation: the interconnect HTTP route must vanish when its owning\n * fiber unloads, or a stale route keeps serving disposed-plugin handlers.\n * Mirrors the webserver invariant: register/dispose a probe route and assert\n * the disposer really removed it.\n */\nconst install: InvariantInstaller = (ctx, fail) => {\n ctx.on('internal/plugin', () => {\n const server = ctx.get('webServer') as\n | { register(route: { kind: 'exact'; path: string; handler: () => void }): () => void }\n | undefined\n if (server === undefined) return\n const probe = { kind: 'exact' as const, path: '/__dsh_interconnect_invariant_probe__', handler: () => {} }\n try {\n server.register(probe)()\n server.register(probe)()\n } catch {\n fail('interconnect route disposer left a route registered \u2014 route table and fiber lifecycle diverged')\n }\n }, { global: true })\n}\n\n/**\n * Register this package's invariant companion.\n * @param ctx - Cordis context carrying the invariant service.\n * @returns the installed registration's disposer after setup succeeds.\n */\nexport const apply = (ctx: Context): Promise<() => void> =>\n Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))\n/* jscpd:ignore-end */\n"],
|
|
5
|
+
"mappings": ";AASA,IAAM,eAAe;AAGd,IAAM,OAAO;AAEb,IAAM,SAAS,CAAC,YAAY;AAQnC,IAAM,UAA8B,CAAC,KAAK,SAAS;AACjD,MAAI,GAAG,mBAAmB,MAAM;AAC9B,UAAM,SAAS,IAAI,IAAI,WAAW;AAGlC,QAAI,WAAW,OAAW;AAC1B,UAAM,QAAQ,EAAE,MAAM,SAAkB,MAAM,yCAAyC,SAAS,MAAM;AAAA,IAAC,EAAE;AACzG,QAAI;AACF,aAAO,SAAS,KAAK,EAAE;AACvB,aAAO,SAAS,KAAK,EAAE;AAAA,IACzB,QAAQ;AACN,WAAK,qGAAgG;AAAA,IACvG;AAAA,EACF,GAAG,EAAE,QAAQ,KAAK,CAAC;AACrB;AAOO,IAAM,QAAQ,CAAC,QACpB,QAAQ,QAAQ,IAAI,WAAW,SAAS,cAAc,OAAO,CAAC;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// src/tool-interconnect/index.ts
|
|
2
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
3
|
+
var inject = ["interconnect", "tools"];
|
|
4
|
+
function apply(ctx) {
|
|
5
|
+
const interconnect = ctx.interconnect;
|
|
6
|
+
ctx.tools.register(defineTool({
|
|
7
|
+
name: "interconnect_send",
|
|
8
|
+
description: "Deliver one text message to a live session on another DSH instance (same machine, another machine, or another session), over a shared-secret-authenticated channel. Returns whether the peer instance received it and which instance answered.",
|
|
9
|
+
parameters: {
|
|
10
|
+
baseUrl: {
|
|
11
|
+
type: "string",
|
|
12
|
+
required: true,
|
|
13
|
+
description: "Receiver instance origin, e.g. http://127.0.0.1:3080 or http://peer-host:9001."
|
|
14
|
+
},
|
|
15
|
+
sessionId: {
|
|
16
|
+
type: "string",
|
|
17
|
+
required: true,
|
|
18
|
+
description: "Target session id on the receiving instance to deliver the message to."
|
|
19
|
+
},
|
|
20
|
+
text: {
|
|
21
|
+
type: "string",
|
|
22
|
+
required: true,
|
|
23
|
+
description: "Message text delivered to the peer session."
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
output: {
|
|
27
|
+
schema: {
|
|
28
|
+
type: "object",
|
|
29
|
+
additionalProperties: false,
|
|
30
|
+
properties: {
|
|
31
|
+
delivered: { type: "boolean", required: true },
|
|
32
|
+
instance: { type: "string", required: true }
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
render: (_args, value) => [{
|
|
36
|
+
type: "text",
|
|
37
|
+
text: value.delivered ? `delivered to ${value.instance}` : `not delivered (no live session on ${value.instance})`
|
|
38
|
+
}]
|
|
39
|
+
},
|
|
40
|
+
async execute(args) {
|
|
41
|
+
const result = await interconnect.send({
|
|
42
|
+
baseUrl: args.baseUrl,
|
|
43
|
+
sessionId: args.sessionId,
|
|
44
|
+
text: args.text
|
|
45
|
+
});
|
|
46
|
+
return { delivered: result.delivered, instance: result.instance };
|
|
47
|
+
}
|
|
48
|
+
}));
|
|
49
|
+
ctx.tools.register(defineTool({
|
|
50
|
+
name: "interconnect_ping",
|
|
51
|
+
description: "Probe a peer DSH instance for liveness and identity over the shared-secret channel. Returns the peer instance id when reachable, or null on transport/auth failure.",
|
|
52
|
+
parameters: {
|
|
53
|
+
baseUrl: {
|
|
54
|
+
type: "string",
|
|
55
|
+
required: true,
|
|
56
|
+
description: "Peer instance origin, e.g. http://127.0.0.1:3080."
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
output: {
|
|
60
|
+
schema: {
|
|
61
|
+
type: "object",
|
|
62
|
+
additionalProperties: false,
|
|
63
|
+
properties: {
|
|
64
|
+
reachable: { type: "boolean", required: true },
|
|
65
|
+
instance: { type: "string" }
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
render: (_args, value) => [{
|
|
69
|
+
type: "text",
|
|
70
|
+
text: value.reachable ? `reachable: ${value.instance ?? "(unknown instance)"}` : "unreachable or unauthorized"
|
|
71
|
+
}]
|
|
72
|
+
},
|
|
73
|
+
async execute(args) {
|
|
74
|
+
const result = await interconnect.ping(args.baseUrl);
|
|
75
|
+
if (result === void 0) return { reachable: false };
|
|
76
|
+
return { reachable: true, instance: result.instance };
|
|
77
|
+
}
|
|
78
|
+
}));
|
|
79
|
+
}
|
|
80
|
+
export {
|
|
81
|
+
apply,
|
|
82
|
+
inject
|
|
83
|
+
};
|
|
84
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/tool-interconnect/index.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Model-facing tools for cross-instance message handoff: `interconnect_send`\n * delivers one text message to a live session on a peer DSH instance, and\n * `interconnect_ping` probes a peer's liveness and identity.\n *\n * The tools consume the host-plane `interconnect` service and publish nothing\n * themselves, so this row sits as an ordinary tool plugin in a preset while\n * the service it reaches stays host-side (the same split `tool-goal` uses\n * against `goals`).\n * @module @deepseek-ai/dsh-tool-interconnect\n */\n\nimport { Context } from '@deepseek-ai/cordis'\nimport { defineTool } from '@deepseek-ai/dsh-tools'\n// Activates the `Context.interconnect` merge declared by the interconnect service plugin.\nimport type {} from '../interconnect/index.ts'\n\n/** Services required before the tools can register. */\nexport const inject = ['interconnect', 'tools']\n\n/**\n * Register the two tool surfaces. Registration is idempotent per fiber; the\n * tools unregister with the owning fiber.\n * @param ctx - connection context carrying the interconnect service and the tool registry.\n */\nexport function apply(ctx: Context): void {\n const interconnect = ctx.interconnect\n\n ctx.tools.register(defineTool({\n name: 'interconnect_send',\n description: 'Deliver one text message to a live session on another DSH instance (same machine, '\n + 'another machine, or another session), over a shared-secret-authenticated channel. '\n + 'Returns whether the peer instance received it and which instance answered.',\n parameters: {\n baseUrl: {\n type: 'string',\n required: true,\n description: 'Receiver instance origin, e.g. http://127.0.0.1:3080 or http://peer-host:9001.',\n },\n sessionId: {\n type: 'string',\n required: true,\n description: 'Target session id on the receiving instance to deliver the message to.',\n },\n text: {\n type: 'string',\n required: true,\n description: 'Message text delivered to the peer session.',\n },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n delivered: { type: 'boolean', required: true },\n instance: { type: 'string', required: true },\n },\n },\n render: (_args, value) => [{\n type: 'text',\n text: value.delivered\n ? `delivered to ${value.instance}`\n : `not delivered (no live session on ${value.instance})`,\n }],\n },\n async execute(args) {\n const result = await interconnect.send({\n baseUrl: args.baseUrl,\n sessionId: args.sessionId,\n text: args.text,\n })\n return { delivered: result.delivered, instance: result.instance }\n },\n }))\n\n ctx.tools.register(defineTool({\n name: 'interconnect_ping',\n description: 'Probe a peer DSH instance for liveness and identity over the shared-secret channel. '\n + 'Returns the peer instance id when reachable, or null on transport/auth failure.',\n parameters: {\n baseUrl: {\n type: 'string',\n required: true,\n description: 'Peer instance origin, e.g. http://127.0.0.1:3080.',\n },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n reachable: { type: 'boolean', required: true },\n instance: { type: 'string' },\n },\n },\n render: (_args, value) => [{\n type: 'text',\n text: value.reachable\n ? `reachable: ${value.instance ?? '(unknown instance)'}`\n : 'unreachable or unauthorized',\n }],\n },\n async execute(args) {\n const result = await interconnect.ping(args.baseUrl)\n if (result === undefined) return { reachable: false }\n return { reachable: true, instance: result.instance }\n },\n }))\n}\n"],
|
|
5
|
+
"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AAAA,IACF;AAAA,IACA,QAAQ;AAAA,MACN,QAAQ;AAAA,QACN,MAAM;AAAA,QACN,sBAAsB;AAAA,QACtB,YAAY;AAAA,UACV,WAAW,EAAE,MAAM,WAAW,UAAU,KAAK;AAAA,UAC7C,UAAU,EAAE,MAAM,SAAS;AAAA,QAC7B;AAAA,MACF;AAAA,MACA,QAAQ,CAAC,OAAO,UAAU,CAAC;AAAA,QACzB,MAAM;AAAA,QACN,MAAM,MAAM,YACR,cAAc,MAAM,YAAY,oBAAoB,KACpD;AAAA,MACN,CAAC;AAAA,IACH;AAAA,IACA,MAAM,QAAQ,MAAM;AAClB,YAAM,SAAS,MAAM,aAAa,KAAK,KAAK,OAAO;AACnD,UAAI,WAAW,OAAW,QAAO,EAAE,WAAW,MAAM;AACpD,aAAO,EAAE,WAAW,MAAM,UAAU,OAAO,SAAS;AAAA,IACtD;AAAA,EACF,CAAC,CAAC;AACJ;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// src/tool-interconnect/invariant.ts
|
|
2
|
+
var PACKAGE_NAME = "@deepseek-ai/dsh-tool-interconnect";
|
|
3
|
+
var name = "tool-interconnect-invariant";
|
|
4
|
+
var inject = ["invariants"];
|
|
5
|
+
var install = (_ctx, _fail) => {
|
|
6
|
+
};
|
|
7
|
+
var apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
|
|
8
|
+
export {
|
|
9
|
+
apply,
|
|
10
|
+
inject,
|
|
11
|
+
name
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=invariant.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/tool-interconnect/invariant.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Package-owned invariant companion for `@deepseek-ai/dsh-tool-interconnect`.\n * @module @deepseek-ai/dsh-tool-interconnect/invariant\n */\n\n/* jscpd:ignore-start */\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'\n\nconst PACKAGE_NAME = '@deepseek-ai/dsh-tool-interconnect'\n\n/** Cordis companion plugin name. */\nexport const name = 'tool-interconnect-invariant'\n/** Service required before the companion can register. */\nexport const inject = ['invariants']\n\n/**\n * Owned relation: the model-facing tools this package registers must vanish\n * when the owning fiber unloads \u2014 a stale tool would keep dispatching to a\n * disposed interconnect service. Registered at load; the registry's own\n * disposer contract is exercised by the shared tools invariant, so this\n * companion only brackets the relation for this package.\n */\nconst install: InvariantInstaller = (_ctx, _fail) => {}\n\n/**\n * Register this package's invariant companion.\n * @param ctx - Cordis context carrying the invariant service.\n * @returns the installed registration's disposer after setup succeeds.\n */\nexport const apply = (ctx: Context): Promise<() => void> =>\n Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))\n/* jscpd:ignore-end */\n"],
|
|
5
|
+
"mappings": ";AASA,IAAM,eAAe;AAGd,IAAM,OAAO;AAEb,IAAM,SAAS,CAAC,YAAY;AASnC,IAAM,UAA8B,CAAC,MAAM,UAAU;AAAC;AAO/C,IAAM,QAAQ,CAAC,QACpB,QAAQ,QAAQ,IAAI,WAAW,SAAS,cAAc,OAAO,CAAC;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Package root: re-exports the interconnect service surface so `.` importers
|
|
3
|
+
* get the same bindings `build.mjs` bundles into `lib/index.js` from
|
|
4
|
+
* `src/interconnect/index.ts`.
|
|
5
|
+
* @module dsh-interconnect
|
|
6
|
+
*/
|
|
7
|
+
export type * from './interconnect/types.ts';
|
|
8
|
+
export { INTERCONNECT_CHANNEL, INTERCONNECT_TOKEN_REF, InterconnectService, default, } from './interconnect/index.ts';
|
|
9
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,mBAAmB,yBAAyB,CAAA;AAC5C,OAAO,EACL,oBAAoB,EACpB,sBAAsB,EACtB,mBAAmB,EACnB,OAAO,GACR,MAAM,yBAAyB,CAAA"}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-instance message handoff service: inbound half owns one HTTP route on
|
|
3
|
+
* the host webserver and delivers authenticated messages into live sessions;
|
|
4
|
+
* outbound half POSTs the same wire shape to a peer instance.
|
|
5
|
+
*
|
|
6
|
+
* Transport is deliberately NOT the Connection RPC channel: that registry's
|
|
7
|
+
* handler sees only `(endpoint, payload, signal)` and the trust fence is the
|
|
8
|
+
* DNS-rebinding `trustedHosts` check, neither of which carries the shared-key
|
|
9
|
+
* `Authorization` header this service authenticates on. Owning a plain HTTP
|
|
10
|
+
* route keeps bearer-token auth at the boundary where the header is readable
|
|
11
|
+
* and fails closed when the token is unconfigured.
|
|
12
|
+
* @module @deepseek-ai/dsh-interconnect
|
|
13
|
+
*/
|
|
14
|
+
import { Context, Service } from '@deepseek-ai/cordis';
|
|
15
|
+
import z from '@deepseek-ai/schemastery';
|
|
16
|
+
import WebSocket from 'ws';
|
|
17
|
+
import { type Config, type EventNotification, type PingResult, type SendResult, type SendRequest, type WebSocketLinkHandle } from './types.ts';
|
|
18
|
+
export type * from './types.ts';
|
|
19
|
+
export { INTERCONNECT_CHANNEL, INTERCONNECT_TOKEN_REF } from './types.ts';
|
|
20
|
+
declare module '@deepseek-ai/cordis' {
|
|
21
|
+
interface Context {
|
|
22
|
+
interconnect: InterconnectService;
|
|
23
|
+
}
|
|
24
|
+
interface Events {
|
|
25
|
+
/**
|
|
26
|
+
* A remote peer instance pushed one authenticated lifecycle notification
|
|
27
|
+
* into this instance. Payload is the exact {@link EventNotification} that
|
|
28
|
+
* crossed the wire; listeners may react but must not block the HTTP ack.
|
|
29
|
+
*/
|
|
30
|
+
'interconnect/event'(notification: EventNotification, peer: string): void;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Live cross-instance handoff service, registered as `ctx.interconnect`.
|
|
35
|
+
* Requires the host webserver, the live agent registry, and the credential
|
|
36
|
+
* store; activation is availability-driven like every other host service.
|
|
37
|
+
*/
|
|
38
|
+
export declare class InterconnectService extends Service {
|
|
39
|
+
static inject: string[];
|
|
40
|
+
static Config: z<Config>;
|
|
41
|
+
private readonly instanceId;
|
|
42
|
+
private readonly requestTimeoutMs;
|
|
43
|
+
private readonly delivery;
|
|
44
|
+
private readonly peers;
|
|
45
|
+
private readonly subscriptions;
|
|
46
|
+
private readonly server;
|
|
47
|
+
private readonly sockets;
|
|
48
|
+
private readonly linkStates;
|
|
49
|
+
private heartbeatTimer;
|
|
50
|
+
/** Peer identity each live socket announced via its `hello` frame, if any. */
|
|
51
|
+
private readonly peerOf;
|
|
52
|
+
constructor(ctx: Context, config: Config);
|
|
53
|
+
send(request: SendRequest): Promise<SendResult>;
|
|
54
|
+
ping(baseUrl: string): Promise<PingResult | undefined>;
|
|
55
|
+
/**
|
|
56
|
+
* Add a peer origin to the event fan-out set at runtime. Returns a disposer
|
|
57
|
+
* that removes it. Duplicate origins are idempotent.
|
|
58
|
+
* @param peer - receiver origin, e.g. `http://127.0.0.1:3080`.
|
|
59
|
+
* @returns disposer removing the peer from the fan-out set.
|
|
60
|
+
*/
|
|
61
|
+
subscribe(peer: string): () => void;
|
|
62
|
+
/** Remove a peer origin from the event fan-out set. */
|
|
63
|
+
unsubscribe(peer: string): void;
|
|
64
|
+
/**
|
|
65
|
+
* Open (and, on drop, re-open) a persistent WebSocket link to a peer. Local
|
|
66
|
+
* events stream over the link in real time, and events the peer pushes are
|
|
67
|
+
* surfaced as `interconnect/event`. Repeating for the same peer returns the
|
|
68
|
+
* existing handle.
|
|
69
|
+
* @param peer - receiver origin, e.g. `http://127.0.0.1:3080` (dialed as `ws:`).
|
|
70
|
+
* @returns a handle closing the link and cancelling reconnection.
|
|
71
|
+
*/
|
|
72
|
+
link(peer: string): WebSocketLinkHandle;
|
|
73
|
+
/** Remove a closed outbound link's state so a later `link` re-dials fresh. */
|
|
74
|
+
forgetLink(peer: string): void;
|
|
75
|
+
/** Fan one serialized lifecycle fact out to every registered peer, fire-and-forget. */
|
|
76
|
+
private fanout;
|
|
77
|
+
/** Push one fact over every live WebSocket link, dropping closed sockets. */
|
|
78
|
+
private broadcast;
|
|
79
|
+
/** Inbound route handler: bearer auth first, then envelope dispatch. */
|
|
80
|
+
private handle;
|
|
81
|
+
/** Parse the ClientRequest envelope and route to the named endpoint. */
|
|
82
|
+
private dispatch;
|
|
83
|
+
/** Dispatch one authenticated business call. */
|
|
84
|
+
private runEndpoint;
|
|
85
|
+
/** Surface one remote notification to local listeners and the log. */
|
|
86
|
+
private receiveEvent;
|
|
87
|
+
/** Deliver one message to a live local session, if it exists. */
|
|
88
|
+
private deliver;
|
|
89
|
+
/** POST one business call to a peer instance; undefined on transport/auth failure. */
|
|
90
|
+
private post;
|
|
91
|
+
private resolveToken;
|
|
92
|
+
/** Resolve the shared token for an outbound dial (same source as inbound). */
|
|
93
|
+
resolveTokenForDial(): Promise<string | undefined>;
|
|
94
|
+
/** Inbound WebSocket upgrade: authenticate the bearer header, then accept. */
|
|
95
|
+
private handleUpgrade;
|
|
96
|
+
/**
|
|
97
|
+
* Install frame + liveness handling on one socket and add it to the live
|
|
98
|
+
* pool. Used by both the server half (accepted upgrade) and the client half
|
|
99
|
+
* (outbound dial), so a single socket carries events both directions.
|
|
100
|
+
*/
|
|
101
|
+
attachSocket(websocket: WebSocket): void;
|
|
102
|
+
/** Parse and route one inbound link frame, attributing events to the socket's announced peer. */
|
|
103
|
+
private handleFrame;
|
|
104
|
+
}
|
|
105
|
+
export default InterconnectService;
|
|
106
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/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C,MAAM,CAAmC;gBAE9C,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM;IAoFlC,IAAI,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC;IAM/C,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC;IAI5D;;;;;OAKG;IACH,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,IAAI;IAMnC,uDAAuD;IACvD,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAI/B;;;;;;;OAOG;IACH,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,mBAAmB;IAUvC,8EAA8E;IAC9E,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAI9B,uFAAuF;IACvF,OAAO,CAAC,MAAM;IAQd,6EAA6E;IAC7E,OAAO,CAAC,SAAS;IAajB,wEAAwE;YAC1D,MAAM;IAkBpB,wEAAwE;YAC1D,QAAQ;IAqEtB,gDAAgD;IAChD,OAAO,CAAC,WAAW;IA0BnB,sEAAsE;IACtE,OAAO,CAAC,YAAY;IAKpB,iEAAiE;IACjE,OAAO,CAAC,OAAO;IAiBf,sFAAsF;YACxE,IAAI;YA8BJ,YAAY;IAK1B,8EAA8E;IAC9E,mBAAmB,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;IAIlD,8EAA8E;YAChE,aAAa;IAiB3B;;;;OAIG;IACH,YAAY,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI;IAoBxC,iGAAiG;IACjG,OAAO,CAAC,WAAW;CAiBpB;AAmID,eAAe,mBAAmB,CAAA"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Package-owned invariant companion for `@deepseek-ai/dsh-interconnect`.
|
|
3
|
+
* @module @deepseek-ai/dsh-interconnect/invariant
|
|
4
|
+
*/
|
|
5
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
6
|
+
/** Cordis companion plugin name. */
|
|
7
|
+
export declare const name = "interconnect-invariant";
|
|
8
|
+
/** Service required before the companion can register. */
|
|
9
|
+
export declare const inject: string[];
|
|
10
|
+
/**
|
|
11
|
+
* Register this package's invariant companion.
|
|
12
|
+
* @param ctx - Cordis context carrying the invariant service.
|
|
13
|
+
* @returns the installed registration's disposer after setup succeeds.
|
|
14
|
+
*/
|
|
15
|
+
export declare const apply: (ctx: Context) => Promise<() => void>;
|
|
16
|
+
//# sourceMappingURL=invariant.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"invariant.d.ts","sourceRoot":"","sources":["../../../src/interconnect/invariant.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAKlD,oCAAoC;AACpC,eAAO,MAAM,IAAI,2BAA2B,CAAA;AAC5C,0DAA0D;AAC1D,eAAO,MAAM,MAAM,UAAiB,CAAA;AAwBpC;;;;GAIG;AACH,eAAO,MAAM,KAAK,GAAI,KAAK,OAAO,KAAG,OAAO,CAAC,MAAM,IAAI,CACU,CAAA"}
|