dsh-interconnect 0.6.0 → 0.6.1

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 CHANGED
@@ -7,17 +7,19 @@
7
7
 
8
8
  **`interconnect`** —— host 服务(`ctx.interconnect`):
9
9
 
10
- - `send` / `ping` HTTP 端点(`/interconnect/*`):跨实例、跨机器投递消息、探测活性
10
+ - `send` / `list` / `ping` HTTP 端点(`/interconnect/*`):跨实例、跨机器投递消息、枚举 live session、探测活性
11
11
  - `/interconnect/link` WebSocket 端点:双向实时事件推流,含心跳与指数退避重连
12
12
  - 事件 fan-out(HTTP + WebSocket),入站事件以 `interconnect/event` 发出
13
13
  - 共享密钥鉴权(`DSH_INTERCONNECT_TOKEN`,bearer,fail-closed,timing-safe 比较)
14
14
 
15
15
  **`tool-interconnect`** —— 模型可见工具:
16
16
 
17
- - `interconnect_send`:向对端实例的指定 session 投递消息,可选 `delivery` 指定投递模式
17
+ - `interconnect_send`:向对端实例的指定 session 投递消息;可选 `delivery` 选投递模式、`resume` 唤醒离线 session
18
18
  - `interconnect_list`:列出对端实例的 live session(id + 标题 + 状态),用于在不预先知道 session id 时寻址
19
19
  - `interconnect_ping`:探测对端实例活性与身份
20
20
 
21
+ ## 用法
22
+
21
23
  ### 寻址
22
24
 
23
25
  `interconnect_send` 需要一个 session id,而调用方通常并不知道。`interconnect_list` 返回对端
@@ -73,6 +75,22 @@ context** 拥有,实测确认插件 fiber 被 dispose 时会把 resume 出来
73
75
  没有 Host lookup 的部署(headless、无 api-proxy 的 profile)会降级为 `session-not-live`,
74
76
  不会报错。
75
77
 
78
+ 唤醒**只把消息放进 inbox**,是否真的开始处理取决于 `delivery`:
79
+
80
+ ```text
81
+ # 唤醒并让对方实际处理(会起一个计费回合)
82
+ interconnect_send(baseUrl, sessionId, text, resume=true, delivery="followup")
83
+
84
+ # 唤醒但不起回合:只写入上下文,等对方下次被唤醒时一起读
85
+ interconnect_send(baseUrl, sessionId, text, resume=true, delivery="inject")
86
+ ```
87
+
88
+ 已实测:`resume=true` + `inject` 之后目标从非 live 变 live(`interconnect_list` 计数 +1),
89
+ 且该 session 日志里只多一条 `agent/inbox/spliced`、**后面没有 `turn/start`**。
90
+
91
+ **已知限制**:磁盘格式过旧的 session 无法唤醒,返回 `resume-failed`。这不是本插件的限制——
92
+ Host 自己的 resume 路径对同一个 session 报 `SessionFormatUnsupportedError`,同样失败。
93
+
76
94
  ### 投递模式
77
95
 
78
96
  `delivery` 的三个取值各自对应一个 `Agent` 方法,即 `(inbox target, wakeup)` 组合:
@@ -87,6 +105,30 @@ context** 拥有,实测确认插件 fiber 被 dispose 时会把 resume 出来
87
105
  该字段时沿用接收方 `Config.delivery` 的配置。`SendResult.delivery` 回报实际生效的
88
106
  模式,发送方据此判断覆盖是否被采纳。
89
107
 
108
+ ## 配置
109
+
110
+ `interconnect` 行的 `config`(全部可选,下表为默认值):
111
+
112
+ | 字段 | 默认 | 说明 |
113
+ |---|---|---|
114
+ | `instanceId` | `'dsh'` | 本实例自报的 id,出现在 `ping`/`send`/`list` 的回包里。仅诊断用,**不作为路由依据** |
115
+ | `requestTimeoutMs` | `10000` | 出站请求超时,上限 60000 |
116
+ | `peers` | `[]` | 启动时的事件 fan-out 目标;运行时可用 `subscribe()` 增补 |
117
+ | `delivery` | `'followup'` | 入站消息未带 `delivery` 时的默认投递模式 |
118
+ | `allowResume` | `true` | 是否允许发送方用 `resume` 唤醒本机的离线 session |
119
+
120
+ ```yaml
121
+ - id: interconnect
122
+ config:
123
+ instanceId: my-box
124
+ peers: ['http://peer-host:3080']
125
+ delivery: followup
126
+ allowResume: false # 拒绝一切唤醒请求
127
+ ```
128
+
129
+ 鉴权用的共享密钥不在这里,而是取自 credentials 的 `DSH_INTERCONNECT_TOKEN`(fail-closed:
130
+ 没有 token 时端点返回 403)。
131
+
90
132
  ## 安装
91
133
 
