@capyclaw/rsp-suite 0.0.0-stage → 0.1.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 (146) hide show
  1. package/README.md +84 -2
  2. package/cordis.patch.yml +8 -0
  3. package/dsh-suite.json +91 -0
  4. package/node_modules/@capyclaw/foundation/README.md +51 -0
  5. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  6. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
  7. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  8. package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
  9. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  10. package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
  11. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  12. package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
  13. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  14. package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
  15. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  16. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  17. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  18. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  19. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  20. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  21. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
  22. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  25. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  29. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  30. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
  31. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
  32. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
  33. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
  34. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  35. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
  36. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  37. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  38. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  39. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
  40. package/node_modules/@capyclaw/foundation/package.json +53 -0
  41. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  42. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  43. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  44. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  45. package/node_modules/@capyclaw/plugin-kit/package.json +72 -0
  46. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  47. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  48. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
  49. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  50. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/ledger.mjs +151 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  72. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
  73. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  74. package/node_modules/@capyclaw/rsp-skill-remote-screen/README.md +7 -0
  75. package/node_modules/@capyclaw/rsp-skill-remote-screen/contract/rsp-contract.json +478 -0
  76. package/node_modules/@capyclaw/rsp-skill-remote-screen/cordis.patch.yml +4 -0
  77. package/node_modules/@capyclaw/rsp-skill-remote-screen/package.json +33 -0
  78. package/node_modules/@capyclaw/rsp-skill-remote-screen/plugin.mjs +15 -0
  79. package/node_modules/@capyclaw/rsp-skill-remote-screen/skills/remote-screen/SKILL.md +131 -0
  80. package/node_modules/@capyclaw/rsp-workbench/contract/capabilities.json +203 -0
  81. package/node_modules/@capyclaw/rsp-workbench/lib/client.mjs +681 -0
  82. package/node_modules/@capyclaw/rsp-workbench/lib/descriptors.mjs +28 -0
  83. package/node_modules/@capyclaw/rsp-workbench/lib/host.mjs +51 -0
  84. package/node_modules/@capyclaw/rsp-workbench/lib/manager.mjs +333 -0
  85. package/node_modules/@capyclaw/rsp-workbench/lib/session-mode.mjs +68 -0
  86. package/node_modules/@capyclaw/rsp-workbench/lib/tools.mjs +485 -0
  87. package/node_modules/@capyclaw/rsp-workbench/lib/workbench.mjs +184 -0
  88. package/node_modules/@capyclaw/rsp-workbench/package.json +47 -0
  89. package/node_modules/@capyclaw/rsp-workbench/plugin.mjs +17 -0
  90. package/node_modules/@capyclaw/rsp-workbench/ui/index.html +578 -0
  91. package/node_modules/@capyclaw/service-host/README.md +86 -0
  92. package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
  93. package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
  94. package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
  95. package/node_modules/@capyclaw/service-host/package.json +60 -0
  96. package/node_modules/@capyclaw/service-host/src/index.mjs +597 -0
  97. package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
  98. package/node_modules/@capyclaw/suite-kit/README.md +289 -0
  99. package/node_modules/@capyclaw/suite-kit/bin/dsh-domain.mjs +98 -0
  100. package/node_modules/@capyclaw/suite-kit/bin/dsh-suite.mjs +174 -0
  101. package/node_modules/@capyclaw/suite-kit/client/embed.js +35 -0
  102. package/node_modules/@capyclaw/suite-kit/domain.schema.json +129 -0
  103. package/node_modules/@capyclaw/suite-kit/package.json +58 -0
  104. package/node_modules/@capyclaw/suite-kit/src/activation-registry.mjs +184 -0
  105. package/node_modules/@capyclaw/suite-kit/src/artifacts.mjs +131 -0
  106. package/node_modules/@capyclaw/suite-kit/src/capability.mjs +181 -0
  107. package/node_modules/@capyclaw/suite-kit/src/compose.mjs +201 -0
  108. package/node_modules/@capyclaw/suite-kit/src/domain.mjs +138 -0
  109. package/node_modules/@capyclaw/suite-kit/src/embed.mjs +81 -0
  110. package/node_modules/@capyclaw/suite-kit/src/host.mjs +251 -0
  111. package/node_modules/@capyclaw/suite-kit/src/index.mjs +24 -0
  112. package/node_modules/@capyclaw/suite-kit/src/manifest.mjs +263 -0
  113. package/node_modules/@capyclaw/suite-kit/src/orchestration.mjs +100 -0
  114. package/node_modules/@capyclaw/suite-kit/src/profile.mjs +584 -0
  115. package/node_modules/@capyclaw/suite-kit/src/surface.mjs +28 -0
  116. package/node_modules/@capyclaw/suite-kit/suite.schema.json +128 -0
  117. package/node_modules/@capyclaw/tool-host/README.md +56 -0
  118. package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
  119. package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
  120. package/node_modules/@capyclaw/tool-host/lib/host.mjs +46 -0
  121. package/node_modules/@capyclaw/tool-host/package.json +59 -0
  122. package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
  123. package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
  124. package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
  125. package/node_modules/@capyclaw/tool-host/src/index.mjs +461 -0
  126. package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +272 -0
  127. package/node_modules/ws/LICENSE +20 -0
  128. package/node_modules/ws/README.md +539 -0
  129. package/node_modules/ws/browser.js +8 -0
  130. package/node_modules/ws/index.js +22 -0
  131. package/node_modules/ws/lib/buffer-util.js +142 -0
  132. package/node_modules/ws/lib/constants.js +19 -0
  133. package/node_modules/ws/lib/event-target.js +292 -0
  134. package/node_modules/ws/lib/extension.js +203 -0
  135. package/node_modules/ws/lib/limiter.js +55 -0
  136. package/node_modules/ws/lib/permessage-deflate.js +530 -0
  137. package/node_modules/ws/lib/receiver.js +751 -0
  138. package/node_modules/ws/lib/sender.js +610 -0
  139. package/node_modules/ws/lib/stream.js +161 -0
  140. package/node_modules/ws/lib/subprotocol.js +62 -0
  141. package/node_modules/ws/lib/validation.js +152 -0
  142. package/node_modules/ws/lib/websocket-server.js +562 -0
  143. package/node_modules/ws/lib/websocket.js +1440 -0
  144. package/node_modules/ws/package.json +74 -0
  145. package/node_modules/ws/wrapper.mjs +21 -0
  146. package/package.json +53 -4
