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,36 @@
1
+ /**
2
+ * The plugin row fields whose changed value must reload the row to take
3
+ * effect (T17): `role` chooses which halves load; `port` / `host` /
4
+ * `targetPort` / `rateLimit` / `trustedProxies` become the gateway child's
5
+ * runtime shape; `vapidSubject` / `lang` / `pushEvents` / `pushDebounceMs` /
6
+ * `pushSummary` / `pushTurnEnd` / `pushTool` are the push leg's startup
7
+ * values. Everything else (serverName, idleHours, autoShareNewSessions,
8
+ * serverUrl, deviceToken, and the interface-half knobs) is read live per use
9
+ * and needs no reload.
10
+ *
11
+ * Single source shared by both halves: the host's restart watcher
12
+ * (src/restart-watcher.ts) fingerprints exactly these fields, and the
13
+ * settings page (src/client-data/settings-form.ts) shows the "saving reloads
14
+ * the plugin" note while one of them has a staged change. Deliberately
15
+ * dependency-free — the client bundler inlines every reachable module, so
16
+ * this file must never import node builtins or schemastery, which is why the
17
+ * list does not live in src/config.ts (T17b).
18
+ */
19
+ export const RESTART_FIELDS = [
20
+ 'role',
21
+ 'port',
22
+ 'host',
23
+ 'targetPort',
24
+ 'rateLimit',
25
+ 'trustedProxies',
26
+ 'vapidSubject',
27
+ 'lang',
28
+ 'pushEvents',
29
+ 'pushDebounceMs',
30
+ 'pushSummary',
31
+ 'pushTurnEnd',
32
+ 'pushTool',
33
+ ] as const
34
+
35
+ /** One field of {@link RESTART_FIELDS}. */
36
+ export type RestartField = (typeof RESTART_FIELDS)[number]
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Auto-reload of the plugin row when a "needs restart" config field changes
3
+ * (T17). Every Config field is volatile (src/config.ts — DSH's settings
4
+ * service only surfaces volatile fields), so "this value only takes effect
5
+ * after the row re-runs apply()" can no longer ride the volatility flag.
6
+ * Instead the host half re-resolves the effective config and compares a
7
+ * fingerprint over exactly the restart-required fields; a changed fingerprint
8
+ * reloads the row via cordis, which re-runs `apply()` and with it the gateway
9
+ * child and the push half. The comparison runs on two triggers (T17b): the
10
+ * loader's `loader/volatile-update` event (a settings save that only moves
11
+ * volatile fields commits without a restart and announces itself — the
12
+ * immediate path) and a 2s poll (the fallback for lan-gate.config.json and
13
+ * environment changes, which no loader event ever covers).
14
+ *
15
+ * Pure logic — no imports beyond src/restart-fields.ts and src/config.ts
16
+ * types, and timers only through injectable functions
17
+ * (test/restart-watcher.test.cjs drives every tick from a fake clock, same
18
+ * shape as startSweeper in src/activity.ts).
19
+ */
20
+
21
+ import type { ZenRemoteConfig } from './config.js'
22
+ import { RESTART_FIELDS } from './restart-fields.js'
23
+
24
+ export { RESTART_FIELDS } from './restart-fields.js'
25
+ export type { RestartField } from './restart-fields.js'
26
+
27
+ /**
28
+ * The restart fingerprint of one resolved config: the restart-required
29
+ * fields' values, JSON-stringified under a stable (sorted) key order, so a
30
+ * deep-equal config always yields the same string regardless of key order or
31
+ * the values of every other field. Takes a loose record (the resolved values
32
+ * type satisfies it structurally) because tests feed partial objects; a
33
+ * missing field and an undefined one are the same "not set".
34
+ */
35
+ export function restartKey(values: { [K in keyof ZenRemoteConfig]?: unknown }): string {
36
+ const picked: Record<string, unknown> = {}
37
+ for (const field of [...RESTART_FIELDS].sort()) picked[field] = values[field]
38
+ return JSON.stringify(picked)
39
+ }
40
+
41
+ /** Duck-typed timer halves, exactly like src/activity.ts's sweeper: Node's
42
+ * setInterval/clearInterval at runtime, fakes in tests. */
43
+ type StartInterval = (callback: () => void, ms: number) => unknown
44
+ type ClearInterval = (handle: unknown) => void
45
+
46
+ export interface RestartWatcherOptions {
47
+ /** Resolve the CURRENT effective config values; called once immediately
48
+ * (the baseline) and once per trigger. A throw is swallowed and retried on
49
+ * the next trigger — the watcher must survive a transient resolution
50
+ * failure. */
51
+ getValues: () => ZenRemoteConfig
52
+ /** Called at most once, when the fingerprint diverges from the baseline.
53
+ * After the call the watcher is done: it clears its own timer, so a slow
54
+ * or failing reload can never trigger a second one (the reload itself
55
+ * re-runs apply(), which starts a fresh watcher). */
56
+ onChange: () => void
57
+ /** Poll cadence in ms. Default 2000. */
58
+ intervalMs?: number
59
+ /** Injectable timer halves (tests drive ticks by hand). */
60
+ setIntervalImpl?: StartInterval
61
+ clearIntervalImpl?: ClearInterval
62
+ }
63
+
64
+ /** The two handles {@link startRestartWatcher} gives back: the poll's stop
65
+ * function (the host half hands it to ctx.effect as the disposer) and the
66
+ * immediate check the `loader/volatile-update` listener calls (T17b). */
67
+ export interface RestartWatcher {
68
+ stop(): void
69
+ /** One fingerprint comparison right now, bypassing the poll cadence.
70
+ * Identical semantics to a poll tick that sees a change: fires
71
+ * {@link RestartWatcherOptions.onChange} at most once, then disarms
72
+ * itself. */
73
+ checkNow(): void
74
+ }
75
+
76
+ /**
77
+ * Watch the restart-required fields and call `onChange` (once) when their
78
+ * resolved values diverge from the values {@link startRestartWatcher} was
79
+ * started with. Two triggers share the one fire-at-most-once guard: the
80
+ * returned `checkNow()` (the loader's `loader/volatile-update` event — a
81
+ * volatile-only settings save commits without a restart and announces itself
82
+ * on the row context, so the fingerprint is re-checked immediately instead
83
+ * of at the next tick, T17b) and the 2s poll, which remains the safety net
84
+ * for the layers no loader event ever covers — `lan-gate.config.json` and
85
+ * `LAN_GATE_*` / `DSH_PUSH_*` environment changes are picked up by the same
86
+ * comparison (getValues re-resolves every layer), which is the desired
87
+ * behavior: those layers below the row are just as invisible to a live read
88
+ * as a restart-required row field. `stop` is the disposer (the host half
89
+ * hands it to ctx.effect); the underlying timer is unref()ed so the poll
90
+ * alone never keeps the DSH process alive.
91
+ */
92
+ export function startRestartWatcher(options: RestartWatcherOptions): RestartWatcher {
93
+ const { getValues, onChange, intervalMs = 2_000 } = options
94
+ const setIntervalImpl: StartInterval = options.setIntervalImpl ?? ((callback, ms) => setInterval(callback, ms))
95
+ const clearIntervalImpl: ClearInterval =
96
+ options.clearIntervalImpl ?? ((handle) => clearInterval(handle as ReturnType<typeof setInterval>))
97
+ // A failing BASELINE read must not kill the watcher (apply() would fail to
98
+ // load the row): undefined means "not primed yet" — the first successful
99
+ // trigger primes it without firing.
100
+ let lastKey: string | undefined
101
+ try {
102
+ lastKey = restartKey(getValues())
103
+ } catch {
104
+ lastKey = undefined
105
+ }
106
+ let stopped = false
107
+ // `let`, not `const`: a fake timer may fire the first tick synchronously
108
+ // during setIntervalImpl, before the handle assignment below completes.
109
+ let handle: unknown
110
+ const stop = () => {
111
+ if (stopped) return
112
+ stopped = true
113
+ clearIntervalImpl(handle)
114
+ }
115
+ // One body for both triggers: an event dispatch and a poll tick are the
116
+ // same comparison, and `stopped` makes either path fire exactly once.
117
+ const checkNow = () => {
118
+ if (stopped) return
119
+ let key: string
120
+ try {
121
+ key = restartKey(getValues())
122
+ } catch {
123
+ return
124
+ }
125
+ if (lastKey === undefined) {
126
+ lastKey = key
127
+ return
128
+ }
129
+ if (key === lastKey) return
130
+ // Fire exactly once: stop before invoking, so the callback (the row
131
+ // reload) can neither re-trigger nor race a second tick.
132
+ stop()
133
+ onChange()
134
+ }
135
+ handle = setIntervalImpl(checkNow, intervalMs)
136
+ if (typeof handle === 'object' && handle !== null && typeof (handle as { unref?: unknown }).unref === 'function') {
137
+ ;(handle as { unref: () => void }).unref()
138
+ }
139
+ return { stop, checkNow }
140
+ }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * The `dsh-session:` reference discipline BOTH ends share (T41a-fix2):
3
+ *
4
+ * - the CODEC — the canonical reference addresses the host's own parser
5
+ * accepts (dsh-session-reference lib/index.js: a Markdown mention
6
+ * `@[label](URI)` or a bare URI; the payload is
7
+ * base64url(JSON.stringify(sessionId)) and the decode is CANONICAL —
8
+ * re-encoding must reproduce the URI byte for byte);
9
+ * - the SCAN RULE — which texts of one relayed call DSH would inject
10
+ * through. `prepareDirectMessages` parses the text blocks of EVERY
11
+ * user-sourced message wherever the message came from, and three wire
12
+ * paths put remote text into such a message: the prompt content
13
+ * (`session/prompt`, `subagents/prompt`), a queue edit — the edit
14
+ * REPLACES the queued user message's content verbatim (RT
15
+ * dsh-api-session-controller updateQueue) — and a slash command's raw
16
+ * input, which handlers steer in as a fresh user message (`/plan <text>`
17
+ * does exactly that, RT dsh-plan-mode). So the rule reads:
18
+ *
19
+ * `session/prompt` / `subagents/prompt` → the text blocks of
20
+ * `request.content`;
21
+ * `session/updateQueue` → when `request.action.kind === 'edit'`, the
22
+ * text blocks of `request.action.content` (steer/remove carry no
23
+ * content the host would inject);
24
+ * `commands/execute` → EVERY string in the arguments, recursively —
25
+ * the injection surface is whatever the command's handler does with
26
+ * the line, so the scan does not depend on the argument field name.
27
+ *
28
+ * Everything else contributes nothing. The relay server decodes every
29
+ * reference found in these texts and refuses the call when one names a
30
+ * session off its share table (relay-server.ts); the sub-client restores
31
+ * THIS server's virtual ids inside them and refuses references naming
32
+ * anything else (intercept.ts). One module serves both so the ends
33
+ * cannot drift — the previous two private copies are gone.
34
+ *
35
+ * Pure functions, no I/O; safe for both the host bundle and the tests.
36
+ */
37
+
38
+ /** The canonical reference shape, as {@link decodeSessionReferenceUri}
39
+ * consumes it. Match group 1 is a mention's URI, group 2 a bare URI. */
40
+ export const SESSION_REFERENCE_URI = /@\[(?:\\.|[^\\\]])*\]\((dsh-session:[^\s)]*)\)|(dsh-session:[A-Za-z0-9_-]+)/gu
41
+
42
+ /** Encode one session id into the canonical reference URI (matching the
43
+ * host's encoder, the mirror of {@link decodeSessionReferenceUri}). */
44
+ export function encodeSessionReferenceUri(sessionId: string): string {
45
+ return `dsh-session:${Buffer.from(JSON.stringify(sessionId), 'utf8').toString('base64url')}`
46
+ }
47
+
48
+ /**
49
+ * Decode one `dsh-session:` URI the way the host does, or `undefined` when
50
+ * it is not canonical. The host parser THROWS on non-canonical addresses —
51
+ * those become gateway business errors — so an address this decoder rejects
52
+ * can never inject anything and needs no guarding.
53
+ */
54
+ export function decodeSessionReferenceUri(uri: string): string | undefined {
55
+ const payload = uri.slice('dsh-session:'.length)
56
+ if (!/^[A-Za-z0-9_-]+$/.test(payload)) return undefined
57
+ try {
58
+ const parsed: unknown = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))
59
+ if (typeof parsed !== 'string') return undefined
60
+ if (encodeSessionReferenceUri(parsed).slice('dsh-session:'.length) !== payload) return undefined
61
+ return parsed
62
+ } catch {
63
+ return undefined
64
+ }
65
+ }
66
+
67
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
68
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
69
+ }
70
+
71
+ /** The text blocks of one content array, visited in order. */
72
+ function visitTextBlocks(content: unknown, visit: (text: string) => string): boolean {
73
+ if (!Array.isArray(content)) return false
74
+ let changed = false
75
+ for (const block of content) {
76
+ if (!isPlainObject(block) || block.type !== 'text' || typeof block.text !== 'string') continue
77
+ const next = visit(block.text)
78
+ if (next !== block.text) {
79
+ block.text = next
80
+ changed = true
81
+ }
82
+ }
83
+ return changed
84
+ }
85
+
86
+ /** Clone-on-write deep map over every string (the commands/execute walk):
87
+ * containers rebuild only when something inside them changed. */
88
+ function mapDeep(value: unknown, visit: (text: string) => string): { value: unknown; changed: boolean } {
89
+ if (typeof value === 'string') {
90
+ const next = visit(value)
91
+ return next === value ? { value, changed: false } : { value: next, changed: true }
92
+ }
93
+ if (Array.isArray(value)) {
94
+ let changed = false
95
+ const next = value.map((item) => {
96
+ const mapped = mapDeep(item, visit)
97
+ changed = changed || mapped.changed
98
+ return mapped.value
99
+ })
100
+ return changed ? { value: next, changed: true } : { value, changed: false }
101
+ }
102
+ if (isPlainObject(value)) {
103
+ let changed = false
104
+ const next: Record<string, unknown> = {}
105
+ for (const [key, item] of Object.entries(value)) {
106
+ const mapped = mapDeep(item, visit)
107
+ changed = changed || mapped.changed
108
+ next[key] = mapped.value
109
+ }
110
+ return changed ? { value: next, changed: true } : { value, changed: false }
111
+ }
112
+ return { value, changed: false }
113
+ }
114
+
115
+ /**
116
+ * Apply `visit` to EVERY text of one call the host would inject through —
117
+ * the scan rule above, in one place. The args are mutated IN PLACE where
118
+ * the rule reaches (content blocks) and rebuilt clone-on-write where it
119
+ * walks recursively (commands/execute); the returned args are what should
120
+ * travel (identical to the input when `visit` was the identity on every
121
+ * text). Both ends call THIS to decide what to scan — the server to check,
122
+ * the client to rewrite — so the two cannot disagree on where references
123
+ * hide.
124
+ */
125
+ export function mapReferenceTexts(namespace: string, method: string, args: unknown, visit: (text: string) => string): unknown {
126
+ if (!isPlainObject(args)) return args
127
+ const request = isPlainObject(args.request) ? args.request : undefined
128
+ if ((namespace === 'session' && method === 'prompt') || (namespace === 'subagents' && method === 'prompt')) {
129
+ if (request !== undefined) visitTextBlocks(request.content, visit)
130
+ return args
131
+ }
132
+ if (namespace === 'session' && method === 'updateQueue') {
133
+ if (request !== undefined && isPlainObject(request.action) && request.action.kind === 'edit') {
134
+ visitTextBlocks(request.action.content, visit)
135
+ }
136
+ return args
137
+ }
138
+ if (namespace === 'commands' && method === 'execute') {
139
+ const mapped = mapDeep(args, visit)
140
+ return mapped.value
141
+ }
142
+ return args
143
+ }
144
+
145
+ /**
146
+ * The texts of one call the host would inject through, read-only — the
147
+ * server-side face of {@link mapReferenceTexts}.
148
+ */
149
+ export function collectReferenceTexts(namespace: string, method: string, args: unknown): string[] {
150
+ const texts: string[] = []
151
+ mapReferenceTexts(namespace, method, args, (text) => {
152
+ texts.push(text)
153
+ return text
154
+ })
155
+ return texts
156
+ }
@@ -40,6 +40,11 @@ export const SHARE_EXPORT_ROUTE = '/_dsh/mobile-nav/share-export'
40
40
  * careless `turns=99999999` from quietly meaning "the whole log". */
