@qwen-code/channel-wecom 0.28.0 → 0.28.1-preview.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.
@@ -0,0 +1,830 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Qwen Team
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { randomUUID } from 'node:crypto';
7
+ import { setTimeout as delay } from 'node:timers/promises';
8
+ import { fitInboundText, MANAGED_OUTBOUND_LIMIT, resolvePrivatePolicy, } from '@qwen-code/channel-base';
9
+ import { MANAGED_WECOM_PENDING_LIMIT, ManagedWecomStateStore, RECENT_LIMIT, } from './managed-state.js';
10
+ const CLAIM_BATCH = 16;
11
+ const DEFAULT_POLL_INTERVAL = 2_000;
12
+ // Shared by the clamp and the operator-facing diagnostic so a bound change
13
+ // cannot leave the message stating a range the code no longer enforces.
14
+ const MIN_POLL_INTERVAL = 250;
15
+ const MAX_POLL_INTERVAL = 2_147_483_647;
16
+ const INSTANCE_SCOPED_REFUSALS = new Set([
17
+ 'workspace_not_found',
18
+ 'workspace_forbidden',
19
+ 'actor_scope_mismatch',
20
+ 'workspace_unavailable',
21
+ ]);
22
+ const INSTANCE_REFUSAL_DROP_LIMIT = 1;
23
+ const CHANNEL_NOT_FOUND = 'channel_not_found';
24
+ export function wecomSettings(config) {
25
+ const botId = config['botId'];
26
+ const secret = config['secret'];
27
+ if (!validCredential(botId))
28
+ throw new Error('WeCom channel requires a botId.');
29
+ if (!validCredential(secret))
30
+ throw new Error('WeCom channel requires a secret.');
31
+ const rawWsUrl = config['wsUrl'];
32
+ let wsUrl;
33
+ // A blank or null optional wsUrl is absent, like the Legacy parser and the
34
+ // sibling pollInterval key — not a refusal of the whole channel. A real
35
+ // value still must be a wss:// URL, and a non-string is refused.
36
+ if (rawWsUrl !== undefined && rawWsUrl !== null) {
37
+ if (typeof rawWsUrl !== 'string')
38
+ throw new Error('WeCom channel requires wsUrl to use wss://.');
39
+ const trimmed = rawWsUrl.trim();
40
+ if (trimmed) {
41
+ if (!isSecureWebSocketUrl(trimmed))
42
+ throw new Error('WeCom channel requires wsUrl to use wss://.');
43
+ wsUrl = trimmed;
44
+ }
45
+ }
46
+ const rawInterval = config['pollInterval'];
47
+ const pollInterval = Number(rawInterval ?? DEFAULT_POLL_INTERVAL);
48
+ const intervalAccepted = Number.isSafeInteger(pollInterval) &&
49
+ pollInterval >= MIN_POLL_INTERVAL &&
50
+ pollInterval <= MAX_POLL_INTERVAL;
51
+ return {
52
+ botId: botId.trim(),
53
+ secret: secret.trim(),
54
+ ...(wsUrl ? { wsUrl } : {}),
55
+ pollInterval: intervalAccepted ? pollInterval : DEFAULT_POLL_INTERVAL,
56
+ pollIntervalRewritten: rawInterval !== undefined && !intervalAccepted,
57
+ };
58
+ }
59
+ // Mirror the email credential rule: a copy-paste trailing newline or an
60
+ // embedded CR/LF/NUL must be rejected, not passed through to the SDK auth
61
+ // frame where it surfaces as an auth error pointing at the credential.
62
+ function validCredential(value) {
63
+ return typeof value === 'string' && !!value.trim() && !/[\r\n\0]/.test(value);
64
+ }
65
+ function isSecureWebSocketUrl(value) {
66
+ try {
67
+ return new URL(value).protocol === 'wss:';
68
+ }
69
+ catch {
70
+ return false;
71
+ }
72
+ }
73
+ export class ManagedWecomAdapter {
74
+ settings;
75
+ policy;
76
+ store;
77
+ controlPlane;
78
+ deps;
79
+ log;
80
+ pollLoop;
81
+ state;
82
+ stream;
83
+ releaseLock;
84
+ running = false;
85
+ ownershipLost = false;
86
+ displaced = false;
87
+ loop;
88
+ abort;
89
+ registeredGeneration;
90
+ instanceStalled = false;
91
+ loggedNoClaimSlot = false;
92
+ lastDropCause;
93
+ loggedAcceptFailure = false;
94
+ loggedRegistrationFailure = false;
95
+ constructor(options) {
96
+ this.settings = wecomSettings(options.config);
97
+ const senderPolicy = resolvePrivatePolicy(options.config);
98
+ if (senderPolicy === 'pairing') {
99
+ // The managed policy shape has no pairing arm; silently coercing it to
100
+ // an empty allowlist would skip every message while reporting running.
101
+ throw new Error('The managed WeCom path does not support privatePolicy "pairing"; use allowedUsers, open, or disabled.');
102
+ }
103
+ const allowed = options.config['allowedUsers'];
104
+ this.policy = {
105
+ adapter: 'wecom',
106
+ senderPolicy: senderPolicy === 'disabled' || senderPolicy === 'open'
107
+ ? senderPolicy
108
+ : 'allowlist',
109
+ allowedSenders: Array.isArray(allowed)
110
+ ? allowed.filter((entry) => typeof entry === 'string')
111
+ : [],
112
+ dispatchMode: options.config['dispatchMode'] === 'steer' ? 'steer' : 'followup',
113
+ };
114
+ this.store = new ManagedWecomStateStore(options.name, options.cwd, this.settings.botId, options.controlPlane.destinationKey ?? '');
115
+ this.controlPlane = options.controlPlane;
116
+ this.deps = options.deps;
117
+ this.log =
118
+ options.deps.log ?? ((line) => process.stderr.write(`${line}\n`));
119
+ // The clamp in wecomSettings is silent; say so when it reports a rewrite,
120
+ // or an operator tuning the poll rate sees no effect and no explanation.
121
+ // The decision and the bounds come from the settings clamp itself, never
122
+ // re-derived here.
123
+ if (this.settings.pollIntervalRewritten) {
124
+ this.log(`Managed WeCom pollInterval ${String(options.config['pollInterval'])} is not an integer in [${MIN_POLL_INTERVAL}, ${MAX_POLL_INTERVAL}]; using ${this.settings.pollInterval} ms.`);
125
+ }
126
+ this.pollLoop = options.pollLoop ?? true;
127
+ }
128
+ get stateFile() {
129
+ return this.store.file;
130
+ }
131
+ get generation() {
132
+ return this.state?.generation;
133
+ }
134
+ async connect() {
135
+ if (this.running || this.releaseLock)
136
+ throw new Error('Managed WeCom adapter is already connected.');
137
+ try {
138
+ this.releaseLock = await this.deps.lock(this.store.directory, () => {
139
+ // A reaped stale lock means a second owner won the state directory.
140
+ // Stop, and stop persisting: an in-flight tick or the shutdown drain
141
+ // must not rewrite the file the new owner now holds.
142
+ this.ownershipLost = true;
143
+ this.log('Managed WeCom state ownership was lost to another process; adapter stopped.');
144
+ this.stop();
145
+ });
146
+ }
147
+ catch {
148
+ throw new Error('WeCom state is owned by another process; managed adapter not started.');
149
+ }
150
+ try {
151
+ this.state = this.store.load() ?? {
152
+ version: 1,
153
+ generation: 1,
154
+ pending: [],
155
+ outbound: [],
156
+ recent: [],
157
+ };
158
+ if (this.state.pending.some((entry) => entry.held)) {
159
+ this.instanceStalled = true;
160
+ this.state.instanceRefusals = Math.max(this.state.instanceRefusals ?? 0, INSTANCE_REFUSAL_DROP_LIMIT + 1);
161
+ }
162
+ this.persist();
163
+ this.abort = new AbortController();
164
+ this.running = true;
165
+ this.displaced = false;
166
+ this.loggedNoClaimSlot = false;
167
+ this.lastDropCause = undefined;
168
+ this.loggedAcceptFailure = false;
169
+ this.loggedRegistrationFailure = false;
170
+ this.registeredGeneration = undefined;
171
+ this.stream = this.deps.createStreamClient(this.settings, (messageId, data) => this.onMessage(messageId, data), (reason) => {
172
+ // A server kick displaced this connection; reconnecting would
173
+ // displace the new owner in turn. Stop instead of reporting a
174
+ // healthy start that is permanently deaf.
175
+ this.log(`Managed WeCom stream stopped: ${reason}; adapter stopped.`);
176
+ this.displaced = true;
177
+ this.stop();
178
+ // The kick displaced the WS connection, not the state-file lock
179
+ // (still ours): release it now so a restart of this entry can
180
+ // acquire it, instead of holding it until SIGTERM while this
181
+ // process will never work again. Distinct from ownershipLost,
182
+ // where the lock belongs to another process and is NOT released.
183
+ void this.release();
184
+ });
185
+ await this.stream.connect();
186
+ if (!this.running)
187
+ throw new Error('Managed WeCom adapter stopped during connection.');
188
+ await this.ensureRegistered(this.state);
189
+ // Orphan-receipt replay contains its own transient refusals (it keeps
190
+ // the entry and lets the outbox pull run), so a stale row cannot keep a
191
+ // healthy stream from starting nor wedge outbound after it.
192
+ await this.reportOrphanedOutbound();
193
+ // A lock compromise or a kick can land during the awaits above. Re-check
194
+ // so connect() rejects rather than resolving a healthy-looking start for
195
+ // a stopped, deaf adapter the CLI would then park on.
196
+ if (!this.running || this.ownershipLost)
197
+ throw new Error('Managed WeCom adapter stopped during connection.');
198
+ if (this.pollLoop)
199
+ this.loop = this.runLoop();
200
+ }
201
+ catch (error) {
202
+ this.stop();
203
+ // Frames staged between stream.connect() and a failed registration were
204
+ // already persisted as claims by onMessage, so a restart re-drives them;
205
+ // there is no in-memory inbox to drain.
206
+ await this.release();
207
+ throw error;
208
+ }
209
+ }
210
+ async disconnect() {
211
+ this.stop();
212
+ await this.loop;
213
+ // Accepted frames are already durable claims (onMessage persists before
214
+ // returning), so shutdown has no inbox to drain. Neither a displaced nor a
215
+ // lock-compromised adapter still owns the shared channel row: disconnecting
216
+ // it would deregister the new owner (the server's disconnect has no
217
+ // generation guard), which then drops inbound frames WeCom never
218
+ // redelivers. Skip the row disconnect on both "no longer the owner" paths.
219
+ // The lock difference stays: a kick released our lock above, but on
220
+ // compromise the lock belongs to another process and release() is a no-op.
221
+ if (!this.displaced && !this.ownershipLost) {
222
+ await this.controlPlane.disconnect().catch(() => undefined);
223
+ }
224
+ await this.release();
225
+ }
226
+ /** One admission re-drive and one outbound pull, for callers that drive it. */
227
+ async tick() {
228
+ await this.ensureRegistered(this.state);
229
+ await this.resubmitPending();
230
+ await this.reportOrphanedOutbound();
231
+ await this.pullOutbox();
232
+ }
233
+ // The SDK pushes each frame once and never redelivers it, so there is no
234
+ // ack to withhold: acceptance is the durable staging itself. A full claim
235
+ // table or a stall leaves the frame dropped (logged, latched); a store.save()
236
+ // failure also drops it — unlike DingTalk's LATER arm, there is no provider
237
+ // redelivery to leave it for, and the loss must be visible instead of silent.
238
+ onMessage(messageId, data) {
239
+ if (!this.running || this.ownershipLost)
240
+ return;
241
+ const tableFull = (this.state?.pending.length ?? 0) >= MANAGED_WECOM_PENDING_LIMIT;
242
+ if (this.instanceStalled || this.registeredGeneration === 0 || tableFull) {
243
+ // Name the actual cause: a stall or a registration outage drops frames
244
+ // with slots free, so a claim-slot line would blame the wrong thing.
245
+ // Latched per cause transition: one outage yields one line, and a cause
246
+ // change mid-outage is still announced. The next accepted frame re-arms.
247
+ const cause = this.instanceStalled
248
+ ? 'admission is stalled (instance-scoped refusal)'
249
+ : this.registeredGeneration === 0
250
+ ? 'the channel is re-registering'
251
+ : 'no durable claim slot';
252
+ if (!this.loggedNoClaimSlot || this.lastDropCause !== cause) {
253
+ this.loggedNoClaimSlot = true;
254
+ this.lastDropCause = cause;
255
+ this.log(`Managed WeCom dropped message ${messageId}: ${cause} (the provider does not redeliver).`);
256
+ }
257
+ return;
258
+ }
259
+ try {
260
+ // Only a staged claim is an acceptance: a skipped frame also returns
261
+ // normally, and must not re-arm the outage latches.
262
+ if (this.stageInbound({ messageId, data })) {
263
+ this.loggedNoClaimSlot = false;
264
+ this.lastDropCause = undefined;
265
+ this.loggedAcceptFailure = false;
266
+ }
267
+ }
268
+ catch (error) {
269
+ // A failed save loses the frame: the provider never redelivers it. Say
270
+ // why, or a disk outage reads as silent message loss. Latched like the
271
+ // no-slot line: a persistent store failure drops every frame, and a
272
+ // line per frame would drown the log.
273
+ if (!this.loggedAcceptFailure) {
274
+ this.loggedAcceptFailure = true;
275
+ this.log(`Managed WeCom could not durably accept message ${messageId}: ${String(error)}; it is lost (the provider does not redeliver).`);
276
+ }
277
+ }
278
+ }
279
+ async runLoop() {
280
+ try {
281
+ while (this.running) {
282
+ try {
283
+ await this.tick();
284
+ }
285
+ catch (error) {
286
+ // A persistent registration failure rethrows every tick; latch it
287
+ // like the other outage diagnostics so the most important failure
288
+ // does not flood one raw line per poll interval.
289
+ if (error.registrationFailure) {
290
+ if (!this.loggedRegistrationFailure) {
291
+ this.loggedRegistrationFailure = true;
292
+ this.log(`Managed WeCom registration is failing (${String(error)}); inbound is dropped until it recovers.`);
293
+ }
294
+ }
295
+ else {
296
+ this.log(`Managed WeCom tick failed: ${String(error)}`);
297
+ }
298
+ }
299
+ if (this.running)
300
+ await delay(this.settings.pollInterval, undefined, {
301
+ signal: this.abort.signal,
302
+ }).catch(() => { });
303
+ }
304
+ }
305
+ finally {
306
+ this.stop();
307
+ }
308
+ }
309
+ senderAllowed(sender) {
310
+ switch (this.policy.senderPolicy) {
311
+ case 'disabled':
312
+ return false;
313
+ case 'open':
314
+ return true;
315
+ default:
316
+ return this.policy.allowedSenders.includes(sender);
317
+ }
318
+ }
319
+ // Synchronously stage the frame as a durable claim. The SDK event handler
320
+ // calls this before returning, so the claim is on disk before the frame is
321
+ // gone for good — the provider never redelivers it. The async submit() is
322
+ // left to the tick (resubmitPending). A store.save() failure throws and
323
+ // onMessage logs the loss. Returns whether a claim was staged: a skipped
324
+ // frame is not an acceptance.
325
+ stageInbound(item) {
326
+ const state = this.state;
327
+ let parsed;
328
+ try {
329
+ parsed = JSON.parse(item.data);
330
+ }
331
+ catch {
332
+ this.log(`Managed WeCom message ${item.messageId} is not JSON; skipped.`);
333
+ return false;
334
+ }
335
+ // `null`, arrays and primitives parse successfully but are not frames;
336
+ // reject them here so indexing below cannot throw into onMessage's catch
337
+ // and poison the durable-store loss latch with a malformed-frame error.
338
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
339
+ this.log(`Managed WeCom message ${item.messageId} is not a JSON object; skipped.`);
340
+ return false;
341
+ }
342
+ const senderId = str(getRecord(parsed, 'from')?.['userid']) ?? '';
343
+ // Single-chat frames may carry no chatid; the SDK's send contract and the
344
+ // Legacy channel both address a single chat by the sender userid.
345
+ const chatId = str(parsed['chatid']) ?? senderId;
346
+ const chattype = str(parsed['chattype']);
347
+ const rawText = extractText(parsed);
348
+ const text = rawText ? fitInboundText(rawText) : rawText;
349
+ const eventId = `wecom:${item.messageId}`;
350
+ const skip = () => {
351
+ state.recent = [...state.recent, eventId].slice(-RECENT_LIMIT);
352
+ // A skipped frame was never a durable claim, so a store failure here
353
+ // loses nothing — contain it separately so it cannot poison the
354
+ // durable-loss latch (loggedAcceptFailure) reserved for real staging
355
+ // failures, which would then silence a genuinely lost text frame.
356
+ try {
357
+ this.persist();
358
+ }
359
+ catch (error) {
360
+ this.log(`Managed WeCom could not record skipped message ${eventId}: ${String(error)}; nothing was lost.`);
361
+ }
362
+ };
363
+ // The managed path serves private chats under the private-chat policy.
364
+ // A group frame would be answered into the group for every member to
365
+ // read, so drop it until an explicit group policy exists (the DingTalk
366
+ // slice made the same decision).
367
+ if (chattype === 'group') {
368
+ this.log(`Managed WeCom group message ${item.messageId} is skipped; the managed path serves private chats only.`);
369
+ skip();
370
+ return false;
371
+ }
372
+ if (!senderId || !chatId || !text) {
373
+ // A non-text or unroutable frame is dropped; leave a line so the drop is
374
+ // visible instead of silent. Name the actual cause: a non-text frame
375
+ // carrying both ids is the common trigger and must not read as a
376
+ // malformed frame. Only the messageId and the field/msgtype are logged —
377
+ // never the text.
378
+ const msgtype = str(parsed['msgtype']);
379
+ const missing = [
380
+ !senderId ? 'senderId' : undefined,
381
+ !chatId ? 'chatId' : undefined,
382
+ !text ? 'text' : undefined,
383
+ ].filter((field) => field !== undefined);
384
+ const reason = missing.length === 1 &&
385
+ missing[0] === 'text' &&
386
+ msgtype &&
387
+ msgtype !== 'text'
388
+ ? `is not a text frame (msgtype ${msgtype})`
389
+ : `is missing ${missing.join(', ')}`;
390
+ this.log(`Managed WeCom message ${item.messageId} ${reason}; skipped.`);
391
+ skip();
392
+ return false;
393
+ }
394
+ if (!this.senderAllowed(senderId)) {
395
+ this.log(`Managed WeCom sender ${senderId} is not allowed; message skipped.`);
396
+ skip();
397
+ return false;
398
+ }
399
+ // Dedupe against both the settled window and the in-flight claims: a frame
400
+ // redelivered by the SDK while its claim is still pending (its admission
401
+ // answer was lost) must not be staged a second time before recent is
402
+ // updated.
403
+ if (state.recent.includes(eventId) ||
404
+ state.pending.some((entry) => entry.eventId === eventId)) {
405
+ return false;
406
+ }
407
+ const event = {
408
+ accountGeneration: state.generation,
409
+ platformEventId: eventId,
410
+ semanticRevision: 1,
411
+ scope: {
412
+ kind: 'chat_thread',
413
+ senderId: null,
414
+ chatId,
415
+ threadId: chatId,
416
+ },
417
+ senderId,
418
+ chatId,
419
+ threadId: chatId,
420
+ subject: null,
421
+ text,
422
+ attachments: [],
423
+ replyContext: {
424
+ chatId,
425
+ senderId,
426
+ botId: this.settings.botId,
427
+ },
428
+ };
429
+ const previousPending = state.pending;
430
+ state.pending = [...state.pending, { eventId, event }].slice(-MANAGED_WECOM_PENDING_LIMIT);
431
+ try {
432
+ this.persist();
433
+ }
434
+ catch (error) {
435
+ // A failed save must not leave the claim in memory: the dedupe arm would
436
+ // then drop a later copy of a claim the store never accepted. Roll back
437
+ // so the loss is exactly one frame; onMessage logs it.
438
+ state.pending = previousPending;
439
+ throw error;
440
+ }
441
+ return true;
442
+ }
443
+ async submit(eventId, event) {
444
+ const state = this.state;
445
+ let admitted;
446
+ try {
447
+ admitted = await this.controlPlane.submitInbound(event);
448
+ }
449
+ catch (error) {
450
+ const status = error.status;
451
+ const code = error.code;
452
+ if (this.isRegistrationRefusal(error)) {
453
+ this.registeredGeneration = 0;
454
+ return;
455
+ }
456
+ if (typeof status === 'number' &&
457
+ (status === 400 ||
458
+ status === 403 ||
459
+ status === 409 ||
460
+ (status === 404 && INSTANCE_SCOPED_REFUSALS.has(String(code))))) {
461
+ if (INSTANCE_SCOPED_REFUSALS.has(String(code))) {
462
+ state.instanceRefusals = (state.instanceRefusals ?? 0) + 1;
463
+ const entry = state.pending.find((p) => p.eventId === eventId);
464
+ if (entry?.held ||
465
+ state.instanceRefusals > INSTANCE_REFUSAL_DROP_LIMIT) {
466
+ if (!entry?.held) {
467
+ state.pending = state.pending.map((p) => p.eventId === eventId ? { ...p, held: true } : p);
468
+ this.persist();
469
+ }
470
+ // Log only on the transition: a stalled adapter re-probes the held
471
+ // claim every tick, and re-emitting the line would drown the log.
472
+ if (!this.instanceStalled) {
473
+ this.instanceStalled = true;
474
+ this.log(`Managed WeCom stopped admitting: every message is refused with ${status} ${String(code)}; check the instance's --workspace and --actor flags.`);
475
+ }
476
+ return;
477
+ }
478
+ }
479
+ this.log(`Managed WeCom admission of ${eventId} was refused (${status}); the message is skipped.`);
480
+ state.pending = state.pending.filter((p) => p.eventId !== eventId);
481
+ state.recent = [...state.recent, eventId].slice(-RECENT_LIMIT);
482
+ this.liftStallWhenNothingHeld(true);
483
+ this.persist();
484
+ return;
485
+ }
486
+ // A lost answer or a transient refusal: the claim, with its persisted
487
+ // event, stays in pending so the next tick re-drives the identical
488
+ // event, never a rebuilt one.
489
+ return;
490
+ }
491
+ // Success path — outside the control-plane classifier so a store failure
492
+ // here is handled as a store failure, never swallowed as a transient
493
+ // refusal that leaves memory settled while disk still holds the claim.
494
+ const wasHeld = state.pending.some((entry) => entry.eventId === eventId && entry.held === true);
495
+ state.pending = state.pending.filter((entry) => entry.eventId !== eventId);
496
+ state.recent = [...state.recent, eventId].slice(-RECENT_LIMIT);
497
+ const streakReset = !admitted.replayed && wasHeld;
498
+ if (streakReset) {
499
+ state.instanceRefusals = 0;
500
+ }
501
+ // Lift (and log) the stall when the last held claim leaves — including a
502
+ // fresh held admission, so recovery is visible, not silent. The resume line
503
+ // states the streak's actual fate: a fresh admission just reset it.
504
+ this.liftStallWhenNothingHeld(!streakReset);
505
+ try {
506
+ this.persist();
507
+ }
508
+ catch (error) {
509
+ this.log(`Managed WeCom could not persist settled claim ${eventId}: ${String(error)}`);
510
+ throw error;
511
+ }
512
+ }
513
+ /**
514
+ * The stall exists to be lifted by the held claim's probe: when the last
515
+ * held claim leaves no probe remains, and a flag kept armed would gate every
516
+ * later tick. Whether the refusal streak survives depends on HOW the last
517
+ * held claim left: a fresh (non-replayed) admission proves the binding and
518
+ * resets the streak (submit() clears instanceRefusals before calling here);
519
+ * a per-message verdict drop, a policy drop, or a replayed answer leaves the
520
+ * streak standing, so the next instance-scoped refusal re-holds without a new
521
+ * first-occurrence drop. The caller passes which case it is so the resume line
522
+ * states the streak's actual fate rather than always claiming it stands.
523
+ */
524
+ liftStallWhenNothingHeld(streakSurvived) {
525
+ if (this.instanceStalled &&
526
+ !this.state.pending.some((entry) => entry.held === true)) {
527
+ this.instanceStalled = false;
528
+ this.log(streakSurvived
529
+ ? 'Managed WeCom admission resumed; no claim remains held, and the refusal streak still stands for the next instance-scoped refusal.'
530
+ : "Managed WeCom admission resumed; no claim remains held, and the held claim's fresh admission proved the binding, so the refusal streak is reset.");
531
+ }
532
+ }
533
+ async resubmitPending() {
534
+ const state = this.state;
535
+ if (!state)
536
+ return;
537
+ // Probe held claims first: the stall lifts only on a held claim's fresh
538
+ // admission, and push order lets an earlier claim whose answer never
539
+ // comes shadow the one probe per tick — wedging admission across
540
+ // restarts. The sort is stable: unheld claims keep their push order.
541
+ const ordered = [...state.pending].sort((a, b) => Number(b.held === true) - Number(a.held === true));
542
+ for (const entry of ordered) {
543
+ if (!this.running)
544
+ return;
545
+ if (!this.senderAllowed(entry.event.senderId)) {
546
+ // The policy moved on since the claim: the persisted event drops
547
+ // visibly rather than drive a Session the current policy forbids.
548
+ this.log(`Managed WeCom event ${entry.eventId} is refused by the current sender policy; its claim drops.`);
549
+ state.pending = state.pending.filter((p) => p.eventId !== entry.eventId);
550
+ this.liftStallWhenNothingHeld(true);
551
+ this.persist();
552
+ continue;
553
+ }
554
+ await this.submit(entry.eventId, entry.event);
555
+ if (this.registeredGeneration === 0 || this.instanceStalled)
556
+ return;
557
+ }
558
+ }
559
+ isRegistrationRefusal(error) {
560
+ const status = error.status;
561
+ const code = error.code;
562
+ return ((status === 404 && String(code) === CHANNEL_NOT_FOUND) ||
563
+ (status === 409 &&
564
+ (code === 'channel_generation_unregistered' ||
565
+ code === 'channel_disconnected')));
566
+ }
567
+ async ensureRegistered(state) {
568
+ if (this.registeredGeneration === state.generation)
569
+ return;
570
+ try {
571
+ await this.controlPlane.register({
572
+ platform: 'wecom',
573
+ accountId: this.settings.botId,
574
+ accountGeneration: state.generation,
575
+ policy: this.policy,
576
+ });
577
+ this.registeredGeneration = state.generation;
578
+ this.loggedRegistrationFailure = false;
579
+ }
580
+ catch (error) {
581
+ this.registeredGeneration = 0;
582
+ // Mark the failure so runLoop latches its diagnostic instead of logging
583
+ // one raw line per poll interval for as long as registration is broken.
584
+ if (error && typeof error === 'object') {
585
+ error.registrationFailure = true;
586
+ }
587
+ throw error;
588
+ }
589
+ }
590
+ async pullOutbox() {
591
+ // Guard before the claim, not in the per-delivery loop: the claim itself
592
+ // moves up to CLAIM_BATCH deliveries to sending server-side, so a stop that
593
+ // lands mid-tick must not claim a batch it would then abandon to settle
594
+ // unknown. The DingTalk reference guards the phase the same way.
595
+ if (!this.running || !this.state)
596
+ return;
597
+ // A transient disconnect (reconnect backoff) leaves the adapter running but
598
+ // unable to send. Pause the claim phase too: claiming now would move
599
+ // deliveries to sending server-side only to settle them unknown, taking
600
+ // them out of automatic delivery while the socket heals.
601
+ if (!this.deps.isConnected())
602
+ return;
603
+ let claimed;
604
+ try {
605
+ claimed = await this.controlPlane.claimDeliveries(CLAIM_BATCH);
606
+ }
607
+ catch (error) {
608
+ if (this.isRegistrationRefusal(error)) {
609
+ this.registeredGeneration = 0;
610
+ return;
611
+ }
612
+ throw error;
613
+ }
614
+ for (const delivery of claimed) {
615
+ if (!this.running)
616
+ return;
617
+ await this.send(delivery);
618
+ }
619
+ }
620
+ async send(delivery) {
621
+ const state = this.state;
622
+ const context = delivery.replyContext;
623
+ const chatId = context?.chatId;
624
+ if (!chatId || !this.senderAllowed(context?.senderId ?? '')) {
625
+ // One delivery's unreportable rejection receipt must never abort the
626
+ // claimed batch: the deliveries behind it were already moved to sending
627
+ // server-side and would settle unknown (lost) if the tick escaped here.
628
+ // The rejection itself stays unreported — the control plane's lease
629
+ // reconciliation settles that one delivery — while the rest of the batch
630
+ // still sends.
631
+ try {
632
+ await this.controlPlane.receipt(delivery.deliveryId, {
633
+ outcome: 'rejected',
634
+ });
635
+ }
636
+ catch (error) {
637
+ if (this.isRegistrationRefusal(error)) {
638
+ this.registeredGeneration = 0;
639
+ return;
640
+ }
641
+ this.log(`Managed WeCom rejection receipt for ${delivery.deliveryId} could not be reported (${String(error)}); the rest of the batch still sends.`);
642
+ }
643
+ return;
644
+ }
645
+ for (const segment of delivery.segments) {
646
+ if (!this.running)
647
+ return;
648
+ const messageId = randomUUID();
649
+ const previousOutbound = state.outbound;
650
+ state.outbound = [
651
+ ...state.outbound,
652
+ {
653
+ deliveryId: delivery.deliveryId,
654
+ ordinal: segment.ordinal,
655
+ messageId,
656
+ },
657
+ ].slice(-MANAGED_OUTBOUND_LIMIT);
658
+ try {
659
+ this.persist();
660
+ }
661
+ catch (error) {
662
+ // The ledger entry is the double-send guard: without it on disk, a
663
+ // crash after the send would re-send on restart. Roll back and abandon
664
+ // this delivery before the side effect; the lease reconciler settles
665
+ // it unknown. The rest of the claimed batch is still attempted.
666
+ state.outbound = previousOutbound;
667
+ this.log(`Managed WeCom could not persist the outbound ledger for ${delivery.deliveryId}: ${String(error)}; the send is abandoned and the lease reconciler settles it.`);
668
+ return;
669
+ }
670
+ let outcome;
671
+ try {
672
+ await this.deps.sendMessage(chatId, segment.text);
673
+ outcome = {
674
+ outcome: 'accepted',
675
+ ordinal: segment.ordinal,
676
+ providerMessageId: messageId,
677
+ acceptedAt: (this.deps.now ?? Date.now)(),
678
+ };
679
+ }
680
+ catch {
681
+ // The aibot send path has no verified errcode retryability table, so
682
+ // every send failure — socket failure, ack timeout, queue overflow or
683
+ // a non-zero-errcode receipt frame — classifies as unknown: re-drivable,
684
+ // never a claimed definitive refusal that could settle a rate-limited
685
+ // segment's whole delivery rejected. A verified errcode table is a
686
+ // follow-up (design decision 4).
687
+ outcome = { outcome: 'unknown' };
688
+ }
689
+ const entry = state.outbound.find((candidate) => candidate.deliveryId === delivery.deliveryId &&
690
+ candidate.ordinal === segment.ordinal);
691
+ if (entry)
692
+ entry.receipt = outcome;
693
+ try {
694
+ this.persist();
695
+ }
696
+ catch (error) {
697
+ // The send already happened: report the outcome to the control plane
698
+ // even if the local write failed — the server-side settle is the
699
+ // durable record, and the orphan re-drive replays the in-memory
700
+ // receipt until the local write lands.
701
+ this.log(`Managed WeCom could not persist the receipt for ${delivery.deliveryId}: ${String(error)}; it is still reported and re-driven locally.`);
702
+ }
703
+ try {
704
+ await this.controlPlane.receipt(delivery.deliveryId, outcome);
705
+ }
706
+ catch (error) {
707
+ // One delivery's unreportable receipt never aborts the claimed
708
+ // batch: the entry stays outbound with the outcome persisted, so
709
+ // every later tick re-drives exactly this receipt — never the send.
710
+ // Its remaining segments wait behind the settled one, the same
711
+ // ordering the !accepted arm already owns.
712
+ this.log(`Managed WeCom receipt for ${delivery.deliveryId} could not be reported (${String(error)}); it re-drives on the next tick.`);
713
+ return;
714
+ }
715
+ state.outbound = state.outbound.filter((candidate) => !(candidate.deliveryId === delivery.deliveryId &&
716
+ candidate.ordinal === segment.ordinal));
717
+ try {
718
+ this.persist();
719
+ }
720
+ catch (error) {
721
+ // The receipt is already reported; disk keeps the entry, so the next
722
+ // tick's orphan re-drive replays the receipt and removes it again.
723
+ this.log(`Managed WeCom could not persist the settled segment of ${delivery.deliveryId}: ${String(error)}; the orphan re-drive removes it on the next tick.`);
724
+ }
725
+ if (outcome.outcome !== 'accepted')
726
+ return;
727
+ }
728
+ }
729
+ async reportOrphanedOutbound() {
730
+ const state = this.state;
731
+ if (!state)
732
+ return;
733
+ for (const entry of [...state.outbound]) {
734
+ if (!this.running)
735
+ return;
736
+ // A segment whose send produced a persisted receipt replays that
737
+ // receipt — the control plane may already hold it (its answer was
738
+ // lost) and settles idempotently. Only a segment whose send never
739
+ // produced an outcome settles unknown.
740
+ try {
741
+ await this.controlPlane.receipt(entry.deliveryId, entry.receipt ?? { outcome: 'unknown' });
742
+ }
743
+ catch (error) {
744
+ const status = error.status;
745
+ const code = error.code;
746
+ // The instance row is gone — keep the entry and reset the
747
+ // generation: the next tick re-registers first, then the re-driven
748
+ // receipt settles or meets the deterministic drop below.
749
+ if (this.isRegistrationRefusal(error)) {
750
+ this.registeredGeneration = 0;
751
+ this.log(`Managed WeCom receipt for ${entry.deliveryId} was refused as not registered (${String(status)} ${String(code)}); it re-drives after the next tick re-registers.`);
752
+ return;
753
+ }
754
+ // A transient (or status-less) refusal on ONE entry must not wedge
755
+ // every later delivery: reportOrphanedOutbound runs before pullOutbox,
756
+ // so rethrowing here would abort the tick before any reply is sent for
757
+ // as long as the fault lasts. Contain it PER ENTRY — keep this entry
758
+ // for re-drive and carry on to the next, so a fault scoped to one row
759
+ // never starves the receipts behind it. (Unlike the registration arm's
760
+ // `return`: while unregistered every later receipt would be refused
761
+ // identically, so stopping there is right; a transient row fault is not.)
762
+ if (!(status === 400 ||
763
+ status === 403 ||
764
+ status === 409 ||
765
+ (status === 404 && code === 'delivery_not_found'))) {
766
+ this.log(`Managed WeCom receipt for ${entry.deliveryId} could not be reported (${String(error)}); it re-drives on the next tick.`);
767
+ continue;
768
+ }
769
+ // A deterministic refusal never converges on re-drive, and a held
770
+ // entry runs before every outbox pull: it would stall every later
771
+ // delivery. Drop it visibly; the lease reconciler records the
772
+ // delivery unknown.
773
+ this.log(`Managed WeCom receipt for ${entry.deliveryId} was refused (${String(status)}); it is dropped.`);
774
+ }
775
+ state.outbound = state.outbound.filter((candidate) => candidate !== entry);
776
+ try {
777
+ this.persist();
778
+ }
779
+ catch (error) {
780
+ // Disk keeps the entry; the next tick replays the same idempotent
781
+ // receipt and retries the removal. Never abort the remaining orphans.
782
+ this.log(`Managed WeCom could not persist the orphan removal of ${entry.deliveryId}: ${String(error)}; it re-drives on the next tick.`);
783
+ }
784
+ }
785
+ }
786
+ persist() {
787
+ // Once the lock is compromised the state file belongs to another process;
788
+ // never rewrite it, even from an in-flight tick's post-await persist. A
789
+ // displaced adapter has likewise released its lock on the kick, so it must
790
+ // not write either — a restart of the entry may already own the file.
791
+ if (this.ownershipLost || this.displaced)
792
+ return;
793
+ if (this.state)
794
+ this.store.save(this.state);
795
+ }
796
+ stop() {
797
+ this.running = false;
798
+ this.abort?.abort();
799
+ try {
800
+ this.stream?.disconnect();
801
+ }
802
+ catch {
803
+ // The stream may already be closed; stopping is best-effort.
804
+ }
805
+ }
806
+ async release() {
807
+ const releaseLock = this.releaseLock;
808
+ this.releaseLock = undefined;
809
+ if (releaseLock)
810
+ await releaseLock().catch(() => undefined);
811
+ }
812
+ }
813
+ function str(value) {
814
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
815
+ }
816
+ function getRecord(value, key) {
817
+ const entry = value[key];
818
+ return entry && typeof entry === 'object' && !Array.isArray(entry)
819
+ ? entry
820
+ : undefined;
821
+ }
822
+ function extractText(parsed) {
823
+ const msgtype = str(parsed['msgtype']);
824
+ if (msgtype && msgtype !== 'text')
825
+ return undefined;
826
+ const text = getRecord(parsed, 'text');
827
+ const content = text ? str(text['content']) : undefined;
828
+ return content;
829
+ }
830
+ //# sourceMappingURL=managed-wecom-adapter.js.map