dsh-zen-remote 1.1.16 → 2.0.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.
Files changed (261) hide show
  1. package/AGENTS.md +54 -9
  2. package/README.md +249 -190
  3. package/README.zh-CN.md +247 -201
  4. package/assets/home.png +0 -0
  5. package/assets/info.png +0 -0
  6. package/assets/pairing.png +0 -0
  7. package/assets/session.png +0 -0
  8. package/assets/sheet.png +0 -0
  9. package/cordis.patch.yml +12 -11
  10. package/cordis.patch.yml.example +24 -9
  11. package/docs/interface.md +57 -2
  12. package/docs/remote-access.en.md +99 -58
  13. package/docs/remote-access.md +99 -42
  14. package/dsh-push.mjs +67 -54
  15. package/lan-gate.mjs +88 -20
  16. package/lib/activity.js +168 -0
  17. package/lib/activity.js.map +1 -0
  18. package/lib/admin-routes.js +526 -0
  19. package/lib/admin-routes.js.map +1 -0
  20. package/lib/client-pairing.js +224 -0
  21. package/lib/client-pairing.js.map +1 -0
  22. package/lib/client-routes.js +674 -0
  23. package/lib/client-routes.js.map +1 -0
  24. package/lib/client.js +11498 -5990
  25. package/lib/config.js +346 -0
  26. package/lib/config.js.map +1 -0
  27. package/lib/fetch-route-intercept.js +418 -0
  28. package/lib/fetch-route-intercept.js.map +1 -0
  29. package/lib/fingerprint.js +365 -0
  30. package/lib/fingerprint.js.map +1 -0
  31. package/lib/http.js +69 -0
  32. package/lib/http.js.map +1 -0
  33. package/lib/index.js +675 -54
  34. package/lib/index.js.map +1 -1
  35. package/lib/intercept-shape.js +81 -0
  36. package/lib/intercept-shape.js.map +1 -0
  37. package/lib/intercept.js +3181 -0
  38. package/lib/intercept.js.map +1 -0
  39. package/lib/lan-gate-server.cjs +532 -121
  40. package/lib/merge-streams.js +1172 -0
  41. package/lib/merge-streams.js.map +1 -0
  42. package/lib/relay-access.js +496 -0
  43. package/lib/relay-access.js.map +1 -0
  44. package/lib/relay-client.js +1303 -0
  45. package/lib/relay-client.js.map +1 -0
  46. package/lib/relay-filter.js +282 -0
  47. package/lib/relay-filter.js.map +1 -0
  48. package/lib/relay-server.js +1813 -0
  49. package/lib/relay-server.js.map +1 -0
  50. package/lib/restart-fields.js +34 -0
  51. package/lib/restart-fields.js.map +1 -0
  52. package/lib/restart-watcher.js +106 -0
  53. package/lib/restart-watcher.js.map +1 -0
  54. package/lib/session-reference.js +157 -0
  55. package/lib/session-reference.js.map +1 -0
  56. package/lib/share-export.js +16 -1
  57. package/lib/share-export.js.map +1 -1
  58. package/lib/share-ops.js +86 -0
  59. package/lib/share-ops.js.map +1 -0
  60. package/lib/share-store.js +294 -0
  61. package/lib/share-store.js.map +1 -0
  62. package/lib/types/activity.d.ts +99 -0
  63. package/lib/types/activity.d.ts.map +1 -0
  64. package/lib/types/admin-routes.d.ts +129 -0
  65. package/lib/types/admin-routes.d.ts.map +1 -0
  66. package/lib/types/client/MobileDrawerFooter.d.ts.map +1 -1
  67. package/lib/types/client/MobileHome.d.ts +1 -1
  68. package/lib/types/client/MobileHome.d.ts.map +1 -1
  69. package/lib/types/client/MobileHomeChips.d.ts +1 -1
  70. package/lib/types/client/MobileHomeChips.d.ts.map +1 -1
  71. package/lib/types/client/MobileSessionHeader.d.ts +13 -2
  72. package/lib/types/client/MobileSessionHeader.d.ts.map +1 -1
  73. package/lib/types/client/MobileSessionInfo.d.ts +20 -3
  74. package/lib/types/client/MobileSessionInfo.d.ts.map +1 -1
  75. package/lib/types/client/RemoteComposerBanner.d.ts +42 -0
  76. package/lib/types/client/RemoteComposerBanner.d.ts.map +1 -0
  77. package/lib/types/client/RemoteHeaderIcon.d.ts +37 -0
  78. package/lib/types/client/RemoteHeaderIcon.d.ts.map +1 -0
  79. package/lib/types/client/RemoteShareMenu.d.ts +28 -0
  80. package/lib/types/client/RemoteShareMenu.d.ts.map +1 -0
  81. package/lib/types/client/RemoteStatusIcon.d.ts +36 -0
  82. package/lib/types/client/RemoteStatusIcon.d.ts.map +1 -0
  83. package/lib/types/client/compat/desktop.d.ts +21 -0
  84. package/lib/types/client/compat/desktop.d.ts.map +1 -0
  85. package/lib/types/client/compat/types.d.ts +57 -0
  86. package/lib/types/client/compat/types.d.ts.map +1 -1
  87. package/lib/types/client/current-session-report.d.ts +37 -0
  88. package/lib/types/client/current-session-report.d.ts.map +1 -0
  89. package/lib/types/client/effects/header-status.d.ts.map +1 -1
  90. package/lib/types/client/effects/keyboard-guard.d.ts.map +1 -1
  91. package/lib/types/client/effects/model-group-side.d.ts +13 -0
  92. package/lib/types/client/effects/model-group-side.d.ts.map +1 -0
  93. package/lib/types/client/effects/permission-sheet.d.ts +39 -0
  94. package/lib/types/client/effects/permission-sheet.d.ts.map +1 -0
  95. package/lib/types/client/effects/remote-session.d.ts +25 -0
  96. package/lib/types/client/effects/remote-session.d.ts.map +1 -0
  97. package/lib/types/client/effects/turn-fold.d.ts +9 -0
  98. package/lib/types/client/effects/turn-fold.d.ts.map +1 -1
  99. package/lib/types/client/index.d.ts.map +1 -1
  100. package/lib/types/client/locales.d.ts +187 -2
  101. package/lib/types/client/locales.d.ts.map +1 -1
  102. package/lib/types/client/remote-fetch.d.ts +51 -0
  103. package/lib/types/client/remote-fetch.d.ts.map +1 -0
  104. package/lib/types/client/remote-group-expansion.d.ts +41 -0
  105. package/lib/types/client/remote-group-expansion.d.ts.map +1 -0
  106. package/lib/types/client/remote-share-css.d.ts +19 -0
  107. package/lib/types/client/remote-share-css.d.ts.map +1 -0
  108. package/lib/types/client/remote-share-register.d.ts +113 -0
  109. package/lib/types/client/remote-share-register.d.ts.map +1 -0
  110. package/lib/types/client/remote-status-css.d.ts +15 -0
  111. package/lib/types/client/remote-status-css.d.ts.map +1 -0
  112. package/lib/types/client/remote-status-register.d.ts +46 -0
  113. package/lib/types/client/remote-status-register.d.ts.map +1 -0
  114. package/lib/types/client/settings/SettingsSection.d.ts +46 -0
  115. package/lib/types/client/settings/SettingsSection.d.ts.map +1 -0
  116. package/lib/types/client/settings/register-settings.d.ts +58 -0
  117. package/lib/types/client/settings/register-settings.d.ts.map +1 -0
  118. package/lib/types/client/settings/settings-css.d.ts +10 -0
  119. package/lib/types/client/settings/settings-css.d.ts.map +1 -0
  120. package/lib/types/client/share/share-preview.d.ts.map +1 -1
  121. package/lib/types/client/styles/composer.css.d.ts +1 -1
  122. package/lib/types/client/styles/composer.css.d.ts.map +1 -1
  123. package/lib/types/client/styles/header.css.d.ts +1 -1
  124. package/lib/types/client/styles/header.css.d.ts.map +1 -1
  125. package/lib/types/client/styles/info.css.d.ts +1 -1
  126. package/lib/types/client/styles/info.css.d.ts.map +1 -1
  127. package/lib/types/client/styles/remote-session.css.d.ts +2 -0
  128. package/lib/types/client/styles/remote-session.css.d.ts.map +1 -0
  129. package/lib/types/client-data/current-session.d.ts +41 -0
  130. package/lib/types/client-data/current-session.d.ts.map +1 -0
  131. package/lib/types/client-data/model-group-side.d.ts +44 -0
  132. package/lib/types/client-data/model-group-side.d.ts.map +1 -0
  133. package/lib/types/client-data/remote-group-expansion.d.ts +76 -0
  134. package/lib/types/client-data/remote-group-expansion.d.ts.map +1 -0
  135. package/lib/types/client-data/remote-status.d.ts +148 -0
  136. package/lib/types/client-data/remote-status.d.ts.map +1 -0
  137. package/lib/types/client-data/settings-form.d.ts +774 -0
  138. package/lib/types/client-data/settings-form.d.ts.map +1 -0
  139. package/lib/types/client-data/shares.d.ts +211 -0
  140. package/lib/types/client-data/shares.d.ts.map +1 -0
  141. package/lib/types/client-pairing.d.ts +114 -0
  142. package/lib/types/client-pairing.d.ts.map +1 -0
  143. package/lib/types/client-routes.d.ts +112 -0
  144. package/lib/types/client-routes.d.ts.map +1 -0
  145. package/lib/types/config.d.ts +200 -0
  146. package/lib/types/config.d.ts.map +1 -0
  147. package/lib/types/fetch-route-intercept.d.ts +156 -0
  148. package/lib/types/fetch-route-intercept.d.ts.map +1 -0
  149. package/lib/types/fingerprint.d.ts +166 -0
  150. package/lib/types/fingerprint.d.ts.map +1 -0
  151. package/lib/types/http.d.ts +41 -0
  152. package/lib/types/http.d.ts.map +1 -0
  153. package/lib/types/index.d.ts +56 -24
  154. package/lib/types/index.d.ts.map +1 -1
  155. package/lib/types/intercept-shape.d.ts +32 -0
  156. package/lib/types/intercept-shape.d.ts.map +1 -0
  157. package/lib/types/intercept.d.ts +442 -0
  158. package/lib/types/intercept.d.ts.map +1 -0
  159. package/lib/types/merge-streams.d.ts +398 -0
  160. package/lib/types/merge-streams.d.ts.map +1 -0
  161. package/lib/types/relay-access.d.ts +310 -0
  162. package/lib/types/relay-access.d.ts.map +1 -0
  163. package/lib/types/relay-client.d.ts +274 -0
  164. package/lib/types/relay-client.d.ts.map +1 -0
  165. package/lib/types/relay-filter.d.ts +103 -0
  166. package/lib/types/relay-filter.d.ts.map +1 -0
  167. package/lib/types/relay-server.d.ts +208 -0
  168. package/lib/types/relay-server.d.ts.map +1 -0
  169. package/lib/types/restart-fields.d.ts +22 -0
  170. package/lib/types/restart-fields.d.ts.map +1 -0
  171. package/lib/types/restart-watcher.d.ts +83 -0
  172. package/lib/types/restart-watcher.d.ts.map +1 -0
  173. package/lib/types/session-reference.d.ts +66 -0
  174. package/lib/types/session-reference.d.ts.map +1 -0
  175. package/lib/types/share-export.d.ts +14 -1
  176. package/lib/types/share-export.d.ts.map +1 -1
  177. package/lib/types/share-ops.d.ts +79 -0
  178. package/lib/types/share-ops.d.ts.map +1 -0
  179. package/lib/types/share-store.d.ts +87 -0
  180. package/lib/types/share-store.d.ts.map +1 -0
  181. package/lib/types/virtual-id.d.ts +52 -0
  182. package/lib/types/virtual-id.d.ts.map +1 -0
  183. package/lib/virtual-id.js +66 -0
  184. package/lib/virtual-id.js.map +1 -0
  185. package/llms.txt +17 -14
  186. package/package.json +60 -50
  187. package/scripts/build-client.mjs +5 -3
  188. package/scripts/check-host-shadow.mjs +19 -2
  189. package/scripts/check-settings-form.mjs +933 -0
  190. package/scripts/check-shares.mjs +397 -0
  191. package/scripts/check-upload-endpoint.mjs +59 -3
  192. package/scripts/sync-doc-version.mjs +8 -15
  193. package/scripts/verify-fingerprint-live.mjs +111 -0
  194. package/src/activity.ts +218 -0
  195. package/src/admin-routes.ts +627 -0
  196. package/src/client/MobileAttachButton.tsx +2 -2
  197. package/src/client/MobileAttachChips.tsx +3 -3
  198. package/src/client/MobileDrawerFooter.tsx +7 -4
  199. package/src/client/MobileHome.tsx +20 -16
  200. package/src/client/MobileHomeChips.tsx +16 -16
  201. package/src/client/MobileNavOverlay.tsx +2 -2
  202. package/src/client/MobileNavToggle.tsx +3 -3
  203. package/src/client/MobileSessionHeader.tsx +63 -42
  204. package/src/client/MobileSessionInfo.tsx +118 -17
  205. package/src/client/RemoteComposerBanner.tsx +76 -0
  206. package/src/client/RemoteHeaderIcon.tsx +103 -0
  207. package/src/client/RemoteShareMenu.tsx +57 -0
  208. package/src/client/RemoteStatusIcon.tsx +91 -0
  209. package/src/client/compat/desktop.ts +22 -0
  210. package/src/client/compat/types.ts +62 -0
  211. package/src/client/current-session-report.ts +164 -0
  212. package/src/client/effects/header-status.ts +21 -17
  213. package/src/client/effects/keyboard-guard.ts +65 -1
  214. package/src/client/effects/model-group-side.ts +132 -0
  215. package/src/client/effects/permission-sheet.ts +149 -0
  216. package/src/client/effects/remote-session.ts +68 -0
  217. package/src/client/effects/turn-fold.ts +52 -0
  218. package/src/client/index.tsx +158 -36
  219. package/src/client/locales.ts +396 -2
  220. package/src/client/remote-fetch.ts +125 -0
  221. package/src/client/remote-group-expansion.ts +190 -0
  222. package/src/client/remote-share-css.ts +54 -0
  223. package/src/client/remote-share-register.ts +244 -0
  224. package/src/client/remote-status-css.ts +64 -0
  225. package/src/client/remote-status-register.ts +107 -0
  226. package/src/client/settings/SettingsSection.tsx +1229 -0
  227. package/src/client/settings/register-settings.ts +116 -0
  228. package/src/client/settings/settings-css.ts +236 -0
  229. package/src/client/share/share-preview.tsx +6 -3
  230. package/src/client/share/share-sheet.tsx +3 -3
  231. package/src/client/styles/composer.css.ts +119 -26
  232. package/src/client/styles/header.css.ts +7 -7
  233. package/src/client/styles/info.css.ts +74 -0
  234. package/src/client/styles/remote-session.css.ts +274 -0
  235. package/src/client-data/current-session.ts +57 -0
  236. package/src/client-data/model-group-side.ts +65 -0
  237. package/src/client-data/remote-group-expansion.ts +145 -0
  238. package/src/client-data/remote-status.ts +374 -0
  239. package/src/client-data/settings-form.ts +1371 -0
  240. package/src/client-data/shares.ts +467 -0
  241. package/src/client-pairing.ts +244 -0
  242. package/src/client-routes.ts +732 -0
  243. package/src/config.ts +447 -0
  244. package/src/fetch-route-intercept.ts +510 -0
  245. package/src/fingerprint.ts +410 -0
  246. package/src/http.ts +68 -0
  247. package/src/index.ts +719 -62
  248. package/src/intercept-shape.ts +87 -0
  249. package/src/intercept.ts +3510 -0
  250. package/src/merge-streams.ts +1279 -0
  251. package/src/relay-access.ts +672 -0
  252. package/src/relay-client.ts +1514 -0
  253. package/src/relay-filter.ts +291 -0
  254. package/src/relay-server.ts +2063 -0
  255. package/src/restart-fields.ts +36 -0
  256. package/src/restart-watcher.ts +140 -0
  257. package/src/session-reference.ts +156 -0
  258. package/src/share-export.ts +26 -1
  259. package/src/share-ops.ts +114 -0
  260. package/src/share-store.ts +373 -0
  261. package/src/virtual-id.ts +74 -0
