@mcviseron/dsh-qq-bridge 0.0.0-stage → 0.2.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/lib/server.js ADDED
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Loopback HTTP carrier between the external QQ bot process and this Host
3
+ * plugin: inbound prompts go in, replies and approval questions come out
4
+ * through a long-poll event log.
5
+ */
6
+ import { createServer } from 'node:http'
7
+
8
+ const MAX_BODY_BYTES = 1 << 20
9
+ const LOOPBACK = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1'])
10
+ const ROUTES = new Set(['health', 'status', 'pull', 'inbound', 'approval', 'reset', 'switch', 'sessions', 'judge', 'permission', 'rebind', 'commands', 'command', 'answer'])
11
+
12
+ /** Write one JSON response. */
13
+ function respond(res, status, value) {
14
+ const body = Buffer.from(JSON.stringify(value), 'utf8')
15
+ res.writeHead(status, {
16
+ 'content-type': 'application/json; charset=utf-8',
17
+ 'content-length': body.length,
18
+ 'cache-control': 'no-store',
19
+ })
20
+ res.end(body)
21
+ }
22
+
23
+ /** Read one bounded JSON request body. */
24
+ async function readJson(req) {
25
+ const chunks = []
26
+ let size = 0
27
+ for await (const chunk of req) {
28
+ size += chunk.length
29
+ if (size > MAX_BODY_BYTES) throw new Error('request body too large')
30
+ chunks.push(chunk)
31
+ }
32
+ if (chunks.length === 0) return {}
33
+ const text = Buffer.concat(chunks).toString('utf8')
34
+ if (text.trim() === '') return {}
35
+ return JSON.parse(text)
36
+ }
37
+
38
+ export class HttpBridge {
39
+ #events = []
40
+ #seq = 0
41
+ #waiters = new Set()
42
+ #handlers = {}
43
+ #onPull
44
+ #server
45
+
46
+ /** @param {{host?: string, port: number, token?: string, log?: (message: string) => void, capacity?: number}} options */
47
+ constructor({ host = '127.0.0.1', port, token = '', log = () => {}, capacity = 1000 }) {
48
+ this.host = host
49
+ this.port = port
50
+ this.token = token
51
+ this.log = log
52
+ this.capacity = capacity
53
+ }
54
+
55
+ /** Register the business handlers the routes delegate to. */
56
+ setHandlers(handlers) {
57
+ this.#handlers = { ...handlers }
58
+ }
59
+
60
+ /** Called on every /pull so the host knows the bot is alive and listening. */
61
+ setOnPull(callback) {
62
+ this.#onPull = callback
63
+ }
64
+
65
+ /** Append one outbound event and wake every waiting poll. */
66
+ push(event) {
67
+ const entry = { seq: ++this.#seq, at: Date.now(), ...event }
68
+ this.#events.push(entry)
69
+ if (this.#events.length > this.capacity) this.#events.splice(0, this.#events.length - this.capacity)
70
+ const waiters = [...this.#waiters]
71
+ this.#waiters.clear()
72
+ for (const wake of waiters) wake()
73
+ return entry
74
+ }
75
+
76
+ /** Events strictly newer than `since`. */
77
+ take(since) {
78
+ return this.#events.filter(event => event.seq > since)
79
+ }
80
+
81
+ /** Current sequence number, so a fresh client can begin at "now". */
82
+ get cursor() {
83
+ return this.#seq
84
+ }
85
+
86
+ /** Resolve once a newer event exists or the wait elapses. */
87
+ #waitFor(since, timeoutMs) {
88
+ if (this.take(since).length > 0) return Promise.resolve()
89
+ return new Promise(resolve => {
90
+ const finish = () => {
91
+ clearTimeout(timer)
92
+ this.#waiters.delete(finish)
93
+ resolve()
94
+ }
95
+ const timer = setTimeout(finish, timeoutMs)
96
+ this.#waiters.add(finish)
97
+ })
98
+ }
99
+
100
+ /** Bind the loopback port; resolves with the effective address. */
101
+ async start() {
102
+ this.#server = createServer((req, res) => {
103
+ void this.#dispatch(req, res).catch(error => {
104
+ this.log(`request failed: ${error instanceof Error ? error.message : String(error)}`)
105
+ if (!res.headersSent) respond(res, 500, { ok: false, error: 'internal error' })
106
+ })
107
+ })
108
+ await new Promise((resolve, reject) => {
109
+ this.#server.once('error', reject)
110
+ this.#server.listen(this.port, this.host, () => {
111
+ this.#server.off('error', reject)
112
+ resolve()
113
+ })
114
+ })
115
+ const address = this.#server.address()
116
+ if (address !== null && typeof address === 'object') this.port = address.port
117
+ return address
118
+ }
119
+
120
+ /** Release the port. */
121
+ async stop() {
122
+ const server = this.#server
123
+ this.#server = undefined
124
+ this.#waiters.clear()
125
+ if (server === undefined) return
126
+ await new Promise(resolve => server.close(() => resolve()))
127
+ }
128
+
129
+ /** Route, authenticate, and answer one request. */
130
+ async #dispatch(req, res) {
131
+ const remote = req.socket.remoteAddress ?? ''
132
+ if (!LOOPBACK.has(remote)) {
133
+ respond(res, 403, { ok: false, error: 'loopback only' })
134
+ return
135
+ }
136
+ if (this.token !== '' && req.headers['x-bridge-token'] !== this.token) {
137
+ respond(res, 401, { ok: false, error: 'bad token' })
138
+ return
139
+ }
140
+
141
+ const url = new URL(req.url ?? '/', `http://${this.host}:${this.port}`)
142
+ const path = url.pathname.replace(/^\/+|\/+$/g, '')
143
+ if (!ROUTES.has(path)) {
144
+ respond(res, 404, { ok: false, error: 'unknown route' })
145
+ return
146
+ }
147
+
148
+ if (path === 'pull') {
149
+ if (req.method !== 'GET') {
150
+ respond(res, 405, { ok: false, error: 'GET only' })
151
+ return
152
+ }
153
+ const sinceRaw = url.searchParams.get('since')
154
+ const since = sinceRaw === null ? this.#seq : Number.parseInt(sinceRaw, 10)
155
+ const waitRaw = Number.parseInt(url.searchParams.get('wait') ?? '0', 10)
156
+ const wait = Number.isFinite(waitRaw) ? Math.min(Math.max(waitRaw, 0), 55000) : 0
157
+ if (!Number.isFinite(since)) {
158
+ respond(res, 400, { ok: false, error: 'bad since' })
159
+ return
160
+ }
161
+ try {
162
+ this.#onPull?.()
163
+ } catch {
164
+ // a broken observer must never break the pull route
165
+ }
166
+ await this.#waitFor(since, wait)
167
+ respond(res, 200, { ok: true, cursor: this.#seq, events: this.take(since) })
168
+ return
169
+ }
170
+
171
+ const handler = this.#handlers[path]
172
+ if (typeof handler !== 'function') {
173
+ respond(res, 503, { ok: false, error: `${path} not ready` })
174
+ return
175
+ }
176
+
177
+ let body = {}
178
+ if (req.method === 'POST') {
179
+ try {
180
+ body = await readJson(req)
181
+ } catch (error) {
182
+ respond(res, 400, { ok: false, error: `bad body: ${error instanceof Error ? error.message : String(error)}` })
183
+ return
184
+ }
185
+ } else if (req.method !== 'GET') {
186
+ respond(res, 405, { ok: false, error: 'method not allowed' })
187
+ return
188
+ }
189
+
190
+ try {
191
+ const value = await handler(body)
192
+ const status = value !== null && typeof value === 'object' && value.ok === false ? 400 : 200
193
+ respond(res, status, value)
194
+ } catch (error) {
195
+ respond(res, 400, { ok: false, error: error instanceof Error ? error.message : String(error) })
196
+ }
197
+ }
198
+ }
package/lib/store.js ADDED
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Conversation ↔ Session mapping, persisted as JSON so a Host restart keeps
3
+ * every QQ conversation attached to the Session that already holds its history.
4
+ */
5
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
6
+ import { dirname } from 'node:path'
7
+
8
+ /** Empty mapping document. */
9
+ function emptyState() {
10
+ return { version: 1, conversations: {}, sessions: {}, approvalTargets: {}, returns: {} }
11
+ }
12
+
13
+ export class ConversationStore {
14
+ #path
15
+ #data = emptyState()
16
+ #writing = Promise.resolve()
17
+
18
+ /** @param {string} path absolute state file path. */
19
+ constructor(path) {
20
+ this.#path = path
21
+ }
22
+
23
+ /** Read the persisted document; a missing file starts an empty mapping. */
24
+ async load() {
25
+ try {
26
+ const parsed = JSON.parse(await readFile(this.#path, 'utf8'))
27
+ if (parsed !== null && typeof parsed === 'object') {
28
+ this.#data = {
29
+ version: 1,
30
+ conversations: { ...(parsed.conversations ?? {}) },
31
+ sessions: { ...(parsed.sessions ?? {}) },
32
+ approvalTargets: { ...(parsed.approvalTargets ?? {}) },
33
+ returns: { ...(parsed.returns ?? {}) },
34
+ }
35
+ }
36
+ } catch (error) {
37
+ if (error?.code !== 'ENOENT') throw error
38
+ }
39
+ return this
40
+ }
41
+
42
+ /** Session bound to one QQ conversation, if any. */
43
+ sessionOf(convKey) {
44
+ return this.#data.conversations[convKey]
45
+ }
46
+
47
+ /** QQ conversation owning one Session, if any. */
48
+ convOf(sessionId) {
49
+ return this.#data.sessions[sessionId]
50
+ }
51
+
52
+ /** Conversation that receives this conversation's approval questions. */
53
+ approvalTargetOf(convKey) {
54
+ return this.#data.approvalTargets[convKey]
55
+ }
56
+
57
+ /** Number of bound conversations, for /status. */
58
+ size() {
59
+ return Object.keys(this.#data.conversations).length
60
+ }
61
+
62
+ /** Bind (or rebind) one conversation to a Session. */
63
+ async bind(convKey, sessionId, approvalTarget) {
64
+ this.#data.conversations[convKey] = sessionId
65
+ this.#data.sessions[sessionId] = convKey
66
+ if (typeof approvalTarget === 'string' && approvalTarget !== '') {
67
+ this.#data.approvalTargets[convKey] = approvalTarget
68
+ }
69
+ await this.#flush()
70
+ }
71
+
72
+ /** Drop one conversation binding (the Session itself is left untouched). */
73
+ async unbind(convKey) {
74
+ const sessionId = this.#data.conversations[convKey]
75
+ delete this.#data.conversations[convKey]
76
+ delete this.#data.approvalTargets[convKey]
77
+ delete this.#data.returns[convKey]
78
+ if (sessionId !== undefined) delete this.#data.sessions[sessionId]
79
+ await this.#flush()
80
+ }
81
+
82
+ /** Session remembered by switchTo so the conversation can go back. */
83
+ returnOf(convKey) {
84
+ return this.#data.returns[convKey]
85
+ }
86
+
87
+ /** Every conversation that has a remembered return target. */
88
+ returnEntries() {
89
+ return Object.entries(this.#data.returns)
90
+ }
91
+
92
+ /** Rebind a conversation onto another existing Session, remembering the old one. */
93
+ async switchTo(convKey, sessionId) {
94
+ const current = this.#data.conversations[convKey]
95
+ if (current !== undefined && current !== sessionId) {
96
+ this.#data.returns[convKey] = current
97
+ if (this.#data.sessions[current] === convKey) delete this.#data.sessions[current]
98
+ }
99
+ this.#data.conversations[convKey] = sessionId
100
+ this.#data.sessions[sessionId] = convKey
101
+ await this.#flush()
102
+ }
103
+
104
+ /** Undo one switchTo; resolves with the restored Session id, or undefined. */
105
+ async switchBack(convKey) {
106
+ const previous = this.#data.returns[convKey]
107
+ if (previous === undefined) return undefined
108
+ delete this.#data.returns[convKey]
109
+ const temporary = this.#data.conversations[convKey]
110
+ if (temporary !== undefined && this.#data.sessions[temporary] === convKey) delete this.#data.sessions[temporary]
111
+ this.#data.conversations[convKey] = previous
112
+ this.#data.sessions[previous] = convKey
113
+ await this.#flush()
114
+ return previous
115
+ }
116
+
117
+ /** Every bound conversation, newest state first seen order. */
118
+ entries() {
119
+ return Object.entries(this.#data.conversations)
120
+ }
121
+
122
+ /** Serialized atomic write so concurrent binds cannot interleave. */
123
+ #flush() {
124
+ this.#writing = this.#writing.then(async () => {
125
+ await mkdir(dirname(this.#path), { recursive: true })
126
+ const temporary = `${this.#path}.tmp`
127
+ await writeFile(temporary, JSON.stringify(this.#data, null, 2), 'utf8')
128
+ await rename(temporary, this.#path)
129
+ })
130
+ return this.#writing
131
+ }
132
+ }
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@mcviseron/dsh-qq-bridge",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "DeepSeek Harness plugin: bridge QQ conversations (driven by an external viseron-botpy bot) to DSH sessions — injects user messages, captures assistant replies, streams C2C answers, and relays tool approvals to the bot owner.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "lib/index.js",
8
+ "exports": {
9
+ ".": "./lib/index.js",
10
+ "./client": "./lib/client.js",
11
+ "./cordis.patch.yml": "./cordis.patch.yml",
12
+ "./package.json": "./package.json"
13
+ },
14
+ "files": [
15
+ "lib",
16
+ "cordis.patch.yml",
17
+ "README.md"
18
+ ],
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/MCviseron/dsh-qqbot-bridge.git"
22
+ },
23
+ "bugs": {
24
+ "url": "https://github.com/MCviseron/dsh-qqbot-bridge/issues"
25
+ },
26
+ "keywords": [
27
+ "dsh",
28
+ "dsh-plugin",
29
+ "cordis",
30
+ "qq",
31
+ "qqbot",
32
+ "bridge",
33
+ "streaming"
34
+ ],
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "dsh": {
39
+ "bundle": {
40
+ "patch": "./cordis.patch.yml"
41
+ },
42
+ "client": {
43
+ "inject": [
44
+ "@deepseek-ai/dsh-client-ui-settings",
45
+ "@deepseek-ai/dsh-client-ui-slots"
46
+ ],
47
+ "platform": "web"
48
+ }
49
+ },
50
+ "engines": {
51
+ "node": "^22.19.0 || >=24"
52
+ },
53
+ "dependencies": {},
54
+ "peerDependencies": {
55
+ "@deepseek-ai/cordis": "*"
56
+ },
57
+ "peerDependenciesMeta": {
58
+ "@deepseek-ai/cordis": {
59
+ "optional": true
60
+ }
61
+ }
62
+ }