41
41
  export const MAX_SHARE_TURNS = 500
42
42
 
43
+ /** What `connection.admit` answers: the operator peer, or the refusal status.
44
+ * Declared locally (same union as admin-routes.ts's AdminAdmission) so this
45
+ * module stays import-free of the entry file. */
46
+ export type ShareExportAdmission = { readonly peer: unknown } | { readonly rejection: 401 | 403 }
47
+
43
48
  /** One exportable content block of a transcript row. */
44
49
  export type ShareBlock =
45
50
  | { kind: 'text'; text: string }
@@ -391,8 +396,28 @@ function sliceLastTurns(rows: readonly FoldedRow[], count: number): ShareTurn[]
391
396
  * @param ctx - host context carrying the sessionQuery service and logger.
392
397
  * @param req - inbound request; no body is read.
393
398
  * @param res - the response this call owns end to end.
399
+ * @param admit - DSH's connection-service admission, passed by the apply()
400
+ * wiring (T17): webServer routes skip DSH's /api authentication, so every
401
+ * request must ask the connection service itself, its refusal relayed
402
+ * verbatim — same first wall as the admin and client routes. Optional only
403
+ * for the direct-drive tests; production always passes it.
394
404
  */
395
- export async function handleShareExport(ctx: Context, req: IncomingMessage, res: ServerResponse): Promise<void> {
405
+ export async function handleShareExport(
406
+ ctx: Context,
407
+ req: IncomingMessage,
408
+ res: ServerResponse,
409
+ admit?: (req: IncomingMessage) => ShareExportAdmission,
410
+ ): Promise<void> {
411
+ if (admit !== undefined) {
412
+ const admission = admit(req)
413
+ if ('rejection' in admission) {
414
+ responseJson(res, admission.rejection, {
415
+ ok: false,
416
+ error: { code: admission.rejection === 401 ? 'unauthorized' : 'forbidden' },
417
+ })
418
+ return
419
+ }
420
+ }
396
421
  if (req.method !== 'GET') {
397
422
  res.setHeader('Allow', 'GET')
398
423
  responseJson(res, 405, { ok: false, error: { code: 'method-not-allowed', message: 'Use GET' } })
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Pure share-table operations driven by host-side observations (T33a): the
3
+ * busy restore after a restart, and the share decision for a freshly created
4
+ * session. No DSH imports, no I/O, no clock — the table and every host fact
5
+ * come in as arguments, so the tests can drive them with plain objects.
6
+ *
7
+ * Field semantics verified against the DSH 0.2.0 sources (and spot-checked
8
+ * against the 0.1.7 line this package still supports):
9
+ *
10
+ * - `agents.list()` returns live agents whose `id` IS the session id (the
11
+ * agent registry is keyed by it, its typert wire type is
12
+ * `dsh-session/types#SessionId`, and `hasDesktopActiveTasks` in
13
+ * dsh-desktop-host feeds `agent.id` straight into `workspace/session-activity`'s
14
+ * `sessionId`). `status` is a getter answering `'idle'` or `'running'`;
15
+ * `'running'` means a turn is in flight (including waiting on approval).
16
+ * - a session header's `origin` is only ever `'subagent'` (subagent child,
17
+ * with `parentSession` naming its delegating parent); a FORK carries
18
+ * `parentSession` (its source) and `isSeeded: true` with NO origin — per
19
+ * `session/fork`'s `meta` in dsh-api-session-controller and
20
+ * `validateSessionHeader` in dsh-session.
21
+ */
22
+
23
+ import type { ShareStore } from './share-store.js'
24
+
25
+ /** The slice of a live agent the busy restore reads. Declared structurally
26
+ * so this module never imports DSH types and the tests can feed plain
27
+ * objects — the same discipline as activity.ts's ObservableSession. */
28
+ export interface AgentStatusLike {
29
+ id?: unknown
30
+ status?: unknown
31
+ }
32
+
33
+ /** The slice of a DSH session header the share decision reads. Field names
34
+ * per `validateSessionHeader`: `id` (matches the session id), `origin`
35
+ * (only legal value `'subagent'`), `parentSession` (a string when set). */
36
+ export interface CreatedSessionHeaderLike {
37
+ id?: unknown
38
+ origin?: unknown
39
+ parentSession?: unknown
40
+ }
41
+
42
+ /**
43
+ * Re-mark the busy flags a restart wiped. `busy` is deliberately never
44
+ * persisted, so after a plugin-row restart every shared session resumes as
45
+ * idle — and an idle session whose agent is actually mid-turn would idle out
46
+ * from under it. For every shared session whose agent currently reports
47
+ * `status === 'running'`, set busy; everything else keeps the post-restart
48
+ * idle default (setting busy FALSE here would re-stamp lastActivityAt and
49
+ * silently restart idle clocks for sessions nobody touched). The running
50
+ * flags then live their normal life: T22c's activity tracker clears them on
51
+ * `turn/end`.
52
+ *
53
+ * A throwing `listAgents` means "no information", not "nothing runs" — the
54
+ * restore degrades to a no-op instead of failing its caller (a route, or
55
+ * plugin startup).
56
+ */
57
+ export function restoreBusy(store: ShareStore, listAgents: () => readonly AgentStatusLike[]): void {
58
+ let roster: readonly AgentStatusLike[]
59
+ try {
60
+ roster = listAgents()
61
+ } catch {
62
+ return
63
+ }
64
+ const running = new Set<string>()
65
+ for (const agent of roster) {
66
+ if (agent !== null && typeof agent === 'object' && typeof agent.id === 'string' && agent.status === 'running') {
67
+ running.add(agent.id)
68
+ }
69
+ }
70
+ if (running.size === 0) return
71
+ for (const entry of store.list()) {
72
+ if (running.has(entry.sessionId)) store.setBusy(entry.sessionId, true)
73
+ }
74
+ }
75
+
76
+ export interface OnSessionCreatedOptions {
77
+ /** The shared-session table the decision writes into. */
78
+ store: ShareStore
79
+ /** The volatile `autoShareNewSessions` knob, resolved by the caller AT
80
+ * EVENT TIME — never snapshotted at apply. */
81
+ autoShare: boolean
82
+ /** Ancestor lookup for fork-source reachability (the same index the
83
+ * activity tracker and relay use). */
84
+ parentOf: (id: string) => string | undefined
85
+ }
86
+
87
+ /**
88
+ * The share decision for one freshly created session (the `agent/created`
89
+ * `source: 'startup'` payload's session header). Returns whether the session
90
+ * entered the table.
91
+ *
92
+ * Three shapes, judged off the header alone:
93
+ * - subagent child (`origin === 'subagent'`): never enters the table — it
94
+ * borrows reachability from its ancestor chain.
95
+ * - fork (`parentSession` set, origin absent): an ORDINARY user-created
96
+ * session (its header has no subagent marker), so the auto-share knob
97
+ * applies to it exactly as to a top-level one, with the fork source as an
98
+ * extra path: shared when its source is accessible OR the knob is on.
99
+ * - top-level: shared only when the auto-share knob is on right now.
100
+ */
101
+ export function onSessionCreated(
102
+ header: CreatedSessionHeaderLike | undefined | null,
103
+ options: OnSessionCreatedOptions,
104
+ ): boolean {
105
+ if (header === null || typeof header !== 'object') return false
106
+ const { store, autoShare, parentOf } = options
107
+ if (header.origin === 'subagent') return false
108
+ const { id, parentSession } = header
109
+ if (typeof id !== 'string' || id === '') return false
110
+ if (typeof parentSession === 'string' && parentSession !== '') {
111
+ return store.isAccessible(parentSession, parentOf) || autoShare ? store.share(id) : false
112
+ }
113
+ return autoShare ? store.share(id) : false
114
+ }