@flyer103/dsh-kian 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 flyer103
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,143 @@
1
- # Temporary Holding Version
1
+ # dsh-kian
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A Kian conversation panel for the DSH Web GUI. One conversation, two mount points:
4
+ the central main panel (opened from the sidebar icon) and a right-sidebar tab. Both
5
+ read and send through the host half's `/dsh-kian/api/*` routes, which proxy the local
6
+ `kian` bridge. The bridge bearer token stays in the host process and never reaches the
7
+ renderer.
8
+
9
+ [![CI](https://github.com/flyer103/dsh-kian/actions/workflows/test.yml/badge.svg)](https://github.com/flyer103/dsh-kian/actions/workflows/test.yml)
10
+ [![Release](https://img.shields.io/github/v/release/flyer103/dsh-kian)](https://github.com/flyer103/dsh-kian/releases)
11
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
12
+
13
+ ## Requirements
14
+
15
+ - DSH Desktop with a profile whose `webServer` service is available (the panel is a
16
+ client bundle plus four host routes).
17
+ - A running kian bridge (see `kian-runtime/design/CHANNEL-DSH.md` §3.2) listening on a
18
+ loopback address, e.g. `http://127.0.0.1:7421`.
19
+ - A bridge token file readable only by the current user (mode `0600`).
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ # GitHub, default branch or a pinned tag
25
+ dsh plugin --profile desktop add github:flyer103/dsh-kian
26
+ dsh plugin --profile desktop add github:flyer103/dsh-kian#v0.1.0
27
+
28
+ # local checkout (records a link: dependency)
29
+ cd /path/to/dsh-kian
30
+ dsh plugin --profile desktop add "$(pwd)"
31
+
32
+ # or run the idempotent installer from a checkout
33
+ node scripts/install.mjs --profile desktop
34
+ node scripts/install.mjs --profile desktop --dry-run
35
+ ```
36
+
37
+ Use the profile you actually run: `desktop` for the Desktop app, `web` for a web
38
+ profile. `add` also appends the bundle to the profile's `dsh.profile.bundles`; you do
39
+ not edit the profile's `cordis.patch.yml` by hand. Re-running is safe. Then **restart
40
+ DSH**; the bundle patch in `cordis.patch.yml` inserts the plugin into the profile's
41
+ layer stack, and `package.json` declares the client bundle and its platform (`web`).
42
+
43
+ The panel is one end of the kian channel: the Mac daemon `kian-dsh-bridge` must be
44
+ running with a 0600 token file, and the server side (`kian-ext-host serve` with the
45
+ `type: dsh` channel) must be deployed. Setup and verification live in kian-runtime:
46
+ [`docs/runbook-dsh-kian.md`](https://github.com/flyer103/kian-runtime/blob/main/docs/runbook-dsh-kian.md);
47
+ the wire contract is
48
+ [`design/CHANNEL-DSH.md`](https://github.com/flyer103/kian-runtime/blob/main/design/CHANNEL-DSH.md).
49
+
50
+ ## Configuration
51
+
52
+ `~/.config/kian/dsh-kian.json` (mode `0600`):
53
+
54
+ ```json
55
+ {
56
+ "bridge_url": "http://127.0.0.1:7421",
57
+ "token_file": "~/.config/kian/dsh-bridge.token"
58
+ }
59
+ ```
60
+
61
+ `bridge_url` must point at the loopback interface. `token_file` is read at plugin
62
+ startup, must have mode `0600`, and is never logged. When the file is missing, invalid,
63
+ or the token is world-readable, the plugin's routes answer `503 plugin_misconfigured`,
64
+ naming the offending file (never the secret) so the panel can show a fixable error.
65
+
66
+ ## Mounts
67
+
68
+ - **Main panel**: contributes a keyed `main` slot entry (`kian`) and a
69
+ `sidebar.panellist` icon. Clicking the icon opens the panel through
70
+ `ctx.layout.selectPanel('kian')`.
71
+ - **Right-sidebar tab**: registers the `kian` tab kind (`keepMounted`, multiple) and
72
+ its body and title seats under `sidebar.right.pane.tab`.
73
+
74
+ Both mounts render the same conversation component (full width in the main panel,
75
+ compact in the right tab). Each mount owns its own store and stream: a message sent in
76
+ one mount shows up in the other within one stream interval. Rows are seq-ordered and
77
+ deduped by `seq`.
78
+
79
+ ## Behaviour
80
+
81
+ - User `in` rows and Router `out` rows render as bubbles; text keeps newlines
82
+ (`white-space: pre-wrap`) and each bubble carries a local timestamp.
83
+ - History loads `GET /dsh-kian/api/history?since_seq=0&limit=200`, then
84
+ `GET /dsh-kian/api/stream?since_seq=<last>` serves SSE frames (`id: <seq>` plus a
85
+ JSON `data:` row) with a 15 s heartbeat comment.
86
+ - The composer sends on Enter, inserts a newline on Shift+Enter, ignores Enter while
87
+ an IME composition is active, and disables sending for empty or in-flight text.
88
+ - A failed send keeps the text and reuses the same `client_id` on retry, so the bridge
89
+ deduplicates a retried message.
90
+ - A 10 s health poll drives an unreachable-bridge banner.
91
+ - Scope: no editing, deleting, reactions, read receipts, typing indicators or
92
+ attachments.
93
+
94
+ ## Routes and guard
95
+
96
+ | route | method | bridge call |
97
+ | --- | --- | --- |
98
+ | `/dsh-kian/api/health` | GET | `GET /v1/health` |
99
+ | `/dsh-kian/api/history` | GET | `GET /v1/panel/updates` |
100
+ | `/dsh-kian/api/stream` | GET (SSE) | `GET /v1/panel/updates` long-poll |
101
+ | `/dsh-kian/api/send` | POST | `POST /v1/panel/send` |
102
+
103
+ Plugin routes are not covered by DSH's own authentication, so every request must carry
104
+ `x-dsh-kian: 1`; a POST must be `application/json` with a body of at most 64 KiB; and an
105
+ `Origin` header, when present, must match `Host`. Failures answer `403 forbidden` and the
106
+ host logs at most one rejection per minute. The bridge answers are passed through with
107
+ their `protocol` field and rows unchanged; transport failures become
108
+ `503 bridge_unavailable` with `retry_safe: true`.
109
+
110
+ ## Tests
111
+
112
+ ```bash
113
+ npm test # node --test test/
114
+ npm run check # node --check lib/index.js && node --check lib/client.js
115
+ ```
116
+
117
+ The host suite starts a fake kian bridge on `127.0.0.1` and drives the real service
118
+ through fake requests: config and token validation, route registration, the guard,
119
+ proxying, error envelopes and the SSE stream. The client suite loads the real
120
+ `lib/client.js` bundle with stub React and a stub module loader; it asserts the exported
121
+ pure helpers and the apply-time registrations (both mounts).
122
+
123
+ ## Not verified
124
+
125
+ This plugin has not been loaded into a real DSH build. Concretely unverified: whether
126
+ the shipped DSH `0.2.2-rc.5` client accepts an external bundle that registers both a
127
+ `main` panel and a right-sidebar tab; whether the Electron renderer sends an `Origin`
128
+ header (or an opaque one) for same-origin `fetch`; and how the two mounts behave at
129
+ scale with long histories. The tests above are unit/contract level only.
130
+
131
+ ## Layout
132
+
133
+ | path | role |
134
+ | --- | --- |
135
+ | `lib/index.js` | host half: config and token loading, four routes, guard, bridge proxy, SSE |
136
+ | `lib/client.js` | client half: hand-written `window.__ModuleLoader__` bundle (no build step) |
137
+ | `cordis.patch.yml` | bundle patch inserting the plugin |
138
+ | `test/host.test.mjs` | host contract tests (fake bridge, fake ctx) |
139
+ | `test/client.test.mjs` | client bundle tests (stub React and module loader) |
140
+
141
+ ## License
142
+
143
+ MIT
@@ -0,0 +1,4 @@
1
+ # dsh bundle patch: inserts this plugin into a profile's layer stack.
2
+ - insert:
3
+ - id: dsh-kian
4
+ name: '@flyer103/dsh-kian'
@@ -0,0 +1,16 @@
1
+ {
2
+ "id": "dsh-kian",
3
+ "version": "0.1.0",
4
+ "main": "./lib/index.js",
5
+ "description": "Kian conversation panel for the DSH Web GUI.",
6
+ "contributes": {
7
+ "tools": [],
8
+ "skills": []
9
+ },
10
+ "license": "MIT",
11
+ "homepage": "https://github.com/flyer103/dsh-kian",
12
+ "testedWith": {
13
+ "dsh": "0.2.2-rc.5",
14
+ "note": "metadata only; DSH does not read this file and enforces nothing from it"
15
+ }
16
+ }
package/lib/client.js ADDED
@@ -0,0 +1,591 @@
1
+ /**
2
+ * dsh-kian — Client half.
3
+ *
4
+ * Hand-written DSH browser ModuleLoader bundle (no build step), following the
5
+ * packaging shape of @flyer103/dsh-side-chat. The bundle id is the package name
6
+ * and the factory's require resolves the shell's frozen platform seed table.
7
+ *
8
+ * One conversation, two mount points:
9
+ * - the central 'main' panel (keyed slot 'main', opened from the sidebar icon)
10
+ * - the right-sidebar tab (sidebarRightTabs kind 'kian' + 'sidebar.right.pane.tab')
11
+ * Each mount owns its own store and stream; rows are seq-ordered and deduped by
12
+ * seq, so a send in one mount appears in the other within one stream interval.
13
+ */
14
+ window.__ModuleLoader__.load({
15
+ id: '@flyer103/dsh-kian',
16
+ factory: (require) => {
17
+ var module = { exports: {} }
18
+ var exports = module.exports
19
+
20
+ const React = require('react')
21
+ const h = React.createElement
22
+
23
+ const PANEL_ID = 'kian'
24
+ const LOCALE_NS = 'dsh-kian'
25
+ const TAB_TYPE_ID = '@flyer103/dsh-kian'
26
+ const TAB_KIND = 'kian'
27
+ const API_PREFIX = '/dsh-kian/api/'
28
+ const STYLE_ATTR = 'dsh-kian'
29
+ const HEALTH_POLL_MS = 10000
30
+ const STICK_THRESHOLD_PX = 40
31
+ const STREAM_RETRY_MS = 1000
32
+
33
+ const EN_DICT = {
34
+ 'panel.label': 'Kian',
35
+ 'panel.title': 'Kian conversation',
36
+ 'tab.title': 'Kian',
37
+ 'guide.title': 'Kian',
38
+ 'guide.description': 'Talk to the Kian router from this window.',
39
+ 'status.connecting': 'Connecting to Kian',
40
+ 'status.live': 'Kian is live',
41
+ 'status.offline': 'Kian is unreachable',
42
+ 'banner.offline': 'The Kian bridge is unreachable. Check that the bridge is running and that ~/.config/kian/dsh-kian.json points at it.',
43
+ 'panel.empty': 'No messages yet. Say hello to the Kian router.',
44
+ 'composer.placeholder': 'Message Kian',
45
+ 'composer.send': 'Send',
46
+ 'composer.sending': 'Sending',
47
+ 'composer.error': 'Send failed. The text is kept; press Enter to retry.',
48
+ 'composer.hint': 'Enter to send, Shift+Enter for a new line',
49
+ 'jump.latest': 'Jump to latest',
50
+ 'direction.in': 'You',
51
+ 'direction.out': 'Kian'
52
+ }
53
+
54
+ const ZH_DICT = {
55
+ 'panel.label': 'Kian',
56
+ 'panel.title': 'Kian 对话',
57
+ 'tab.title': 'Kian',
58
+ 'guide.title': 'Kian',
59
+ 'guide.description': '在这个窗口里与 Kian 路由器对话。',
60
+ 'status.connecting': '正在连接 Kian',
61
+ 'status.live': 'Kian 在线',
62
+ 'status.offline': 'Kian 不可达',
63
+ 'banner.offline': 'Kian 桥不可达。请确认桥正在运行,且 ~/.config/kian/dsh-kian.json 指向它。',
64
+ 'panel.empty': '还没有消息。先向 Kian 路由器打个招呼。',
65
+ 'composer.placeholder': '发消息给 Kian',
66
+ 'composer.send': '发送',
67
+ 'composer.sending': '发送中',
68
+ 'composer.error': '发送失败。文本已保留;按 Enter 重试。',
69
+ 'composer.hint': 'Enter 发送,Shift+Enter 换行',
70
+ 'jump.latest': '跳到最新',
71
+ 'direction.in': '你',
72
+ 'direction.out': 'Kian'
73
+ }
74
+
75
+ function apiPath(path, query) {
76
+ const params = []
77
+ if (query !== undefined && query !== null) {
78
+ for (const key of Object.keys(query)) {
79
+ const value = query[key]
80
+ if (value === undefined || value === null) continue
81
+ params.push(encodeURIComponent(key) + '=' + encodeURIComponent(String(value)))
82
+ }
83
+ }
84
+ return params.length === 0 ? path : path + '?' + params.join('&')
85
+ }
86
+
87
+ function mergeRows(existing, incoming) {
88
+ const bySeq = new Map()
89
+ for (const row of Array.isArray(existing) ? existing : []) {
90
+ if (row !== null && typeof row === 'object' && Number.isSafeInteger(row.seq)) bySeq.set(row.seq, row)
91
+ }
92
+ for (const row of Array.isArray(incoming) ? incoming : []) {
93
+ if (row !== null && typeof row === 'object' && Number.isSafeInteger(row.seq)) bySeq.set(row.seq, row)
94
+ }
95
+ return Array.from(bySeq.values()).sort((left, right) => left.seq - right.seq)
96
+ }
97
+
98
+ function latestSeq(rows) {
99
+ let seq = 0
100
+ for (const row of Array.isArray(rows) ? rows : []) {
101
+ if (row !== null && typeof row === 'object' && Number.isSafeInteger(row.seq) && row.seq > seq) seq = row.seq
102
+ }
103
+ return seq
104
+ }
105
+
106
+ function parseSseBlock(raw) {
107
+ const lines = String(raw).split('\n')
108
+ let id = null
109
+ let event = null
110
+ const data = []
111
+ for (const rawLine of lines) {
112
+ const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine
113
+ if (line === '' || line.startsWith(':')) continue
114
+ const colon = line.indexOf(':')
115
+ const field = colon === -1 ? line : line.slice(0, colon)
116
+ let value = colon === -1 ? '' : line.slice(colon + 1)
117
+ if (value.startsWith(' ')) value = value.slice(1)
118
+ if (field === 'id') id = value
119
+ else if (field === 'event') event = value
120
+ else if (field === 'data') data.push(value)
121
+ }
122
+ if (id === null && event === null && data.length === 0) return null
123
+ return { id, event, data: data.join('\n') }
124
+ }
125
+
126
+ function createSseParser() {
127
+ let buffer = ''
128
+ return {
129
+ push(text) {
130
+ buffer += String(text)
131
+ const frames = []
132
+ let index = buffer.indexOf('\n\n')
133
+ while (index !== -1) {
134
+ const raw = buffer.slice(0, index)
135
+ buffer = buffer.slice(index + 2)
136
+ const frame = parseSseBlock(raw)
137
+ if (frame !== null) frames.push(frame)
138
+ index = buffer.indexOf('\n\n')
139
+ }
140
+ return frames
141
+ }
142
+ }
143
+ }
144
+
145
+ function editorKeyAction(event) {
146
+ if (event === null || event === undefined) return 'ignore'
147
+ const native = event.nativeEvent ?? event
148
+ if (native.isComposing === true || event.isComposing === true) return 'ignore'
149
+ if (native.keyCode === 229 || event.keyCode === 229) return 'ignore'
150
+ if (event.key !== 'Enter') return 'ignore'
151
+ if (event.shiftKey === true || event.altKey === true) return 'newline'
152
+ return 'submit'
153
+ }
154
+
155
+ function formatTime(ms) {
156
+ if (!Number.isFinite(ms)) return ''
157
+ try {
158
+ return new Date(ms).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
159
+ } catch (error) {
160
+ return ''
161
+ }
162
+ }
163
+
164
+ function makeClientId() {
165
+ const crypto = globalThis.crypto
166
+ if (crypto !== null && crypto !== undefined && typeof crypto.randomUUID === 'function') return crypto.randomUUID()
167
+ return 'kian-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 10)
168
+ }
169
+
170
+ function createRuntime() {
171
+ return {
172
+ dispose() {}
173
+ }
174
+ }
175
+
176
+ function injectStyle() {
177
+ if (typeof document === 'undefined' || document === null || typeof document.createElement !== 'function') return null
178
+ const style = document.createElement('style')
179
+ style.dataset.dyn = STYLE_ATTR
180
+ style.textContent = PANEL_CSS
181
+ document.head.append(style)
182
+ return style
183
+ }
184
+
185
+ function statusLabel(status, t) {
186
+ if (status === 'live') return t('status.live')
187
+ if (status === 'offline') return t('status.offline')
188
+ return t('status.connecting')
189
+ }
190
+
191
+ function apply(ctx) {
192
+ const runtime = createRuntime()
193
+ const t = ctx.locale.bind(LOCALE_NS)
194
+ ctx.effect(() => {
195
+ const disposeEn = ctx.locale.register(LOCALE_NS, 'en', EN_DICT)
196
+ const disposeZh = ctx.locale.register(LOCALE_NS, 'zh', ZH_DICT)
197
+ return () => {
198
+ disposeZh()
199
+ disposeEn()
200
+ }
201
+ }, 'dsh-kian: copy')
202
+ ctx.effect(() => {
203
+ const style = injectStyle()
204
+ return () => {
205
+ if (style !== null && typeof style.remove === 'function') style.remove()
206
+ }
207
+ }, 'dsh-kian: panel stylesheet')
208
+ ctx.effect(() => () => runtime.dispose(), 'dsh-kian: panel runtime')
209
+ ctx.effect(() => ctx.slots.inject('main', () => ctx.slots.register({
210
+ name: 'main',
211
+ key: PANEL_ID,
212
+ locale: LOCALE_NS,
213
+ inject: () => ({ runtime, t })
214
+ }, KianPanel)), 'dsh-kian: main panel')
215
+ ctx.effect(() => ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
216
+ name: 'sidebar.panellist',
217
+ id: PANEL_ID,
218
+ order: 1,
219
+ label: () => t('panel.label'),
220
+ locale: LOCALE_NS
221
+ }, KianPanelIcon)), 'dsh-kian: sidebar entry')
222
+ ctx.effect(() => ctx.sidebarRightTabs.register({
223
+ id: TAB_TYPE_ID,
224
+ kind: TAB_KIND,
225
+ priority: 'extension',
226
+ title: () => t('tab.title'),
227
+ guide: [{
228
+ id: 'kian',
229
+ order: 20,
230
+ title: () => t('guide.title'),
231
+ description: () => t('guide.description')
232
+ }],
233
+ keepMounted: true,
234
+ multiple: true
235
+ }), 'dsh-kian: sidebar tab type')
236
+ ctx.effect(() => ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
237
+ name: 'sidebar.right.pane.tab',
238
+ key: TAB_TYPE_ID,
239
+ locale: LOCALE_NS,
240
+ inject: (sessionId) => ({ runtime, sessionId, t })
241
+ }, KianTabBody)), 'dsh-kian: sidebar tab body')
242
+ ctx.effect(() => ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
243
+ name: 'sidebar.right.pane.tab.title',
244
+ key: TAB_TYPE_ID,
245
+ locale: LOCALE_NS,
246
+ inject: (sessionId) => ({ runtime, sessionId, t })
247
+ }, KianTabTitle)), 'dsh-kian: sidebar tab title')
248
+ if (ctx.sidebarRight !== null && ctx.sidebarRight !== undefined && typeof ctx.sidebarRight.registerCloseHandler === 'function') {
249
+ ctx.effect(() => ctx.sidebarRight.registerCloseHandler(TAB_KIND, () => {
250
+ runtime.dispose()
251
+ }), 'dsh-kian: sidebar tab close')
252
+ }
253
+ }
254
+
255
+ function KianPanelIcon(props) {
256
+ const size = props !== null && props !== undefined && typeof props.size === 'number' ? props.size : 16
257
+ return h('svg', {
258
+ width: size,
259
+ height: size,
260
+ viewBox: '0 0 16 16',
261
+ fill: 'none',
262
+ 'aria-hidden': 'true',
263
+ className: 'dk-icon'
264
+ }, h('path', {
265
+ d: 'M2.5 3.5h11v6.5h-6.2L4 13v-3H2.5z',
266
+ stroke: 'currentColor',
267
+ strokeWidth: 1.2,
268
+ strokeLinejoin: 'round'
269
+ }))
270
+ }
271
+
272
+ function KianPanel(props) {
273
+ const t = typeof props.t === 'function' ? props.t : (key) => key
274
+ return h('div', { className: 'dk-root' }, h(KianConversation, { runtime: props.runtime, t, compact: false }))
275
+ }
276
+
277
+ function KianTabBody(props) {
278
+ const t = typeof props.t === 'function' ? props.t : (key) => key
279
+ return h('div', { className: 'dk-root dk-root-tab' }, h(KianConversation, { runtime: props.runtime, t, compact: true }))
280
+ }
281
+
282
+ function KianTabTitle(props) {
283
+ const t = typeof props.t === 'function' ? props.t : (key) => key
284
+ return h('span', { className: 'dk-tab-title' }, t('tab.title'))
285
+ }
286
+
287
+ function KianConversation(props) {
288
+ const runtime = props.runtime
289
+ const t = typeof props.t === 'function' ? props.t : (key) => key
290
+ const compact = props.compact === true
291
+ const [rows, setRows] = React.useState([])
292
+ const [status, setStatus] = React.useState('connecting')
293
+ const [bridge, setBridge] = React.useState(null)
294
+ const [draft, setDraft] = React.useState('')
295
+ const [sending, setSending] = React.useState(false)
296
+ const [error, setError] = React.useState(null)
297
+ const [atBottom, setAtBottom] = React.useState(true)
298
+ const listRef = React.useRef(null)
299
+ const seqRef = React.useRef(0)
300
+ const clientIdRef = React.useRef(null)
301
+
302
+ React.useEffect(() => {
303
+ let disposed = false
304
+ let controller = null
305
+ if (typeof AbortController === 'function') controller = new AbortController()
306
+ const signal = controller === null ? undefined : controller.signal
307
+ const appendRows = (incoming) => {
308
+ if (!Array.isArray(incoming) || incoming.length === 0) return
309
+ setRows((previous) => mergeRows(previous, incoming))
310
+ const next = latestSeq(incoming)
311
+ if (next > seqRef.current) seqRef.current = next
312
+ }
313
+ const applyFrame = (frame) => {
314
+ if (frame.event === 'error') { setStatus('offline'); return }
315
+ if (frame.event === 'retry' || frame.event === 'gap') return
316
+ if (typeof frame.data !== 'string' || frame.data === '') return
317
+ let row = null
318
+ try { row = JSON.parse(frame.data) } catch (parseError) { return }
319
+ appendRows([row])
320
+ }
321
+ const sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms) })
322
+ const consumeStream = async () => {
323
+ while (!disposed) {
324
+ try {
325
+ const response = await fetch(apiPath(API_PREFIX + 'stream', { since_seq: seqRef.current }), { headers: { 'x-dsh-kian': '1' }, cache: 'no-store', signal })
326
+ if (!response.ok || response.body === null) throw new Error('stream unavailable')
327
+ setStatus('live')
328
+ const reader = response.body.getReader()
329
+ const decoder = new TextDecoder()
330
+ const parser = createSseParser()
331
+ for (;;) {
332
+ const chunk = await reader.read()
333
+ if (chunk.done) break
334
+ const frames = parser.push(decoder.decode(chunk.value, { stream: true }))
335
+ for (const frame of frames) applyFrame(frame)
336
+ }
337
+ throw new Error('stream ended')
338
+ } catch (streamError) {
339
+ if (disposed) return
340
+ setStatus('offline')
341
+ await sleep(STREAM_RETRY_MS)
342
+ }
343
+ }
344
+ }
345
+ const refreshHealth = async () => {
346
+ try {
347
+ const response = await fetch(apiPath(API_PREFIX + 'health'), { headers: { 'x-dsh-kian': '1' }, cache: 'no-store', signal })
348
+ const value = response.ok ? await response.json() : null
349
+ setBridge(value)
350
+ } catch (healthError) {
351
+ setBridge(null)
352
+ }
353
+ }
354
+ void (async () => {
355
+ try {
356
+ const response = await fetch(apiPath(API_PREFIX + 'history', { since_seq: 0, limit: 200 }), { headers: { 'x-dsh-kian': '1' }, cache: 'no-store', signal })
357
+ const value = response.ok ? await response.json() : null
358
+ if (disposed) return
359
+ if (value !== null && Array.isArray(value.rows)) appendRows(value.rows)
360
+ setStatus(response.ok ? 'live' : 'offline')
361
+ } catch (historyError) {
362
+ if (!disposed) setStatus('offline')
363
+ }
364
+ if (!disposed) void consumeStream()
365
+ })()
366
+ const poll = setInterval(() => { void refreshHealth() }, HEALTH_POLL_MS)
367
+ void refreshHealth()
368
+ return () => {
369
+ disposed = true
370
+ clearInterval(poll)
371
+ if (controller !== null) controller.abort()
372
+ if (runtime !== null && runtime !== undefined && typeof runtime.dispose === 'function') runtime.dispose()
373
+ }
374
+ }, [])
375
+
376
+ React.useEffect(() => {
377
+ const node = listRef.current
378
+ if (node !== null && node !== undefined && atBottom) node.scrollTop = node.scrollHeight
379
+ }, [rows, atBottom])
380
+
381
+ const onScroll = (event) => {
382
+ const node = event.currentTarget
383
+ const distance = node.scrollHeight - node.scrollTop - node.clientHeight
384
+ setAtBottom(distance < STICK_THRESHOLD_PX)
385
+ }
386
+ const jumpToLatest = () => {
387
+ const node = listRef.current
388
+ if (node !== null && node !== undefined) node.scrollTop = node.scrollHeight
389
+ setAtBottom(true)
390
+ }
391
+ const submit = () => {
392
+ if (sending || draft.trim() === '') return
393
+ void (async () => {
394
+ const clientId = clientIdRef.current === null ? makeClientId() : clientIdRef.current
395
+ clientIdRef.current = clientId
396
+ setSending(true)
397
+ setError(null)
398
+ try {
399
+ const response = await fetch(apiPath(API_PREFIX + 'send'), {
400
+ method: 'POST',
401
+ headers: { 'x-dsh-kian': '1', 'content-type': 'application/json' },
402
+ body: JSON.stringify({ text: draft, client_id: clientId })
403
+ })
404
+ let value = null
405
+ try { value = await response.json() } catch (parseError) { value = null }
406
+ if (!response.ok || value === null || value.ok !== true) { setError(t('composer.error')); return }
407
+ setDraft('')
408
+ clientIdRef.current = null
409
+ if (Number.isSafeInteger(value.seq)) setRows((previous) => mergeRows(previous, [{ seq: value.seq, direction: 'in', text: draft, client_id: clientId, created_at_ms: value.created_at_ms }]))
410
+ } catch (sendError) {
411
+ setError(t('composer.error'))
412
+ } finally {
413
+ setSending(false)
414
+ }
415
+ })()
416
+ }
417
+ const onKeyDown = (event) => {
418
+ const action = editorKeyAction(event)
419
+ if (action === 'submit') { event.preventDefault(); submit(); return }
420
+ if (action === 'newline') return
421
+ if (event.key === 'Enter') event.preventDefault()
422
+ }
423
+ const renderRow = (row) => {
424
+ const mine = row.direction === 'in'
425
+ const label = mine ? t('direction.in') : t('direction.out')
426
+ return h('div', { key: String(row.seq), className: 'dk-row ' + (mine ? 'dk-in' : 'dk-out') },
427
+ h('div', { className: 'dk-bubble' },
428
+ h('div', { className: 'dk-text' }, row.text),
429
+ h('div', { className: 'dk-meta' }, label + ' · ' + formatTime(row.created_at_ms))))
430
+ }
431
+ const bridgeDown = bridge === null || (typeof bridge === 'object' && bridge.ok === false)
432
+ return h('div', { className: compact ? 'dk-conversation dk-compact' : 'dk-conversation' },
433
+ h('div', { className: 'dk-statusbar' },
434
+ h('span', { className: 'dk-dot dk-dot-' + status }),
435
+ h('span', { className: 'dk-status-text' }, statusLabel(status, t)),
436
+ h('span', { className: 'dk-spacer' }),
437
+ h('span', { className: 'dk-count' }, String(rows.length))),
438
+ bridgeDown ? h('div', { className: 'dk-banner', role: 'status' }, t('banner.offline')) : null,
439
+ h('div', { className: 'dk-list', ref: listRef, onScroll },
440
+ rows.length === 0 ? h('div', { className: 'dk-empty' }, t('panel.empty')) : rows.map(renderRow),
441
+ atBottom ? null : h('button', { className: 'dk-jump', type: 'button', onClick: jumpToLatest }, t('jump.latest'))),
442
+ h('div', { className: 'dk-composer' },
443
+ h('textarea', {
444
+ className: 'dk-input',
445
+ value: draft,
446
+ rows: compact ? 3 : 4,
447
+ placeholder: t('composer.placeholder'),
448
+ 'aria-label': t('composer.placeholder'),
449
+ onChange: (event) => setDraft(event.target.value),
450
+ onKeyDown
451
+ }),
452
+ h('div', { className: 'dk-composer-row' },
453
+ h('span', { className: 'dk-hint' }, t('composer.hint')),
454
+ h('button', { className: 'dk-send', type: 'button', disabled: sending || draft.trim() === '', onClick: submit }, sending ? t('composer.sending') : t('composer.send'))),
455
+ error === null ? null : h('div', { className: 'dk-error', role: 'alert' }, error)))
456
+ }
457
+
458
+ const PANEL_CSS = `
459
+ .dk-root {
460
+ display: flex;
461
+ flex-direction: column;
462
+ width: 100%;
463
+ height: 100%;
464
+ min-height: 0;
465
+ background: var(--dsw-alias-bg-base, #ffffff);
466
+ color: var(--dsw-alias-label-primary, #0f1115);
467
+ font-size: 15px;
468
+ line-height: 1.5;
469
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
470
+ }
471
+ .dk-conversation {
472
+ display: flex;
473
+ flex-direction: column;
474
+ flex: 1 1 auto;
475
+ min-height: 0;
476
+ }
477
+ .dk-compact { font-size: 14px; }
478
+ .dk-statusbar {
479
+ flex: none;
480
+ display: flex;
481
+ align-items: center;
482
+ gap: 7px;
483
+ padding: 8px 14px;
484
+ border-bottom: 1px solid var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.08));
485
+ font-size: 12px;
486
+ color: var(--dsw-alias-label-tertiary, #81858c);
487
+ }
488
+ .dk-dot { width: 7px; height: 7px; border-radius: 50%; background: #c9ccd1; flex: none; }
489
+ .dk-dot-live { background: #22a06b; }
490
+ .dk-dot-offline { background: #d94f4f; }
491
+ .dk-spacer { flex: 1 1 auto; }
492
+ .dk-banner {
493
+ flex: none;
494
+ padding: 8px 14px;
495
+ font-size: 12px;
496
+ background: rgba(217, 79, 79, 0.08);
497
+ color: #b42318;
498
+ border-bottom: 1px solid rgba(217, 79, 79, 0.2);
499
+ }
500
+ .dk-list {
501
+ flex: 1 1 auto;
502
+ min-height: 0;
503
+ overflow-y: auto;
504
+ padding: 14px;
505
+ display: flex;
506
+ flex-direction: column;
507
+ gap: 10px;
508
+ position: relative;
509
+ }
510
+ .dk-empty { color: var(--dsw-alias-label-tertiary, #81858c); font-size: 13px; padding: 18px 4px; }
511
+ .dk-row { display: flex; flex-direction: column; max-width: 86%; }
512
+ .dk-in { align-self: flex-end; align-items: flex-end; }
513
+ .dk-out { align-self: flex-start; align-items: flex-start; }
514
+ .dk-bubble {
515
+ border-radius: 10px;
516
+ padding: 8px 12px;
517
+ background: var(--dsw-alias-bg-layer-1, #f4f5f7);
518
+ word-break: break-word;
519
+ }
520
+ .dk-in .dk-bubble { background: var(--dsw-alias-bg-brand, #e6f0ff); }
521
+ .dk-text { white-space: pre-wrap; word-break: break-word; }
522
+ .dk-meta { margin-top: 4px; font-size: 11px; color: var(--dsw-alias-label-tertiary, #81858c); }
523
+ .dk-jump {
524
+ position: sticky;
525
+ bottom: 0;
526
+ align-self: center;
527
+ margin-top: 6px;
528
+ padding: 4px 10px;
529
+ font-size: 12px;
530
+ border-radius: 999px;
531
+ border: 1px solid var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.12));
532
+ background: var(--dsw-alias-bg-base, #ffffff);
533
+ cursor: pointer;
534
+ }
535
+ .dk-composer {
536
+ flex: none;
537
+ display: flex;
538
+ flex-direction: column;
539
+ gap: 6px;
540
+ padding: 10px 14px 14px;
541
+ border-top: 1px solid var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.08));
542
+ }
543
+ .dk-input {
544
+ width: 100%;
545
+ resize: vertical;
546
+ min-height: 52px;
547
+ max-height: 220px;
548
+ box-sizing: border-box;
549
+ padding: 8px 10px;
550
+ border-radius: 8px;
551
+ border: 1px solid var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.15));
552
+ background: var(--dsw-alias-bg-base, #ffffff);
553
+ color: inherit;
554
+ font: inherit;
555
+ }
556
+ .dk-composer-row { display: flex; align-items: center; gap: 8px; }
557
+ .dk-hint { flex: 1 1 auto; font-size: 11px; color: var(--dsw-alias-label-tertiary, #81858c); }
558
+ .dk-send {
559
+ padding: 5px 14px;
560
+ border-radius: 7px;
561
+ border: 1px solid transparent;
562
+ background: var(--dsw-alias-bg-brand, #2f6fed);
563
+ color: #ffffff;
564
+ font: inherit;
565
+ font-size: 13px;
566
+ cursor: pointer;
567
+ }
568
+ .dk-send:disabled { opacity: 0.5; cursor: default; }
569
+ .dk-error { font-size: 12px; color: #b42318; }
570
+ .dk-tab-title { font-size: 13px; }
571
+ `
572
+
573
+ exports.name = 'dsh-kian'
574
+ exports.inject = ['slots', 'sidebarRightTabs', 'locale', 'sidebarRight']
575
+ exports.apply = apply
576
+ exports.createRuntime = createRuntime
577
+ exports.createSseParser = createSseParser
578
+ exports.mergeRows = mergeRows
579
+ exports.latestSeq = latestSeq
580
+ exports.apiPath = apiPath
581
+ exports.editorKeyAction = editorKeyAction
582
+ exports.formatTime = formatTime
583
+ exports.makeClientId = makeClientId
584
+ exports.statusLabel = statusLabel
585
+ exports.PANEL_ID = PANEL_ID
586
+ exports.TAB_TYPE_ID = TAB_TYPE_ID
587
+ exports.TAB_KIND = TAB_KIND
588
+
589
+ return module.exports
590
+ }
591
+ })
package/lib/index.js ADDED
@@ -0,0 +1,530 @@
1
+ /**
2
+ * dsh-kian — Host half.
3
+ *
4
+ * The Kian panel's transport floor: four exact webServer routes that proxy the
5
+ * local kian bridge (kian-runtime design/CHANNEL-DSH.md §3.2 and §4) for the
6
+ * client bundle. The bridge bearer token never leaves this module: the browser
7
+ * only ever talks to /dsh-kian/api/*.
8
+ */
9
+ import { readFileSync, statSync } from 'node:fs'
10
+ import { homedir } from 'node:os'
11
+ import { join } from 'node:path'
12
+
13
+ export const name = 'dsh-kian'
14
+ export const inject = ['webServer']
15
+
16
+ export const ROUTE_PREFIX = '/dsh-kian/api/'
17
+ export const ROUTES = {
18
+ health: ROUTE_PREFIX + 'health',
19
+ history: ROUTE_PREFIX + 'history',
20
+ stream: ROUTE_PREFIX + 'stream',
21
+ send: ROUTE_PREFIX + 'send'
22
+ }
23
+ export const DEFAULT_CONFIG_PATH = '~/.config/kian/dsh-kian.json'
24
+ const BRIDGE_PROTOCOL = 1
25
+ const MAX_BODY_BYTES = 64 * 1024
26
+ const MAX_TEXT_BYTES = 64 * 1024
27
+ const DEFAULT_LIMIT = 200
28
+ const MAX_LIMIT = 500
29
+ const MAX_WAIT_MS = 25000
30
+ const SSE_HEARTBEAT_MS = 15000
31
+ const BRIDGE_TIMEOUT_MS = 5000
32
+ const STREAM_RETRY_MS = 1000
33
+ const STREAM_IDLE_MS = 250
34
+ const FORBIDDEN_LOG_INTERVAL_MS = 60000
35
+ const SSE_HEADERS = {
36
+ 'content-type': 'text/event-stream; charset=utf-8',
37
+ 'cache-control': 'no-cache, no-transform',
38
+ connection: 'keep-alive',
39
+ 'x-accel-buffering': 'no'
40
+ }
41
+
42
+ export function errorMessage(error) {
43
+ const text = error instanceof Error ? error.message : String(error)
44
+ return text.length > 500 ? text.slice(0, 500) : text
45
+ }
46
+
47
+ export function expandHomePath(value, home = homedir()) {
48
+ if (typeof value !== 'string') return ''
49
+ if (value === '~') return home
50
+ if (value.startsWith('~/')) return join(home, value.slice(2))
51
+ return value
52
+ }
53
+
54
+ function isLoopbackHost(hostname) {
55
+ return hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '::1' || hostname === '[::1]'
56
+ }
57
+
58
+ export function parseBridgeUrl(raw) {
59
+ if (typeof raw !== 'string' || raw.trim() === '') throw new Error('bridge_url must be a non-empty string')
60
+ const url = new URL(raw)
61
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new Error('bridge_url must use http or https')
62
+ if (!isLoopbackHost(url.hostname)) throw new Error('bridge_url must point at the loopback interface')
63
+ return url
64
+ }
65
+
66
+ export function parseConfigText(text) {
67
+ let value = null
68
+ try {
69
+ value = JSON.parse(text)
70
+ } catch (error) {
71
+ throw new Error('config file is not valid JSON')
72
+ }
73
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('config file must contain a JSON object')
74
+ const bridgeUrl = parseBridgeUrl(value.bridge_url)
75
+ if (typeof value.token_file !== 'string' || value.token_file.trim() === '') throw new Error('token_file must be a non-empty string')
76
+ return { bridgeUrl, tokenFile: expandHomePath(value.token_file.trim()) }
77
+ }
78
+
79
+ export function readTokenFile(tokenFile) {
80
+ const info = statSync(tokenFile)
81
+ const mode = info.mode & 0o777
82
+ if ((mode & 0o077) !== 0) {
83
+ const error = new Error('token file ' + tokenFile + ' is readable by other users (mode ' + mode.toString(8) + '); run chmod 600 ' + tokenFile)
84
+ error.code = 'token_permissions'
85
+ throw error
86
+ }
87
+ const token = readFileSync(tokenFile, 'utf8').trim()
88
+ if (token === '') throw new Error('token file ' + tokenFile + ' is empty')
89
+ return token
90
+ }
91
+
92
+ export function loadConfig(configPath) {
93
+ try {
94
+ const config = parseConfigText(readFileSync(configPath, 'utf8'))
95
+ const token = readTokenFile(config.tokenFile)
96
+ return { ok: true, config: { bridgeUrl: config.bridgeUrl, tokenFile: config.tokenFile, token, configPath } }
97
+ } catch (error) {
98
+ return { ok: false, message: errorMessage(error) }
99
+ }
100
+ }
101
+
102
+ export function sendJson(res, status, value) {
103
+ const body = JSON.stringify(value)
104
+ const headers = {
105
+ 'content-type': 'application/json; charset=utf-8',
106
+ 'cache-control': 'no-store',
107
+ 'content-length': String(Buffer.byteLength(body))
108
+ }
109
+ if (typeof res.writeHead === 'function') res.writeHead(status, headers)
110
+ else res.statusCode = status
111
+ res.end(body)
112
+ }
113
+
114
+ export function sendBridgeError(res, status, kind, detail, retrySafe) {
115
+ const value = { protocol: BRIDGE_PROTOCOL, ok: false, kind }
116
+ if (detail !== undefined) value.detail = detail
117
+ if (retrySafe === true) value.retry_safe = true
118
+ sendJson(res, status, value)
119
+ }
120
+
121
+ class BodyTooLargeError extends Error {
122
+ constructor(maxBytes) { super('request body exceeds ' + maxBytes + ' bytes'); this.code = 'too_large' }
123
+ }
124
+
125
+ export async function readRequestBody(req, maxBytes = MAX_BODY_BYTES) {
126
+ const chunks = []
127
+ let size = 0
128
+ for await (const chunk of req) {
129
+ const buffer = typeof chunk === 'string' ? Buffer.from(chunk) : chunk
130
+ size += buffer.length
131
+ if (size > maxBytes) throw new BodyTooLargeError(maxBytes)
132
+ chunks.push(buffer)
133
+ }
134
+ return Buffer.concat(chunks).toString('utf8')
135
+ }
136
+
137
+ export function parseQuery(url) {
138
+ const index = typeof url === 'string' ? url.indexOf('?') : -1
139
+ return new URLSearchParams(index === -1 ? '' : url.slice(index + 1))
140
+ }
141
+
142
+ export function parseCountParam(raw, fallback) {
143
+ if (raw === null || raw === undefined || raw === '') return { ok: true, value: fallback }
144
+ if (!/^\d+$/.test(String(raw))) return { ok: false, message: 'must be a non-negative integer' }
145
+ const value = Number(raw)
146
+ if (!Number.isSafeInteger(value)) return { ok: false, message: 'is out of range' }
147
+ return { ok: true, value }
148
+ }
149
+
150
+ function delay(ms) {
151
+ return new Promise((resolve) => { setTimeout(resolve, ms) })
152
+ }
153
+
154
+ function sseFrame(event, data) {
155
+ const payload = 'data: ' + JSON.stringify(data) + '\n\n'
156
+ return event === null || event === undefined ? payload : 'event: ' + event + '\n' + payload
157
+ }
158
+ export class KianBridgeService {
159
+ constructor(options = {}) {
160
+ this.logger = options.logger ?? null
161
+ this.env = options.env ?? process.env
162
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch
163
+ this.heartbeatMs = options.heartbeatMs ?? SSE_HEARTBEAT_MS
164
+ this.bridgeTimeoutMs = options.bridgeTimeoutMs ?? BRIDGE_TIMEOUT_MS
165
+ this.retryDelayMs = options.retryDelayMs ?? STREAM_RETRY_MS
166
+ this.streamIdleMs = options.streamIdleMs ?? STREAM_IDLE_MS
167
+ this.now = options.now ?? Date.now
168
+ this.configPath = expandHomePath(this.env.KIAN_DSH_CONFIG ?? DEFAULT_CONFIG_PATH)
169
+ this.config = null
170
+ this.failure = null
171
+ this.lastForbiddenLogAt = 0
172
+ this.activeStreams = new Set()
173
+ }
174
+
175
+ load() {
176
+ const result = loadConfig(this.configPath)
177
+ if (result.ok) {
178
+ this.config = result.config
179
+ this.failure = null
180
+ this.logger?.info?.('[dsh-kian] bridge configured at ' + this.config.bridgeUrl.origin + ' (token file ' + this.config.tokenFile + ')')
181
+ } else {
182
+ this.config = null
183
+ this.failure = { message: result.message, configPath: this.configPath }
184
+ this.logger?.warn?.('[dsh-kian] bridge is not configured: ' + result.message)
185
+ }
186
+ return result.ok
187
+ }
188
+
189
+ checkGuard(req) {
190
+ const headers = req.headers ?? {}
191
+ if (headers['x-dsh-kian'] !== '1') return 'missing x-dsh-kian header'
192
+ const origin = headers.origin
193
+ if (origin !== undefined && origin !== null) {
194
+ const host = headers.host
195
+ if (typeof host !== 'string' || host === '') return 'missing Host header'
196
+ let originHost = null
197
+ try {
198
+ originHost = new URL(origin).host
199
+ } catch (error) {
200
+ return 'malformed Origin header'
201
+ }
202
+ if (originHost.toLowerCase() !== host.toLowerCase()) return 'Origin does not match Host'
203
+ }
204
+ return null
205
+ }
206
+
207
+ noteForbidden(reason) {
208
+ const now = this.now()
209
+ if (now - this.lastForbiddenLogAt < FORBIDDEN_LOG_INTERVAL_MS) return
210
+ this.lastForbiddenLogAt = now
211
+ this.logger?.warn?.('[dsh-kian] rejected request: ' + reason)
212
+ }
213
+
214
+ reject(res, reason) {
215
+ this.noteForbidden(reason)
216
+ sendJson(res, 403, { ok: false, code: 'forbidden', reason })
217
+ }
218
+
219
+ ensureConfigured(res) {
220
+ if (this.config !== null) return true
221
+ const message = this.failure === null ? 'the dsh-kian config could not be loaded' : this.failure.message
222
+ sendJson(res, 503, { ok: false, code: 'plugin_misconfigured', message, config_path: this.configPath })
223
+ return false
224
+ }
225
+
226
+ async callBridge(path, options = {}) {
227
+ const config = this.config
228
+ if (config === null) throw new Error('the kian bridge is not configured')
229
+ const url = new URL(path, config.bridgeUrl)
230
+ const query = options.query
231
+ if (query !== undefined && query !== null) {
232
+ for (const key of Object.keys(query)) {
233
+ const value = query[key]
234
+ if (value !== undefined && value !== null) url.searchParams.set(key, String(value))
235
+ }
236
+ }
237
+ const headers = { authorization: 'Bearer ' + config.token, accept: 'application/json' }
238
+ const init = { method: options.method ?? 'GET', headers, signal: AbortSignal.timeout(options.timeoutMs ?? this.bridgeTimeoutMs) }
239
+ if (options.body !== undefined) {
240
+ headers['content-type'] = 'application/json'
241
+ init.body = JSON.stringify(options.body)
242
+ }
243
+ const response = await this.fetchImpl(url, init)
244
+ const text = await response.text()
245
+ let value = null
246
+ if (text !== '') {
247
+ try {
248
+ value = JSON.parse(text)
249
+ } catch (error) {
250
+ value = { protocol: BRIDGE_PROTOCOL, ok: false, kind: 'bridge_unavailable', detail: 'the kian bridge returned a non-JSON response', retry_safe: true }
251
+ }
252
+ }
253
+ return { status: response.status, value }
254
+ }
255
+
256
+ forward(res, upstream) {
257
+ if (upstream.value === null) {
258
+ sendBridgeError(res, 502, 'bridge_unavailable', 'the kian bridge returned an empty response', true)
259
+ return
260
+ }
261
+ sendJson(res, upstream.status, upstream.value)
262
+ }
263
+
264
+ unreachable(res, error) {
265
+ this.logger?.warn?.('[dsh-kian] bridge request failed: ' + errorMessage(error))
266
+ sendBridgeError(res, 503, 'bridge_unavailable', 'the kian bridge is unreachable', true)
267
+ }
268
+
269
+ badRequest(res, message) {
270
+ sendJson(res, 400, { ok: false, code: 'bad_request', message })
271
+ }
272
+
273
+ async handleHealth(req, res) {
274
+ const guard = this.checkGuard(req)
275
+ if (guard !== null) {
276
+ this.reject(res, guard)
277
+ return
278
+ }
279
+ if (!this.ensureConfigured(res)) return
280
+ let upstream = null
281
+ try {
282
+ upstream = await this.callBridge('/v1/health', { timeoutMs: this.bridgeTimeoutMs })
283
+ } catch (error) {
284
+ this.unreachable(res, error)
285
+ return
286
+ }
287
+ this.forward(res, upstream)
288
+ }
289
+
290
+ async handleHistory(req, res) {
291
+ const guard = this.checkGuard(req)
292
+ if (guard !== null) {
293
+ this.reject(res, guard)
294
+ return
295
+ }
296
+ if (!this.ensureConfigured(res)) return
297
+ const query = parseQuery(req.url)
298
+ const sinceSeq = parseCountParam(query.get('since_seq'), 0)
299
+ if (!sinceSeq.ok) { this.badRequest(res, 'since_seq ' + sinceSeq.message); return }
300
+ const limit = parseCountParam(query.get('limit'), DEFAULT_LIMIT)
301
+ if (!limit.ok) { this.badRequest(res, 'limit ' + limit.message); return }
302
+ if (limit.value < 1 || limit.value > MAX_LIMIT) { this.badRequest(res, 'limit must be between 1 and ' + MAX_LIMIT); return }
303
+ const waitMs = parseCountParam(query.get('wait_ms'), 0)
304
+ if (!waitMs.ok) { this.badRequest(res, 'wait_ms ' + waitMs.message); return }
305
+ if (waitMs.value > MAX_WAIT_MS) { this.badRequest(res, 'wait_ms must be between 0 and ' + MAX_WAIT_MS); return }
306
+ let upstream = null
307
+ try {
308
+ upstream = await this.callBridge('/v1/panel/updates', {
309
+ query: { since_seq: sinceSeq.value, limit: limit.value, wait_ms: waitMs.value },
310
+ timeoutMs: Math.max(this.bridgeTimeoutMs, waitMs.value + 5000)
311
+ })
312
+ } catch (error) {
313
+ this.unreachable(res, error)
314
+ return
315
+ }
316
+ this.forward(res, upstream)
317
+ }
318
+
319
+ async handleSend(req, res) {
320
+ const guard = this.checkGuard(req)
321
+ if (guard !== null) {
322
+ this.reject(res, guard)
323
+ return
324
+ }
325
+ const headers = req.headers ?? {}
326
+ const contentType = String(headers['content-type'] ?? '').toLowerCase()
327
+ if (!contentType.startsWith('application/json')) {
328
+ this.reject(res, 'content-type must be application/json')
329
+ return
330
+ }
331
+ let text = ''
332
+ try {
333
+ text = await readRequestBody(req)
334
+ } catch (error) {
335
+ if (error instanceof BodyTooLargeError || error?.code === 'too_large') {
336
+ this.reject(res, 'request body exceeds ' + MAX_BODY_BYTES + ' bytes')
337
+ return
338
+ }
339
+ throw error
340
+ }
341
+ if (!this.ensureConfigured(res)) return
342
+ let payload = null
343
+ try {
344
+ payload = JSON.parse(text)
345
+ } catch (error) {
346
+ this.badRequest(res, 'body is not valid JSON')
347
+ return
348
+ }
349
+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {
350
+ this.badRequest(res, 'body must be a JSON object')
351
+ return
352
+ }
353
+ if (typeof payload.text !== 'string' || payload.text.trim() === '') {
354
+ this.badRequest(res, 'text must be a non-empty string')
355
+ return
356
+ }
357
+ if (Buffer.byteLength(payload.text, 'utf8') > MAX_TEXT_BYTES) {
358
+ this.badRequest(res, 'text exceeds ' + MAX_TEXT_BYTES + ' bytes')
359
+ return
360
+ }
361
+ const clientId = payload.client_id
362
+ if (clientId !== undefined && (typeof clientId !== 'string' || clientId === '' || clientId.length > 128)) {
363
+ this.badRequest(res, 'client_id must be a string of 1 to 128 characters')
364
+ return
365
+ }
366
+ const body = { protocol: BRIDGE_PROTOCOL, conversation: 'main', text: payload.text }
367
+ if (clientId !== undefined) body.client_id = clientId
368
+ let upstream = null
369
+ try {
370
+ upstream = await this.callBridge('/v1/panel/send', { method: 'POST', body, timeoutMs: this.bridgeTimeoutMs })
371
+ } catch (error) {
372
+ this.unreachable(res, error)
373
+ return
374
+ }
375
+ this.forward(res, upstream)
376
+ }
377
+
378
+ handleStream(req, res) {
379
+ const guard = this.checkGuard(req)
380
+ if (guard !== null) {
381
+ this.reject(res, guard)
382
+ return Promise.resolve()
383
+ }
384
+ if (!this.ensureConfigured(res)) return Promise.resolve()
385
+ return this.openStream(req, res)
386
+ }
387
+
388
+ async openStream(req, res) {
389
+ const query = parseQuery(req.url)
390
+ const since = parseCountParam(query.get('since_seq'), 0)
391
+ if (!since.ok) {
392
+ this.badRequest(res, 'since_seq ' + since.message)
393
+ return
394
+ }
395
+ const stream = { closed: false }
396
+ this.activeStreams.add(stream)
397
+ const closeStream = () => { stream.closed = true }
398
+ if (typeof res.writeHead === 'function') res.writeHead(200, SSE_HEADERS)
399
+ else res.statusCode = 200
400
+ const onClose = () => { closeStream() }
401
+ req.on?.('close', onClose)
402
+ res.on?.('close', onClose)
403
+ const heartbeat = setInterval(() => {
404
+ if (stream.closed) return
405
+ try {
406
+ res.write(': ping\n\n')
407
+ } catch (error) {
408
+ closeStream()
409
+ }
410
+ }, this.heartbeatMs)
411
+ if (typeof heartbeat.unref === 'function') heartbeat.unref()
412
+ const write = (chunk) => {
413
+ if (stream.closed) return false
414
+ try {
415
+ res.write(chunk)
416
+ return true
417
+ } catch (error) {
418
+ closeStream()
419
+ return false
420
+ }
421
+ }
422
+ let sinceSeq = since.value
423
+ try {
424
+ write(': kian stream\n\n')
425
+ while (!stream.closed) {
426
+ let upstream = null
427
+ try {
428
+ upstream = await this.callBridge('/v1/panel/updates', {
429
+ query: { since_seq: sinceSeq, limit: DEFAULT_LIMIT, wait_ms: MAX_WAIT_MS },
430
+ timeoutMs: MAX_WAIT_MS + 5000
431
+ })
432
+ } catch (error) {
433
+ if (stream.closed) break
434
+ this.logger?.warn?.('[dsh-kian] stream bridge request failed: ' + errorMessage(error))
435
+ if (!write(sseFrame('retry', { protocol: BRIDGE_PROTOCOL, ok: false, kind: 'bridge_unavailable', retry_safe: true }))) break
436
+ await delay(this.retryDelayMs)
437
+ continue
438
+ }
439
+ if (stream.closed) break
440
+ const value = upstream.value
441
+ const status = upstream.status
442
+ if (status === 401 || (value !== null && value.ok === false && value.kind === 'unauthorized')) {
443
+ write(sseFrame('error', value ?? { protocol: BRIDGE_PROTOCOL, ok: false, kind: 'unauthorized' }))
444
+ break
445
+ }
446
+ if (status >= 500) {
447
+ if (!write(sseFrame('retry', value ?? { protocol: BRIDGE_PROTOCOL, ok: false, kind: 'bridge_unavailable', retry_safe: true }))) break
448
+ await delay(this.retryDelayMs)
449
+ continue
450
+ }
451
+ if (status >= 400) {
452
+ write(sseFrame('error', value ?? { protocol: BRIDGE_PROTOCOL, ok: false, kind: 'bad_request' }))
453
+ break
454
+ }
455
+ if (value === null || !Array.isArray(value.rows)) {
456
+ if (!write(sseFrame('retry', { protocol: BRIDGE_PROTOCOL, ok: false, kind: 'bridge_unavailable', detail: 'the kian bridge returned no rows', retry_safe: true }))) break
457
+ await delay(this.retryDelayMs)
458
+ continue
459
+ }
460
+ if (value.gap !== undefined && value.gap !== null) write(sseFrame('gap', value.gap))
461
+ for (const row of value.rows) {
462
+ if (stream.closed) break
463
+ if (!write('id: ' + row.seq + '\ndata: ' + JSON.stringify(row) + '\n\n')) break
464
+ if (Number.isSafeInteger(row.seq) && row.seq > sinceSeq) sinceSeq = row.seq
465
+ }
466
+ if (stream.closed) break
467
+ if (Number.isSafeInteger(value.next_seq) && value.next_seq > sinceSeq) sinceSeq = value.next_seq
468
+ if (value.has_more === true) continue
469
+ await delay(this.streamIdleMs)
470
+ }
471
+ } finally {
472
+ clearInterval(heartbeat)
473
+ this.activeStreams.delete(stream)
474
+ req.off?.('close', onClose)
475
+ res.off?.('close', onClose)
476
+ try {
477
+ res.end?.()
478
+ } catch (error) {
479
+ // The carrier is already gone.
480
+ }
481
+ }
482
+ }
483
+
484
+ disposeAll() {
485
+ for (const stream of this.activeStreams) stream.closed = true
486
+ this.activeStreams.clear()
487
+ }
488
+
489
+ routes() {
490
+ const bind = (handler) => (req, res) => Promise.resolve(handler.call(this, req, res)).catch((error) => {
491
+ this.logger?.warn?.('[dsh-kian] request failed: ' + errorMessage(error))
492
+ try {
493
+ if (res.headersSent === true) res.end?.()
494
+ else sendJson(res, 500, { ok: false, code: 'internal_error' })
495
+ } catch (failure) {
496
+ // Nothing is left to answer.
497
+ }
498
+ })
499
+ return [
500
+ { kind: 'exact', path: ROUTES.health, handler: bind(this.handleHealth) },
501
+ { kind: 'exact', path: ROUTES.history, handler: bind(this.handleHistory) },
502
+ { kind: 'exact', path: ROUTES.stream, handler: bind(this.handleStream) },
503
+ { kind: 'exact', path: ROUTES.send, handler: bind(this.handleSend) }
504
+ ]
505
+ }
506
+ }
507
+
508
+ export function apply(ctx) {
509
+ const service = new KianBridgeService({ logger: ctx.logger })
510
+ service.load()
511
+ const webServer = ctx.webServer
512
+ if (webServer === undefined || webServer === null || typeof webServer.register !== 'function') {
513
+ ctx.logger?.warn?.('[dsh-kian] webServer is unavailable; the kian routes are not mounted')
514
+ return
515
+ }
516
+ const disposers = []
517
+ for (const route of service.routes()) {
518
+ try {
519
+ disposers.push(webServer.register(route))
520
+ } catch (error) {
521
+ ctx.logger?.warn?.('[dsh-kian] route ' + route.path + ' not registered: ' + errorMessage(error))
522
+ }
523
+ }
524
+ if (typeof ctx.effect === 'function') ctx.effect(() => () => {
525
+ for (const dispose of disposers) {
526
+ if (typeof dispose === 'function') dispose()
527
+ }
528
+ service.disposeAll()
529
+ }, 'dsh-kian: routes')
530
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@flyer103/dsh-kian",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Kian conversation panel for the DSH Web GUI: one conversation mounted as a main panel and as a right-sidebar tab, proxied to the local kian bridge.",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./client": "./lib/client.js",
10
+ "./cordis.patch.yml": "./cordis.patch.yml",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "files": [
14
+ "lib",
15
+ "cordis.patch.yml",
16
+ "dsh.plugin.json",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "scripts": {
21
+ "test": "node --test test/",
22
+ "check": "node --check lib/index.js && node --check lib/client.js"
23
+ },
24
+ "dsh": {
25
+ "bundle": {
26
+ "patch": "./cordis.patch.yml"
27
+ },
28
+ "client": {
29
+ "inject": [
30
+ "@deepseek-ai/dsh-client-ui-primitives",
31
+ "@deepseek-ai/dsh-client-locale"
32
+ ],
33
+ "platform": "web"
34
+ }
35
+ },
36
+ "keywords": [
37
+ "dsh",
38
+ "deepseek-harness",
39
+ "dsh-plugin",
40
+ "kian",
41
+ "panel"
42
+ ],
43
+ "license": "MIT",
44
+ "author": {
45
+ "name": "flyer103",
46
+ "email": "flyer103@gmail.com",
47
+ "url": "https://github.com/flyer103"
48
+ },
49
+ "homepage": "https://github.com/flyer103/dsh-kian",
50
+ "repository": {
51
+ "type": "git",
52
+ "url": "git+https://github.com/flyer103/dsh-kian.git"
53
+ },
54
+ "engines": {
55
+ "node": ">=22"
56
+ }
57
+ }