@@ -0,0 +1,578 @@
1
+ <!doctype html>
2
+ <html lang="zh">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>RSP 远程屏幕工作台</title>
7
+ <style>
8
+ :root { color-scheme: dark; --bg:#0b1018; --panel:#141c2b; --line:#232f45; --ink:#e6ebf5; --dim:#8b9ab8; --accent:#4c7dff; }
9
+ * { box-sizing: border-box; }
10
+ html, body { height: 100%; }
11
+ body { margin: 0; font: 13px/1.5 system-ui, -apple-system, "Segoe UI", "PingFang SC", sans-serif; background: var(--bg); color: var(--ink); display: flex; flex-direction: column; overflow: hidden; }
12
+ header { flex: none; display: flex; align-items: center; gap: 10px; padding: 10px 14px; border-bottom: 1px solid var(--line); background: #0e1521; }
13
+ header h1 { font-size: 14px; margin: 0; font-weight: 600; white-space: nowrap; }
14
+ .pill { display: inline-flex; align-items: center; gap: 6px; padding: 2px 9px; border-radius: 999px; font-size: 12px; border: 1px solid transparent; white-space: nowrap; }
15
+ .pill i { width: 7px; height: 7px; border-radius: 50%; background: currentColor; display: inline-block; }
16
+ .on { background: #10331f; color: #57d98a; border-color: #1d4d2f; }
17
+ .off { background: #33161d; color: #ff8a9b; border-color: #4d1f29; }
18
+ .warn { background: #33280f; color: #ffc46b; border-color: #4d3a14; }
19
+ .spacer { flex: 1; }
20
+ .meta { color: var(--dim); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
21
+ button { font: inherit; border-radius: 7px; border: 1px solid var(--line); background: #1b2436; color: #cdd7ee; padding: 5px 10px; cursor: pointer; white-space: nowrap; }
22
+ button:hover { border-color: #33425f; background: #1f2a3f; }
23
+ button.primary { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 600; }
24
+ main { flex: 1; min-height: 0; display: flex; }
25
+ .stage { position: relative; flex: 1; min-width: 0; background: #05080d; overflow: hidden; }
26
+ .stage img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; display: block; }
27
+ #screen { z-index: 2; }
28
+ #snapshot { z-index: 1; }
29
+ #video { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; display: block; z-index: 3; background: #05080d; }
30
+ .placeholder { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: #5b6884; text-align: center; padding: 30px; font-size: 13px; line-height: 1.8; }
31
+ .overlay { position: absolute; left: 10px; bottom: 10px; z-index: 3; display: flex; gap: 8px; align-items: center; padding: 4px 10px; border-radius: 8px; background: rgba(8,12,20,.72); border: 1px solid #1e2940; font-size: 12px; color: #9fb0d0; backdrop-filter: blur(6px); }
32
+ .overlay b { color: #e6ebf5; font-weight: 600; }
33
+ aside { flex: none; width: 300px; border-left: 1px solid var(--line); background: #0e1521; overflow: auto; padding: 12px; }
34
+ aside section { margin-bottom: 14px; }
35
+ aside h2 { font-size: 11px; margin: 0 0 8px; color: var(--dim); text-transform: uppercase; letter-spacing: .06em; }
36
+ .kv { display: flex; justify-content: space-between; gap: 10px; padding: 4px 0; border-bottom: 1px dashed #1d2740; font-size: 12px; }
37
+ .kv:last-child { border-bottom: none; }
38
+ .kv .k { color: var(--dim); flex: none; }
39
+ .kv .v { text-align: right; word-break: break-all; }
40
+ label { display: block; font-size: 11px; color: var(--dim); margin: 8px 0 3px; }
41
+ input, select { width: 100%; padding: 6px 8px; border-radius: 6px; border: 1px solid var(--line); background: #0b1018; color: var(--ink); font: inherit; }
42
+ input:focus, select:focus { outline: none; border-color: var(--accent); }
43
+ .row { display: flex; gap: 6px; }
44
+ .row > * { flex: 1; min-width: 0; }
45
+ .btns { display: flex; gap: 6px; margin-top: 10px; }
46
+ .btns button { flex: 1; }
47
+ .msg { margin-top: 8px; font-size: 12px; min-height: 16px; color: var(--dim); }
48
+ .msg.err { color: #ff8a9b; }
49
+ .msg.ok { color: #57d98a; }
50
+ details > summary { cursor: pointer; color: var(--dim); font-size: 12px; }
51
+ @media (max-width: 900px) { aside { display: none; } }
52
+ </style>
53
+ </head>
54
+ <body>
55
+ <header>
56
+ <h1>RSP 远程屏幕工作台</h1>
57
+ <span id="pill" class="pill off"><i></i><span id="pillText">未连接</span></span>
58
+ <span id="target" class="meta"></span>
59
+ <span class="spacer"></span>
60
+ <button id="fullscreen" title="全屏查看">全屏</button>
61
+ <button id="resync" title="重新拉取画面流">重连画面</button>
62
+ </header>
63
+ <main>
64
+ <div class="stage" id="stage">
65
+ <div class="placeholder" id="placeholder">未连接被控端。<br/>连接后这里显示实时画面;画面只读,操控由 AI 经 rsp_* 工具完成。</div>
66
+ <img id="snapshot" alt="" style="display:none" />
67
+ <img id="screen" alt="remote screen" style="display:none" />
68
+ <canvas id="video" style="display:none"></canvas>
69
+ <div class="overlay" id="overlay" style="display:none">
70
+ <span>更新于 <b id="age">—</b></span>
71
+ <span id="dims">—</span>
72
+ <span id="liveTag" class="pill on" style="padding:0 6px"><i></i><span id="liveText">实时</span></span>
73
+ </div>
74
+ </div>
75
+ <aside>
76
+ <section>
77
+ <h2>状态</h2>
78
+ <div id="status"><div class="kv"><span class="k">尚未连接</span></div></div>
79
+ </section>
80
+ <section>
81
+ <h2>记住的目标(跨会话共享)</h2>
82
+ <select id="remembered"><option value="">(暂无记住的目标)</option></select>
83
+ <div class="btns"><button id="connectRemembered">连接选中目标</button></div>
84
+ <div class="msg">令牌掩码显示;连接信息持久化在本机,会话下次动作自动重连。</div>
85
+ </section>
86
+ <section>
87
+ <h2>观看会话</h2>
88
+ <select id="watchSession"><option value="">默认(最近活动的会话)</option></select>
89
+ <div class="msg">每个会话独立连接;嵌入主区时自动跟随当前会话,也可手动切换观看别的会话。</div>
90
+ </section>
91
+ <section>
92
+ <details id="connDetails">
93
+ <summary>连接 / 切换被控端</summary>
94
+ <label>基址 URL</label>
95
+ <input id="url" placeholder="http://192.168.1.5:8765" />
96
+ <div class="row">
97
+ <div><label>Host</label><input id="host" placeholder="192.168.1.5" /></div>
98
+ <div><label>Port</label><input id="port" placeholder="8765" /></div>
99
+ </div>
100
+ <label>访问令牌 token</label>
101
+ <input id="token" type="password" placeholder="bearer 令牌" />
102
+ <label>别名(可选)</label>
103
+ <input id="name" placeholder="我的电脑" />
104
+ <div class="btns">
105
+ <button id="connect" class="primary">连接</button>
106
+ <button id="disconnect">断开</button>
107
+ </div>
108
+ <div id="msg" class="msg"></div>
109
+ </details>
110
+ </section>
111
+ <section>
112
+ <h2>说明</h2>
113
+ <div class="msg">画面经服务端代理,令牌不下发到浏览器。被控端在画面无变化时不上报新帧:静止画面下显示的是最后一帧,左上角“更新于 N 秒前”即静止时长。</div>
114
+ </section>
115
+ </aside>
116
+ </main>
117
+ <script>
118
+ const $ = (id) => document.getElementById(id)
119
+ const msg = (t, kind) => { const m = $('msg'); if (!m) return; m.textContent = t || ''; m.className = 'msg ' + (kind || '') }
120
+ let streaming = false
121
+ let streamToken = 0
122
+ let lastFrameAt = 0
123
+ let lastFrameCount = -1
124
+ let retryTimer = null
125
+ let snapshotUrl = null
126
+ let h264Live = false // true once the H.264 canvas has painted a real frame
127
+ let isConnected = false
128
+ /* 与 service-host 的会话段规则一致:/s/<sid>(sid 字母数字开头,可含 . _ ~ -)。
129
+ GUI 主区给每个会话嵌的地址都带这一段——不认领它,所有会话的查看器就都看同一个桶。
130
+ 注意:SESSION_RE 必须先于 watchSid 初始化声明,否则 sidFromUrl() 立即执行时 const 还在 TDZ。 */
131
+ const SESSION_RE = /\/s\/([A-Za-z0-9][A-Za-z0-9._~-]{0,127})(?=\/|$)/
132
+ function sidFromUrl() {
133
+ const m = SESSION_RE.exec(location.pathname)
134
+ if (m) return m[1]
135
+ try { return new URLSearchParams(location.search).get('session') || null } catch { return null }
136
+ }
137
+ let watchSid = sidFromUrl() // 观看/操作的会话桶;嵌入时从自身 URL 的 /s/<sid>/ 段认领,null=服务端默认
138
+ const sessQ = () => watchSid ? '&session=' + encodeURIComponent(watchSid) : ''
139
+ const statusQ = () => watchSid ? '?session=' + encodeURIComponent(watchSid) : ''
140
+
141
+ /* portal-hud 换会话时不重载 iframe,改发 postMessage 就地换桶;回 ack 免它 600ms 后兜底硬重载。 */
142
+ window.addEventListener('message', (ev) => {
143
+ const d = ev.data
144
+ if (!d || d.type !== 'capyclaw:workbench:session') return
145
+ if (ev.origin !== location.origin) return
146
+ try { ev.source && ev.source.postMessage({ type: 'capyclaw:workbench:session-ack', sid: d.sid }, ev.origin) } catch {}
147
+ const sid = typeof d.sid === 'string' && d.sid ? d.sid : null
148
+ if (sid === watchSid) return
149
+ watchSid = sid
150
+ resetStage()
151
+ refresh()
152
+ })
153
+
154
+ /* ---------- 表面可见性(渲染面生命周期,标准 §2/§5) ----------
155
+ 本 UI 无构建、原样拷贝部署(workbench.mjs 的 app.static(uiDir)),不能 import 共享包,
156
+ 故内联一个最小 visibility 订阅器(纯订阅,无桥)。协议常量真源:
157
+ C/packages/capyclaw-foundation/abi/visibility.mjs —— 改那边必须同步这里
158
+ (test/ui-visibility.test.mjs 有静态 parity 守护)。
159
+ iframe 内 document.hidden 只反映顶层 tab,被宿主藏起来不触发 visibilitychange,
160
+ 表面可见性只能由宿主 postMessage 告知;hidden 必须挂起渲染面。
161
+ 边界(标准 P1):这里只停 UI 侧屏幕流(api/screen.mjpg、api/screen.h264 代理)与渲染循环;
162
+ 服务端常驻 screen.ws/control.ws 是 AI 无头观察/操控通道,绝不因表面隐藏而关。 */
163
+ const VISIBILITY_MESSAGE = 'capyclaw:workbench:visibility'
164
+ const VISIBILITY_ACK_MESSAGE = 'capyclaw:workbench:visibility-ack'
165
+ const VISIBILITY_STATES = ['foreground', 'background', 'hidden', 'detached']
166
+
167
+ let renderSuspended = false
168
+ let refreshTimer = null
169
+ let ageTimer = null
170
+
171
+ /* 渲染面循环的唯一起点:句柄 null-guard,快速切换不会叠出重复定时器。
172
+ 起 = 状态轮询(1.5s) + 帧龄刷新(250ms);屏幕流由 refresh→renderStatus 按需重开。 */
173
+ function startRenderLoops() {
174
+ if (refreshTimer === null) refreshTimer = setInterval(refresh, 1500)
175
+ if (ageTimer === null) ageTimer = setInterval(tickAge, 250)
176
+ }
177
+
178
+ /* 停 = 渲染循环全清 + UI 侧屏幕流 abort(MJPEG img 与 H.264 fetch)。
179
+ 上游每个 UI MJPEG 请求各算一个被控端 viewer,abort 即取消该订阅;
180
+ 服务端常驻 screen.ws 仍是 AI 的 viewer,被控端采集不停(标准 P1/§5)。 */
181
+ function stopRenderLoops() {
182
+ if (refreshTimer !== null) { clearInterval(refreshTimer); refreshTimer = null }
183
+ if (ageTimer !== null) { clearInterval(ageTimer); ageTimer = null }
184
+ stopStream()
185
+ stopH264()
186
+ }
187
+
188
+ /* 幂等:同态重复消息不重启/重停。hidden/detached 挂起渲染面;
189
+ foreground/background 恢复(background 只是失焦、仍可见,渲染面保持运转)。 */
190
+ function setRenderVisibility(next) {
191
+ const suspend = next === 'hidden' || next === 'detached'
192
+ if (suspend === renderSuspended) return
193
+ renderSuspended = suspend
194
+ if (suspend) { stopRenderLoops(); return }
195
+ startRenderLoops()
196
+ /* 回前台立即补一次状态:重开屏幕流并刷新画面(隐藏期可能已换会话/断连)。 */
197
+ refresh()
198
+ }
199
+
200
+ function onVisibilityMessage(event) {
201
+ /* 只认同源宿主(浮标/portal 与本页同 origin);跨源消息一律丢弃。
202
+ 状态按 abi 白名单校验,非法状态丢弃不回 ack(宿主发送前已归一化)。 */
203
+ if (event.origin !== location.origin) return
204
+ const data = event.data
205
+ if (!data || data.type !== VISIBILITY_MESSAGE) return
206
+ if (VISIBILITY_STATES.indexOf(data.state) === -1) return
207
+ setRenderVisibility(data.state)
208
+ try {
209
+ if (event.source) event.source.postMessage({ type: VISIBILITY_ACK_MESSAGE, state: data.state, sid: data.sid }, event.origin)
210
+ } catch {}
211
+ }
212
+ window.addEventListener('message', onVisibilityMessage)
213
+
214
+ /* 真实卸载:清渲染面循环并摘 visibility 订阅监听;
215
+ bfcache 冻结(persisted)保持原样——定时器被冻结而非销毁,恢复时自会续跑。 */
216
+ window.addEventListener('pagehide', (event) => {
217
+ if (event && event.persisted) return
218
+ renderSuspended = true // 卸载期禁止 stopH264 的兜底回退再拉起新流
219
+ stopRenderLoops()
220
+ window.removeEventListener('message', onVisibilityMessage)
221
+ })
222
+
223
+ /* Single source of truth for which stage layer is visible. A layer is only made
224
+ visible when it actually holds content, so transitions never flash blank. */
225
+ function showLayer(name) {
226
+ for (const id of ['video', 'screen', 'snapshot']) $(id).style.display = (id === name) ? 'block' : 'none'
227
+ $('placeholder').style.display = (name === 'placeholder') ? 'flex' : 'none'
228
+ $('overlay').style.display = (name === 'placeholder') ? 'none' : 'flex'
229
+ }
230
+
231
+ async function jfetch(route, opts) {
232
+ const res = await fetch(route, opts)
233
+ let data = null
234
+ try { data = await res.json() } catch {}
235
+ if (!res.ok) throw new Error((data && (data.error || data.code)) || ('HTTP ' + res.status))
236
+ return data
237
+ }
238
+
239
+ function setPill(kind, text) { $('pill').className = 'pill ' + kind; $('pillText').textContent = text }
240
+
241
+ /* 静态快照层:保证任何时刻都有图可看(含静止画面/刚打开时)。 */
242
+ async function refreshSnapshot() {
243
+ if (renderSuspended) return
244
+ try {
245
+ const r = await fetch('api/frame?t=' + Date.now() + sessQ())
246
+ if (!r.ok) return
247
+ const blob = await r.blob()
248
+ const img = $('snapshot')
249
+ const old = snapshotUrl
250
+ snapshotUrl = URL.createObjectURL(blob)
251
+ img.onload = () => {
252
+ if (old) URL.revokeObjectURL(old)
253
+ // only reveal the static layer when no live layer is on top
254
+ if (!h264Live && !streaming) showLayer('snapshot')
255
+ }
256
+ img.src = snapshotUrl
257
+ } catch {}
258
+ }
259
+
260
+ /* 实时流层:叠加在快照之上;有变化时由被控端推帧覆盖。 */
261
+ function startStream() {
262
+ if (renderSuspended) return
263
+ if (streaming) return
264
+ streaming = true
265
+ const my = ++streamToken
266
+ const img = $('screen')
267
+ img.onload = () => { if (my === streamToken && !h264Live) showLayer('screen') }
268
+ img.onerror = () => {
269
+ if (my !== streamToken) return
270
+ img.onerror = null
271
+ if (!streaming) return
272
+ clearTimeout(retryTimer)
273
+ retryTimer = setTimeout(() => { if (streaming && my === streamToken) { streaming = false; startStream() } }, 1500)
274
+ }
275
+ img.src = 'api/screen.mjpg?t=' + Date.now() + '-' + my + sessQ()
276
+ }
277
+
278
+ function stopStream() {
279
+ streaming = false
280
+ streamToken++
281
+ clearTimeout(retryTimer)
282
+ const img = $('screen')
283
+ img.onerror = null
284
+ img.onload = null
285
+ img.removeAttribute('src') // abort the MJPEG connection; canvas/snapshot hold the picture
286
+ }
287
+
288
+ /* ---- 实时 H.264 层:fetch chunked + WebCodecs 硬解 + canvas rAF(ToDesk 级低延迟) ---- */
289
+ let h264 = null // {abort, decoder, ...}
290
+ let h264Fps = 0
291
+ function stopH264() {
292
+ if (!h264) return
293
+ try { h264.abort.abort() } catch {}
294
+ try { h264.decoder.close() } catch {}
295
+ h264 = null
296
+ h264Live = false
297
+ // keep the last decoded frame on the canvas as a freeze-frame; bring a live
298
+ // fallback up underneath and let it hide the canvas once it has content.
299
+ if (isConnected) { startStream(); refreshSnapshot() }
300
+ }
301
+ function nalBody(nal) { // 去掉 Annex-B 起始码
302
+ if (nal[0] === 0 && nal[1] === 0 && nal[2] === 0 && nal[3] === 1) return nal.subarray(4)
303
+ if (nal[0] === 0 && nal[1] === 0 && nal[2] === 1) return nal.subarray(3)
304
+ return nal
305
+ }
306
+ function nalType(nal) { return nalBody(nal)[0] & 0x1f }
307
+ function buildAvcC(sps, pps) {
308
+ const s = nalBody(sps), p = nalBody(pps)
309
+ const len = (n) => [(n >> 8) & 255, n & 255]
310
+ return new Uint8Array([1, s[1], s[2], s[3], 0xff, 0xe1, ...len(s.length), ...s, 1, ...len(p.length), ...p])
311
+ }
312
+ const hex2 = (n) => n.toString(16).padStart(2, '0')
313
+ async function startH264() {
314
+ if (renderSuspended) return false
315
+ if (h264) return
316
+ if (!('VideoDecoder' in window)) return false // 无 WebCodecs → 回退 JPEG
317
+ const abort = new AbortController()
318
+ const canvas = $('video')
319
+ // desynchronized = low-latency canvas: hints the browser to present this surface
320
+ // outside the normal compositor vsync queue (tearing allowed), cutting the
321
+ // present-phase wait (up to one refresh) toward native. Falls back silently where
322
+ // unsupported. This is the client-side half of "near-native" latency.
323
+ const ctx = canvas.getContext('2d', { desynchronized: true })
324
+ let sps = null, pps = null, configured = false, ts = 0, decoded = 0, fpsT = performance.now(), lastOut = 0
325
+ // S5: decode-queue backpressure. When the decoder falls behind (slow hardware /
326
+ // throttled tab), feeding more deltas only grows latency. Drop deltas until the
327
+ // next self-contained IDR, then resume — bounds latency instead of letting it
328
+ // climb. Normal path (queue≈0) is untouched, preserving the zero-drop render.
329
+ let waitingKey = false
330
+ const QUEUE_LIMIT = 8
331
+ const sameNal = (a, b) => a && b && a.length === b.length && a.every((v, i) => v === b[i])
332
+ const decoder = new VideoDecoder({
333
+ output: (frame) => {
334
+ if (canvas.width !== frame.displayWidth || canvas.height !== frame.displayHeight) {
335
+ canvas.width = frame.displayWidth; canvas.height = frame.displayHeight
336
+ }
337
+ // Zero-drop rendering: draw EVERY decoded frame immediately (no rAF gate that
338
+ // coalesces/drops frames when 2 arrive per refresh). drawImage is GPU-backed;
339
+ // the browser presents the latest at vsync. Closing the previous pending frame
340
+ // only releases an already-rendered surface, never an unshown one.
341
+ ctx.drawImage(frame, 0, 0)
342
+ frame.close()
343
+ if (!h264Live) { h264Live = true; showLayer('video') }
344
+ decoded++
345
+ const now = performance.now()
346
+ if (now - fpsT >= 1000) { h264Fps = Math.round(decoded * 1000 / (now - fpsT)); decoded = 0; fpsT = now }
347
+ lastFrameAt = Date.now()
348
+ $('dims').textContent = canvas.width + '×' + canvas.height
349
+ },
350
+ error: () => { stopH264() },
351
+ })
352
+ h264 = { abort, decoder }
353
+ try {
354
+ const res = await fetch('api/screen.h264?t=' + Date.now() + sessQ(), { signal: abort.signal })
355
+ if (!res.ok || !res.body) { stopH264(); return false }
356
+ const reader = res.body.getReader()
357
+ let buf = new Uint8Array(0)
358
+ const concat = (a, b) => { const m = new Uint8Array(a.length + b.length); m.set(a); m.set(b, a.length); return m }
359
+ const push = (nal) => {
360
+ const t = nalType(nal)
361
+ if (t === 7) {
362
+ // S1: a resolution/quality switch emits a new SPS — reconfigure on the next
363
+ // IDR instead of decoding new geometry with the old avcC description.
364
+ if (configured && !sameNal(sps, nal)) { configured = false; waitingKey = true; try { decoder.reset() } catch {} }
365
+ sps = nal; return
366
+ }
367
+ if (t === 8) { pps = nal; return }
368
+ if (t !== 1 && t !== 5) return
369
+ if (decoder.decodeQueueSize > QUEUE_LIMIT) waitingKey = true
370
+ if (waitingKey) {
371
+ if (t !== 5) return // drop deltas until a keyframe resyncs the stream
372
+ waitingKey = false
373
+ }
374
+ if (!configured) {
375
+ if (!sps || !pps) return
376
+ const s = nalBody(sps)
377
+ decoder.configure({ codec: 'avc1.' + hex2(s[1]) + hex2(s[2]) + hex2(s[3]), description: buildAvcC(sps, pps), optimizeForLatency: true, hardwareAcceleration: 'prefer-hardware' })
378
+ configured = true
379
+ }
380
+ const body = nalBody(nal)
381
+ const data = new Uint8Array(4 + body.length)
382
+ new DataView(data.buffer).setUint32(0, body.length)
383
+ data.set(body, 4)
384
+ // Dynamic presentation timestamps from the real inter-frame interval (works at
385
+ // 30/55/60fps; the old fixed 33333µs assumed 30fps and mis-timed 60fps streams).
386
+ // bf=0 + optimizeForLatency means no reorder buffer, so ts only orders output.
387
+ const nowUs = Math.round(performance.now() * 1000)
388
+ ts = lastOut ? ts + Math.max(1000, Math.min(100000, nowUs - lastOut)) : nowUs
389
+ lastOut = nowUs
390
+ decoder.decode(new EncodedVideoChunk({ type: t === 5 ? 'key' : 'delta', timestamp: ts, data }))
391
+ }
392
+ for (;;) {
393
+ const { done, value } = await reader.read()
394
+ if (done) break
395
+ buf = concat(buf, value)
396
+ // 一个 NAL 在「看到下一个起始码」时才算完整;尾部不完整 NAL 留到下次 read
397
+ const sc = findSC(buf, 0)
398
+ if (sc === -1) { buf = buf.subarray(Math.max(0, buf.length - 3)); continue }
399
+ if (sc > 0) buf = buf.subarray(sc)
400
+ for (;;) {
401
+ const next = findSC(buf, 3)
402
+ if (next === -1) break
403
+ push(buf.subarray(0, next))
404
+ buf = buf.subarray(next)
405
+ }
406
+ }
407
+ } catch { /* abort/网络 → 回退 */ }
408
+ if (h264 && h264.abort === abort) stopH264()
409
+ return true
410
+ }
411
+ function findSC(b, from) {
412
+ for (let i = from; i + 3 < b.length; i++) {
413
+ if (b[i] === 0 && b[i + 1] === 0 && (b[i + 2] === 1 || (b[i + 2] === 0 && b[i + 3] === 1))) return i
414
+ }
415
+ return -1
416
+ }
417
+
418
+ function fmtAge(ms) {
419
+ if (!ms || ms < 0) return '—'
420
+ if (ms < 1000) return (Math.round(ms / 100) / 10) + ' 秒前'
421
+ if (ms < 60000) return Math.round(ms / 1000) + ' 秒前'
422
+ return Math.round(ms / 60000) + ' 分钟前'
423
+ }
424
+
425
+ // 目标名/基址来自 rsp_connect 参数(调用者可控),插 innerHTML 前必须转义,防存储型 XSS。
426
+ function esc(s) {
427
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
428
+ }
429
+
430
+ function fillSelect(sel, options, keepValue) {
431
+ const cur = keepValue !== undefined ? keepValue : sel.value
432
+ sel.innerHTML = options.map(([v, label]) => '<option value="' + String(v).replace(/"/g, '&quot;') + '">' + esc(label) + '</option>').join('')
433
+ if ([...sel.options].some((o) => o.value === cur)) sel.value = cur
434
+ }
435
+
436
+ function renderMemory(s) {
437
+ const rem = s.remembered || { targets: [], sessions: {} }
438
+ const opts = [['', '(选择记住的目标)']]
439
+ for (const t of rem.targets || []) opts.push([t.name, (rem.active === t.name ? '★ ' : '') + t.name + ' · ' + t.baseUrl])
440
+ fillSelect($('remembered'), opts)
441
+ }
442
+
443
+ async function refreshSessions() {
444
+ try {
445
+ const r = await jfetch('api/sessions')
446
+ const opts = [['', '默认(最近活动的会话)']]
447
+ const list = r.sessions || []
448
+ // 嵌入认领的会话可能还没连接(不在列表里):也要出现在下拉中,标明「本会话」
449
+ if (watchSid && !list.some((s) => s.session === watchSid)) {
450
+ opts.push([watchSid, '◌ ' + String(watchSid).slice(0, 8) + ' · 本会话(未连接)'])
451
+ }
452
+ for (const s of list) {
453
+ const label = (s.connected ? '● ' : '○ ') + String(s.session).slice(0, 8) + ' · ' + (s.target || s.baseUrl || '—')
454
+ opts.push([s.session, s.session === watchSid ? label + '(本会话)' : label])
455
+ }
456
+ fillSelect($('watchSession'), opts, watchSid || '')
457
+ } catch {}
458
+ }
459
+
460
+ function renderStatus(s) {
461
+ const c = s.client || {}
462
+ const connected = !!s.connected
463
+ setPill(connected ? 'on' : 'off', connected ? '已连接' : '未连接')
464
+ $('target').textContent = connected && s.target ? ((s.target.name ? s.target.name + ' · ' : '') + s.target.baseUrl) : ''
465
+ $('connDetails').open = !connected
466
+ const rows = [
467
+ ['目标', s.target ? (s.target.name || '—') : '—'],
468
+ ['基址', s.target ? s.target.baseUrl : '—'],
469
+ ['令牌', s.target ? s.target.token : '—'],
470
+ ['画面通道', c.screenState || '—'],
471
+ ['实时通道', c.h264 ? ('H.264 · ' + h264Fps + ' fps') : (c.h264State && c.h264State !== 'idle' ? c.h264State : 'JPEG')],
472
+ ['操控通道', (c.controlState || '—') + (c.controlMode ? ' / ' + c.controlMode : '')],
473
+ ['逻辑尺寸', c.logical ? (c.logical.width + '×' + c.logical.height) : '—'],
474
+ ['最近帧', c.lastFrame ? (c.lastFrame.width + '×' + c.lastFrame.height) : '—'],
475
+ ['帧数', c.frameCount ?? '—'],
476
+ ['引擎就绪', c.engine ? String(c.engine.ready) : '—'],
477
+ ['辅助功能', c.engine ? String(c.engine.axTrusted) : '—'],
478
+ ['屏幕录制', c.engine ? String(c.engine.screenCapture) : '—'],
479
+ ]
480
+ $('status').innerHTML = rows.map(([k, v]) => '<div class="kv"><span class="k">' + esc(k) + '</span><span class="v">' + esc(v) + '</span></div>').join('')
481
+ renderMemory(s)
482
+ const fc = c.frameCount ?? -1
483
+ if (c.lastFrame && c.lastFrame.at) lastFrameAt = c.lastFrame.at
484
+ $('dims').textContent = c.lastFrame ? (c.lastFrame.width + '×' + c.lastFrame.height) : '—'
485
+
486
+ isConnected = connected
487
+ if (!connected) { if (streaming) stopStream(); stopH264(); showLayer('placeholder'); return }
488
+ if (c.h264) {
489
+ // 实时 H.264 优先:画布真正出帧后才收掉 MJPEG/快照层,避免切换空白闪
490
+ startH264()
491
+ if (h264Live) { if (streaming) stopStream() }
492
+ else {
493
+ if (!streaming) startStream()
494
+ if (fc !== lastFrameCount) { lastFrameCount = fc; refreshSnapshot() }
495
+ }
496
+ return
497
+ }
498
+ stopH264()
499
+ if (!streaming) startStream()
500
+ // 帧数变化(或有首帧)时刷新快照层,兜住 MJPEG 静止时拿不到首帧的情况
501
+ if (fc !== lastFrameCount) { lastFrameCount = fc; refreshSnapshot() }
502
+ }
503
+
504
+ function tickAge() {
505
+ const age = lastFrameAt ? Date.now() - lastFrameAt : 0
506
+ $('age').textContent = fmtAge(age)
507
+ const tag = $('liveTag')
508
+ if (h264) { tag.className = 'pill on'; $('liveText').textContent = 'H.264 ' + h264Fps + 'fps'; return }
509
+ if (streaming && age > 3000) { tag.className = 'pill warn'; $('liveText').textContent = '静止' }
510
+ else if (streaming) { tag.className = 'pill on'; $('liveText').textContent = '实时' }
511
+ }
512
+
513
+ async function refresh() {
514
+ try { renderStatus(await jfetch('api/status' + statusQ())) } catch {}
515
+ refreshSessions()
516
+ }
517
+
518
+ function resetStage() {
519
+ stopStream(); stopH264(); h264Live = false; lastFrameCount = -1; lastFrameAt = 0
520
+ showLayer('placeholder')
521
+ }
522
+
523
+ $('connectRemembered').onclick = async () => {
524
+ const name = $('remembered').value
525
+ if (!name) { msg('先在下拉中选择一个记住的目标', 'err'); return }
526
+ msg('连接中…')
527
+ const body = { name }
528
+ if (watchSid) body.session = watchSid
529
+ try {
530
+ const r = await jfetch('api/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
531
+ msg('已连接 ' + (r.info && r.info.protocol), 'ok')
532
+ resetStage()
533
+ renderStatus(r.status)
534
+ } catch (e) { msg(e.message, 'err') }
535
+ }
536
+ $('watchSession').onchange = () => {
537
+ watchSid = $('watchSession').value || null
538
+ resetStage()
539
+ refresh()
540
+ }
541
+
542
+ $('connect').onclick = async () => {
543
+ msg('连接中…')
544
+ const body = {}
545
+ if ($('url').value.trim()) body.url = $('url').value.trim()
546
+ if ($('host').value.trim()) body.host = $('host').value.trim()
547
+ if ($('port').value.trim()) body.port = Number($('port').value.trim())
548
+ if ($('token').value) body.token = $('token').value
549
+ if ($('name').value.trim()) body.name = $('name').value.trim()
550
+ if (watchSid) body.session = watchSid
551
+ try {
552
+ const r = await jfetch('api/connect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
553
+ msg('已连接 ' + (r.info && r.info.protocol), 'ok')
554
+ $('token').value = ''
555
+ resetStage()
556
+ renderStatus(r.status)
557
+ } catch (e) { msg(e.message, 'err') }
558
+ }
559
+ $('disconnect').onclick = async () => {
560
+ try { await jfetch('api/disconnect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(watchSid ? { session: watchSid } : {}) }); msg('已断开', 'ok') } catch (e) { msg(e.message, 'err') }
561
+ resetStage()
562
+ refresh()
563
+ }
564
+ $('resync').onclick = () => { const was = streaming; stopStream(); stopH264(); lastFrameCount = -1; if (was) { startStream(); refreshSnapshot() } refresh() }
565
+ $('fullscreen').onclick = () => {
566
+ const el = $('stage')
567
+ if (document.fullscreenElement) document.exitFullscreen()
568
+ else if (el.requestFullscreen) el.requestFullscreen()
569
+ else if (el.webkitRequestFullscreen) el.webkitRequestFullscreen()
570
+ }
571
+
572
+ /* 渲染面循环统一由 startRenderLoops 起(状态轮询 1.5s + 帧龄 250ms),
573
+ 宿主 visibility 消息 hidden 时经 stopRenderLoops 全停、foreground 时重建。 */
574
+ refresh()
575
+ startRenderLoops()
576
+ </script>
577
+ </body>
578
+ </html>
@@ -0,0 +1,86 @@
1
+ # @capyclaw/service-host
2
+
3
+ DSH 公共服务宿主插件。功能插件通过 `ctx.serviceHost` 获得统一的 HTTP 运行时,不必再为每个插件复制 relay/路由/健康/指标/锁/静态资源代码。
4
+
5
+ ## 使用
6
+
7
+ ```js
8
+ export const inject = ['serviceHost']
9
+
10
+ export function apply(ctx, config) {
11
+ const app = ctx.serviceHost.createApp({
12
+ id: 'my-plugin',
13
+ title: 'My Plugin',
14
+ version: '1.0.0',
15
+ contractVersion: '1.0.0',
16
+ health: () => ({ ready: true }),
17
+ metrics: () => [['my_items', 3]],
18
+ })
19
+ app.use(myRoutes)
20
+ await app.listen({
21
+ port: config.port,
22
+ hostDir: config.hostDir,
23
+ strictPort: config.strictPort,
24
+ })
25
+ return () => app.close()
26
+ }
27
+ ```
28
+
29
+ 独立运行:
30
+
31
+ ```js
32
+ import { createServiceApp } from '@capyclaw/service-host/src'
33
+ const app = createServiceApp({ id: 'my-plugin' })
34
+ app.get('/ping', (req, res) => res.end('pong'))
35
+ const info = await app.listen({ port: 39500 })
36
+ ```
37
+
38
+ 嵌入 DSH Web:
39
+
40
+ ```js
41
+ await app.listen({ webServer: ctx.webServer, basePath: '/plugins/my-plugin' })
42
+ ```
43
+
44
+ ## 共享宿主(多插件一个端口)
45
+
46
+ ```js
47
+ const host = ctx.serviceHost.createSharedHost({ id: 'dsh-app' })
48
+ host.mount('/plugins/ppt', pptApp)
49
+ host.mount('/plugins/canvas', canvasApp)
50
+ await host.listen({ port: 3080 })
51
+ ```
52
+
53
+ 子 app 仍由 `createServiceApp()` 创建;共享宿主只做前缀分发和统一生命周期。
54
+
55
+ ## 每个会话一个地址(会话段)
56
+
57
+ 挂载前缀之后允许再挂一层可选的会话段,`dispatch()` 会把它剥掉再交给工作台自己的路由:
58
+
59
+ ```
60
+ /capyclaw/ppt/ # 全局入口(不带会话)
61
+ /capyclaw/ppt/s/<会话id>/ # 这个会话的入口:页面就是编辑器本身
62
+ /capyclaw/ppt/s/<会话id>/app.js # 相对资源照旧
63
+ /capyclaw/ppt/s/<会话id>/api/... # 相对 API 照旧
64
+ ```
65
+
66
+ - 剥段之后 `u.pathname` 与不带会话时完全一致,所以**工作台一行代码都不用改**;
67
+ 需要区分会话的路由读 `u.sessionId`(或 `req.sessionId`)。
68
+ - 形状与网关的 `/s/<会话id>/` 一致;sid 只放行 `[A-Za-z0-9._~-]`,不会引入路径分隔歧义。
69
+ - `<prefix>/s/<会话id>` 少了尾斜杠会 301 补上——否则相对地址会被解析成
70
+ `<prefix>/s/<文件名>`,页面里的 `./app.js` 直接 404。
71
+ - 拿不到会话 id 时就不带这一段,行为与以前完全相同。
72
+
73
+ ## 提供什么
74
+
75
+ - `createServiceApp(options)`:路由、静态、健康、指标、生命周期
76
+ - `createServiceHost(config)`:插件侧工厂
77
+ - 标准 `/healthz`:`{ ok, service, name, version, contractVersion, pid, port, uptimeSec, ...业务字段 }`
78
+ - 标准 `/metrics`:`<slug>_up`、`<slug>_uptime_seconds`、`<slug>_port` + 业务指标
79
+ - standalone:端口扫描、`strictPort`、复用探测、单实例锁、discovery 文件、优雅关闭
80
+ - embedded:注册到 `ctx.webServer` 的 `<basePath>` 前缀;每个会话自动获得 `<basePath>/s/<会话id>/` 子树
81
+
82
+ ## 边界
83
+
84
+ - 不拥有业务状态;状态持久化用 `@capyclaw/document-workbench`(store/file-backend)
85
+ - 不拥有资产;资产用 `@capyclaw/asset-service`
86
+ - 不拥有编辑器;编辑器用 `@capyclaw/editor-host`
@@ -0,0 +1,4 @@
1
+ # 由 @capyclaw/service-host 提供;功能插件通过 inject: ['serviceHost'] 或 ctx.get('serviceHost') 使用。
2
+ - insert:
3
+ - id: service-host
4
+ name: "@capyclaw/service-host"