92
134
  本包已发布到 npm:[`dsh-interconnect`](https://www.npmjs.com/package/dsh-interconnect)。
@@ -130,16 +172,20 @@ pnpm run build # esbuild → lib/
130
172
 
131
173
  ## 验证
132
174
 
133
- - 22/22 单测通过(服务 17 + 工具 5);类型检查、构建均干净。
175
+ - 50/50 单测通过(服务 + 工具);类型检查、构建均干净。
134
176
  - 已在两台机器之间实测双向互通:消息投递、WebSocket 事件推流、以及 agent 经
135
177
  `interconnect_send` 工具反向回发,均验证通过。
136
178
  - CI(GitHub Actions):clone 公开 DSH 仓库作为 sibling,跑 `pnpm run check`。
137
179
  - 已发布版本:从 registry 下载的 tarball 与本地构建 shasum 一致;干净消费端
138
180
  解析 `.`、`./tool-interconnect` 两个入口的类型均通过,负例(把 `string` 赋给
139
181
  `number`)如期报 `TS2322`。
140
- - 投递消息的 `source` 为 `{ kind: 'plugin', plugin: 'dsh-interconnect' }`,不是
141
- `{ kind: 'user' }`——接收方 agent 据此区分跨实例投递与本地用户输入。负例:把
142
- 该 source 改回 `kind: 'user'`,对应断言转红。
182
+ - 投递消息以 `source: { kind: 'plugin', plugin: 'dsh-interconnect' }` 落库,而不是
183
+ `{ kind: 'user' }`。负例:把该 source 改回 `kind: 'user'`,对应断言转红。
184
+ **注意 `source` 不进模型上下文**——只有 `role` 和 `content` 会,而 `role` 是 `user`。
185
+ 所以这个字段的价值在持久化日志与 UI 归因,接收方的**模型本身分辨不出**消息来自插件。
186
+ - 每个行为改动都配负例对照(删掉实现使对应断言转红),而不只是「测试通过」。
187
+ 例如:去掉请求处理器的 `await` 会让 25 个测试转红;去掉 `resume` 的发送方 opt-in
188
+ 门或接收方否决门,各让 1 个转红。
143
189
 
144
190
  ## 许可
145
191
 
package/lib/index.js CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  } from "@deepseek-ai/dsh-host-apiproxy/api";
8
8
  import { credentialRef } from "@deepseek-ai/dsh-credentials";
9
9
  import { boundContextSummary, createUserMessage } from "@deepseek-ai/dsh-llm";
10
+ import { hasApiRemoteSubagentOwner } from "@deepseek-ai/dsh-api-remotes";
10
11
 
11
12
  // ../.dsh/source/staging-20260807T143236Z/vendor/cosmokit/src/misc.ts
