@im-more/dsh-milky 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 +21 -0
- package/cordis.patch.yml +11 -0
- package/lib/index.js +2311 -0
- package/lib/index.js.map +1 -0
- package/lib/types/bot.d.ts +127 -0
- package/lib/types/bot.d.ts.map +1 -0
- package/lib/types/bot.js +303 -0
- package/lib/types/bot.js.map +1 -0
- package/lib/types/config.d.ts +24 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js +39 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/decode.d.ts +43 -0
- package/lib/types/decode.d.ts.map +1 -0
- package/lib/types/decode.js +277 -0
- package/lib/types/decode.js.map +1 -0
- package/lib/types/errors.d.ts +66 -0
- package/lib/types/errors.d.ts.map +1 -0
- package/lib/types/errors.js +170 -0
- package/lib/types/errors.js.map +1 -0
- package/lib/types/identity.d.ts +24 -0
- package/lib/types/identity.d.ts.map +1 -0
- package/lib/types/identity.js +33 -0
- package/lib/types/identity.js.map +1 -0
- package/lib/types/ids.d.ts +110 -0
- package/lib/types/ids.d.ts.map +1 -0
- package/lib/types/ids.js +166 -0
- package/lib/types/ids.js.map +1 -0
- package/lib/types/index.d.ts +10 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +9 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/internal.d.ts +2002 -0
- package/lib/types/internal.d.ts.map +1 -0
- package/lib/types/internal.js +408 -0
- package/lib/types/internal.js.map +1 -0
- package/lib/types/modes/text.d.ts +66 -0
- package/lib/types/modes/text.d.ts.map +1 -0
- package/lib/types/modes/text.js +275 -0
- package/lib/types/modes/text.js.map +1 -0
- package/lib/types/reads.d.ts +57 -0
- package/lib/types/reads.d.ts.map +1 -0
- package/lib/types/reads.js +219 -0
- package/lib/types/reads.js.map +1 -0
- package/lib/types/request.d.ts +55 -0
- package/lib/types/request.d.ts.map +1 -0
- package/lib/types/request.js +174 -0
- package/lib/types/request.js.map +1 -0
- package/lib/types/send.d.ts +34 -0
- package/lib/types/send.d.ts.map +1 -0
- package/lib/types/send.js +99 -0
- package/lib/types/send.js.map +1 -0
- package/lib/types/types/schema.d.ts +11726 -0
- package/lib/types/types/schema.d.ts.map +1 -0
- package/lib/types/types/schema.js +1422 -0
- package/lib/types/types/schema.js.map +1 -0
- package/lib/types/ws.d.ts +60 -0
- package/lib/types/ws.d.ts.map +1 -0
- package/lib/types/ws.js +335 -0
- package/lib/types/ws.js.map +1 -0
- package/package.json +62 -3
- package/src/bot.ts +431 -0
- package/src/config.ts +61 -0
- package/src/decode.ts +367 -0
- package/src/errors.ts +195 -0
- package/src/identity.ts +43 -0
- package/src/ids.ts +226 -0
- package/src/index.ts +44 -0
- package/src/internal.ts +657 -0
- package/src/modes/text.ts +368 -0
- package/src/reads.ts +315 -0
- package/src/request.ts +230 -0
- package/src/send.ts +175 -0
- package/src/types/schema.ts +1827 -0
- package/src/ws.ts +383 -0
- package/README.md +0 -3
package/src/ws.ts
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The client WebSocket to `<origin>/event`: a self-written loop because core's `WsClientBase` treats `retryTimes` as
|
|
3
|
+
* a give-up limit.
|
|
4
|
+
*
|
|
5
|
+
* Three failure classes are kept apart:
|
|
6
|
+
* - configuration failures are found by `connect()` before the loop starts and thrown there;
|
|
7
|
+
* - transport failures (dial, handshake, socket close, identity read) log a warning and enter the reconnect loop;
|
|
8
|
+
* - runtime permanent failures (the endpoint is logged into another account, or a frame names another `self_id`)
|
|
9
|
+
* log an error, take the bot offline and stop the loop.
|
|
10
|
+
*
|
|
11
|
+
* Frames are handled one at a time in arrival order. A frame whose intake throws is logged and dropped — the protocol
|
|
12
|
+
* has no acknowledgement and no redelivery, so retrying it would only delay the frames behind it.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { Status, type WebSocket } from '@deepseek-ai/cordis-plugin-im-core'
|
|
16
|
+
import type { MilkyBot } from './bot.ts'
|
|
17
|
+
import { decodeFrame } from './decode.ts'
|
|
18
|
+
import { MilkyIdentityError } from './errors.ts'
|
|
19
|
+
import type { Event } from './types/schema.ts'
|
|
20
|
+
|
|
21
|
+
/** Resolve after `ms`, or as soon as `signal` aborts. */
|
|
22
|
+
function sleep(ms: number, signal: AbortSignal): Promise<void> {
|
|
23
|
+
return new Promise((resolve) => {
|
|
24
|
+
if (signal.aborted) {
|
|
25
|
+
resolve()
|
|
26
|
+
return
|
|
27
|
+
}
|
|
28
|
+
const onAbort = (): void => {
|
|
29
|
+
clearTimeout(timer)
|
|
30
|
+
resolve()
|
|
31
|
+
}
|
|
32
|
+
const timer = setTimeout(() => {
|
|
33
|
+
signal.removeEventListener('abort', onAbort)
|
|
34
|
+
resolve()
|
|
35
|
+
}, ms)
|
|
36
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
37
|
+
})
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A settled promise nobody waits for. */
|
|
41
|
+
const noop = (): void => {}
|
|
42
|
+
|
|
43
|
+
/** Describe a caught value for a log line. */
|
|
44
|
+
function messageOf(error: unknown): string {
|
|
45
|
+
return error instanceof Error ? error.message : String(error)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The event stream of one Milky protocol endpoint. */
|
|
49
|
+
export class MilkyWs {
|
|
50
|
+
private controller: AbortController | undefined
|
|
51
|
+
private running: Promise<void> | undefined
|
|
52
|
+
private socket: WebSocket | undefined
|
|
53
|
+
private queue: Event[] = []
|
|
54
|
+
private draining: Promise<void> | undefined
|
|
55
|
+
private processing = false
|
|
56
|
+
private stopping = false
|
|
57
|
+
private warnedDepth = 0
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @param bot - the adapter whose identity, configuration and logger the loop uses.
|
|
61
|
+
*/
|
|
62
|
+
constructor(private readonly bot: MilkyBot) {}
|
|
63
|
+
|
|
64
|
+
/** Start the reconnect loop; resolves immediately, without waiting for the first connection. */
|
|
65
|
+
start(): void {
|
|
66
|
+
if (this.controller !== undefined) return
|
|
67
|
+
const controller = new AbortController()
|
|
68
|
+
this.controller = controller
|
|
69
|
+
this.stopping = false
|
|
70
|
+
const running = this.loop(controller.signal)
|
|
71
|
+
this.running = running
|
|
72
|
+
void running.catch(noop)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Stop the stream: abort the loop, close the socket, drop the frames that have not started, and wait for the frame
|
|
77
|
+
* being handled to finish.
|
|
78
|
+
*/
|
|
79
|
+
async stop(): Promise<void> {
|
|
80
|
+
this.stopping = true
|
|
81
|
+
this.controller?.abort(new Error('adapter stopped'))
|
|
82
|
+
this.controller = undefined
|
|
83
|
+
this.closeSocket(1000, 'adapter stopped')
|
|
84
|
+
this.dropQueue()
|
|
85
|
+
await this.running?.catch(noop)
|
|
86
|
+
this.running = undefined
|
|
87
|
+
await this.draining?.catch(noop)
|
|
88
|
+
this.draining = undefined
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The reconnect loop: dial, identify, consume, then retry at the fast or lazy interval. */
|
|
92
|
+
private async loop(signal: AbortSignal): Promise<void> {
|
|
93
|
+
let failures = 0
|
|
94
|
+
while (!signal.aborted) {
|
|
95
|
+
try {
|
|
96
|
+
const socket = await this.dial(signal)
|
|
97
|
+
if (signal.aborted) {
|
|
98
|
+
this.closeSocketOf(socket, 1000, 'adapter stopped')
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
this.socket = socket
|
|
102
|
+
await this.bot.identify()
|
|
103
|
+
failures = 0
|
|
104
|
+
this.bot.online()
|
|
105
|
+
const closed = await this.consume(socket, signal)
|
|
106
|
+
if (signal.aborted) return
|
|
107
|
+
throw new Error(
|
|
108
|
+
`websocket closed with ${closed.code}${closed.reason === '' ? '' : `: ${closed.reason}`}`,
|
|
109
|
+
)
|
|
110
|
+
} catch (error) {
|
|
111
|
+
this.closeSocket(3000, 'milky connection failed')
|
|
112
|
+
if (signal.aborted) return
|
|
113
|
+
if (error instanceof MilkyIdentityError) {
|
|
114
|
+
this.bot.ctx.logger.error('milky: %s', error.message)
|
|
115
|
+
this.bot.offline(error)
|
|
116
|
+
this.stopping = true
|
|
117
|
+
return
|
|
118
|
+
}
|
|
119
|
+
this.bot.ctx.logger.warn(
|
|
120
|
+
'milky: connection failed: %s',
|
|
121
|
+
messageOf(error),
|
|
122
|
+
)
|
|
123
|
+
this.bot.status = Status.RECONNECT
|
|
124
|
+
// `retryTimes` is a fast-retry budget, not a give-up limit: the loop keeps retrying at the lazy interval.
|
|
125
|
+
const delay =
|
|
126
|
+
failures < this.bot.config.ws.retryTimes
|
|
127
|
+
? this.bot.config.ws.retryIntervalMs
|
|
128
|
+
: this.bot.config.ws.retryLazyMs
|
|
129
|
+
failures += 1
|
|
130
|
+
await sleep(delay, signal)
|
|
131
|
+
} finally {
|
|
132
|
+
this.socket = undefined
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Open one socket and wait for its `open` event; a close or error before that is a transport failure. */
|
|
138
|
+
private dial(signal: AbortSignal): Promise<WebSocket> {
|
|
139
|
+
return new Promise<WebSocket>((resolve, reject) => {
|
|
140
|
+
let socket: WebSocket
|
|
141
|
+
try {
|
|
142
|
+
socket = this.bot.openEventSocket()
|
|
143
|
+
} catch (error) {
|
|
144
|
+
reject(error)
|
|
145
|
+
return
|
|
146
|
+
}
|
|
147
|
+
const cleanup = (): void => {
|
|
148
|
+
socket.removeEventListener('open', onOpen)
|
|
149
|
+
socket.removeEventListener('close', onClose)
|
|
150
|
+
socket.removeEventListener('error', onError)
|
|
151
|
+
signal.removeEventListener('abort', onAbort)
|
|
152
|
+
}
|
|
153
|
+
const onOpen = (): void => {
|
|
154
|
+
cleanup()
|
|
155
|
+
resolve(socket)
|
|
156
|
+
}
|
|
157
|
+
const onClose = (event: { code: number }): void => {
|
|
158
|
+
cleanup()
|
|
159
|
+
reject(
|
|
160
|
+
new Error(`websocket closed with ${event.code} before it opened`),
|
|
161
|
+
)
|
|
162
|
+
}
|
|
163
|
+
const onError = (event: { message?: string }): void => {
|
|
164
|
+
cleanup()
|
|
165
|
+
reject(
|
|
166
|
+
new Error(
|
|
167
|
+
event.message ?? 'websocket transport error before it opened',
|
|
168
|
+
),
|
|
169
|
+
)
|
|
170
|
+
}
|
|
171
|
+
const onAbort = (): void => {
|
|
172
|
+
cleanup()
|
|
173
|
+
this.closeSocketOf(socket, 1000, 'adapter stopped')
|
|
174
|
+
reject(signal.reason ?? new Error('adapter stopped'))
|
|
175
|
+
}
|
|
176
|
+
socket.addEventListener('open', onOpen)
|
|
177
|
+
socket.addEventListener('close', onClose)
|
|
178
|
+
socket.addEventListener('error', onError)
|
|
179
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
180
|
+
if (signal.aborted) onAbort()
|
|
181
|
+
})
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Deliver every frame of one open socket until it closes; resolves with the close details. */
|
|
185
|
+
private consume(
|
|
186
|
+
socket: WebSocket,
|
|
187
|
+
signal: AbortSignal,
|
|
188
|
+
): Promise<{ code: number; reason: string }> {
|
|
189
|
+
return new Promise((resolve) => {
|
|
190
|
+
const cleanup = (): void => {
|
|
191
|
+
socket.removeEventListener('message', onMessage)
|
|
192
|
+
socket.removeEventListener('close', onClose)
|
|
193
|
+
socket.removeEventListener('error', onError)
|
|
194
|
+
signal.removeEventListener('abort', onAbort)
|
|
195
|
+
}
|
|
196
|
+
const onMessage = (event: { data: unknown }): void => {
|
|
197
|
+
if (typeof event.data === 'string') this.accept(event.data)
|
|
198
|
+
else
|
|
199
|
+
this.bot.ctx.logger.warn(
|
|
200
|
+
'milky: ignored a websocket frame that was not text',
|
|
201
|
+
)
|
|
202
|
+
}
|
|
203
|
+
const onClose = (event: { code: number; reason: string }): void => {
|
|
204
|
+
cleanup()
|
|
205
|
+
resolve({ code: event.code, reason: event.reason })
|
|
206
|
+
}
|
|
207
|
+
const onError = (): void => {
|
|
208
|
+
this.bot.ctx.logger.warn('milky: websocket transport error')
|
|
209
|
+
}
|
|
210
|
+
const onAbort = (): void => {
|
|
211
|
+
cleanup()
|
|
212
|
+
this.closeSocketOf(socket, 1000, 'adapter stopped')
|
|
213
|
+
resolve({ code: 1000, reason: 'adapter stopped' })
|
|
214
|
+
}
|
|
215
|
+
socket.addEventListener('message', onMessage)
|
|
216
|
+
socket.addEventListener('close', onClose)
|
|
217
|
+
socket.addEventListener('error', onError)
|
|
218
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
219
|
+
if (signal.aborted) onAbort()
|
|
220
|
+
// A socket that reported close before this listener was attached would never fire it again.
|
|
221
|
+
else if (socket.readyState === 3) {
|
|
222
|
+
cleanup()
|
|
223
|
+
resolve({ code: 1006, reason: 'closed before the frame listener' })
|
|
224
|
+
}
|
|
225
|
+
})
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Parse, validate and queue one frame. */
|
|
229
|
+
private accept(raw: string): void {
|
|
230
|
+
let parsed: unknown
|
|
231
|
+
try {
|
|
232
|
+
parsed = JSON.parse(raw)
|
|
233
|
+
} catch (error) {
|
|
234
|
+
// A frame this adapter cannot read is dropped; the next frame is unaffected.
|
|
235
|
+
this.bot.ctx.logger.warn(
|
|
236
|
+
'milky: ignored a frame that is not JSON: %s',
|
|
237
|
+
messageOf(error),
|
|
238
|
+
)
|
|
239
|
+
return
|
|
240
|
+
}
|
|
241
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
242
|
+
this.bot.ctx.logger.warn(
|
|
243
|
+
'milky: ignored a frame that is not an event object',
|
|
244
|
+
)
|
|
245
|
+
return
|
|
246
|
+
}
|
|
247
|
+
const event = parsed as Partial<Event> & {
|
|
248
|
+
self_id?: unknown
|
|
249
|
+
time?: unknown
|
|
250
|
+
}
|
|
251
|
+
if (
|
|
252
|
+
typeof event.event_type !== 'string' ||
|
|
253
|
+
typeof event.self_id !== 'number' ||
|
|
254
|
+
typeof event.time !== 'number'
|
|
255
|
+
) {
|
|
256
|
+
this.bot.ctx.logger.warn(
|
|
257
|
+
'milky: ignored a frame without event_type, self_id or time',
|
|
258
|
+
)
|
|
259
|
+
return
|
|
260
|
+
}
|
|
261
|
+
if (String(event.self_id) !== this.bot.selfId) {
|
|
262
|
+
// Another account's event would be stored as this bot's message: permanent, and retrying cannot fix it.
|
|
263
|
+
this.halt(
|
|
264
|
+
new MilkyIdentityError(
|
|
265
|
+
`milky: a frame names account ${String(event.self_id)}, but this adapter is configured for ${this.bot.selfId}`,
|
|
266
|
+
),
|
|
267
|
+
)
|
|
268
|
+
return
|
|
269
|
+
}
|
|
270
|
+
this.enqueue(event as Event)
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Queue one frame behind the frames already waiting, warning once per doubling of the backlog. */
|
|
274
|
+
private enqueue(event: Event): void {
|
|
275
|
+
this.queue.push(event)
|
|
276
|
+
const depth = this.queue.length
|
|
277
|
+
if (depth >= 2 && (depth & (depth - 1)) === 0 && depth > this.warnedDepth) {
|
|
278
|
+
this.warnedDepth = depth
|
|
279
|
+
this.bot.ctx.logger.warn('milky: %d events are waiting for intake', depth)
|
|
280
|
+
}
|
|
281
|
+
if (this.processing) return
|
|
282
|
+
const draining = this.drain()
|
|
283
|
+
this.draining = draining
|
|
284
|
+
void draining.finally(() => {
|
|
285
|
+
if (this.draining === draining) this.draining = undefined
|
|
286
|
+
})
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Handle queued frames one at a time, in arrival order. */
|
|
290
|
+
private async drain(): Promise<void> {
|
|
291
|
+
if (this.processing) return
|
|
292
|
+
this.processing = true
|
|
293
|
+
try {
|
|
294
|
+
while (this.queue.length > 0) {
|
|
295
|
+
if (this.stopping) {
|
|
296
|
+
this.dropQueue()
|
|
297
|
+
return
|
|
298
|
+
}
|
|
299
|
+
const event = this.queue.shift()!
|
|
300
|
+
await this.handle(event)
|
|
301
|
+
}
|
|
302
|
+
this.warnedDepth = 0
|
|
303
|
+
} finally {
|
|
304
|
+
this.processing = false
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Decode and receive one frame; a failure drops that frame and nothing else. */
|
|
309
|
+
private async handle(event: Event): Promise<void> {
|
|
310
|
+
if (event.event_type === 'bot_offline') {
|
|
311
|
+
this.bot.ctx.logger.warn(
|
|
312
|
+
'milky: the protocol endpoint reports the account offline: %s',
|
|
313
|
+
event.data.reason,
|
|
314
|
+
)
|
|
315
|
+
return
|
|
316
|
+
}
|
|
317
|
+
let session
|
|
318
|
+
try {
|
|
319
|
+
session = decodeFrame(this.bot, event)
|
|
320
|
+
} catch (error) {
|
|
321
|
+
this.bot.ctx.logger.error(
|
|
322
|
+
'milky: a %s frame could not be decoded: %s',
|
|
323
|
+
event.event_type,
|
|
324
|
+
messageOf(error),
|
|
325
|
+
)
|
|
326
|
+
return
|
|
327
|
+
}
|
|
328
|
+
if (session === undefined) {
|
|
329
|
+
this.bot.ctx.logger.debug('milky: ignored event %s', event.event_type)
|
|
330
|
+
return
|
|
331
|
+
}
|
|
332
|
+
try {
|
|
333
|
+
await this.bot.receive(session)
|
|
334
|
+
} catch (error) {
|
|
335
|
+
this.bot.ctx.logger.error(
|
|
336
|
+
'milky: event %s could not be received: %s',
|
|
337
|
+
session.event.id ?? event.event_type,
|
|
338
|
+
messageOf(error),
|
|
339
|
+
)
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Stop the loop for a failure that reconnecting cannot fix. */
|
|
344
|
+
private halt(error: Error): void {
|
|
345
|
+
this.bot.ctx.logger.error('milky: %s', error.message)
|
|
346
|
+
this.bot.offline(error)
|
|
347
|
+
this.stopping = true
|
|
348
|
+
this.controller?.abort(error)
|
|
349
|
+
this.closeSocket(1000, 'milky identity mismatch')
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Drop every frame that has not started; the frame being handled still finishes. */
|
|
353
|
+
private dropQueue(): void {
|
|
354
|
+
const count = this.queue.length
|
|
355
|
+
if (count === 0) return
|
|
356
|
+
this.queue = []
|
|
357
|
+
this.warnedDepth = 0
|
|
358
|
+
this.bot.ctx.logger.warn(
|
|
359
|
+
'milky: dropped %d event(s) that had not started yet',
|
|
360
|
+
count,
|
|
361
|
+
)
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Close the current socket, ignoring a socket that is already gone. */
|
|
365
|
+
private closeSocket(code: number, reason: string): void {
|
|
366
|
+
const socket = this.socket
|
|
367
|
+
this.socket = undefined
|
|
368
|
+
if (socket !== undefined) this.closeSocketOf(socket, code, reason)
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** Close one socket, ignoring a close that the transport refuses because it is already closed. */
|
|
372
|
+
private closeSocketOf(socket: WebSocket, code: number, reason: string): void {
|
|
373
|
+
try {
|
|
374
|
+
socket.close(code, reason)
|
|
375
|
+
} catch (error) {
|
|
376
|
+
// A socket that already reported close rejects a second close; there is nothing left to release.
|
|
377
|
+
this.bot.ctx.logger.debug(
|
|
378
|
+
'milky: a closed socket was closed again: %s',
|
|
379
|
+
messageOf(error),
|
|
380
|
+
)
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
package/README.md
DELETED