@@ -0,0 +1,2063 @@
1
+ /**
2
+ * Server-side relay routes for the desktop client (T22a routes, T22b
3
+ * streaming, T32 event forwarding, T41b plain-HTTP passthrough):
4
+ * authentication, ping, handshake, the single invoke passthrough, the
5
+ * `relay/v1/http` GET dispatch through the host's shared `/api` fetch
6
+ * handler, the NDJSON stream subscription route with share-change
7
+ * synchronization, and the forwarded-event half — the
8
+ * `$zr/events` subscription over the gateway's `$events` wire stream plus
9
+ * the `relay/v1/event-result` answer route. Activity stats remain a later
10
+ * task.
11
+ *
12
+ * Why the secret: the desktop client is a Node process on another machine —
13
+ * it has no DSH login cookie, so the gateway authenticates it with a Bearer
14
+ * pairing token and marks the forwarded request with `x-zen-remote-*` headers.
15
+ * But DSH only listens on 127.0.0.1, where any local process could bypass the
16
+ * gateway and forge those headers. The plugin therefore mints a per-apply
17
+ * secret, hands it to the gateway child through `LAN_GATE_RELAY_SECRET`, the
18
+ * gateway stamps every device-authenticated forward with it, and these routes
19
+ * re-verify it on every request with `timingSafeEqual`.
20
+ *
21
+ * Path dispatch never decodes the request path. The gateway only admits relay
22
+ * paths whose raw and URL-normalized forms are byte-identical, which lets
23
+ * `/_dsh/zen-remote/relay/..%2f..%2fapi` through — decoding it here before
24
+ * matching would reopen the traversal the gateway just closed. Every route is
25
+ * an exact comparison on `new URL(req.url).pathname` as-is; anything else is
26
+ * a 404.
27
+ */
28
+
29
+ import { randomBytes, timingSafeEqual } from 'node:crypto'
30
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
31
+ import { createRequire } from 'node:module'
32
+ import { join } from 'node:path'
33
+ import type { IncomingMessage, ServerResponse } from 'node:http'
34
+ import type { ShareStore } from './share-store.js'
35
+ import { decideHttpRoute, decideInvoke, decideStream, decideUploadQuery, parseEventResultBody } from './relay-access.js'
36
+ import {
37
+ createWorkspaceFollowState,
38
+ filterControlFrame,
39
+ filterJobListFrame,
40
+ filterModelCatalogResult,
41
+ filterSessionListResult,
42
+ filterWorkspaceFrame,
43
+ } from './relay-filter.js'
44
+ import { SESSION_REFERENCE_URI, collectReferenceTexts, decodeSessionReferenceUri } from './session-reference.js'
45
+
46
+ /**
47
+ * Registration prefix on the host webServer. Deliberately WITHOUT the
48
+ * trailing slash: the webserver matches a prefix route as `pathname === p ||
49
+ * pathname.startsWith(p + '/')`, so a trailing slash here would match only
50
+ * `…/relay//…` shapes and never `…/relay/ping`.
51
+ */
52
+ export const RELAY_PREFIX = '/_dsh/zen-remote/relay'
53
+
54
+ /** The one protocol version this file speaks; the handshake reports it. */
55
+ const RELAY_PROTOCOL = 1
56
+
57
+ /** Request body ceiling for the POST routes other than invoke. */
58
+ const MAX_BODY_BYTES = 1024 * 1024
59
+
60
+ /**
61
+ * Body ceiling for the binary upload channel alone (T51): a shared session's
62
+ * non-image file attachments. DSH's own upload route has NO byte cap — the
63
+ * host stores the stream verbatim (`saveFileStreamVerbatim` →
64
+ * `publishImmutableObjectStream`, RT dsh-attachment-local lib/index.js
65
+ * ~699-716; the 20 MiB `maxImageBytes` there covers INLINE images only), so
66
+ * there is no host number to mirror and this relay picks its own: 100 MiB
67
+ * per upload, checked first against `Content-Length` (refused before a byte
68
+ * moves) and then counted while the stream is pumped (a chunked body has no
69
+ * length header — the sub-client's undici forbids hand-set length headers,
70
+ * so the streaming count is the path its uploads normally take). Past the
71
+ * cap the forward is aborted, the rest of the request is drained and the
72
+ * answer is 413 `payload-too-large`.
73
+ *
74
+ * SLOW-LINK BOUND (T51-fix, for the docs): a single legitimate upload is
75
+ * also bounded in TIME — the host's HTTP server keeps its default 300 s
76
+ * request deadline, and the sub-client's own round-trip budget caps at the
77
+ * same 300 s (relay-client.ts, the T31-fix rule) — so a 100 MiB body needs
78
+ * roughly 2.8 Mbps sustained end to end; slower links fail the call (the
79
+ * client-side refusal keeps the connection state) rather than hanging.
80
+ */
81
+ export const MAX_UPLOAD_BYTES = 100 * 1024 * 1024
82
+
83
+ /** The `/api` route the upload channel dispatches into, verbatim from the
84
+ * host's own registration (RT dsh-client-file-upload lib/index.js:73). */
85
+ export const UPLOAD_HTTP_PATH = '/api/session/uploadFileBinary'
86
+
87
+ /**
88
+ * Body ceiling for the invoke route alone: the prompt routes carry inline
89
+ * images in their content blocks (`session/prompt` / `subagents/prompt` take
90
+ * base64 `image` parts; DSH admits one image up to 20 MiB by default —
91
+ * `maxImageBytes`, dsh-attachment-local — which base64 inflates to ~27 MiB),
92
+ * so one full-size inline image plus its envelope needs 32 MiB. It is NOT
93
+ * sized for `fileUploads/upload`: the UI's real file uploads ride the HTTP
94
+ * route `api/session/uploadFileBinary` (T41b), not this JSON relay. The
95
+ * buffer only ever grows to the REAL body size; the cap decides
96
+ * accept/refuse, and a body that outgrows it is drained and answered 413
97
+ * like any other oversized read.
98
+ */
99
+ const MAX_INVOKE_BODY_BYTES = 32 * 1024 * 1024
100
+
101
+ /** Error messages forwarded to the client are clipped to this many chars. */
102
+ const MAX_MESSAGE_CHARS = 500
103
+
104
+ /**
105
+ * DSH's own error vocabulary is `namespace/name` (`gateway/cancelled`,
106
+ * `session/unknown-session`, …). Only codes of that exact SHAPE travel to the
107
+ * client with their message — Node's system errors also carry a string
108
+ * `code` (`ENOENT`), and their messages quote server-side absolute paths, so
109
+ * anything not shaped like a DSH code reports `internal` with no message.
110
+ */
111
+ const DSH_ERROR_CODE = /^[a-z][a-zA-Z-]*\/[a-zA-Z-]+$/
112
+
113
+ /** Concurrent streams one device may hold open (per `x-zen-remote-device`). */
114
+ const MAX_STREAMS_PER_DEVICE = 32
115
+
116
+ /**
117
+ * Concurrent invokes one device may keep in flight (CP4): a runaway or
118
+ * hostile client must not pin unbounded host work behind this route the way
119
+ * it must not hold unbounded streams. CP5 raises the cap to 32, the same
120
+ * budget as the stream cap above: opening one remote session in the UI fires
121
+ * a burst of concurrent invokes, and under high latency they stay in flight
122
+ * long enough for the old 8 to refuse real traffic. Past the cap the request
123
+ * answers 429 `too-many-invokes` and the counter is untouched.
124
+ */
125
+ const MAX_INVOKES_PER_DEVICE = 32
126
+
127
+ /**
128
+ * Concurrent uploads one device may keep in flight (T51-fix): the invoke
129
+ * twin of the budgets above, at the same 8 that fits a burst of attachments.
130
+ * Counted only after the query, handler and budget walls passed; a 429 is
131
+ * answered (after the body is drained) without touching the counter. Without
132
+ * this, a stalled or hostile client pins unbounded host uploads — each an
133
+ * in-process dispatch writing to the attachments store — behind this route.
134
+ */
135
+ const MAX_UPLOADS_PER_DEVICE = 8
136
+
137
+ /** Most recent forwarded waterfall events remembered per `$zr/events`
138
+ * subscription (T32-fix): the registry is only an ownership record, so this
139
+ * bounds a pathological burst the same way the job cache does — past the
140
+ * cap the OLDEST entry is dropped (a forwarded-but-forgotten event answers
141
+ * `unknown-event`, which the client surfaces as the same silent ok DSH
142
+ * gives a stale result). */
143
+ const EVENT_REGISTRY_LIMIT = 500
144
+
145
+ /** Stream heartbeat when the caller does not inject one. */
146
+ const DEFAULT_HEARTBEAT_MS = 15_000
147
+
148
+ /** How long a stream's finish may wait for a backed-up socket buffer to
149
+ * drain before the response is destroyed (T43-A). */
150
+ const DEFAULT_END_DRAIN_TIMEOUT_MS = 5_000
151
+
152
+ /** The upload cap used unless the wiring injects one (tests shrink it). */
153
+ const DEFAULT_UPLOAD_CAP_BYTES = MAX_UPLOAD_BYTES
154
+
155
+ /**
156
+ * Decode the gateway's `x-zen-remote-device-name` marking header (T59): the
157
+ * gateway percent-encodes the device table's current name; `undefined` when
158
+ * the header is absent, blank, or not valid percent-encoding (an old gateway,
159
+ * a direct local call). Never throws.
160
+ */
161
+ function deviceNameHeaderOf(req: IncomingMessage): string | undefined {
162
+ const raw = headerValue(req, 'x-zen-remote-device-name')
163
+ if (raw === undefined || raw === '') return undefined
164
+ try {
165
+ const decoded = decodeURIComponent(raw)
166
+ return decoded === '' ? undefined : decoded
167
+ } catch {
168
+ return undefined
169
+ }
170
+ }
171
+
172
+ /** Most recent jobs remembered per session for ownership checks (4b): the
173
+ * latest `job/list` frame replaces the whole set, so this only bounds a
174
+ * pathological single frame. */
175
+ const JOB_CACHE_LIMIT = 1024
176
+
177
+ /** Shape of the `typertGateway` service this route needs (measured live,
178
+ * docs/spike-relay.md §2.1: invoke returns the unwrapped business value and
179
+ * throws errors carrying a string `code`; stream opens one `mode: 'stream'`
180
+ * method and resolves to an async iterable of its frames). Declared
181
+ * structurally instead of augmenting `Context`: the providing package is not
182
+ * a devDependency here, and a local augmentation could collide with its own
183
+ * once that changes.
184
+ *
185
+ * T32 adds the two event surfaces, both OPTIONAL: only `$zr/events` and
186
+ * `relay/v1/event-result` touch them, so a composition (or test fake) without
187
+ * them keeps every other route working and the event routes answer
188
+ * `gateway/service-unavailable`.
189
+ *
190
+ * - `wireStream.open('$events', …)` is the ONLY way to the forwarded-event
191
+ * stream — `gw.stream({namespace:'$events'})` refuses with
192
+ * `gateway/invocation-unavailable` (docs/spike-relay.md §2.1 坑 1). It
193
+ * resolves to an async iterable whose first frame is the `ready` frame.
194
+ * - `dispatchRpc('$events/result', payload, signal, peer)` is the only way to
195
+ * answer a forwarded waterfall — the gateway special-cases the endpoint
196
+ * before its typert dispatch — and returns the `{ok,…}` envelope itself.
197
+ */
198
+ export interface RelayGateway {
199
+ invoke(call: { namespace: string; method: string; args: unknown; signal?: AbortSignal }): Promise<unknown>
200
+ stream(call: {
201
+ namespace: string
202
+ method: string
203
+ args: unknown
204
+ signal?: AbortSignal
205
+ }): Promise<AsyncIterable<unknown>>
206
+ /** The host's wire adapter, shared by the WebSocket mux and the local
207
+ * transports. `open` is the async 0.2.0 method. */
208
+ wireStream?: {
209
+ open(endpoint: string, payload: unknown, uplink: unknown, peer: unknown, signal: AbortSignal | undefined): unknown
210
+ }
211
+ /** The host's `/api` dispatch, owning the `$events/result` special case. */
212
+ dispatchRpc?(
213
+ endpoint: string,
214
+ payload: unknown,
215
+ signal: AbortSignal | undefined,
216
+ peer: unknown,
217
+ ): Promise<unknown>
218
+ }
219
+
220
+ /** What the handshake reports about this server. `serverName` is a CALLBACK
221
+ * on purpose: the row value is a volatile (`{ get() }` wrapped) setting that
222
+ * can change without restarting the plugin row, so it must be recomputed at
223
+ * handshake time, not snapshotted at registration. `fingerprints` is a
224
+ * callback too (T42), awaited per handshake so a just-restarted server never
225
+ * serves a stale map; a THROWN compute degrades to the empty map here so a
226
+ * broken fingerprint source can never fail the handshake itself — the
227
+ * client's comparison judges every group `unavailable`, never `different`. */
228
+ export interface RelayServerInfo {
229
+ serverId: string
230
+ serverName: () => string
231
+ dshVersion: string
232
+ fingerprints?: () => Record<string, string> | Promise<Record<string, string>>
233
+ }
234
+
235
+ export interface RelayHandlerOptions {
236
+ /** The per-apply shared secret; an empty one refuses every request. */
237
+ secret: string
238
+ /** The shared-session table deciding reachability. */
239
+ store: ShareStore
240
+ /** The host gateway service invokes and streams go through. */
241
+ gateway: RelayGateway
242
+ /** Handshake facts. */
243
+ serverInfo: RelayServerInfo
244
+ /** Ancestor lookup for subagent reachability; defaults to "no parent". */
245
+ parentOf?: (id: string) => string | undefined
246
+ /** The host's `/api` shared-fetch dispatcher (T41b), probed lazily per
247
+ * request: `undefined` — no connection service, or no shared handler —
248
+ * answers 501 `unsupported` instead of touching the network. The wiring
249
+ * builds it from `connection.createSharedFetchHandler('/api').fetch`
250
+ * (dsh-client-connection), the in-process entry that dispatches a
251
+ * synthetic Request to the same exact-fetch route table the browser's
252
+ * `/api` transport uses — no loopback HTTP, no login state. */
253
+ getApiFetch?: () => ((request: Request) => Promise<Response>) | undefined
254
+ /** Stream heartbeat interval in ms (a `{"type":"ping"}` line that keeps
255
+ * reverse proxies from timing the idle stream away); defaults to 15000.
256
+ * Tests inject a small value. */
257
+ heartbeatMs?: number
258
+ /** How long a stream's finish may wait for a backed-up write buffer to
259
+ * drain before the response is destroyed (T43-A: a client that stopped
260
+ * reading must not pin the viewer count and the device budget forever);
261
+ * defaults to 5000. Tests inject a small value. */
262
+ endDrainTimeoutMs?: number
263
+ /** The binary upload channel's byte cap (T51); defaults to
264
+ * {@link MAX_UPLOAD_BYTES} (100 MiB). Tests inject a small value so the
265
+ * Content-Length and streaming-count refusals stay cheap to drive. */
266
+ uploadCapBytes?: number
267
+ /** How long an upload refusal's tail drain may run before the socket is
268
+ * destroyed (the {@link DRAIN_DEADLINE_MS} bound); defaults to 10000.
269
+ * Tests inject a small value so the deadline path stays cheap to drive. */
270
+ drainDeadlineMs?: number
271
+ }
272
+
273
+ /**
274
+ * The relay route handler plus its introspection surface. A function WITH
275
+ * properties on purpose: the webServer registration wants exactly a request
276
+ * handler, and the "who is looking" badge (a later UI task) wants the
277
+ * per-session viewer counts — while the row-reload path (T22b-fix) needs to
278
+ * tear every open stream down with the handler that owns it.
279
+ */
280
+ export interface RelayHandler {
281
+ (req: IncomingMessage, res: ServerResponse): Promise<void>
282
+ /** How many session-scoped relay streams currently reference the session
283
+ * (across all devices). */
284
+ viewerCount(sessionId: string): number
285
+ /** End every currently open stream: each client gets one
286
+ * `error{code:'server-restart'}` line, then the response ends (a client
287
+ * that stopped reading is destroyed after {@link RelayHandlerOptions.endDrainTimeoutMs}),
288
+ * the upstream subscription aborts and every counter/listener cleans up —
289
+ * including the handler's own share-table subscriptions, so a table change
290
+ * after the close never reaches this handler again (T43-B). A plugin row
291
+ * reload builds a new handler and share table; without this the streams of
292
+ * the OLD handler would keep pushing, unreachable by any unshare. */
293
+ closeAll(reason: string): void
294
+ }
295
+
296
+ /** One 8-hex-character short server id: four random bytes, enough to tell a
297
+ * handful of servers apart in a client's server list without leaking anything
298
+ * countable about the deployment. */
299
+ const SERVER_ID_PATTERN = /^[0-9a-f]{8}$/
300
+
301
+ const SERVER_ID_FILE = 'zen-remote-server.json'
302
+
303
+ /**
304
+ * Read the persisted server id, creating (and persisting) one on first use.
305
+ * A missing file is the normal first run; an unreadable or damaged file must
306
+ * never take the host down, so every failure degrades to a fresh per-process
307
+ * id that simply is not remembered across restarts.
308
+ */
309
+ export function loadServerId(home: string): string {
310
+ const file = join(home, SERVER_ID_FILE)
311
+ try {
312
+ const parsed: unknown = JSON.parse(readFileSync(file, 'utf8'))
313
+ const id = (parsed as { serverId?: unknown } | null)?.serverId
314
+ if (typeof id === 'string' && SERVER_ID_PATTERN.test(id)) return id
315
+ } catch {
316
+ // First run, unreadable path, or unparsable JSON — mint a new one below.
317
+ }
318
+ const id = randomBytes(4).toString('hex')
319
+ try {
320
+ // tmp + rename, the same atomic dance the share table uses: a crash
321
+ // mid-write must not leave a half-file that would corrupt the next read.
322
+ mkdirSync(home, { recursive: true })
323
+ writeFileSync(`${file}.tmp`, JSON.stringify({ serverId: id }))
324
+ renameSync(`${file}.tmp`, file)
325
+ } catch {
326
+ // Unwritable home: the id stays process-local. Nothing may throw here.
327
+ }
328
+ return id
329
+ }
330
+
331
+ /**
332
+ * The DSH version reported in the handshake: `DSH_CLIENT_VERSION` when the
333
+ * host sets it, else the version of the `@deepseek-ai/dsh` package resolved
334
+ * from here (compositions without that package installed — tests, Electron —
335
+ * report `'unknown'`). Never throws.
336
+ */
337
+ export function resolveDshVersion(): string {
338
+ const fromEnv = process.env.DSH_CLIENT_VERSION
339
+ if (typeof fromEnv === 'string' && fromEnv !== '') return fromEnv
340
+ try {
341
+ const require = createRequire(import.meta.url)
342
+ const pkg = require('@deepseek-ai/dsh/package.json') as { version?: unknown }
343
+ if (pkg !== null && typeof pkg === 'object' && typeof pkg.version === 'string') return pkg.version
344
+ } catch {
345
+ // Not resolvable in this composition — 'unknown' is an honest answer.
346
+ }
347
+ return 'unknown'
348
+ }
349
+
350
+ function responseJson(res: ServerResponse, status: number, body: unknown): void {
351
+ const bytes = Buffer.from(JSON.stringify(body))
352
+ res.setHeader('Content-Type', 'application/json; charset=utf-8')
353
+ res.setHeader('Content-Length', String(bytes.length))
354
+ res.setHeader('Cache-Control', 'no-store')
355
+ res.setHeader('X-Content-Type-Options', 'nosniff')
356
+ res.setHeader('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none'")
357
+ res.writeHead(status)
358
+ res.end(bytes)
359
+ }
360
+
361
+ /** First (and in practice only) value of one request header. */
362
+ function headerValue(req: IncomingMessage, name: string): string | undefined {
363
+ const raw = req.headers[name]
364
+ const value = Array.isArray(raw) ? raw[0] : raw
365
+ return typeof value === 'string' ? value : undefined
366
+ }
367
+
368
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
369
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
370
+ }
371
+
372
+ /** Non-empty string — the client face's `isRemoteEventId` /
373
+ * `isRemoteEventAgentId` / `validRemoteEventName` (dsh-api-gateway
374
+ * lib/client.js). */
375
+ function isEventId(value: unknown): value is string {
376
+ return typeof value === 'string' && value !== ''
377
+ }
378
+
379
+ /**
380
+ * The two `$events` frame shapes a sub-client may be shown, proven
381
+ * well-formed BEFORE forwarding (T32-fix2). The client face's
382
+ * `parseRemoteEventFrame` validates every variant with exact keys — one
383
+ * extra or missing field throws and fails the sub-client's whole `$events`
384
+ * generation — so the relay only forwards frames that would survive that
385
+ * parse. A waterfall's `request` must additionally be a plain object
386
+ * without `agent`/`signal`: the host projection strips those, and the
387
+ * client face refuses them back.
388
+ */
389
+ interface ForwardableWaterfallFrame extends Record<string, unknown> {
390
+ type: 'waterfall'
391
+ event: string
392
+ eventId: string
393
+ agentId: string
394
+ request: Record<string, unknown>
395
+ }
396
+
397
+ interface ForwardableCancelFrame extends Record<string, unknown> {
398
+ type: 'cancel'
399
+ eventId: string
400
+ }
401
+
402
+ /**
403
+ * T75: the ONE emit shape the relay forwards — a single session's
404
+ * running-state flip (`api-session/status`), exactly what the host emits on
405
+ * `agent/status` (RT dsh-api-session-controller lib/index.js:2884-2886:
406
+ * `ctx.emit("api-session/status", agent.id, status === "running")`), carried
407
+ * on the wire as the client face's exact-keys emit with a JSON-array `args`
408
+ * (RT dsh-api-gateway lib/index.js:846-853 builds `{type, event, args}`;
409
+ * lib/client.js `parseRemoteEventFrame` demands that shape back).
410
+ */
411
+ interface ForwardableStatusEmitFrame extends Record<string, unknown> {
412
+ type: 'emit'
413
+ event: 'api-session/status'
414
+ args: [string, boolean]
415
+ }
416
+
417
+ function isForwardableWaterfall(frame: Record<string, unknown>): frame is ForwardableWaterfallFrame {
418
+ return (
419
+ Reflect.ownKeys(frame).length === 5 &&
420
+ ['type', 'event', 'eventId', 'agentId', 'request'].every((key) => Object.hasOwn(frame, key)) &&
421
+ isEventId(frame.event) &&
422
+ isEventId(frame.eventId) &&
423
+ isEventId(frame.agentId) &&
424
+ isPlainObject(frame.request) &&
425
+ !Object.hasOwn(frame.request, 'agent') &&
426
+ !Object.hasOwn(frame.request, 'signal')
427
+ )
428
+ }
429
+
430
+ function isForwardableCancel(frame: Record<string, unknown>): frame is ForwardableCancelFrame {
431
+ return (
432
+ Reflect.ownKeys(frame).length === 2 &&
433
+ Object.hasOwn(frame, 'type') &&
434
+ Object.hasOwn(frame, 'eventId') &&
435
+ isEventId(frame.eventId)
436
+ )
437
+ }
438
+
439
+ function isForwardableStatusEmit(frame: Record<string, unknown>): frame is ForwardableStatusEmitFrame {
440
+ return (
441
+ Reflect.ownKeys(frame).length === 3 &&
442
+ ['type', 'event', 'args'].every((key) => Object.hasOwn(frame, key)) &&
443
+ frame.event === 'api-session/status' &&
444
+ Array.isArray(frame.args) &&
445
+ frame.args.length === 2 &&
446
+ isEventId(frame.args[0]) &&
447
+ typeof frame.args[1] === 'boolean'
448
+ )
449
+ }
450
+
451
+ /**
452
+ * Constant-time secret comparison. Different lengths are trivially unequal
453
+ * (timingSafeEqual itself throws on that); an empty configured secret refuses
454
+ * everything, so "the gateway half is off" can never fail open.
455
+ */
456
+ function secretsMatch(provided: string | undefined, secret: string): boolean {
457
+ if (secret === '' || provided === undefined) return false
458
+ const left = Buffer.from(provided, 'utf8')
459
+ const right = Buffer.from(secret, 'utf8')
460
+ if (left.length !== right.length) return false
461
+ return timingSafeEqual(left, right)
462
+ }
463
+
464
+ /**
465
+ * Read one JSON object body under the byte cap. The EMPTY body parses as the
466
+ * empty object (the handshake takes no arguments; invoke then fails its own
467
+ * field checks). Three outcomes, kept apart: a parsed object (`ok`),
468
+ * unparsable or non-object JSON (`invalid` → the routes answer 400), and a
469
+ * body past the cap (`too-large` → the routes answer 413). An oversized body
470
+ * is DRAINED, not aborted mid-read: destroying the socket before the
471
+ * response goes out would leave the desktop client with a connection error
472
+ * instead of the status code explaining the refusal. A `Content-Length`
473
+ * that already names more than the cap skips the buffering entirely — the
474
+ * drain still runs to the body's end before the verdict resolves.
475
+ */
476
+ type JsonBody =
477
+ | { kind: 'ok'; body: Record<string, unknown> }
478
+ | { kind: 'invalid' }
479
+ | { kind: 'too-large' }
480
+
481
+ const PAYLOAD_TOO_LARGE = Object.freeze({ ok: false, error: { code: 'payload-too-large', details: {} } })
482
+
483
+ /**
484
+ * One readJsonObject plus the two failure answers every POST route shares:
485
+ * an oversized body is 413 `payload-too-large`, unparsable JSON is 400
486
+ * `bad-request` — the two are distinct answers, not one "bad body" pile.
487
+ * `undefined` means the response is already written and the caller returns.
488
+ */
489
+ async function readBodyOrRespond(
490
+ req: IncomingMessage,
491
+ res: ServerResponse,
492
+ cap = MAX_BODY_BYTES,
493
+ ): Promise<Record<string, unknown> | undefined> {
494
+ const read = await readJsonObject(req, cap)
495
+ if (read.kind === 'too-large') {
496
+ responseJson(res, 413, PAYLOAD_TOO_LARGE)
497
+ return undefined
498
+ }
499
+ if (read.kind === 'invalid') {
500
+ responseJson(res, 400, { ok: false, error: { code: 'bad-request' } })
501
+ return undefined
502
+ }
503
+ return read.body
504
+ }
505
+
506
+ async function readJsonObject(req: IncomingMessage, cap = MAX_BODY_BYTES): Promise<JsonBody> {
507
+ return new Promise((resolve) => {
508
+ const chunks: Buffer[] = []
509
+ // `Number(undefined)` is NaN, and `NaN > cap` is false: a chunked body
510
+ // (no length header) simply falls through to the byte counting below.
511
+ let tooLarge = Number(req.headers['content-length']) > cap
512
+ let size = 0
513
+ let done = false
514
+ const finish = (value: JsonBody): void => {
515
+ if (!done) {
516
+ done = true
517
+ resolve(value)
518
+ }
519
+ }
520
+ req.on('data', (chunk: Buffer) => {
521
+ if (done || tooLarge) return
522
+ size += chunk.length
523
+ if (size > cap) {
524
+ tooLarge = true
525
+ chunks.length = 0
526
+ return
527
+ }
528
+ chunks.push(chunk)
529
+ // Past the cap: keep consuming without buffering.
530
+ })
531
+ req.on('end', () => {
532
+ if (done) return
533
+ if (tooLarge) {
534
+ finish({ kind: 'too-large' })
535
+ return
536
+ }
537
+ if (size === 0) {
538
+ finish({ kind: 'ok', body: {} })
539
+ return
540
+ }
541
+ let parsed: unknown
542
+ try {
543
+ parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'))
544
+ } catch {
545
+ finish({ kind: 'invalid' })
546
+ return
547
+ }
548
+ finish(
549
+ parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
550
+ ? { kind: 'ok', body: parsed as Record<string, unknown> }
551
+ : { kind: 'invalid' },
552
+ )
553
+ })
554
+ req.on('error', () => finish({ kind: 'invalid' }))
555
+ })
556
+ }
557
+
558
+ /**
559
+ * How much MORE of an upload request's body a refusal is willing to swallow
560
+ * beyond what was already read (`fromBytes` — the cap pump's count carries
561
+ * over, the drain never gets a fresh allowance), and how long it will wait
562
+ * for that tail before cutting the socket: the answer goes out BEFORE the
563
+ * drain (the two 413 paths write it with `connection: close`), so a
564
+ * still-sending client reads the status code first and its tail is disposed
565
+ * second. A hostile endless stream costs at most this much for this long —
566
+ * never the answer, never the process.
567
+ */
568
+ const DRAIN_SLACK_BYTES = 8 * 1024 * 1024
569
+ const DRAIN_DEADLINE_MS = 10_000
570
+
571
+ /**
572
+ * Consume and discard the tail of one upload request, bounded by
573
+ * {@link DRAIN_SLACK_BYTES} past `fromBytes` and by `deadlineMs`. Resolves on
574
+ * end, error, close, or either bound (the socket is destroyed on a bound — by
575
+ * then the caller's answer is already on the wire). Every upload refusal path
576
+ * runs this; the ones whose answer is NOT yet written (400/403/429/501) await
577
+ * it before answering, so a client still mid-send reads the status code
578
+ * rather than a reset.
579
+ */
580
+ function drainUpload(req: IncomingMessage, fromBytes: number, deadlineMs: number): Promise<void> {
581
+ return new Promise((resolve) => {
582
+ let size = fromBytes
583
+ let settled = false
584
+ const timer = setTimeout(() => {
585
+ req.destroy()
586
+ finish()
587
+ }, deadlineMs)
588
+ if (typeof timer.unref === 'function') timer.unref()
589
+ const onData = (chunk: Buffer): void => {
590
+ size += chunk.byteLength
591
+ if (size - fromBytes > DRAIN_SLACK_BYTES) {
592
+ req.destroy()
593
+ finish()
594
+ }
595
+ }
596
+ const finish = (): void => {
597
+ if (settled) return
598
+ settled = true
599
+ req.off('data', onData)
600
+ req.off('end', finish)
601
+ req.off('error', finish)
602
+ req.off('close', finish)
603
+ clearTimeout(timer)
604
+ resolve()
605
+ }
606
+ req.on('data', onData)
607
+ req.once('end', finish)
608
+ req.once('error', finish)
609
+ req.once('close', finish)
610
+ req.resume()
611
+ })
612
+ }
613
+
614
+ /**
615
+ * What may travel to the client about a failed gateway call. DSH's own errors
616
+ * always carry a `namespace/name`-shaped string `code` — those pass through
617
+ * with a clipped message. EVERYTHING else — a plugin bug, or a Node system
618
+ * error whose `code` (`ENOENT`, …) and message (`… '/Users/x/…'`) quote the
619
+ * server's filesystem — reports `internal` and NO message at all (T22a-fix).
620
+ */
621
+ function errorOf(error: unknown): { code: string; message?: string } {
622
+ const code =
623
+ error !== null && typeof error === 'object' && typeof (error as { code?: unknown }).code === 'string'
624
+ ? (error as { code: string }).code
625
+ : ''
626
+ if (!DSH_ERROR_CODE.test(code)) return { code: 'internal' }
627
+ // CP4: a DSH `*/internal` code (`gateway/internal`, …) is the server saying
628
+ // "my own failure" — its message quotes server-side facts just like a Node
629
+ // error would, so only the code travels.
630
+ if (code.endsWith('/internal')) return { code }
631
+ const text = error instanceof Error ? error.message : String(error)
632
+ return { code, message: text.slice(0, MAX_MESSAGE_CHARS) }
633
+ }
634
+
635
+ /**
636
+ * One live `$zr/events` subscription's forwarding bookkeeping (T32). The
637
+ * answer route (`relay/v1/event-result`) proves an `eventId` was forwarded
638
+ * through HERE before it composes the gateway payload, so the registry is
639
+ * the whole ownership story: event → the agent (session) it belongs to,
640
+ * judged accessible AT ANSWER TIME, and the subscription's own `clientId`
641
+ * — the server is ONE client of the host's `$events` stream, and DSH
642
+ * matches every result against THAT id (`parseRemoteEventResult`), never
643
+ * the sub-client's local one.
644
+ *
645
+ * T32-fix: the events handed to the sub-client are rewritten to
646
+ * `<token>.<eventId>` so an answer names the subscription it belongs to —
647
+ * answers are matched against THAT sub only, on THAT sub's device, never
648
+ * across devices. The registry survives the event's own `cancel` frame
649
+ * NO LONGER: cancel closes the entry (the client already closed its
650
+ * prompt; a later answer refuses `unknown-event`, which the client turns
651
+ * into the same silent ok DSH gives a stale result).
652
+ */
653
+ interface EventsSubscription {
654
+ /** The `x-zen-remote-device` the subscription rides on; answers from any
655
+ * other device are refused before the registry is read. */
656
+ device: string
657
+ /** The random token baked into every forwarded eventId. */
658
+ token: string
659
+ /** The server's `$events` clientId, taken from the subscription's ready
660
+ * frame; undefined until it arrived. */
661
+ clientId: string | undefined
662
+ /** Forwarded waterfall eventIds (ORIGINAL ids — the token stays in the
663
+ * wire form) → the `agentId` each belongs to. Capped at
664
+ * {@link EVENT_REGISTRY_LIMIT}, oldest dropped. */
665
+ events: Map<string, string>
666
+ }
667
+
668
+ /**
669
+ * Build the relay route handler mounted under {@link RELAY_PREFIX}. Exported
670
+ * as a factory so the route tests can drive it against a plain node:http
671
+ * server with a fake gateway and a real share store — no harness required.
672
+ *
673
+ * Every request passes the same gate first: gateway secret, then the two
674
+ * marking headers. Failures answer a uniform 401 that does not say WHICH
675
+ * check failed — the difference would only help someone probing the wall.
676
+ * After the gate, `x-zen-remote-device` is the caller's device id (the
677
+ * per-device stream budget hangs off it).
678
+ *
679
+ * @param options - secret, share store, gateway service and server facts.
680
+ * @returns the handler owning the full response lifecycle of one request,
681
+ * with `viewerCount` alongside for the "who is looking" surface.
682
+ */
683
+ export function createRelayHandler(options: RelayHandlerOptions): RelayHandler {
684
+ const { secret, store, gateway, serverInfo } = options
685
+ const heartbeatMs = options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS
686
+ const endDrainTimeoutMs = options.endDrainTimeoutMs ?? DEFAULT_END_DRAIN_TIMEOUT_MS
687
+ const uploadCapBytes = options.uploadCapBytes ?? DEFAULT_UPLOAD_CAP_BYTES
688
+ const drainDeadlineMs = options.drainDeadlineMs ?? DRAIN_DEADLINE_MS
689
+ const parentOf = options.parentOf ?? (() => undefined)
690
+ const isAccessible = (sessionId: string): boolean => store.isAccessible(sessionId, parentOf)
691
+
692
+ /**
693
+ * The server display name as of the last second (T59-fix): every stream's
694
+ * heartbeat reads it per ping, and a deployment whose `serverName()`
695
+ * callback re-reads the row's configuration would otherwise do so per
696
+ * STREAM per tick — all streams share this one value instead, refreshed
697
+ * at most once a second (a 15s heartbeat still reads a fresh name every
698
+ * round; the handshake route keeps reading the callback directly).
699
+ */
700
+ let cachedServerName: string | undefined
701
+ let cachedServerNameAt = 0
702
+ const currentServerName = (): string => {
703
+ const now = Date.now()
704
+ if (cachedServerName === undefined || now - cachedServerNameAt >= 1_000) {
705
+ cachedServerName = serverInfo.serverName()
706
+ cachedServerNameAt = now
707
+ }
708
+ return cachedServerName
709
+ }
710
+
711
+ /** Session-scoped streams currently open, per session (cross-device). */
712
+ const viewers = new Map<string, number>()
713
+
714
+ /** Open streams per device id, for the per-device budget. */
715
+ const streamsByDevice = new Map<string, number>()
716
+
717
+ /** Invokes currently in flight per device id, for the invoke budget. */
718
+ const invokesByDevice = new Map<string, number>()
719
+
720
+ /** Uploads currently in flight per device id, for the upload budget (T51-fix). */
721
+ const uploadsByDevice = new Map<string, number>()
722
+
723
+ /**
724
+ * The device NAME this process last saw per device id (T59): every relay
725
+ * request rides the gateway's fresh `x-zen-remote-device-name` marking
726
+ * header, so the map learns a rename as soon as that device sends anything
727
+ * at all — and the NDJSON heartbeat reads the LATEST known name per ping,
728
+ * which is how a server-side rename reaches a connected client without a
729
+ * reconnect. Tiny by construction (paired device ids only).
730
+ */
731
+ const deviceNames = new Map<string, string>()
732
+
733
+ /** The `$zr/events` subscriptions currently open — the event-result
734
+ * route searches these for every incoming eventId. A closed
735
+ * subscription removes itself; closeAll empties the set. */
736
+ const liveEventSubscriptions = new Set<EventsSubscription>()
737
+
738
+ /** Latest `job/list` rows seen per session — the recent-state half of the
739
+ * job ownership check (the other half is a one-shot list on a cache miss).
740
+ * An unshared session's rows are forgotten (T22b-fix): its jobs are none of
741
+ * this client's business anymore. */
742
+ const recentJobs = new Map<string, Map<string, string | undefined>>()
743
+ /**
744
+ * Every share-table listener this handler registered — the ownership
745
+ * cache's unshare sweeper below, plus one per open stream. closeAll
746
+ * detaches them ALL (T43-B): after the handler closed, a share/unshare on
747
+ * the table must never re-enter the dead handler, not even through a
748
+ * stream whose pump is still parked on a full socket buffer.
749
+ */
750
+ const tableUnsubscribers = new Set<() => void>()
751
+ tableUnsubscribers.add(
752
+ store.subscribe((event) => {
753
+ if (event.type === 'unshared') recentJobs.delete(event.sessionId)
754
+ }),
755
+ )
756
+
757
+ /** Kill switches of the streams currently open on THIS handler, and the
758
+ * reason recorded by closeAll — a request that was mid-ownership-probe
759
+ * when closeAll ran reads it just before it would open its upstream. */
760
+ const openStreamKills = new Set<() => void>()
761
+ let serverClosedReason: string | null = null
762
+
763
+ /** Record one raw `job/list` frame into the ownership cache (unfiltered:
764
+ * ownerless entries are remembered too, as "not owned by anyone"). */
765
+ const rememberJobs = (sessionId: string, frame: unknown): void => {
766
+ if (!isPlainObject(frame) || frame.type !== 'rows' || !Array.isArray(frame.jobs)) return
767
+ const jobs = new Map<string, string | undefined>()
768
+ for (const job of frame.jobs) {
769
+ if (jobs.size >= JOB_CACHE_LIMIT) break
770
+ if (isPlainObject(job) && typeof job.id === 'string' && job.id !== '') {
771
+ jobs.set(job.id, typeof job.owner === 'string' ? job.owner : undefined)
772
+ }
773
+ }
774
+ recentJobs.set(sessionId, jobs)
775
+ }
776
+
777
+ /**
778
+ * Whether `jobId` belongs to `sessionId` — the relay-side ownership check
779
+ * for `job/follow` / `job/kill`. DSH opens ownerless jobs to every session,
780
+ * so without this a shared session would be a window onto server-wide
781
+ * processes. The answer comes from the most recent `job/list` rows; on a
782
+ * cache miss, one throwaway `job/list` stream is opened and abandoned. A
783
+ * job the list does not mention is REFUSED: no answer is treated as no
784
+ * permission, never the reverse.
785
+ */
786
+ const ownsJob = async (sessionId: string, jobId: string, signal: AbortSignal): Promise<boolean> => {
787
+ const cached = recentJobs.get(sessionId)
788
+ if (cached !== undefined && cached.has(jobId)) return cached.get(jobId) === sessionId
789
+ try {
790
+ const iterable = await gateway.stream({
791
+ namespace: 'job',
792
+ method: 'list',
793
+ args: { request: { sessionId } },
794
+ signal,
795
+ })
796
+ for await (const frame of iterable) {
797
+ rememberJobs(sessionId, frame)
798
+ const jobs = recentJobs.get(sessionId)
799
+ // The first frame is the whole recent set; anything the client could
800
+ // have seen lives in it or nowhere.
801
+ return jobs !== undefined && jobs.has(jobId) && jobs.get(jobId) === sessionId
802
+ }
803
+ return false
804
+ } catch {
805
+ return false
806
+ }
807
+ }
808
+
809
+ /**
810
+ * Whether `workspaceId` names a workspace the server currently has, answered
811
+ * from a one-shot `workspace/follow` baseline (T31 — the only workspace read
812
+ * the gateway exposes; the stream is abandoned after its first frame). Any
813
+ * failure — transport, unexpected first frame, missing entry — is `false`:
814
+ * no answer is not permission. The create route pins the call to the
815
+ * workspace rather than to a path on purpose: with `workspaceId` attached,
816
+ * DSH takes `workspace.path` as the session cwd itself and attaches the new
817
+ * session to the workspace (the group the client created it from).
818
+ */
819
+ const workspaceExists = async (workspaceId: string, signal: AbortSignal): Promise<boolean> => {
820
+ try {
821
+ const iterable = await gateway.stream({ namespace: 'workspace', method: 'follow', args: {}, signal })
822
+ for await (const frame of iterable) {
823
+ if (!isPlainObject(frame) || frame.type !== 'baseline') return false
824
+ const value = isPlainObject(frame.value) ? frame.value : undefined
825
+ const items = value !== undefined && Array.isArray(value.items) ? value.items : []
826
+ return items.some((item) => isPlainObject(item) && item.workspaceId === workspaceId)
827
+ }
828
+ return false
829
+ } catch {
830
+ return false
831
+ }
832
+ }
833
+
834
+ /**
835
+ * Open THIS server's own `$events` subscription (T32) — through the
836
+ * host's wire adapter, the only door (docs/spike-relay.md §2.1 坑 1:
837
+ * `gw.stream({namespace:'$events'})` refuses with
838
+ * `gateway/invocation-unavailable`). The payload must be exactly
839
+ * `{args:{}}` (gateway `openRemoteEvents`); the uplink is undefined —
840
+ * the endpoint takes none and the host half-closes whatever arrives.
841
+ */
842
+ const openEventsStream = async (signal: AbortSignal): Promise<AsyncIterable<unknown>> => {
843
+ const open = gateway.wireStream?.open
844
+ if (typeof open !== 'function') {
845
+ throw Object.assign(new Error('forwarded Remote event source is unavailable'), {
846
+ code: 'gateway/service-unavailable',
847
+ })
848
+ }
849
+ const opened = (await (open as (this: unknown, ...openArgs: unknown[]) => unknown).call(
850
+ gateway.wireStream,
851
+ '$events',
852
+ { args: {} },
853
+ undefined,
854
+ undefined,
855
+ signal,
856
+ )) as unknown
857
+ if (
858
+ opened === null ||
859
+ typeof opened !== 'object' ||
860
+ typeof (opened as Record<symbol, unknown>)[Symbol.asyncIterator] !== 'function'
861
+ ) {
862
+ throw Object.assign(new Error('forwarded Remote event stream did not open'), {
863
+ code: 'gateway/service-unavailable',
864
+ })
865
+ }
866
+ return opened as AsyncIterable<unknown>
867
+ }
868
+
869
+ /** Record one forwarded waterfall in the subscription's registry (oldest
870
+ * dropped past the cap), under its ORIGINAL id. */
871
+ const rememberEvent = (sub: EventsSubscription, eventId: string, agentId: string): void => {
872
+ if (sub.events.size >= EVENT_REGISTRY_LIMIT) {
873
+ const oldest = sub.events.keys().next().value
874
+ if (oldest !== undefined) sub.events.delete(oldest)
875
+ }
876
+ sub.events.set(eventId, agentId)
877
+ }
878
+
879
+ /**
880
+ * The `$zr/events` frame discipline (T32, reworked in T32-fix2), one
881
+ * function for the pump:
882
+ *
883
+ * - READY is recorded (the subscription's clientId, for the answer route)
884
+ * and forwarded SCRUBBED — the client learns "ready", never the host
885
+ * facts (`clientId`, `home`) that would let it speak to the gateway
886
+ * around this relay.
887
+ * - WATERFALL frames whose `agentId` is not reachable right now are
888
+ * dropped — NOT answered on the sub-client's behalf (see DROPPED
889
+ * DELIVERIES below). Forwarded ones are registered and rewritten to
890
+ * `<token>.<eventId>`: the answer route resolves the subscription (and
891
+ * its device) from the token, so ids never cross subscriptions.
892
+ * Rewriting to virtual ids for the UI stays the CLIENT's job — it
893
+ * prefixes the whole thing with `zr~<serverId>~`.
894
+ * - CANCEL frames are forwarded only for events this subscription
895
+ * forwarded (an unshared session's activity timeline must not leak
896
+ * through cancels), and the entry goes with the forward.
897
+ * - EMIT frames are dropped, with ONE exception (T75): a
898
+ * `api-session/status` emit whose `args[0]` names an accessible session
899
+ * crosses as a fresh `{type, event, args:[id, running]}` — it is the
900
+ * only share-SCOPED emit the host produces (one session's running flip,
901
+ * judged per frame by `isAccessible` like a waterfall's `agentId`).
902
+ * Every other emit is server-wide state (`api-session/added` summaries
903
+ * and titles, account expirations, cordis chatter) that is not
904
+ * share-scoped: forwarding it would leak unshared sessions and feed the
905
+ * sub-client ids it would treat as local. Everything else a sub-client
906
+ * needs about a session's state travels the workspace/control streams,
907
+ * which ARE share-filtered.
908
+ * - Anything not shaped exactly like a forwardable waterfall, cancel, or
909
+ * status emit (T32-fix2, mirroring the client face's
910
+ * `parseRemoteEventFrame` exact-keys validation) is dropped too: a frame
911
+ * that slipped through would fail the sub-client's whole `$events`
912
+ * generation and leave it failing and reconnecting in a loop.
913
+ *
914
+ * DROPPED DELIVERIES STAY PENDING (T32-fix2): a dropped waterfall used to
915
+ * be abstained `next` on behalf. That is gone on purpose. DSH's `next`
916
+ * only retracts the answering client's OWN delivery, and the event
917
+ * settles `next` — falling through to the host's fallback, where
918
+ * `approval/request` resolves `unavailable` (which dsh-user-approval
919
+ * treats as a rejection) and `user-questions/request` throws NO_PROVIDER
920
+ * — only when NO delivery remains (RT dsh-api-gateway
921
+ * `receiveRemoteEventResult`). With the desktop window closed and the
922
+ * phone asleep, the relay IS the only delivery: one abstention would fail
923
+ * every pending approval of the dropped session at once and break the
924
+ * push → wake → approve flow. The price: a waterfall dropped here keeps
925
+ * the relay's delivery pending, so an event the server UI answered `next`
926
+ * waits until the next `$events` client connects — the gateway
927
+ * re-delivers still-pending events to a fresh subscription
928
+ * (`openRemoteEvents`). A wait, never a rejection.
929
+ *
930
+ * KNOWN LIMITATION: an event that arrives while its session is still
931
+ * unshared is dropped; sharing the session later does NOT resurrect it
932
+ * for the sub-client — it only sees such events from the next reconnect
933
+ * onward, when the gateway re-delivers still-pending events to the fresh
934
+ * subscription.
935
+ */
936
+ const filterEventsFrame = (sub: EventsSubscription, frame: unknown): unknown => {
937
+ if (!isPlainObject(frame)) return null
938
+ if (frame.type === 'ready') {
939
+ if (typeof frame.clientId === 'string' && frame.clientId !== '') sub.clientId = frame.clientId
940
+ return { type: 'ready' }
941
+ }
942
+ if (frame.type === 'waterfall') {
943
+ if (!isForwardableWaterfall(frame) || !isAccessible(frame.agentId)) return null
944
+ rememberEvent(sub, frame.eventId, frame.agentId)
945
+ return { ...frame, eventId: `${sub.token}.${frame.eventId}` }
946
+ }
947
+ if (frame.type === 'cancel') {
948
+ if (!isForwardableCancel(frame) || !sub.events.has(frame.eventId)) return null
949
+ sub.events.delete(frame.eventId)
950
+ return { ...frame, eventId: `${sub.token}.${frame.eventId}` }
951
+ }
952
+ if (frame.type === 'emit') {
953
+ // T75: the one share-scoped emit. A NEW frame with a fresh args array
954
+ // leaves — never the host's object itself.
955
+ if (!isForwardableStatusEmit(frame) || !isAccessible(frame.args[0])) return null
956
+ return { type: 'emit', event: frame.event, args: [frame.args[0], frame.args[1]] }
957
+ }
958
+ return null
959
+ }
960
+
961
+ const handle: RelayHandler = async function handleRelay(req, res) {
962
+ if (
963
+ !secretsMatch(headerValue(req, 'x-zen-remote-secret'), secret) ||
964
+ headerValue(req, 'x-zen-remote-via') !== 'gateway' ||
965
+ headerValue(req, 'x-zen-remote-role') !== 'desktop-client'
966
+ ) {
967
+ responseJson(res, 401, { ok: false, error: { code: 'relay-unauthorized' } })
968
+ return
969
+ }
970
+ // The stream route below budgets concurrent streams per device; other
971
+ // routes do not need the id beyond the gate itself.
972
+ // T59: every authenticated request teaches the name cache — the gateway
973
+ // stamps the device table's CURRENT name on every forward, so this line
974
+ // is where a rename (admin edit, or the device's own push) lands.
975
+ const deviceNameHeader = deviceNameHeaderOf(req)
976
+ const gateDeviceId = headerValue(req, 'x-zen-remote-device')
977
+ if (gateDeviceId !== undefined && gateDeviceId !== '' && deviceNameHeader !== undefined) {
978
+ deviceNames.set(gateDeviceId, deviceNameHeader)
979
+ }
980
+
981
+ // The pathname EXACTLY as the webserver saw it — never decoded before
982
+ // matching (see the module comment): a decoded match would turn the
983
+ // gateway-admitted `…%2f…` shapes back into a traversal.
984
+ let pathname = ''
985
+ try {
986
+ pathname = new URL(req.url ?? '/', 'http://dsh.internal').pathname
987
+ } catch {
988
+ responseJson(res, 404, { ok: false, error: { code: 'not-found' } })
989
+ return
990
+ }
991
+
992
+ if (req.method === 'GET' && pathname === `${RELAY_PREFIX}/ping`) {
993
+ responseJson(res, 200, { ok: true })
994
+ return
995
+ }
996
+
997
+ if (req.method === 'POST' && pathname === `${RELAY_PREFIX}/v1/handshake`) {
998
+ const body = await readBodyOrRespond(req, res)
999
+ if (body === undefined) return
1000
+ // The compute rides its own guard (T42-fix): a throwing fingerprint
1001
+ // source answers an empty map and the handshake still succeeds.
1002
+ let fingerprints: Record<string, string> = {}
1003
+ try {
1004
+ fingerprints = (await serverInfo.fingerprints?.()) ?? {}
1005
+ } catch {
1006
+ fingerprints = {}
1007
+ }
1008
+ responseJson(res, 200, {
1009
+ ok: true,
1010
+ relayProtocol: RELAY_PROTOCOL,
1011
+ serverId: serverInfo.serverId,
1012
+ serverName: serverInfo.serverName(),
1013
+ dshVersion: serverInfo.dshVersion,
1014
+ // T42: the server's own interface fingerprints (empty when the wiring
1015
+ // had nothing to compute — the client judges group by group).
1016
+ fingerprints,
1017
+ // T59: the CALLING device's name, as the gateway's device table holds
1018
+ // it at this moment (the header is written fresh per forward, so a
1019
+ // just-renamed device reads its new name here). Undefined without the
1020
+ // header — an old gateway or a direct call — and the field then rides
1021
+ // no further: the client keeps what it has.
1022
+ ...(deviceNameHeaderOf(req) !== undefined ? { deviceName: deviceNameHeaderOf(req) } : {}),
1023
+ })
1024
+ return
1025
+ }
1026
+
1027
+ if (req.method === 'POST' && pathname === `${RELAY_PREFIX}/v1/unshare`) {
1028
+ const body = await readBodyOrRespond(req, res)
1029
+ if (body === undefined) return
1030
+ const sessionId = body.sessionId
1031
+ if (typeof sessionId !== 'string' || sessionId === '') {
1032
+ responseJson(res, 400, { ok: false, error: { code: 'bad-request' } })
1033
+ return
1034
+ }
1035
+ // The TABLE only — isShared, not isAccessible: a subagent or fork
1036
+ // session never entered the table, so it cannot be closed alone; it
1037
+ // leaves remote access together with its family or not at all.
1038
+ if (!store.isShared(sessionId)) {
1039
+ responseJson(res, 403, { ok: false, error: { code: 'not-shared' } })
1040
+ return
1041
+ }
1042
+ store.unshare(sessionId, 'client')
1043
+ responseJson(res, 200, { ok: true })
1044
+ return
1045
+ }
1046
+
1047
+ if (req.method === 'POST' && pathname === `${RELAY_PREFIX}/v1/event-result`) {
1048
+ // The answer half of `$zr/events` (T32): `{eventId, result}`, where
1049
+ // `eventId` is the OPAQUE `<token>.<eventId>` string this relay handed
1050
+ // the sub-client (wrapped in `zr~<serverId>~` by the client), and
1051
+ // `result` is the Remote event OUTCOME, forwarded verbatim.
1052
+ const body = await readBodyOrRespond(req, res)
1053
+ if (body === undefined) return
1054
+ const parsed = parseEventResultBody(body)
1055
+ if (parsed === undefined) {
1056
+ responseJson(res, 400, { ok: false, error: { code: 'bad-request' } })
1057
+ return
1058
+ }
1059
+ // Ownership (T32-fix): the token locates the ONE subscription the
1060
+ // event was forwarded on — the answer is matched against that sub
1061
+ // only, and only from the device that holds it. An unknown token, a
1062
+ // foreign device, or an eventId that subscription did not forward is
1063
+ // the same refusal (no oracle about which half missed).
1064
+ const separator = parsed.eventId.indexOf('.')
1065
+ const token = separator === -1 ? '' : parsed.eventId.slice(0, separator)
1066
+ const originalEventId = separator === -1 ? '' : parsed.eventId.slice(separator + 1)
1067
+ let owner: { clientId: string; agentId: string } | undefined
1068
+ if (token !== '' && originalEventId !== '') {
1069
+ const device = headerValue(req, 'x-zen-remote-device') ?? ''
1070
+ for (const sub of liveEventSubscriptions) {
1071
+ if (sub.token !== token) continue
1072
+ if (sub.device !== device) break
1073
+ const agentId = sub.events.get(originalEventId)
1074
+ if (agentId !== undefined && sub.clientId !== undefined) {
1075
+ owner = { clientId: sub.clientId, agentId }
1076
+ }
1077
+ break
1078
+ }
1079
+ }
1080
+ if (owner === undefined) {
1081
+ responseJson(res, 403, { ok: false, error: { code: 'unknown-event' } })
1082
+ return
1083
+ }
1084
+ if (!isAccessible(owner.agentId)) {
1085
+ responseJson(res, 403, { ok: false, error: { code: 'not-shared' } })
1086
+ return
1087
+ }
1088
+ const dispatch = gateway.dispatchRpc
1089
+ if (typeof dispatch !== 'function') {
1090
+ responseJson(res, 200, {
1091
+ ok: false,
1092
+ error: { code: 'gateway/service-unavailable', message: 'forwarded Remote event source is unavailable' },
1093
+ })
1094
+ return
1095
+ }
1096
+ // A hang-up cancels the answer mid-flight, like invoke's.
1097
+ const hangUp = new AbortController()
1098
+ const onClientGone = (): void => {
1099
+ if (!res.writableEnded) hangUp.abort()
1100
+ }
1101
+ res.on('close', onClientGone)
1102
+ try {
1103
+ // Exactly the gateway's payload contract (parseRemoteEventResult):
1104
+ // one `args` field holding `{clientId, eventId, outcome}` — the
1105
+ // subscription's OWN clientId (the gateway matches results against
1106
+ // the client the event was delivered to) and the ORIGINAL eventId
1107
+ // with the token stripped back off; the outcome untouched. The
1108
+ // envelope — including the gateway's own
1109
+ // `{ok:false, error:{code:'gateway/internal',…}}` for a malformed
1110
+ // outcome — rides back as the 200 body.
1111
+ const envelope = (await dispatch.call(
1112
+ gateway,
1113
+ '$events/result',
1114
+ { args: { clientId: owner.clientId, eventId: originalEventId, outcome: parsed.result } },
1115
+ hangUp.signal,
1116
+ undefined,
1117
+ )) as unknown
1118
+ responseJson(res, 200, isPlainObject(envelope) ? envelope : { ok: false, error: { code: 'internal' } })
1119
+ } catch (error) {
1120
+ const { code, message } = errorOf(error)
1121
+ responseJson(res, 200, message === undefined ? { ok: false, error: { code } } : { ok: false, error: { code, message } })
1122
+ } finally {
1123
+ res.off('close', onClientGone)
1124
+ }
1125
+ return
1126
+ }
1127
+
1128
+ if (req.method === 'POST' && pathname === `${RELAY_PREFIX}/v1/invoke`) {
1129
+ // The prompt-sized cap: a registered invoke may carry inline images in
1130
+ // its content blocks (see MAX_INVOKE_BODY_BYTES).
1131
+ const body = await readBodyOrRespond(req, res, MAX_INVOKE_BODY_BYTES)
1132
+ if (body === undefined) return
1133
+ const namespace = body.namespace
1134
+ const method = body.method
1135
+ const args = body.args
1136
+ if (
1137
+ typeof namespace !== 'string' ||
1138
+ namespace === '' ||
1139
+ typeof method !== 'string' ||
1140
+ method === '' ||
1141
+ args === null ||
1142
+ typeof args !== 'object' ||
1143
+ Array.isArray(args)
1144
+ ) {
1145
+ responseJson(res, 400, { ok: false, error: { code: 'bad-request' } })
1146
+ return
1147
+ }
1148
+ const decision = decideInvoke(namespace, method, args, isAccessible)
1149
+ if (!decision.allow) {
1150
+ responseJson(res, 403, { ok: false, error: { code: decision.reason } })
1151
+ return
1152
+ }
1153
+ // CP4: per-device in-flight budget — the invoke twin of the stream
1154
+ // budget below. Counted only from here (every earlier refusal is
1155
+ // answered before this line) and released in the route's finally,
1156
+ // which every path through the try reaches.
1157
+ const device = headerValue(req, 'x-zen-remote-device') ?? ''
1158
+ if ((invokesByDevice.get(device) ?? 0) >= MAX_INVOKES_PER_DEVICE) {
1159
+ responseJson(res, 429, { ok: false, error: { code: 'too-many-invokes' } })
1160
+ return
1161
+ }
1162
+ invokesByDevice.set(device, (invokesByDevice.get(device) ?? 0) + 1)
1163
+ // A client hanging up must not leave the host running the call to
1164
+ // completion behind a dead socket: the connection's close (arriving
1165
+ // before the response ends) cancels the AbortController whose signal
1166
+ // rides into gateway.invoke. 'close' also fires AFTER a normal end,
1167
+ // so only an unfinished response counts as a hang-up.
1168
+ const hangUp = new AbortController()
1169
+ const onClientGone = (): void => {
1170
+ if (!res.writableEnded) hangUp.abort()
1171
+ }
1172
+ res.on('close', onClientGone)
1173
+ try {
1174
+ // `job/kill` additionally proves the target job belongs to the
1175
+ // claimed session (4b): DSH opens ownerless jobs to everyone, so the
1176
+ // share-table check alone would let one shared session kill
1177
+ // server-wide background jobs.
1178
+ if (namespace === 'job' && method === 'kill') {
1179
+ const request = isPlainObject(args) ? args.request : undefined
1180
+ const jobId =
1181
+ isPlainObject(request) && typeof request.jobId === 'string' && request.jobId !== ''
1182
+ ? request.jobId
1183
+ : undefined
1184
+ const sessionId = isPlainObject(request) && typeof request.sessionId === 'string' ? request.sessionId : ''
1185
+ if (jobId === undefined || sessionId === '' || !(await ownsJob(sessionId, jobId, hangUp.signal))) {
1186
+ responseJson(res, 403, { ok: false, error: { code: 'forbidden' } })
1187
+ return
1188
+ }
1189
+ // The ownership probe can take a round trip — remote may have been
1190
+ // closed while it ran (T22b-fix). The decision above is stale the
1191
+ // moment an await happened; re-run the share-table check before
1192
+ // anything is forwarded.
1193
+ if (!isAccessible(sessionId)) {
1194
+ responseJson(res, 403, { ok: false, error: { code: 'not-shared' } })
1195
+ return
1196
+ }
1197
+ }
1198
+ // T31-fix: the forwarded create is REBUILT as a whitelist, not
1199
+ // trimmed by deletion — exactly `{workspaceId, agentPreset?}` and
1200
+ // nothing else, so a hostile or buggy client cannot smuggle extra
1201
+ // fields (env, permissionMode, a caller-chosen sessionId, a decoy
1202
+ // cwd) through to DSH. The workspace was probed above; the new
1203
+ // session's id and cwd are DSH's own business (it mints the id and
1204
+ // takes `workspace.path`; a create naming BOTH workspaceId and cwd
1205
+ // would be a `gateway/bad-request`).
1206
+ if (namespace === 'session' && method === 'create') {
1207
+ const request = isPlainObject(args) ? args.request : undefined
1208
+ const workspaceId =
1209
+ isPlainObject(request) && typeof request.workspaceId === 'string' && request.workspaceId !== ''
1210
+ ? request.workspaceId
1211
+ : undefined
1212
+ if (workspaceId === undefined || !(await workspaceExists(workspaceId, hangUp.signal))) {
1213
+ responseJson(res, 403, { ok: false, error: { code: 'workspace/not-found' } })
1214
+ return
1215
+ }
1216
+ ;(args as Record<string, unknown>).request = {
1217
+ workspaceId,
1218
+ ...(isPlainObject(request) && typeof request.agentPreset === 'string'
1219
+ ? { agentPreset: request.agentPreset }
1220
+ : {}),
1221
+ }
1222
+ }
1223
+ // T41a-fix: a canonical `dsh-session:` address in an injectable text
1224
+ // makes DSH inject the referenced session's content with no access
1225
+ // check of its own (dsh-session-reference prepareDirectMessages →
1226
+ // readSurface). Every referenced session must pass the share table
1227
+ // before the call is forwarded — the prompt-text sibling of the
1228
+ // job/kill ownership probe above. T41a-fix2 closed the two bypasses
1229
+ // the prompt-only scan left: a queue EDIT replaces a queued USER
1230
+ // message's content verbatim (RT dsh-api-session-controller
1231
+ // updateQueue), and a slash command's raw input is steered in as a
1232
+ // USER message by its handler (`/plan <text>` does exactly that, RT
1233
+ // dsh-plan-mode) — both are parsed at the next turn start, exactly
1234
+ // like prompt text. WHERE the injectable texts live is the shared
1235
+ // rule (session-reference.ts), the same one the sub-client rewrites
1236
+ // by; everything else in the arguments is not parsed by the host.
1237
+ if (referencedSessionIds(namespace, method, args).some((id) => !isAccessible(id))) {
1238
+ responseJson(res, 403, { ok: false, error: { code: 'not-shared' } })
1239
+ return
1240
+ }
1241
+ const value = await gateway.invoke({ namespace, method, args, signal: hangUp.signal })
1242
+ // T31: a session created or forked THROUGH the relay is shared
1243
+ // automatically — the client only ever sees shared sessions, so an
1244
+ // unshared result would be born unreachable. Re-sharing (a fork the
1245
+ // new-session listener already caught) is a table no-op.
1246
+ if (namespace === 'session' && (method === 'create' || method === 'fork')) {
1247
+ const created = isPlainObject(value) && typeof value.sessionId === 'string' ? value.sessionId : undefined
1248
+ if (created !== undefined) store.share(created)
1249
+ }
1250
+ // T41a-fix: the @ resolver names EVERY server session in its answer —
1251
+ // a row the share table cannot reach never travels (the session/list
1252
+ // discipline). T52-fix: the model catalog's answer leaves with its
1253
+ // `failures` emptied — the host's per-group error texts may carry
1254
+ // endpoint or credential details (relay-filter.ts
1255
+ // filterModelCatalogResult).
1256
+ const travels =
1257
+ decision.filter === 'session-list'
1258
+ ? filterSessionListResult(value, isAccessible)
1259
+ : decision.filter === 'session-reference-candidates'
1260
+ ? filterAccessibleCandidateRows(value, isAccessible)
1261
+ : decision.filter === 'model-catalog'
1262
+ ? filterModelCatalogResult(value)
1263
+ : value
1264
+ responseJson(res, 200, { ok: true, value: travels })
1265
+ } catch (error) {
1266
+ // The gateway's own failures (unknown namespace, absent service) are
1267
+ // business answers, not transport errors: they ride a 200 envelope
1268
+ // like every other result, with the gateway's string code preserved.
1269
+ const { code, message } = errorOf(error)
1270
+ responseJson(res, 200, message === undefined ? { ok: false, error: { code } } : { ok: false, error: { code, message } })
1271
+ } finally {
1272
+ res.off('close', onClientGone)
1273
+ // The invoke is over — answered, refused mid-flight, or its client
1274
+ // gone: the budget slot goes back.
1275
+ const remaining = (invokesByDevice.get(device) ?? 1) - 1
1276
+ if (remaining <= 0) invokesByDevice.delete(device)
1277
+ else invokesByDevice.set(device, remaining)
1278
+ }
1279
+ return
1280
+ }
1281
+
1282
+ if (req.method === 'POST' && pathname === `${RELAY_PREFIX}/v1/http`) {
1283
+ // The plain-HTTP panel long tail (T41b): `{route, query}` names one
1284
+ // GET the sub-client's `/api/...` fetch wrapper intercepted. GET
1285
+ // semantics ONLY — the body carries the coordinates of the request to
1286
+ // dispatch, never a request body to forward, so a `body` field is a
1287
+ // protocol violation rather than data.
1288
+ const body = await readBodyOrRespond(req, res)
1289
+ if (body === undefined) return
1290
+ if (body.body !== undefined) {
1291
+ responseJson(res, 400, { ok: false, error: { code: 'bad-request' } })
1292
+ return
1293
+ }
1294
+ const route = body.route
1295
+ const query = body.query
1296
+ if (typeof route !== 'string' || typeof query !== 'string') {
1297
+ responseJson(res, 400, { ok: false, error: { code: 'bad-request' } })
1298
+ return
1299
+ }
1300
+ const decision = decideHttpRoute(route, query, isAccessible)
1301
+ if (!decision.allow) {
1302
+ const status =
1303
+ decision.reason === 'unknown-route'
1304
+ ? 404
1305
+ : decision.reason === 'not-shared'
1306
+ ? 403
1307
+ : 400 // no-session / bad-query — malformed coordinates
1308
+ responseJson(res, status, { ok: false, error: { code: decision.reason } })
1309
+ return
1310
+ }
1311
+ const dispatch = options.getApiFetch?.()
1312
+ if (dispatch === undefined) {
1313
+ responseJson(res, 501, { ok: false, error: { code: 'unsupported' } })
1314
+ return
1315
+ }
1316
+ let request: Request
1317
+ try {
1318
+ // The URL is composed from the DECISION's normalized query alone —
1319
+ // never the raw wire string. The two parsers disagree about control
1320
+ // characters (URLSearchParams keeps them in key names, the URL
1321
+ // constructor strips them), and that differential was an
1322
+ // authorization bypass (T41b-fix): decideHttpRoute now rebuilds the
1323
+ // whitelisted parameters itself, so what was checked is exactly what
1324
+ // is dispatched.
1325
+ request = new Request(`http://relay.local/api/${route}?${decision.query}`, {
1326
+ method: 'GET',
1327
+ signal: hangUpOf(res),
1328
+ })
1329
+ } catch {
1330
+ responseJson(res, 400, { ok: false, error: { code: 'bad-request' } })
1331
+ return
1332
+ }
1333
+ try {
1334
+ // In-process dispatch through the shared `/api` handler — the same
1335
+ // exact-fetch route table the browser's transport uses, no loopback
1336
+ // HTTP, no login state. Both registered routes answer buffered JSON,
1337
+ // so the whole response is read and re-wrapped as the envelope value.
1338
+ const upstream = await dispatch(request)
1339
+ const bodyText = await upstream.text()
1340
+ const contentType = upstream.headers.get('content-type') ?? undefined
1341
+ responseJson(res, 200, {
1342
+ ok: true,
1343
+ value: { status: upstream.status, ...(contentType !== undefined ? { contentType } : {}), body: bodyText },
1344
+ })
1345
+ } catch {
1346
+ // A dispatch failure is this server's fault, not a business answer —
1347
+ // and errorOf keeps any message off the wire.
1348
+ responseJson(res, 502, { ok: false, error: { code: 'internal' } })
1349
+ }
1350
+ return
1351
+ }
1352
+
1353
+ if (req.method === 'POST' && pathname === `${RELAY_PREFIX}/v1/upload`) {
1354
+ // The binary upload channel (T51): the sub-client's wrapped
1355
+ // `/api/session/uploadFileBinary` forwards a remote session's raw
1356
+ // attachment bytes here, and this route dispatches them through the
1357
+ // host's shared `/api` handler IN PROCESS — the same exact-fetch route
1358
+ // entry the local upload would have reached, so the staged receipt
1359
+ // lands under the same session the later `session/prompt` resolves it
1360
+ // against. The body is a STREAM, not JSON: nothing here buffers it
1361
+ // beyond the cap verdict, and the host's own upload route has no cap
1362
+ // to inherit (see MAX_UPLOAD_BYTES), so this relay brings its own —
1363
+ // Content-Length first, a counting pump as the chunked-body fallback.
1364
+ //
1365
+ // Refusal discipline (T51-fix): the two 413 paths answer FIRST — the
1366
+ // status code plus `connection: close` are on the wire before a single
1367
+ // tail byte is drained, so a client still pumping a huge body reads
1368
+ // the refusal instead of a reset — and only then swallow a bounded,
1369
+ // timed tail (drainUpload). The small-body refusals (query, access,
1370
+ // budget, no dispatcher) keep the drain-first order: their clients are
1371
+ // ordinary requests, and draining keeps the answer off a reset.
1372
+ if (Number(req.headers['content-length']) > uploadCapBytes) {
1373
+ res.setHeader('Connection', 'close')
1374
+ responseJson(res, 413, PAYLOAD_TOO_LARGE)
1375
+ await drainUpload(req, 0, drainDeadlineMs)
1376
+ return
1377
+ }
1378
+ // The query is parsed ONCE (decideUploadQuery, the T41b-fix
1379
+ // discipline): what was share-checked is exactly the normalized query
1380
+ // the synthetic URL below is composed from — a duplicate sessionId, a
1381
+ // tab-carrying key name, or a smuggled second coordinate can never
1382
+ // re-enter between the check and the dispatch.
1383
+ const decision = decideUploadQuery(new URL(req.url ?? '/', 'http://dsh.internal').search, isAccessible)
1384
+ if (!decision.allow) {
1385
+ await drainUpload(req, 0, drainDeadlineMs)
1386
+ responseJson(res, decision.reason === 'not-shared' ? 403 : 400, { ok: false, error: { code: decision.reason } })
1387
+ return
1388
+ }
1389
+ const dispatch = options.getApiFetch?.()
1390
+ if (dispatch === undefined) {
1391
+ await drainUpload(req, 0, drainDeadlineMs)
1392
+ responseJson(res, 501, { ok: false, error: { code: 'unsupported' } })
1393
+ return
1394
+ }
1395
+ // The per-device upload budget (T51-fix), checked after every wall
1396
+ // above and released in the route's finally — one stalled client must
1397
+ // not pin unbounded host uploads behind this route. An over-budget
1398
+ // request is drained and refused without touching the counter. The
1399
+ // slot itself is TAKEN only after the synthetic request below built
1400
+ // (T5x): that construction is the one step between the check and the
1401
+ // dispatch that can fail and return outside the finally, and a taken-
1402
+ // then-abandoned slot would quietly shrink this device's budget.
1403
+ const device = headerValue(req, 'x-zen-remote-device') ?? ''
1404
+ if ((uploadsByDevice.get(device) ?? 0) >= MAX_UPLOADS_PER_DEVICE) {
1405
+ await drainUpload(req, 0, drainDeadlineMs)
1406
+ responseJson(res, 429, { ok: false, error: { code: 'too-many-uploads' } })
1407
+ return
1408
+ }
1409
+ // A hang-up cancels the forward mid-stream, like invoke's — and the
1410
+ // cap pump below aborts the SAME controller when it trips, so an
1411
+ // oversized upload dies at the host side the moment it is judged.
1412
+ const hangUp = new AbortController()
1413
+ const onClientGone = (): void => {
1414
+ if (!res.writableEnded) hangUp.abort()
1415
+ }
1416
+ res.on('close', onClientGone)
1417
+ // The counting pump: the client's chunks are re-emitted into the
1418
+ // synthetic body verbatim, counted on the way through, with real
1419
+ // backpressure (the socket pauses whenever the host handler is not
1420
+ // pulling). Past the cap the pump errors — the host's reader throws
1421
+ // out of `requestBodyChunks` and its upload dies mid-write — and the
1422
+ // answer below is the relay's own 413 (written before the tail drain),
1423
+ // never the host's internal failure envelope. `tooLarge` also detaches
1424
+ // the pump from the socket: the tail belongs to drainUpload's bound,
1425
+ // which continues from the pump's own count.
1426
+ let received = 0
1427
+ let tooLarge = false
1428
+ const body = new ReadableStream<Uint8Array>({
1429
+ start: (controller) => {
1430
+ req.pause()
1431
+ req.on('data', (chunk: Buffer) => {
1432
+ if (tooLarge) return
1433
+ received += chunk.byteLength
1434
+ if (received > uploadCapBytes) {
1435
+ tooLarge = true
1436
+ req.pause()
1437
+ hangUp.abort()
1438
+ try {
1439
+ controller.error(new Error('payload-too-large'))
1440
+ } catch {
1441
+ // The host consumer may have cancelled first.
1442
+ }
1443
+ return
1444
+ }
1445
+ try {
1446
+ controller.enqueue(new Uint8Array(chunk))
1447
+ } catch {
1448
+ req.destroy()
1449
+ return
1450
+ }
1451
+ if (controller.desiredSize !== null && controller.desiredSize <= 0) req.pause()
1452
+ })
1453
+ req.on('end', () => {
1454
+ if (tooLarge) return
1455
+ try {
1456
+ controller.close()
1457
+ } catch {
1458
+ // Already errored by the consumer's cancel.
1459
+ }
1460
+ })
1461
+ req.on('error', () => {
1462
+ if (tooLarge) return
1463
+ try {
1464
+ controller.error(new Error('upload stream failed'))
1465
+ } catch {
1466
+ // Already errored.
1467
+ }
1468
+ })
1469
+ req.on('close', () => {
1470
+ if (tooLarge) return
1471
+ try {
1472
+ controller.close()
1473
+ } catch {
1474
+ // A hang-up destroy after a clean end — nothing to close.
1475
+ }
1476
+ })
1477
+ },
1478
+ pull: () => {
1479
+ req.resume()
1480
+ },
1481
+ cancel: () => {
1482
+ // The host consumer stopped reading (its own error path): stop
1483
+ // pulling from the client too — the drain below finishes the wire.
1484
+ req.pause()
1485
+ },
1486
+ })
1487
+ let request: Request
1488
+ try {
1489
+ // The URL is composed from the DECISION's normalized query alone,
1490
+ // and the content type is the one fact the host route mandates
1491
+ // (RT dsh-client-file-upload lib/index.js:18) — set here, never
1492
+ // copied from the wire.
1493
+ const init: RequestInit = {
1494
+ method: 'POST',
1495
+ headers: { 'content-type': 'application/octet-stream' },
1496
+ body,
1497
+ signal: hangUp.signal,
1498
+ }
1499
+ // `duplex: 'half'` is mandatory for a streaming request body; the
1500
+ // resolved RequestInit type hides the field (the DOM-vs-undici
1501
+ // conditional in @types/node), so the assignment carries its own
1502
+ // cast.
1503
+ ;(init as { duplex?: string }).duplex = 'half'
1504
+ request = new Request(`http://relay.local${UPLOAD_HTTP_PATH}?${decision.query}`, init)
1505
+ } catch {
1506
+ responseJson(res, 502, { ok: false, error: { code: 'internal' } })
1507
+ return
1508
+ }
1509
+ // Construction succeeded — from here every exit runs the finally, so
1510
+ // the slot is safe to take (T5x).
1511
+ uploadsByDevice.set(device, (uploadsByDevice.get(device) ?? 0) + 1)
1512
+ try {
1513
+ const upstream = await dispatch(request)
1514
+ // The host's upload route answers buffered JSON in every branch (RT
1515
+ // dsh-client-file-upload lib/index.js:49-55), so the receipt reads
1516
+ // out in full. The status + content type + body ride back VERBATIM
1517
+ // inside the success envelope — the same wrapper the
1518
+ // `relay/v1/http` route uses — so a 200-with-failure-envelope
1519
+ // business answer keeps its code AND its structured details on this
1520
+ // wire, and the sub-client reconstructs the exact Response its UI
1521
+ // would have seen locally.
1522
+ const bodyText = await upstream.text()
1523
+ if (tooLarge) {
1524
+ res.setHeader('Connection', 'close')
1525
+ responseJson(res, 413, PAYLOAD_TOO_LARGE)
1526
+ await drainUpload(req, received, drainDeadlineMs)
1527
+ return
1528
+ }
1529
+ const contentType = upstream.headers.get('content-type') ?? undefined
1530
+ responseJson(res, 200, {
1531
+ ok: true,
1532
+ value: { status: upstream.status, ...(contentType !== undefined ? { contentType } : {}), body: bodyText },
1533
+ })
1534
+ } catch {
1535
+ // A dispatch failure is this server's fault (or the hang-up's), not
1536
+ // a business answer — errorOf keeps any message off the wire. The
1537
+ // cap verdict outranks it: the abort the pump sent INTO the dispatch
1538
+ // surfaces here as a throw, and the client still gets its 413
1539
+ // (before the tail drain, like every oversize answer).
1540
+ if (tooLarge) {
1541
+ res.setHeader('Connection', 'close')
1542
+ responseJson(res, 413, PAYLOAD_TOO_LARGE)
1543
+ await drainUpload(req, received, drainDeadlineMs)
1544
+ return
1545
+ }
1546
+ responseJson(res, 502, { ok: false, error: { code: 'internal' } })
1547
+ } finally {
1548
+ res.off('close', onClientGone)
1549
+ // The upload is over — answered, refused mid-flight, or its client
1550
+ // gone: the budget slot goes back (T51-fix).
1551
+ const remaining = (uploadsByDevice.get(device) ?? 1) - 1
1552
+ if (remaining <= 0) uploadsByDevice.delete(device)
1553
+ else uploadsByDevice.set(device, remaining)
1554
+ }
1555
+ return
1556
+ }
1557
+
1558
+ if (req.method === 'POST' && pathname === `${RELAY_PREFIX}/v1/stream`) {
1559
+ // Body validation identical to invoke: one JSON object naming the
1560
+ // method and carrying object args.
1561
+ const body = await readBodyOrRespond(req, res)
1562
+ if (body === undefined) return
1563
+ const namespace = body.namespace
1564
+ const method = body.method
1565
+ const args = body.args
1566
+ if (
1567
+ typeof namespace !== 'string' ||
1568
+ namespace === '' ||
1569
+ typeof method !== 'string' ||
1570
+ method === '' ||
1571
+ args === null ||
1572
+ typeof args !== 'object' ||
1573
+ Array.isArray(args)
1574
+ ) {
1575
+ responseJson(res, 400, { ok: false, error: { code: 'bad-request' } })
1576
+ return
1577
+ }
1578
+ const decision = decideStream(namespace, method, args, isAccessible)
1579
+ if (!decision.allow) {
1580
+ // Refusals are plain JSON: the NDJSON protocol only starts once the
1581
+ // stream is allowed, so a 403 here is the same shape invoke answers.
1582
+ responseJson(res, 403, { ok: false, error: { code: decision.reason } })
1583
+ return
1584
+ }
1585
+ const device = headerValue(req, 'x-zen-remote-device') ?? ''
1586
+ if ((streamsByDevice.get(device) ?? 0) >= MAX_STREAMS_PER_DEVICE) {
1587
+ responseJson(res, 429, { ok: false, error: { code: 'too-many-streams' } })
1588
+ return
1589
+ }
1590
+ streamsByDevice.set(device, (streamsByDevice.get(device) ?? 0) + 1)
1591
+ try {
1592
+ // `job/follow` proves job ownership before anything is streamed (4b) —
1593
+ // same check, same refusal as `job/kill` on the invoke route.
1594
+ if (namespace === 'job' && method === 'follow') {
1595
+ const request = isPlainObject(args) ? args.request : undefined
1596
+ const jobId =
1597
+ isPlainObject(request) && typeof request.jobId === 'string' && request.jobId !== ''
1598
+ ? request.jobId
1599
+ : undefined
1600
+ const sessionId = decision.sessionIds[0] ?? ''
1601
+ if (jobId === undefined || sessionId === '' || !(await ownsJob(sessionId, jobId, hangUpOf(res)))) {
1602
+ responseJson(res, 403, { ok: false, error: { code: 'forbidden' } })
1603
+ return
1604
+ }
1605
+ }
1606
+
1607
+ // Headers that keep every intermediary from buffering the line
1608
+ // stream: DSH's web server runs a compression middleware that would
1609
+ // hold the response until it is complete (it skips responses marked
1610
+ // `no-transform`), and nginx keeps buffering unless told otherwise.
1611
+ // Flushed immediately, so the client sees 200 + content type before
1612
+ // the first upstream frame exists.
1613
+ res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8')
1614
+ res.setHeader('Cache-Control', 'no-store, no-transform')
1615
+ res.setHeader('X-Accel-Buffering', 'no')
1616
+ res.setHeader('X-Content-Type-Options', 'nosniff')
1617
+ res.flushHeaders()
1618
+
1619
+ let clientGone = false
1620
+ let finished = false
1621
+ const hangUp = new AbortController()
1622
+ const onClientGone = (): void => {
1623
+ if (!res.writableEnded) {
1624
+ clientGone = true
1625
+ hangUp.abort()
1626
+ }
1627
+ }
1628
+ // 'error' rides along because a write racing a destroyed socket
1629
+ // surfaces there first; the reaction is the same as a hang-up.
1630
+ res.on('close', onClientGone)
1631
+ res.on('error', onClientGone)
1632
+
1633
+ const heartbeat = setInterval(() => {
1634
+ if (!finished && !clientGone) {
1635
+ // T59: a PER-STREAM ping carrying the names as of NOW. The
1636
+ // server's display name is re-read live per tick (a host rename
1637
+ // reaches every connected client within one heartbeat), and the
1638
+ // device name comes from the learned cache (updated by that
1639
+ // device's every request) — the old shared PING_LINE constant
1640
+ // could carry neither.
1641
+ const deviceName = deviceNames.get(device)
1642
+ const line = JSON.stringify({
1643
+ type: 'ping',
1644
+ serverName: currentServerName(),
1645
+ ...(deviceName !== undefined ? { deviceName } : {}),
1646
+ })
1647
+ res.write(Buffer.from(`${line}\n`, 'utf8'))
1648
+ }
1649
+ }, heartbeatMs)
1650
+ // The host process must never be kept alive by a heartbeat alone.
1651
+ if (typeof heartbeat.unref === 'function') heartbeat.unref()
1652
+
1653
+ /**
1654
+ * One NDJSON line, honoring backpressure: when the socket buffer is
1655
+ * full the write returns false and the caller waits for `drain`
1656
+ * before the next write runs. A line racing a disconnect resolves
1657
+ * without writing (the 'close' leg of the wait). `tail` exempts the
1658
+ * line closeWith is writing from its own finished gate — without it
1659
+ * the end/error line would silence itself.
1660
+ *
1661
+ * Every write goes through ONE promise chain (T22b-fix): share-change
1662
+ * frames are enqueued behind whatever the pump is draining instead of
1663
+ * `void`-ing into the socket buffer in parallel, so a burst of
1664
+ * synthesized frames neither interleaves the pump's write/drain
1665
+ * cycles nor grows the buffer unboundedly.
1666
+ */
1667
+ let writeChain: Promise<void> = Promise.resolve()
1668
+ const writeLine = (value: unknown, tail = false): Promise<void> => {
1669
+ const run = writeChain.then(() => {
1670
+ if ((!tail && finished) || clientGone || res.destroyed || res.writableEnded) return
1671
+ return new Promise<void>((resolve) => {
1672
+ if (res.write(Buffer.from(`${JSON.stringify(value)}\n`, 'utf8'))) {
1673
+ resolve()
1674
+ return
1675
+ }
1676
+ let settle = (): void => {}
1677
+ const onDrain = (): void => settle()
1678
+ const onClose = (): void => settle()
1679
+ settle = (): void => {
1680
+ res.off('drain', onDrain)
1681
+ res.off('close', onClose)
1682
+ resolve()
1683
+ }
1684
+ res.on('drain', onDrain)
1685
+ res.on('close', onClose)
1686
+ })
1687
+ })
1688
+ writeChain = run.then(
1689
+ () => undefined,
1690
+ () => undefined,
1691
+ )
1692
+ return run
1693
+ }
1694
+
1695
+ /**
1696
+ * The one transition into "response over": idempotent, clears the
1697
+ * heartbeat, writes the optional tail line, then ends the response.
1698
+ *
1699
+ * T43-A/fix: a client that stopped reading must not pin the stream —
1700
+ * with it the viewer count and the device budget — forever. The
1701
+ * watchdog starts UNCONDITIONALLY and owns the whole finish: the
1702
+ * response either FINISHES (tail line and end-of-body handed to the
1703
+ * socket — the `finish` event disarms the timer) or is gone
1704
+ * (`close`), or it is destroyed after `endDrainTimeoutMs`. No
1705
+ * branching on `writableNeedDrain`: a write that returned true can
1706
+ * still be sitting in front of a full kernel buffer, and `finish`
1707
+ * is the only honest "it drained" signal.
1708
+ */
1709
+ const closeWith = (line: Record<string, unknown> | null): void => {
1710
+ if (finished) return
1711
+ finished = true
1712
+ clearInterval(heartbeat)
1713
+ let watchdog: ReturnType<typeof setTimeout> | undefined
1714
+ const stopWatchdog = (): void => {
1715
+ res.off('finish', onSettled)
1716
+ res.off('close', onSettled)
1717
+ if (watchdog !== undefined) {
1718
+ clearTimeout(watchdog)
1719
+ watchdog = undefined
1720
+ }
1721
+ }
1722
+ const onSettled = (): void => {
1723
+ stopWatchdog()
1724
+ }
1725
+ if (!clientGone && !res.destroyed && !res.writableEnded) {
1726
+ res.once('finish', onSettled)
1727
+ res.once('close', onSettled)
1728
+ watchdog = setTimeout(() => {
1729
+ watchdog = undefined
1730
+ res.off('finish', onSettled)
1731
+ res.off('close', onSettled)
1732
+ // The tail is somewhere in the buffers but the client never
1733
+ // reads: destroying is the only way this response (and its
1734
+ // counters) ever finishes.
1735
+ try {
1736
+ res.destroy()
1737
+ } catch {
1738
+ // Already gone.
1739
+ }
1740
+ }, endDrainTimeoutMs)
1741
+ // The host process must never be kept alive by a finish alone.
1742
+ if (typeof watchdog.unref === 'function') watchdog.unref()
1743
+ }
1744
+ const tailLine = line === null ? Promise.resolve() : writeLine(line, true)
1745
+ void tailLine.then(() => {
1746
+ if (!clientGone && !res.destroyed && !res.writableEnded) res.end()
1747
+ })
1748
+ }
1749
+
1750
+ // ---- share-change synchronization (T22b §4) --------------------
1751
+
1752
+ // The `$zr/events` forwarding bookkeeping (T32): registered for the
1753
+ // answer route the moment this stream starts being served, removed
1754
+ // in the pump's finally. The token is baked into every forwarded
1755
+ // eventId and binds the answers to THIS subscription; the device
1756
+ // binds them to THIS connection's pairing.
1757
+ const eventsSub: EventsSubscription | undefined =
1758
+ decision.events === true
1759
+ ? { device, token: randomBytes(8).toString('hex'), clientId: undefined, events: new Map() }
1760
+ : undefined
1761
+ if (eventsSub !== undefined) liveEventSubscriptions.add(eventsSub)
1762
+
1763
+ let unsubscribe = (): void => {}
1764
+ let applyToState: ((frame: unknown) => void) | undefined
1765
+
1766
+ if (decision.filter === 'workspace') {
1767
+ // Keep the UNFILTERED latest workspace state so share changes can
1768
+ // synthesize exactly the frames the client is now allowed to see.
1769
+ const state = createWorkspaceFollowState()
1770
+ applyToState = (frame) => state.apply(frame)
1771
+ unsubscribe = store.subscribe((event) => {
1772
+ if (event.type !== 'shared' && event.type !== 'unshared') return
1773
+ if (finished || clientGone) return
1774
+ for (const frame of state.onShareChange(event.sessionId, isAccessible)) {
1775
+ void writeLine({ type: 'frame', frame })
1776
+ }
1777
+ })
1778
+ } else if (decision.filter === 'control') {
1779
+ // A newly shared session needs its current projections: fetch
1780
+ // them once and emit one synthesized `projection` frame per key,
1781
+ // shaped exactly like the upstream frames. An unshared session
1782
+ // synthesizes nothing — the client drops it via the workspace
1783
+ // stream's re-filtered upserts.
1784
+ const syncProjections = async (sessionId: string): Promise<void> => {
1785
+ let result: unknown
1786
+ try {
1787
+ result = await gateway.invoke({
1788
+ namespace: 'session',
1789
+ method: 'projections',
1790
+ args: { request: { sessionId } },
1791
+ signal: hangUp.signal,
1792
+ })
1793
+ } catch {
1794
+ return // projections unavailable — the next live projection frame will flow anyway
1795
+ }
1796
+ if (!isPlainObject(result) || finished || clientGone || !isAccessible(sessionId)) return
1797
+ const values = isPlainObject(result.values) ? result.values : {}
1798
+ const seq = typeof result.asOfSeq === 'number' ? result.asOfSeq : 0
1799
+ for (const key of Object.keys(values)) {
1800
+ void writeLine({ type: 'frame', frame: { type: 'projection', sessionId, key, value: values[key], seq } })
1801
+ }
1802
+ }
1803
+ unsubscribe = store.subscribe((event) => {
1804
+ if (event.type !== 'shared' || finished || clientGone) return
1805
+ void syncProjections(event.sessionId)
1806
+ })
1807
+ } else if (eventsSub !== undefined) {
1808
+ // `$zr/events` (T32-fix): the share table closing a session must
1809
+ // also close the prompts this subscription is showing for it —
1810
+ // synthesize the same cancel frame the gateway would have sent
1811
+ // and drop the registry entry, so the sub-client closes the
1812
+ // prompt and a late answer refuses unknown-event (which the
1813
+ // client turns into the same silent ok DSH gives a stale
1814
+ // result). The relay's OWN delivery is deliberately NOT abstained
1815
+ // away (T32-fix2, see filterEventsFrame's DROPPED DELIVERIES): it
1816
+ // stays pending at the gateway, still answerable by the server
1817
+ // UI or a future subscriber. Events of still-reachable sessions
1818
+ // are untouched; nothing is synthesized on a share (the known
1819
+ // limitation in filterEventsFrame's comment).
1820
+ unsubscribe = store.subscribe((event) => {
1821
+ if (event.type !== 'unshared' || finished || clientGone) return
1822
+ for (const [eventId, agentId] of [...eventsSub.events]) {
1823
+ if (isAccessible(agentId)) continue
1824
+ eventsSub.events.delete(eventId)
1825
+ void writeLine({
1826
+ type: 'frame',
1827
+ frame: { type: 'cancel', eventId: `${eventsSub.token}.${eventId}` },
1828
+ })
1829
+ }
1830
+ })
1831
+ } else {
1832
+ // Session-scoped stream: count its viewers, and die loudly when
1833
+ // a dependency stops being shared — silence would leave the
1834
+ // client reading a session it can no longer reach.
1835
+ for (const id of decision.sessionIds) viewers.set(id, (viewers.get(id) ?? 0) + 1)
1836
+ unsubscribe = store.subscribe((event) => {
1837
+ if (event.type !== 'unshared' || finished || clientGone) return
1838
+ if (decision.sessionIds.every((id) => isAccessible(id))) return
1839
+ closeWith({
1840
+ type: 'error',
1841
+ error: {
1842
+ code: 'unshared',
1843
+ message: `shared session ${event.sessionId} was unshared (${event.reason})`,
1844
+ // T34: the structured close reason beside the message string —
1845
+ // the sub-client's closed-session display keys on this field.
1846
+ reason: event.reason,
1847
+ },
1848
+ })
1849
+ hangUp.abort()
1850
+ })
1851
+ }
1852
+
1853
+ const filterFrame: (frame: unknown) => unknown =
1854
+ eventsSub !== undefined
1855
+ ? (frame) => filterEventsFrame(eventsSub, frame)
1856
+ : decision.filter === 'workspace'
1857
+ ? (frame) => filterWorkspaceFrame(frame, isAccessible)
1858
+ : decision.filter === 'control'
1859
+ ? (frame) => filterControlFrame(frame, isAccessible)
1860
+ : namespace === 'job' && method === 'list'
1861
+ // 4b: ownerless and foreign jobs stay server-side.
1862
+ ? (frame) => filterJobListFrame(frame, ownerSessionIdOf(args))
1863
+ : (frame) => frame
1864
+
1865
+ // closeAll's kill switch for THIS stream: idempotent, safe to call on
1866
+ // an already-finished stream. Registered only while the response is
1867
+ // being served; the pump's finally unregisters it.
1868
+ const killThisStream = (): void => {
1869
+ hangUp.abort()
1870
+ const reason = serverClosedReason
1871
+ closeWith(
1872
+ reason === null || reason === ''
1873
+ ? { type: 'error', error: { code: 'server-restart' } }
1874
+ : { type: 'error', error: { code: 'server-restart', message: reason } },
1875
+ )
1876
+ }
1877
+ openStreamKills.add(killThisStream)
1878
+ // Registered beside the kill switch: closeAll detaches the stream's
1879
+ // share-table listener synchronously, before the pump's own teardown
1880
+ // gets a turn (T43-B).
1881
+ tableUnsubscribers.add(unsubscribe)
1882
+
1883
+ // Last gate before anything is opened (T22b-fix): both checks cover
1884
+ // the window the ownership probe (or any earlier await) opened — an
1885
+ // unshare or a closeAll during that window fires no event this stream
1886
+ // could have observed, so the CURRENT state decides.
1887
+ const firstInaccessible = decision.sessionIds.find((id) => !isAccessible(id))
1888
+ const restartReason = serverClosedReason
1889
+
1890
+ try {
1891
+ if (restartReason !== null) {
1892
+ // The handler was closed while this request was still deciding —
1893
+ // nothing may open anymore.
1894
+ killThisStream()
1895
+ } else if (firstInaccessible !== undefined) {
1896
+ hangUp.abort()
1897
+ closeWith({
1898
+ type: 'error',
1899
+ // No share-table event was observed on this stream (the session
1900
+ // was already unshared while the request was deciding — e.g.
1901
+ // inside the job ownership probe): the close reason degrades to
1902
+ // the manual close, the only fact that is certain here.
1903
+ error: { code: 'unshared', reason: 'manual', message: `shared session ${firstInaccessible} is no longer shared` },
1904
+ })
1905
+ } else {
1906
+ // `$zr/events` opens through the wire adapter (the ONLY door to
1907
+ // the forwarded-event stream); every other route is a typert
1908
+ // stream method.
1909
+ const iterable =
1910
+ eventsSub !== undefined
1911
+ ? await openEventsStream(hangUp.signal)
1912
+ : await gateway.stream({ namespace, method, args, signal: hangUp.signal })
1913
+ for await (const frame of iterable) {
1914
+ if (finished || clientGone) break
1915
+ if (namespace === 'job' && method === 'list') rememberJobs(ownerSessionIdOf(args), frame)
1916
+ applyToState?.(frame)
1917
+ const filtered = filterFrame(frame)
1918
+ if (filtered === null) continue
1919
+ await writeLine({ type: 'frame', frame: filtered })
1920
+ }
1921
+ closeWith({ type: 'end' })
1922
+ }
1923
+ } catch (error) {
1924
+ if (hangUp.signal.aborted || clientGone) {
1925
+ // The abort a hang-up (or an unshare kill) sends into the
1926
+ // iterator surfaces as gateway/cancelled — that is the stream's
1927
+ // DOCUMENTED normal end, swallowed whole.
1928
+ closeWith(null)
1929
+ } else {
1930
+ const { code, message } = errorOf(error)
1931
+ closeWith(message === undefined ? { type: 'error', error: { code } } : { type: 'error', error: { code, message } })
1932
+ }
1933
+ } finally {
1934
+ openStreamKills.delete(killThisStream)
1935
+ clearInterval(heartbeat)
1936
+ unsubscribe()
1937
+ tableUnsubscribers.delete(unsubscribe)
1938
+ if (eventsSub !== undefined) {
1939
+ liveEventSubscriptions.delete(eventsSub)
1940
+ eventsSub.events.clear()
1941
+ }
1942
+ res.off('close', onClientGone)
1943
+ res.off('error', onClientGone)
1944
+ if (decision.filter === undefined) {
1945
+ for (const id of decision.sessionIds) {
1946
+ const remaining = (viewers.get(id) ?? 1) - 1
1947
+ if (remaining <= 0) viewers.delete(id)
1948
+ else viewers.set(id, remaining)
1949
+ }
1950
+ }
1951
+ }
1952
+ } finally {
1953
+ const remaining = (streamsByDevice.get(device) ?? 1) - 1
1954
+ if (remaining <= 0) streamsByDevice.delete(device)
1955
+ else streamsByDevice.set(device, remaining)
1956
+ }
1957
+ return
1958
+ }
1959
+
1960
+ responseJson(res, 404, { ok: false, error: { code: 'not-found' } })
1961
+ }
1962
+
1963
+ handle.viewerCount = (sessionId: string): number => viewers.get(sessionId) ?? 0
1964
+ handle.closeAll = (reason: string): void => {
1965
+ // Detach EVERY share-table listener first (T43-B): after this point the
1966
+ // dead handler must not be reached by any share/unshare — not even by a
1967
+ // stream whose pump is parked on a full socket buffer and whose own
1968
+ // teardown still awaits the 'close' the kills below cause. Calling an
1969
+ // unsubscribe twice is a no-op, so the pumps' finallys stay honest.
1970
+ for (const detach of [...tableUnsubscribers]) detach()
1971
+ tableUnsubscribers.clear()
1972
+ // The event-forwarding registries go with them (T32): after closeAll no
1973
+ // answer may still compose a payload for a dead handler's clientId —
1974
+ // the streams' own finallys would clear theirs, but only after their
1975
+ // teardown unwinds, and an answer could slip into that window.
1976
+ for (const sub of liveEventSubscriptions) {
1977
+ sub.clientId = undefined
1978
+ sub.events.clear()
1979
+ }
1980
+ liveEventSubscriptions.clear()
1981
+ // Remember the reason for requests still inside their ownership probe —
1982
+ // they read it at the pre-open gate. Killing the open streams runs their
1983
+ // normal teardown (error line, res.end, abort), whose finally releases
1984
+ // the viewer/device counters and the share-table listeners.
1985
+ serverClosedReason = typeof reason === 'string' ? reason : ''
1986
+ for (const kill of [...openStreamKills]) kill()
1987
+ openStreamKills.clear()
1988
+ }
1989
+ return handle
1990
+ }
1991
+
1992
+ /** The claimed session of a `job/list` subscription — decideStream has
1993
+ * already verified it is a non-empty shared id; anything else is '' and the
1994
+ * job filter then keeps nothing. */
1995
+ function ownerSessionIdOf(args: unknown): string {
1996
+ const request = isPlainObject(args) ? args.request : undefined
1997
+ return isPlainObject(request) && typeof request.sessionId === 'string' ? request.sessionId : ''
1998
+ }
1999
+
2000
+ // The `dsh-session:` codec and the shared scan rule live in ONE module the
2001
+ // sub-client's interceptor imports too (session-reference.ts, T41a-fix2) —
2002
+ // re-exported here so the server's public surface keeps carrying them.
2003
+ export {
2004
+ SESSION_REFERENCE_URI,
2005
+ collectReferenceTexts,
2006
+ decodeSessionReferenceUri,
2007
+ encodeSessionReferenceUri,
2008
+ mapReferenceTexts,
2009
+ } from './session-reference.js'
2010
+
2011
+ /**
2012
+ * Every session id one call's injectable texts reference through canonical
2013
+ * `dsh-session:` addresses. WHERE those texts live is the shared scan rule
2014
+ * (session-reference.ts: prompt content, a queue EDIT's replacement content,
2015
+ * every string of a commands/execute call). Non-canonical candidates are
2016
+ * skipped: DSH answers them with its own business error, and the relay must
2017
+ * not crash on them.
2018
+ */
2019
+ function referencedSessionIds(namespace: string, method: string, args: unknown): string[] {
2020
+ const ids: string[] = []
2021
+ for (const text of collectReferenceTexts(namespace, method, args)) {
2022
+ for (const match of text.matchAll(SESSION_REFERENCE_URI)) {
2023
+ const id = decodeSessionReferenceUri(match[1] ?? match[2])
2024
+ if (id !== undefined) ids.push(id)
2025
+ }
2026
+ }
2027
+ return ids
2028
+ }
2029
+
2030
+ /**
2031
+ * Filter one `sessionReferenceResolver/candidates` result: keep only rows
2032
+ * whose `sessionId` passes the share table. The host lists EVERY server
2033
+ * session with title, cwd and a ready-made mention, so an unfiltered row
2034
+ * leaks metadata and hands the client a one-keystroke path into an unshared
2035
+ * session's content. Rows that cannot locate a session (malformed) are
2036
+ * dropped — nothing untrusted travels. A non-array result (a shape this
2037
+ * build does not know — a newer host's evolution) yields `[]`: 宁可不给,
2038
+ * never an unfiltered answer.
2039
+ *
2040
+ * Known limitation: the host caps a candidates page at `candidateLimit`
2041
+ * rows (default 50, RT dsh-session-reference config) BEFORE this filter
2042
+ * runs — on a server with many sessions the accessible rows past the cap
2043
+ * are cut off with the inaccessible ones, and the client just sees fewer
2044
+ * @ candidates. The @ resolver stays a convenience surface; the prompt-text
2045
+ * scan below is the access boundary, and it is not affected.
2046
+ */
2047
+ function filterAccessibleCandidateRows(value: unknown, isAccessible: (sessionId: string) => boolean): unknown {
2048
+ if (!Array.isArray(value)) return []
2049
+ return value.filter((row) => isPlainObject(row) && typeof row.sessionId === 'string' && isAccessible(row.sessionId))
2050
+ }
2051
+
2052
+ /**
2053
+ * A throwaway abort signal for checks that run before the stream's own
2054
+ * controller exists (the job ownership probe). Tied to the response: once the
2055
+ * client is gone there is no point fetching anything for it.
2056
+ */
2057
+ function hangUpOf(res: ServerResponse): AbortSignal {
2058
+ const controller = new AbortController()
2059
+ res.once('close', () => {
2060
+ if (!res.writableEnded) controller.abort()
2061
+ })
2062
+ return controller.signal
2063
+ }