12
13
  function isNullable(value) {
@@ -1162,7 +1163,8 @@ var InterconnectService = class extends Service {
1162
1163
  * matches how the Host's own session listing treats its projection column.
1163
1164
  */
1164
1165
  listSessions() {
1165
- const sessions = this.ctx.agents.list().map((agent) => {
1166
+ const reachable = this.ctx.agents.list().filter((agent) => !hasApiRemoteSubagentOwner(this.ctx, agent.session, agent));
1167
+ const sessions = reachable.map((agent) => {
1166
1168
  let title;
1167
1169
  try {
1168
1170
  const snapshot = this.ctx.get("sessionProjections")?.snapshot(agent.session);
@@ -1199,7 +1201,7 @@ var InterconnectService = class extends Service {
1199
1201
  if (lookup === void 0) return { reason: "session-not-live" };
1200
1202
  try {
1201
1203
  const resolved = await lookup.resolve(payload.sessionId);
1202
- if (resolved === void 0 || resolved === null) return { reason: "resume-failed" };
1204
+ if (resolved === void 0 || resolved === null) return { reason: "session-not-live" };
1203
1205
  return { agent: resolved };
1204
1206
  } catch (error) {
1205
1207
  this.ctx.logger.info(`interconnect: resume refused for ${payload.sessionId}: ${error instanceof Error ? error.message : String(error)}`);
@@ -1219,6 +1221,9 @@ var InterconnectService = class extends Service {
1219
1221
  }
1220
1222
  agent = woken.agent;
1221
1223
  }
1224
+ if (hasApiRemoteSubagentOwner(this.ctx, agent.session, agent)) {
1225
+ return { delivered: false, instance: this.instanceId, reason: "session-owned-by-subagent" };
1226
+ }
1222
1227
  const message = createUserMessage({
1223
1228
  source: {
1224
1229
  kind: "plugin",
@@ -7,6 +7,7 @@ import {
7
7
  } from "@deepseek-ai/dsh-host-apiproxy/api";
8
8
  import { credentialRef } from "@deepseek-ai/dsh-credentials";
9
9
  import { boundContextSummary, createUserMessage } from "@deepseek-ai/dsh-llm";
10
+ import { hasApiRemoteSubagentOwner } from "@deepseek-ai/dsh-api-remotes";
10
11
 
11
12
  // ../.dsh/source/staging-20260807T143236Z/vendor/cosmokit/src/misc.ts
12
13
  function isNullable(value) {
@@ -1162,7 +1163,8 @@ var InterconnectService = class extends Service {
1162
1163
  * matches how the Host's own session listing treats its projection column.
1163
1164
  */
1164
1165
  listSessions() {
1165
- const sessions = this.ctx.agents.list().map((agent) => {
1166
+ const reachable = this.ctx.agents.list().filter((agent) => !hasApiRemoteSubagentOwner(this.ctx, agent.session, agent));
1167
+ const sessions = reachable.map((agent) => {
1166
1168
  let title;
1167
1169
  try {
1168
1170
  const snapshot = this.ctx.get("sessionProjections")?.snapshot(agent.session);
@@ -1199,7 +1201,7 @@ var InterconnectService = class extends Service {
1199
1201
  if (lookup === void 0) return { reason: "session-not-live" };
1200
1202
  try {
1201
1203
  const resolved = await lookup.resolve(payload.sessionId);
1202
- if (resolved === void 0 || resolved === null) return { reason: "resume-failed" };
1204
+ if (resolved === void 0 || resolved === null) return { reason: "session-not-live" };
1203
1205
  return { agent: resolved };
1204
1206
  } catch (error) {
1205
1207
  this.ctx.logger.info(`interconnect: resume refused for ${payload.sessionId}: ${error instanceof Error ? error.message : String(error)}`);
@@ -1219,6 +1221,9 @@ var InterconnectService = class extends Service {
1219
1221
  }
1220
1222
  agent = woken.agent;
1221
1223
  }
1224
+ if (hasApiRemoteSubagentOwner(this.ctx, agent.session, agent)) {
1225
+ return { delivered: false, instance: this.instanceId, reason: "session-owned-by-subagent" };
1226
+ }
1222
1227
  const message = createUserMessage({
1223
1228
  source: {
1224
1229
  kind: "plugin",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
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 { boundContextSummary, 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 DeliveryMode,\n type EventNotification,\n type EventPayload,\n type LinkFrame,\n type ListResult,\n type PingResult,\n type SendPayload,\n type SendResult,\n type SendRequest,\n type SendFailure,\n type SessionSummary,\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/** `source.plugin` for messages this service splices into a local inbox. */\nconst PLUGIN_SOURCE = 'dsh-interconnect'\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/**\n * Wire union the send endpoint expects inside the ClientRequest payload slot.\n * `delivery` is optional and constrained to the same three names the config\n * accepts, so an unknown mode fails the envelope instead of reaching a method\n * lookup on `Agent`.\n */\nconst sendPayloadSchema = z.object({\n sessionId: z.string(),\n text: z.string(),\n delivery: z.union([z.const('followup'), z.const('steer'), z.const('inject')]),\n resume: z.boolean(),\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('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 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 this.allowResume = config.allowResume ?? true\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 // Spread the override only when present: JSON.stringify would otherwise\n // drop an explicit `delivery: undefined` anyway, but building the key\n // conditionally keeps the wire shape identical to a caller that omitted it.\n const payload: SendPayload = {\n sessionId: request.sessionId,\n text: request.text,\n ...(request.delivery === undefined ? {} : { delivery: request.delivery }),\n ...(request.resume === undefined ? {} : { resume: request.resume }),\n }\n const result = await this.post<SendResult>(request.baseUrl, 'send', payload)\n // No usable answer means the receiver never spoke, so the instance id here\n // is this sender's own \u2014 hence `unreachable` rather than any claim about\n // the target session, which may be perfectly fine.\n return result ?? { delivered: false, instance: this.instanceId, reason: 'unreachable' }\n }\n\n async ping(baseUrl: string): Promise<PingResult | undefined> {\n return this.post<PingResult>(baseUrl, 'ping', {})\n }\n\n /**\n * List the peer's live sessions so a caller can discover a valid `send`\n * target. `undefined` on transport or auth failure, matching `ping`.\n */\n async list(baseUrl: string): Promise<ListResult | undefined> {\n return this.post<ListResult>(baseUrl, 'list', {})\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 // Awaited: `send` may resume a persisted session, which is asynchronous.\n // Without the await a Promise would serialize as `{}` and every async\n // rejection would escape this catch as an unhandled rejection.\n const value = await 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 // A payload the endpoint schema rejects is the caller's error, so it gets\n // `bad-request` and no warning: logging it would let a peer fill this\n // instance's log by sending malformed payloads.\n if (error instanceof InvalidPayloadError) {\n writeError(res, rpcId, {\n code: 'bad-request',\n message: error.message,\n details: { issues: [] },\n })\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 async runEndpoint(endpoint: string, payload: unknown): Promise<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 InvalidPayloadError(`send payload invalid: ${error instanceof Error ? error.message : String(error)}`)\n }\n return this.deliver(parsed)\n }\n if (endpoint === 'list') {\n return this.listSessions()\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 InvalidPayloadError(`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 /**\n * Summarize every live local session 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.\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 */\n private listSessions(): ListResult {\n const sessions = this.ctx.agents.list().map((agent): SessionSummary => {\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 return { sessions, instance: this.instanceId }\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 as never)\n if (resolved === undefined || resolved === null) return { reason: 'resume-failed' }\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(`interconnect: resume refused for ${payload.sessionId}: ${error instanceof Error ? error.message : String(error)}`)\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 let agent = this.ctx.agents.get(payload.sessionId as Agent['id'])\n if (agent === undefined) {\n const woken = await this.wake(payload)\n if ('reason' in woken) {\n return { delivered: false, instance: this.instanceId, reason: woken.reason }\n }\n agent = woken.agent\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. `SendPayload` carries no sender field (the wire shape\n // is unauthenticated beyond the shared token), so the notice names the\n // receiving instance the handoff landed on.\n const message = createUserMessage({\n source: {\n kind: 'plugin',\n plugin: PLUGIN_SOURCE,\n form: 'notice',\n summary: boundContextSummary(`interconnect handoff delivered on instance ${this.instanceId}`),\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 }\n return { delivered: true, instance: this.instanceId, delivery: mode }\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 * Thrown when an authenticated envelope carries a business payload its endpoint\n * schema rejects. Typed so the request catch can answer `bad-request` instead of\n * `internal`: the caller sent an unusable payload, so retrying it unchanged can\n * never succeed, and the receiver is not faulty.\n */\nclass InvalidPayloadError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'InvalidPayloadError'\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 * How one inbound message reaches the target agent's inbox. Each value names an\n * existing `Agent` method, which is exactly the pair `(inbox target, wakeup)`:\n * - `followup` \u2014 `next-turn` + wake: the message becomes its own turn, queued\n * behind whatever the agent is currently doing.\n * - `steer` \u2014 `next-step` + wake: the message cuts into the nearest step\n * boundary of a running turn instead of waiting for that turn to finish; an\n * idle agent starts a turn.\n * - `inject` \u2014 `next-step`, no wake: seeds model-facing context without waking\n * an idle agent, so it can sit unread until something else wakes it.\n */\nexport type DeliveryMode = 'followup' | 'steer' | 'inject'\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 * Per-message override of the receiver's configured delivery mode. Urgency is\n * a property of one message, not of the link, so a sender may ask to cut into\n * a running turn. Absent leaves the receiver's configured default in force.\n */\n readonly delivery?: DeliveryMode\n /**\n * Ask the receiver to wake a persisted session that has no running agent.\n *\n * Opt-in, and deliberately not the default: delivery to a woken session runs\n * a real agent turn \u2014 a billed model call whose assembly carries that\n * session's full toolset \u2014 inside a conversation its owner is not watching\n * and cannot interrupt. That is categorically more than nudging an already\n * open session, so the sender must ask for it explicitly. The receiver can\n * still refuse via `Config.allowResume`, because the cost lands on its\n * machine.\n */\n readonly resume?: boolean\n}\n\n/**\n * Why a `send` did not deliver. `delivered: false` alone cannot be acted on,\n * because the causes need different responses:\n * - `session-not-live` \u2014 the receiver answered; that session has no running\n * agent. Retrying the same id is futile until it is opened, so the caller\n * should list live sessions and pick another target.\n * - `unreachable` \u2014 no usable answer from the receiver (transport failure, or\n * auth rejected). The target may well be fine, so retrying can succeed.\n * - `resume-refused` \u2014 the sender asked to wake a persisted session and this\n * receiver does not allow it. Retrying with `resume` set changes nothing.\n * - `resume-failed` \u2014 waking was allowed and attempted but did not yield a live\n * agent (no persisted session under that id, or another owner holds it).\n */\nexport type SendFailure = 'session-not-live' | 'unreachable' | 'resume-refused' | 'resume-failed'\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 * The mode actually used, so a sender can tell whether its requested override\n * took effect. Absent when nothing was delivered.\n */\n readonly delivery?: DeliveryMode\n /**\n * Why delivery failed. Present exactly when `delivered` is false, so a caller\n * can distinguish \"wrong target\" from \"receiver unreachable\" instead of\n * guessing from a bare boolean.\n */\n readonly reason?: SendFailure\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/**\n * One live session on the receiving instance. Only live agents appear: `send`\n * can reach exactly these, so the listing is the set of valid `sessionId`\n * values rather than a directory of everything ever persisted.\n */\nexport interface SessionSummary {\n /** The session id to pass back as `SendPayload.sessionId`. */\n readonly sessionId: string\n /**\n * The session's title when a title projection is available. Absent rather\n * than empty when the projection is missing or the session has no title yet,\n * so a caller can tell \"untitled\" from \"titles unavailable on this receiver\".\n */\n readonly title?: string\n /** The agent's current status, so a sender can prefer an idle target. */\n readonly status?: string\n}\n\n/** Business result of a `list` endpoint call. */\nexport interface ListResult {\n /** Live sessions in registration order. */\n readonly sessions: readonly SessionSummary[]\n /** Echoed receiver instance id (diagnostic; never trusted for routing). */\n readonly instance: string\n}\n\n/** Outbound listing request: just the receiver origin. */\nexport interface ListRequest {\n /** Receiver origin, e.g. `http://127.0.0.1:3080`. */\n readonly baseUrl: 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 /** Per-message delivery override forwarded to the receiver. */\n readonly delivery?: DeliveryMode\n /** Ask the receiver to wake a persisted session; see {@link SendPayload.resume}. */\n readonly resume?: boolean\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 * Default mode for inbound `send` messages that carry no per-message\n * override. See {@link DeliveryMode} for what each mode does.\n */\n readonly delivery?: DeliveryMode\n /**\n * Whether this instance honours a sender's `resume` request. Defaults to\n * true: the sender must opt in per message anyway, and this switch exists so\n * the side that pays \u2014 waking a session runs a billed model turn with that\n * session's tools on THIS machine \u2014 can refuse outright.\n */\n readonly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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;",
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 { boundContextSummary, createUserMessage } from '@deepseek-ai/dsh-llm'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\n// The Host's own subagent-ownership predicate, reused rather than reimplemented:\n// this is a safety rule, and a local copy of it would drift from the Host's.\nimport { hasApiRemoteSubagentOwner } from '@deepseek-ai/dsh-api-remotes'\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 DeliveryMode,\n type EventNotification,\n type EventPayload,\n type LinkFrame,\n type ListResult,\n type PingResult,\n type SendPayload,\n type SendResult,\n type SendRequest,\n type SendFailure,\n type SessionSummary,\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/** `source.plugin` for messages this service splices into a local inbox. */\nconst PLUGIN_SOURCE = 'dsh-interconnect'\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/**\n * Wire union the send endpoint expects inside the ClientRequest payload slot.\n * `delivery` is optional and constrained to the same three names the config\n * accepts, so an unknown mode fails the envelope instead of reaching a method\n * lookup on `Agent`.\n */\nconst sendPayloadSchema = z.object({\n sessionId: z.string(),\n text: z.string(),\n delivery: z.union([z.const('followup'), z.const('steer'), z.const('inject')]),\n resume: z.boolean(),\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('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 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 this.allowResume = config.allowResume ?? true\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 // Spread the override only when present: JSON.stringify would otherwise\n // drop an explicit `delivery: undefined` anyway, but building the key\n // conditionally keeps the wire shape identical to a caller that omitted it.\n const payload: SendPayload = {\n sessionId: request.sessionId,\n text: request.text,\n ...(request.delivery === undefined ? {} : { delivery: request.delivery }),\n ...(request.resume === undefined ? {} : { resume: request.resume }),\n }\n const result = await this.post<SendResult>(request.baseUrl, 'send', payload)\n // No usable answer means the receiver never spoke, so the instance id here\n // is this sender's own \u2014 hence `unreachable` rather than any claim about\n // the target session, which may be perfectly fine.\n return result ?? { delivered: false, instance: this.instanceId, reason: 'unreachable' }\n }\n\n async ping(baseUrl: string): Promise<PingResult | undefined> {\n return this.post<PingResult>(baseUrl, 'ping', {})\n }\n\n /**\n * List the peer's live sessions so a caller can discover a valid `send`\n * target. `undefined` on transport or auth failure, matching `ping`.\n */\n async list(baseUrl: string): Promise<ListResult | undefined> {\n return this.post<ListResult>(baseUrl, 'list', {})\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 // Awaited: `send` may resume a persisted session, which is asynchronous.\n // Without the await a Promise would serialize as `{}` and every async\n // rejection would escape this catch as an unhandled rejection.\n const value = await 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 // A payload the endpoint schema rejects is the caller's error, so it gets\n // `bad-request` and no warning: logging it would let a peer fill this\n // instance's log by sending malformed payloads.\n if (error instanceof InvalidPayloadError) {\n writeError(res, rpcId, {\n code: 'bad-request',\n message: error.message,\n details: { issues: [] },\n })\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 async runEndpoint(endpoint: string, payload: unknown): Promise<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 InvalidPayloadError(`send payload invalid: ${error instanceof Error ? error.message : String(error)}`)\n }\n return this.deliver(parsed)\n }\n if (endpoint === 'list') {\n return this.listSessions()\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 InvalidPayloadError(`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 /**\n * Summarize every live local session 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.\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 */\n private listSessions(): 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 => !hasApiRemoteSubagentOwner(this.ctx, agent.session, agent))\n const sessions = reachable.map((agent): SessionSummary => {\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 return { sessions, instance: this.instanceId }\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 as never)\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(`interconnect: resume refused for ${payload.sessionId}: ${error instanceof Error ? error.message : String(error)}`)\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 let agent = this.ctx.agents.get(payload.sessionId as Agent['id'])\n if (agent === undefined) {\n const woken = await this.wake(payload)\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 (hasApiRemoteSubagentOwner(this.ctx, agent.session, agent)) {\n return { delivered: false, instance: this.instanceId, reason: 'session-owned-by-subagent' }\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. `SendPayload` carries no sender field (the wire shape\n // is unauthenticated beyond the shared token), so the notice names the\n // receiving instance the handoff landed on.\n const message = createUserMessage({\n source: {\n kind: 'plugin',\n plugin: PLUGIN_SOURCE,\n form: 'notice',\n summary: boundContextSummary(`interconnect handoff delivered on instance ${this.instanceId}`),\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 }\n return { delivered: true, instance: this.instanceId, delivery: mode }\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 * Thrown when an authenticated envelope carries a business payload its endpoint\n * schema rejects. Typed so the request catch can answer `bad-request` instead of\n * `internal`: the caller sent an unusable payload, so retrying it unchanged can\n * never succeed, and the receiver is not faulty.\n */\nclass InvalidPayloadError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'InvalidPayloadError'\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 * How one inbound message reaches the target agent's inbox. Each value names an\n * existing `Agent` method, which is exactly the pair `(inbox target, wakeup)`:\n * - `followup` \u2014 `next-turn` + wake: the message becomes its own turn, queued\n * behind whatever the agent is currently doing.\n * - `steer` \u2014 `next-step` + wake: the message cuts into the nearest step\n * boundary of a running turn instead of waiting for that turn to finish; an\n * idle agent starts a turn.\n * - `inject` \u2014 `next-step`, no wake: seeds model-facing context without waking\n * an idle agent, so it can sit unread until something else wakes it.\n */\nexport type DeliveryMode = 'followup' | 'steer' | 'inject'\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 * Per-message override of the receiver's configured delivery mode. Urgency is\n * a property of one message, not of the link, so a sender may ask to cut into\n * a running turn. Absent leaves the receiver's configured default in force.\n */\n readonly delivery?: DeliveryMode\n /**\n * Ask the receiver to wake a persisted session that has no running agent.\n *\n * Opt-in, and deliberately not the default: delivery to a woken session runs\n * a real agent turn \u2014 a billed model call whose assembly carries that\n * session's full toolset \u2014 inside a conversation its owner is not watching\n * and cannot interrupt. That is categorically more than nudging an already\n * open session, so the sender must ask for it explicitly. The receiver can\n * still refuse via `Config.allowResume`, because the cost lands on its\n * machine.\n */\n readonly resume?: boolean\n}\n\n/**\n * Why a `send` did not deliver. `delivered: false` alone cannot be acted on,\n * because the causes need different responses:\n * - `session-not-live` \u2014 the receiver answered; that session has no running\n * agent. Retrying the same id is futile until it is opened, so the caller\n * should list live sessions and pick another target.\n * - `unreachable` \u2014 no usable answer from the receiver (transport failure, or\n * auth rejected). The target may well be fine, so retrying can succeed.\n * - `resume-refused` \u2014 the sender asked to wake a persisted session and this\n * receiver does not allow it. Retrying with `resume` set changes nothing.\n * - `resume-failed` \u2014 waking was allowed and attempted but did not yield a live\n * agent (no persisted session under that id, or another owner holds it).\n * - `session-owned-by-subagent` \u2014 the session is reserved to subagent routing,\n * so its parent agent owns delivery. Injecting here would race that parent;\n * the sender must reach the child through its parent instead.\n */\nexport type SendFailure = 'session-not-live' | 'unreachable' | 'resume-refused' | 'resume-failed' | 'session-owned-by-subagent'\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 * The mode actually used, so a sender can tell whether its requested override\n * took effect. Absent when nothing was delivered.\n */\n readonly delivery?: DeliveryMode\n /**\n * Why delivery failed. Present exactly when `delivered` is false, so a caller\n * can distinguish \"wrong target\" from \"receiver unreachable\" instead of\n * guessing from a bare boolean.\n */\n readonly reason?: SendFailure\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/**\n * One live session on the receiving instance. Only live agents appear: `send`\n * can reach exactly these, so the listing is the set of valid `sessionId`\n * values rather than a directory of everything ever persisted.\n */\nexport interface SessionSummary {\n /** The session id to pass back as `SendPayload.sessionId`. */\n readonly sessionId: string\n /**\n * The session's title when a title projection is available. Absent rather\n * than empty when the projection is missing or the session has no title yet,\n * so a caller can tell \"untitled\" from \"titles unavailable on this receiver\".\n */\n readonly title?: string\n /** The agent's current status, so a sender can prefer an idle target. */\n readonly status?: string\n}\n\n/** Business result of a `list` endpoint call. */\nexport interface ListResult {\n /** Live sessions in registration order. */\n readonly sessions: readonly SessionSummary[]\n /** Echoed receiver instance id (diagnostic; never trusted for routing). */\n readonly instance: string\n}\n\n/** Outbound listing request: just the receiver origin. */\nexport interface ListRequest {\n /** Receiver origin, e.g. `http://127.0.0.1:3080`. */\n readonly baseUrl: 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 /** Per-message delivery override forwarded to the receiver. */\n readonly delivery?: DeliveryMode\n /** Ask the receiver to wake a persisted session; see {@link SendPayload.resume}. */\n readonly resume?: boolean\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 * Default mode for inbound `send` messages that carry no per-message\n * override. See {@link DeliveryMode} for what each mode does.\n */\n readonly delivery?: DeliveryMode\n /**\n * Whether this instance honours a sender's `resume` request. Defaults to\n * true: the sender must opt in per message anyway, and this switch exists so\n * the side that pays \u2014 waking a session runs a billed model turn with that\n * session's tools on THIS machine \u2014 can refuse outright.\n */\n readonly allowResume?: boolean\n}\n"],
5
+ "mappings": ";AAcA,SAAkB,eAAe;AAIjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB,yBAAyB;AAIvD,SAAS,iCAAiC;;;ACVnC,SAAS,WAAW,OAA8C;AACvE,SAAO,UAAU,QAAQ,UAAU;AACrC;AAQO,SAAS,cAA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I,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
6
  "names": ["value", "Binary", "result", "a", "b", "Time", "date", "template", "options", "pattern", "value", "extra", "resolve", "toJSON", "date", "toString", "key"]
7
7
  }
@@ -58,6 +58,8 @@ function apply(ctx) {
58
58
  return `not delivered: ${value.instance} does not allow waking persisted sessions`;
59
59
  case "resume-failed":
60
60
  return `not delivered: could not wake "${_args.sessionId}" on ${value.instance} (no such persisted session, or another owner holds it)`;
61
+ case "session-owned-by-subagent":
62
+ return `not delivered: "${_args.sessionId}" is a subagent's session on ${value.instance} \u2014 its parent agent owns delivery, so reach it through that parent`;
61
63
  default:
62
64
  return `not delivered: no live session "${_args.sessionId}" on ${value.instance} \u2014 use interconnect_list to see which sessions are live there, or set resume to wake this one`;
63
65
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
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 + 'Only a session with a running agent can receive a message; when none is running the result '\n + 'reports reason \"session-not-live\", and interconnect_list shows which sessions are live there.',\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 delivery: {\n type: 'string',\n enum: ['followup', 'steer', 'inject'],\n description: 'How the message reaches the target agent. `followup` queues it as its own turn '\n + 'behind whatever that agent is doing now. `steer` cuts into the nearest step boundary of a '\n + 'running turn, so an urgent message does not wait for that turn to end. `inject` seeds '\n + 'context without waking an idle agent, so it may sit unread. Omit to use the receiver\\'s '\n + 'configured default.',\n },\n resume: {\n type: 'boolean',\n description: 'Wake the target session if it is persisted but has no running agent. Off by '\n + 'default because delivery to a woken session starts a real agent turn \u2014 a billed model call '\n + 'with that session\\'s full toolset \u2014 in a conversation nobody is watching. Prefer '\n + 'interconnect_list and an already-live target; set this only when that specific session must '\n + 'be reached. The receiver may refuse, answering reason \"resume-refused\".',\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 delivery: { type: 'string' },\n reason: { type: 'string' },\n },\n },\n render: (_args, value) => {\n if (value.delivered) {\n return [{\n type: 'text',\n text: `delivered to ${value.instance}${value.delivery === undefined ? '' : ` via ${value.delivery}`}`,\n }]\n }\n // Each failure gets the response it actually needs: a not-live target is\n // the caller's to re-choose, while an unreachable peer may just be worth\n // retrying. The old single line claimed \"no live session\" even when the\n // peer never answered, which pointed at the wrong thing entirely.\n const text = ((): string => {\n switch (value.reason) {\n case 'unreachable':\n return `not delivered: ${value.instance} did not answer (unreachable or unauthorized)`\n case 'resume-refused':\n return `not delivered: ${value.instance} does not allow waking persisted sessions`\n case 'resume-failed':\n return `not delivered: could not wake \"${_args.sessionId}\" on ${value.instance}`\n + ' (no such persisted session, or another owner holds it)'\n default:\n return `not delivered: no live session \"${_args.sessionId}\" on ${value.instance}`\n + ' \u2014 use interconnect_list to see which sessions are live there,'\n + ' or set resume to wake this one'\n }\n })()\n return [{ type: 'text', text }]\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 ...(args.delivery === undefined ? {} : { delivery: args.delivery }),\n ...(args.resume === undefined ? {} : { resume: args.resume }),\n })\n return {\n delivered: result.delivered,\n instance: result.instance,\n ...(result.delivery === undefined ? {} : { delivery: result.delivery }),\n ...(result.reason === undefined ? {} : { reason: result.reason }),\n }\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 ctx.tools.register(defineTool({\n name: 'interconnect_list',\n description: 'List the live sessions on a peer DSH instance, so a message can be addressed without '\n + 'knowing a session id in advance. Every returned sessionId is a valid interconnect_send target at '\n + 'the time of the call. Only live sessions appear: a session that exists on the peer but has no '\n + 'running agent is not listed and cannot receive a message.',\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 sessions: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n sessionId: { type: 'string', required: true },\n title: { type: 'string' },\n status: { type: 'string' },\n },\n },\n },\n },\n },\n render: (_args, value) => {\n if (!value.reachable) return [{ type: 'text', text: 'unreachable or unauthorized' }]\n const sessions = value.sessions ?? []\n if (sessions.length === 0) {\n return [{ type: 'text', text: `no live sessions on ${value.instance ?? '(unknown instance)'}` }]\n }\n const lines = sessions.map((session) => {\n const title = session.title === undefined ? '' : ` ${session.title}`\n const status = session.status === undefined ? '' : ` [${session.status}]`\n return `${session.sessionId}${title}${status}`\n })\n return [{ type: 'text', text: lines.join('\\n') }]\n },\n },\n async execute(args) {\n const result = await interconnect.list(args.baseUrl)\n if (result === undefined) return { reachable: false }\n return {\n reachable: true,\n instance: result.instance,\n // Rebuild each row so an optional key stays absent rather than\n // becoming an explicit undefined the wire schema would reject.\n sessions: result.sessions.map(session => ({\n sessionId: session.sessionId,\n ...(session.title === undefined ? {} : { title: session.title }),\n ...(session.status === undefined ? {} : { status: session.status }),\n })),\n }\n },\n }))\n}\n"],
5
- "mappings": ";AAaA,SAAS,kBAAkB;AAKpB,IAAM,SAAS,CAAC,gBAAgB,OAAO;AAOvC,SAAS,MAAM,KAAoB;AACxC,QAAM,eAAe,IAAI;AAEzB,MAAI,MAAM,SAAS,WAAW;AAAA,IAC5B,MAAM;AAAA,IACN,aAAa;AAAA,IAKb,YAAY;AAAA,MACV,SAAS;AAAA,QACP,MAAM;AAAA,QACN,UAAU;AAAA,QACV,aAAa;AAAA,MACf;AAAA,MACA,WAAW;AAAA,QACT,MAAM;AAAA,QACN,UAAU;AAAA,QACV,aAAa;AA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D;AAAA,IACF;AAAA,IACA,MAAM,QAAQ,MAAM;AAClB,YAAM,SAAS,MAAM,aAAa,KAAK,KAAK,OAAO;AACnD,UAAI,WAAW,OAAW,QAAO,EAAE,WAAW,MAAM;AACpD,aAAO;AAAA,QACL,WAAW;AAAA,QACX,UAAU,OAAO;AAAA;AAAA;AAAA,QAGjB,UAAU,OAAO,SAAS,IAAI,cAAY;AAAA,UACxC,WAAW,QAAQ;AAAA,UACnB,GAAI,QAAQ,UAAU,SAAY,CAAC,IAAI,EAAE,OAAO,QAAQ,MAAM;AAAA,UAC9D,GAAI,QAAQ,WAAW,SAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;AAAA,QACnE,EAAE;AAAA,MACJ;AAAA,IACF;AAAA,EACF,CAAC,CAAC;AACJ;",
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 + 'Only a session with a running agent can receive a message; when none is running the result '\n + 'reports reason \"session-not-live\", and interconnect_list shows which sessions are live there.',\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 delivery: {\n type: 'string',\n enum: ['followup', 'steer', 'inject'],\n description: 'How the message reaches the target agent. `followup` queues it as its own turn '\n + 'behind whatever that agent is doing now. `steer` cuts into the nearest step boundary of a '\n + 'running turn, so an urgent message does not wait for that turn to end. `inject` seeds '\n + 'context without waking an idle agent, so it may sit unread. Omit to use the receiver\\'s '\n + 'configured default.',\n },\n resume: {\n type: 'boolean',\n description: 'Wake the target session if it is persisted but has no running agent. Off by '\n + 'default because delivery to a woken session starts a real agent turn \u2014 a billed model call '\n + 'with that session\\'s full toolset \u2014 in a conversation nobody is watching. Prefer '\n + 'interconnect_list and an already-live target; set this only when that specific session must '\n + 'be reached. The receiver may refuse, answering reason \"resume-refused\".',\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 delivery: { type: 'string' },\n reason: { type: 'string' },\n },\n },\n render: (_args, value) => {\n if (value.delivered) {\n return [{\n type: 'text',\n text: `delivered to ${value.instance}${value.delivery === undefined ? '' : ` via ${value.delivery}`}`,\n }]\n }\n // Each failure gets the response it actually needs: a not-live target is\n // the caller's to re-choose, while an unreachable peer may just be worth\n // retrying. The old single line claimed \"no live session\" even when the\n // peer never answered, which pointed at the wrong thing entirely.\n const text = ((): string => {\n switch (value.reason) {\n case 'unreachable':\n return `not delivered: ${value.instance} did not answer (unreachable or unauthorized)`\n case 'resume-refused':\n return `not delivered: ${value.instance} does not allow waking persisted sessions`\n case 'resume-failed':\n return `not delivered: could not wake \"${_args.sessionId}\" on ${value.instance}`\n + ' (no such persisted session, or another owner holds it)'\n case 'session-owned-by-subagent':\n return `not delivered: \"${_args.sessionId}\" is a subagent's session on ${value.instance}`\n + ' \u2014 its parent agent owns delivery, so reach it through that parent'\n default:\n return `not delivered: no live session \"${_args.sessionId}\" on ${value.instance}`\n + ' \u2014 use interconnect_list to see which sessions are live there,'\n + ' or set resume to wake this one'\n }\n })()\n return [{ type: 'text', text }]\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 ...(args.delivery === undefined ? {} : { delivery: args.delivery }),\n ...(args.resume === undefined ? {} : { resume: args.resume }),\n })\n return {\n delivered: result.delivered,\n instance: result.instance,\n ...(result.delivery === undefined ? {} : { delivery: result.delivery }),\n ...(result.reason === undefined ? {} : { reason: result.reason }),\n }\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 ctx.tools.register(defineTool({\n name: 'interconnect_list',\n description: 'List the live sessions on a peer DSH instance, so a message can be addressed without '\n + 'knowing a session id in advance. Every returned sessionId is a valid interconnect_send target at '\n + 'the time of the call. Only live sessions appear: a session that exists on the peer but has no '\n + 'running agent is not listed and cannot receive a message.',\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 sessions: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n sessionId: { type: 'string', required: true },\n title: { type: 'string' },\n status: { type: 'string' },\n },\n },\n },\n },\n },\n render: (_args, value) => {\n if (!value.reachable) return [{ type: 'text', text: 'unreachable or unauthorized' }]\n const sessions = value.sessions ?? []\n if (sessions.length === 0) {\n return [{ type: 'text', text: `no live sessions on ${value.instance ?? '(unknown instance)'}` }]\n }\n const lines = sessions.map((session) => {\n const title = session.title === undefined ? '' : ` ${session.title}`\n const status = session.status === undefined ? '' : ` [${session.status}]`\n return `${session.sessionId}${title}${status}`\n })\n return [{ type: 'text', text: lines.join('\\n') }]\n },\n },\n async execute(args) {\n const result = await interconnect.list(args.baseUrl)\n if (result === undefined) return { reachable: false }\n return {\n reachable: true,\n instance: result.instance,\n // Rebuild each row so an optional key stays absent rather than\n // becoming an explicit undefined the wire schema would reject.\n sessions: result.sessions.map(session => ({\n sessionId: session.sessionId,\n ...(session.title === undefined ? {} : { title: session.title }),\n ...(session.status === undefined ? {} : { status: session.status }),\n })),\n }\n },\n }))\n}\n"],
5
+ "mappings": ";AAaA,SAAS,kBAAkB;AAKpB,IAAM,SAAS,CAAC,gBAAgB,OAAO;AAOvC,SAAS,MAAM,KAAoB;AACxC,QAAM,eAAe,IAAI;AAEzB,MAAI,MAAM,SAAS,WAAW;AAAA,IAC5B,MAAM;AAAA,IACN,aAAa;AAAA,IAKb,YAAY;AAAA,MACV,SAAS;AAAA,QACP,MAAM;AAAA,QACN,UAAU;AAAA,QACV,aAAa;AAAA,MACf;AAAA,MACA,WAAW;AAAA,QACT,MAAM;AAAA,QACN,UAAU;AAAA,QACV,aAAa;AAAA,MACf;AAAA,MACA,MAAM;AAAA,QACJ,MAAM;AAAA,QACN,UAAU;AAAA,QACV,aAAa;AAAA,MACf;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C,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;IAmFtB,gDAAgD;YAClC,WAAW;IA6BzB,sEAAsE;IACtE,OAAO,CAAC,YAAY;IAKpB;;;;;;;;;OASG;IACH,OAAO,CAAC,YAAY;IAyBpB;;;;;;;;;;;;OAYG;YACW,IAAI;IAyBlB;;;OAGG;YACW,OAAO;IAmDrB,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;AAgJD,eAAe,mBAAmB,CAAA"}
@@ -69,8 +69,11 @@ export interface SendPayload {
69
69
  * receiver does not allow it. Retrying with `resume` set changes nothing.
70
70
  * - `resume-failed` — waking was allowed and attempted but did not yield a live
71
71
  * agent (no persisted session under that id, or another owner holds it).
72
+ * - `session-owned-by-subagent` — the session is reserved to subagent routing,
73
+ * so its parent agent owns delivery. Injecting here would race that parent;
74
+ * the sender must reach the child through its parent instead.
72
75
  */
73
- export type SendFailure = 'session-not-live' | 'unreachable' | 'resume-refused' | 'resume-failed';
76
+ export type SendFailure = 'session-not-live' | 'unreachable' | 'resume-refused' | 'resume-failed' | 'session-owned-by-subagent';
74
77
  /** Business result of a `send` endpoint call. */
75
78
  export interface SendResult {
76
79
  /** True when the target session is live on the receiving instance and the message was delivered. */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/interconnect/types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH;;;GAGG;AACH,eAAO,M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;CAC/B"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/tool-interconnect/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAK7C,uDAAuD;AACvD,eAAO,MAAM,MAAM,UAA4B,CAAA;AAE/C;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAuMxC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/tool-interconnect/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAK7C,uDAAuD;AACvD,eAAO,MAAM,MAAM,UAA4B,CAAA;AAE/C;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CA0MxC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-interconnect",
3
3
  "description": "Cross-instance message/event handoff plugins for DeepSeek Harness (DSH): interconnect service + model-facing tools",
4
- "version": "0.6.0",
4
+ "version": "0.6.1",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",
@@ -42,6 +42,7 @@
42
42
  "peerDependencies": {
43
43
  "@deepseek-ai/cordis": "*",
44
44
  "@deepseek-ai/dsh-agent": "*",
45
+ "@deepseek-ai/dsh-api-remotes": "*",
45
46
  "@deepseek-ai/dsh-credentials": "*",
46
47
  "@deepseek-ai/dsh-llm": "*",
47
48
  "@deepseek-ai/dsh-session": "*",
@@ -57,6 +58,7 @@
57
58
  "@deepseek-ai/cordis": "link:../dsh/vendor/cordis",
58
59
  "@deepseek-ai/schemastery": "link:../dsh/vendor/schemastery",
59
60
  "@deepseek-ai/dsh-agent": "link:../dsh/packages/core/agent",
61
+ "@deepseek-ai/dsh-api-remotes": "link:../dsh/packages/api/remotes",
60
62
  "@deepseek-ai/dsh-credentials": "link:../dsh/packages/credentials/credentials",
61
63
  "@deepseek-ai/dsh-llm": "link:../dsh/packages/llm/llm",
62
64
  "@deepseek-ai/dsh-session": "link:../dsh/packages/core/session",