@qwen-code/channel-dingtalk 0.27.4 → 0.28.0-nightly.20261118.d9ac287c9f

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,866 @@
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_DINGTALK_PENDING_LIMIT, ManagedDingtalkStateStore, RECENT_LIMIT, WEBHOOK_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
+ // (#17396 R1-3).
15
+ const MIN_POLL_INTERVAL = 250;
16
+ const MAX_POLL_INTERVAL = 2_147_483_647;
17
+ const INSTANCE_SCOPED_REFUSALS = new Set([
18
+ 'workspace_not_found',
19
+ 'workspace_forbidden',
20
+ 'actor_scope_mismatch',
21
+ 'workspace_unavailable',
22
+ ]);
23
+ const INSTANCE_REFUSAL_DROP_LIMIT = 1;
24
+ const CHANNEL_NOT_FOUND = 'channel_not_found';
25
+ export function dingtalkSettings(config) {
26
+ const clientId = config['clientId'];
27
+ const clientSecret = config['clientSecret'];
28
+ if (!validCredential(clientId))
29
+ throw new Error('DingTalk channel requires a clientId.');
30
+ if (!validCredential(clientSecret))
31
+ throw new Error('DingTalk channel requires a clientSecret.');
32
+ const rawInterval = config['pollInterval'];
33
+ const pollInterval = Number(rawInterval ?? DEFAULT_POLL_INTERVAL);
34
+ const intervalAccepted = Number.isSafeInteger(pollInterval) &&
35
+ pollInterval >= MIN_POLL_INTERVAL &&
36
+ pollInterval <= MAX_POLL_INTERVAL;
37
+ return {
38
+ clientId: clientId.trim(),
39
+ clientSecret: clientSecret.trim(),
40
+ pollInterval: intervalAccepted ? pollInterval : DEFAULT_POLL_INTERVAL,
41
+ pollIntervalRewritten: rawInterval !== undefined && !intervalAccepted,
42
+ };
43
+ }
44
+ // Mirror the email credential rule: a copy-paste trailing newline or an
45
+ // embedded CR/LF/NUL must be rejected, not passed through to the token
46
+ // exchange where it surfaces as an auth error pointing at the credential.
47
+ function validCredential(value) {
48
+ return typeof value === 'string' && !!value.trim() && !/[\r\n\0]/.test(value);
49
+ }
50
+ export class ManagedDingtalkAdapter {
51
+ settings;
52
+ policy;
53
+ store;
54
+ controlPlane;
55
+ deps;
56
+ log;
57
+ pollLoop;
58
+ state;
59
+ stream;
60
+ releaseLock;
61
+ running = false;
62
+ ownershipLost = false;
63
+ loop;
64
+ abort;
65
+ registeredGeneration;
66
+ instanceStalled = false;
67
+ loggedNoClaimSlot = false;
68
+ loggedAcceptFailure = false;
69
+ loggedNoReplyTarget = false;
70
+ loggedSettleFailure = false;
71
+ constructor(options) {
72
+ this.settings = dingtalkSettings(options.config);
73
+ const senderPolicy = resolvePrivatePolicy(options.config);
74
+ if (senderPolicy === 'pairing') {
75
+ // The managed policy shape has no pairing arm; silently coercing it to
76
+ // an empty allowlist would skip every message while reporting running.
77
+ throw new Error('The managed DingTalk path does not support privatePolicy "pairing"; use allowedUsers, open, or disabled.');
78
+ }
79
+ const allowed = options.config['allowedUsers'];
80
+ this.policy = {
81
+ adapter: 'dingtalk',
82
+ senderPolicy: senderPolicy === 'disabled' || senderPolicy === 'open'
83
+ ? senderPolicy
84
+ : 'allowlist',
85
+ allowedSenders: Array.isArray(allowed)
86
+ ? allowed.filter((entry) => typeof entry === 'string')
87
+ : [],
88
+ dispatchMode: options.config['dispatchMode'] === 'steer' ? 'steer' : 'followup',
89
+ };
90
+ this.store = new ManagedDingtalkStateStore(options.name, options.cwd, this.settings.clientId);
91
+ this.controlPlane = options.controlPlane;
92
+ this.deps = options.deps;
93
+ this.log =
94
+ options.deps.log ?? ((line) => process.stderr.write(`${line}\n`));
95
+ // The clamp in dingtalkSettings is silent; say so when it reports a
96
+ // rewrite, or an operator tuning the poll rate sees no effect and no
97
+ // explanation (#17173 R12). The decision and the bounds come from the
98
+ // settings clamp itself, never re-derived here (#17396 R1-3).
99
+ if (this.settings.pollIntervalRewritten) {
100
+ this.log(`Managed DingTalk pollInterval ${String(options.config['pollInterval'])} is not an integer in [${MIN_POLL_INTERVAL}, ${MAX_POLL_INTERVAL}]; using ${this.settings.pollInterval} ms.`);
101
+ }
102
+ this.pollLoop = options.pollLoop ?? true;
103
+ }
104
+ get stateFile() {
105
+ return this.store.file;
106
+ }
107
+ get generation() {
108
+ return this.state?.generation;
109
+ }
110
+ async connect() {
111
+ if (this.running || this.releaseLock)
112
+ throw new Error('Managed DingTalk adapter is already connected.');
113
+ try {
114
+ this.releaseLock = await this.deps.lock(this.store.directory, () => {
115
+ // A reaped stale lock means a second owner won the state directory.
116
+ // Stop, and stop persisting: an in-flight tick or the shutdown drain
117
+ // must not rewrite the file the new owner now holds.
118
+ this.ownershipLost = true;
119
+ this.log('Managed DingTalk state ownership was lost to another process; adapter stopped.');
120
+ this.stop();
121
+ });
122
+ }
123
+ catch {
124
+ throw new Error('DingTalk state is owned by another process; managed adapter not started.');
125
+ }
126
+ try {
127
+ this.state = this.store.load() ?? {
128
+ version: 1,
129
+ generation: 1,
130
+ pending: [],
131
+ outbound: [],
132
+ recent: [],
133
+ webhooks: {},
134
+ };
135
+ if (this.state.pending.some((entry) => entry.held)) {
136
+ this.instanceStalled = true;
137
+ this.state.instanceRefusals = Math.max(this.state.instanceRefusals ?? 0, INSTANCE_REFUSAL_DROP_LIMIT + 1);
138
+ }
139
+ this.persist();
140
+ this.abort = new AbortController();
141
+ this.running = true;
142
+ this.loggedNoClaimSlot = false;
143
+ this.loggedAcceptFailure = false;
144
+ this.loggedNoReplyTarget = false;
145
+ this.loggedSettleFailure = false;
146
+ this.registeredGeneration = undefined;
147
+ this.stream = this.deps.createStreamClient(this.settings, (messageId, data) => this.onMessage(messageId, data));
148
+ await this.stream.connect();
149
+ if (!this.running)
150
+ throw new Error('Managed DingTalk adapter stopped during connection.');
151
+ await this.ensureRegistered(this.state);
152
+ await this.reportOrphanedOutbound();
153
+ // A lock compromise can land during the awaits above (the update timer
154
+ // fires while register() is in flight). Re-check so connect() rejects
155
+ // rather than resolving a healthy-looking start for a stopped, deaf
156
+ // adapter the CLI would then park on.
157
+ if (!this.running || this.ownershipLost)
158
+ throw new Error('Managed DingTalk adapter stopped during connection.');
159
+ if (this.pollLoop)
160
+ this.loop = this.runLoop();
161
+ }
162
+ catch (error) {
163
+ this.stop();
164
+ // Frames acked between stream.connect() and a failed registration were
165
+ // already persisted as claims by onMessage, so a restart re-drives them;
166
+ // there is no in-memory inbox to drain.
167
+ await this.release();
168
+ throw error;
169
+ }
170
+ }
171
+ async disconnect() {
172
+ this.stop();
173
+ await this.loop;
174
+ // Accepted frames are already durable claims (onMessage persists before
175
+ // acking), so shutdown has no inbox to drain.
176
+ await this.controlPlane.disconnect().catch(() => undefined);
177
+ await this.release();
178
+ }
179
+ /** One admission re-drive and one outbound pull, for callers that drive it. */
180
+ async tick() {
181
+ await this.ensureRegistered(this.state);
182
+ await this.resubmitPending();
183
+ await this.reportOrphanedOutbound();
184
+ await this.pullOutbox();
185
+ }
186
+ // Returns whether the frame was durably accepted. Acceptance is the commit
187
+ // point: the caller acks SUCCESS only on true, and true is returned only
188
+ // after stageInbound has persisted the claim, so a hard kill in the window
189
+ // before the next tick cannot lose an acked frame — the provider never
190
+ // redelivers on this ack-once stream. A full claim table, a stall, or an
191
+ // unregistered instance leaves the frame unacked (LATER) for provider
192
+ // redelivery; a store.save() failure also returns false rather than letting
193
+ // the throw escape into the SDK callback.
194
+ onMessage(messageId, data) {
195
+ if (!this.running || this.ownershipLost)
196
+ return false;
197
+ if (this.instanceStalled ||
198
+ this.registeredGeneration === 0 ||
199
+ (this.state?.pending.length ?? 0) >= MANAGED_DINGTALK_PENDING_LIMIT) {
200
+ // Log only on the transition into the outage: during a stall every
201
+ // redelivery meets this gate, and a line per frame would drown the
202
+ // log (#17173 R12). The next accepted frame re-arms the line.
203
+ if (!this.loggedNoClaimSlot) {
204
+ this.loggedNoClaimSlot = true;
205
+ this.log(`Managed DingTalk has no durable claim slot; message ${messageId} is left unacked for redelivery.`);
206
+ }
207
+ return false;
208
+ }
209
+ try {
210
+ // Only a staged claim is an acceptance: a skipped frame also returns
211
+ // normally (it is acked), and must not re-arm the outage latches.
212
+ if (this.stageInbound({ messageId, data })) {
213
+ this.loggedNoClaimSlot = false;
214
+ this.loggedAcceptFailure = false;
215
+ this.loggedNoReplyTarget = false;
216
+ }
217
+ return true;
218
+ }
219
+ catch (error) {
220
+ // A failed save leaves the frame unacked (LATER); say why, or a disk
221
+ // outage reads as silent message loss (#17173 R10). Latched like the
222
+ // no-slot line: a persistent store failure redelivers every frame, and
223
+ // a line per redelivery would drown the log (#17396 R1-2).
224
+ if (!this.loggedAcceptFailure) {
225
+ this.loggedAcceptFailure = true;
226
+ this.log(`Managed DingTalk could not durably accept message ${messageId}: ${persistErrorText(error)}; it is left unacked for redelivery.`);
227
+ }
228
+ return false;
229
+ }
230
+ }
231
+ async runLoop() {
232
+ try {
233
+ while (this.running) {
234
+ try {
235
+ await this.tick();
236
+ }
237
+ catch (error) {
238
+ this.log(`Managed DingTalk tick failed: ${String(error)}`);
239
+ }
240
+ if (this.running)
241
+ await delay(this.settings.pollInterval, undefined, {
242
+ signal: this.abort.signal,
243
+ }).catch(() => { });
244
+ }
245
+ }
246
+ finally {
247
+ this.stop();
248
+ }
249
+ }
250
+ senderAllowed(sender) {
251
+ switch (this.policy.senderPolicy) {
252
+ case 'disabled':
253
+ return false;
254
+ case 'open':
255
+ return true;
256
+ default:
257
+ return this.policy.allowedSenders.includes(sender);
258
+ }
259
+ }
260
+ // Synchronously stage the frame as a durable claim. Acceptance is the commit
261
+ // point: onMessage calls this before acking SUCCESS, so the claim is on disk
262
+ // before the provider is told the frame was received and a hard kill in the
263
+ // window before the next tick cannot lose it. The async submit() is left to
264
+ // the tick (resubmitPending). A store.save() failure throws and onMessage
265
+ // returns false (LATER) so the provider redelivers. Returns whether a claim
266
+ // was staged: a skipped frame is acked too, but is not an acceptance.
267
+ stageInbound(item) {
268
+ const state = this.state;
269
+ let parsed;
270
+ try {
271
+ parsed = JSON.parse(item.data);
272
+ }
273
+ catch {
274
+ this.log(`Managed DingTalk message ${item.messageId} is not JSON; skipped.`);
275
+ return false;
276
+ }
277
+ const conversationId = str(parsed['conversationId']);
278
+ const sessionWebhook = str(parsed['sessionWebhook']);
279
+ const senderId = str(parsed['senderStaffId']) ?? str(parsed['senderId']) ?? '';
280
+ const msgId = str(parsed['msgId']) ?? item.messageId;
281
+ const conversationType = str(parsed['conversationType']);
282
+ const rawText = extractText(parsed);
283
+ const text = rawText ? fitInboundText(rawText) : rawText;
284
+ const eventId = `dingtalk:${msgId}`;
285
+ const skip = () => {
286
+ state.recent = [...state.recent, eventId].slice(-RECENT_LIMIT);
287
+ this.persist();
288
+ };
289
+ // The managed path serves private chats under the private-chat policy.
290
+ // A group frame would be answered into the group webhook for every member
291
+ // to read, so drop it until an explicit group policy exists (Legacy's
292
+ // GroupGate defaults to disabled for the same reason). Drop it before the
293
+ // webhook cache write so group traffic never spends the cache budget the
294
+ // admission gate depends on (#17173 R3-2).
295
+ if (conversationType === '2') {
296
+ this.log(`Managed DingTalk group message ${item.messageId} is skipped; the managed path serves private chats only.`);
297
+ skip();
298
+ return false;
299
+ }
300
+ if (!conversationId || !senderId || !text) {
301
+ // A non-text or unroutable frame is acked and dropped; leave a line so
302
+ // the drop is visible instead of silent (#17173 R12). Name the actual
303
+ // cause: a non-text frame carrying both ids is the common trigger and
304
+ // must not read as a malformed frame (#17396 R1-4). Only the messageId
305
+ // and the field/msgtype are logged — never the text or the webhook.
306
+ const msgtype = str(parsed['msgtype']);
307
+ const missing = [
308
+ !conversationId ? 'conversationId' : undefined,
309
+ !senderId ? 'senderId' : undefined,
310
+ !text ? 'text' : undefined,
311
+ ].filter((field) => field !== undefined);
312
+ const reason = missing.length === 1 &&
313
+ missing[0] === 'text' &&
314
+ msgtype &&
315
+ msgtype !== 'text'
316
+ ? `is not a text frame (msgtype ${msgtype})`
317
+ : `is missing ${missing.join(', ')}`;
318
+ this.log(`Managed DingTalk message ${item.messageId} ${reason}; skipped.`);
319
+ skip();
320
+ return false;
321
+ }
322
+ // Evaluate the allowlist before touching the cache: a sender the policy
323
+ // refuses must not spend the webhook-cache budget admission depends on
324
+ // (#17173 R4-2).
325
+ if (!this.senderAllowed(senderId)) {
326
+ this.log(`Managed DingTalk sender ${senderId} is not allowed; message skipped.`);
327
+ skip();
328
+ return false;
329
+ }
330
+ // Remember the newest webhook for the conversation: the reply may arrive
331
+ // after this webhook's own message is long gone. Only private frames from
332
+ // allowed senders reach this point, so neither group traffic nor refused
333
+ // senders evict a private conversation (#17173 R3-2, R4-2).
334
+ if (sessionWebhook) {
335
+ this.touchWebhook(conversationId, sessionWebhook);
336
+ }
337
+ // A frame with no usable reply target — neither a committed sessionWebhook
338
+ // nor one cached for the conversation — can never be answered; drop it at
339
+ // admission instead of spending a claim slot and control-plane work on a
340
+ // reply the send path would only reject (#17173 R1-32).
341
+ const cached = this.cachedWebhook(conversationId);
342
+ if (cached === undefined) {
343
+ // Eviction of a definitively refused webhook makes this a routine
344
+ // path; leave a line so the acked drop is diagnosable (#17396 R1-1).
345
+ // Latched: a dead cache entry lands a whole burst here, and the gate
346
+ // runs before the recent-window dedupe. Only ids are logged — the
347
+ // webhook is a bearer capability.
348
+ if (!this.loggedNoReplyTarget) {
349
+ this.loggedNoReplyTarget = true;
350
+ this.log(`Managed DingTalk message ${item.messageId} has no sessionWebhook and none cached for conversation ${conversationId}; skipped.`);
351
+ }
352
+ skip();
353
+ return false;
354
+ }
355
+ // A webhook-less frame admitted on the cached entry still counts as seen:
356
+ // refresh its recency so the busiest conversation is not the one evicted
357
+ // (#17173 R3-4).
358
+ if (!sessionWebhook) {
359
+ this.touchWebhook(conversationId, cached);
360
+ }
361
+ // Dedupe against both the settled window and the in-flight claims: a frame
362
+ // redelivered while its claim is still pending (its admission answer was
363
+ // lost) must not be staged a second time before recent is updated.
364
+ if (state.recent.includes(eventId) ||
365
+ state.pending.some((entry) => entry.eventId === eventId)) {
366
+ return false;
367
+ }
368
+ const event = {
369
+ accountGeneration: state.generation,
370
+ platformEventId: eventId,
371
+ semanticRevision: 1,
372
+ scope: {
373
+ kind: 'chat_thread',
374
+ senderId: null,
375
+ chatId: conversationId,
376
+ threadId: conversationId,
377
+ },
378
+ senderId,
379
+ chatId: conversationId,
380
+ threadId: conversationId,
381
+ subject: null,
382
+ text,
383
+ attachments: [],
384
+ replyContext: {
385
+ conversationId,
386
+ // Snapshot the reply target at admission: a frame admitted on the
387
+ // cached webhook must not lose its reply if the cache entry is evicted
388
+ // before the answer is claimed. send() still prefers the live cache, so
389
+ // a fresher webhook keeps winning (#17173 R3-3).
390
+ sessionWebhook: sessionWebhook ?? cached,
391
+ senderId,
392
+ robotCode: this.settings.clientId,
393
+ },
394
+ };
395
+ const previousPending = state.pending;
396
+ state.pending = [...state.pending, { eventId, event }].slice(-MANAGED_DINGTALK_PENDING_LIMIT);
397
+ try {
398
+ this.persist();
399
+ }
400
+ catch (error) {
401
+ // A failed save must not leave the claim in memory: the dedupe arm would
402
+ // then ack a redelivery for a claim the store never accepted, and this
403
+ // ack-once stream never redelivers a SUCCESS-acked frame. Roll back so the
404
+ // redelivery re-stages; onMessage turns the throw into LATER.
405
+ state.pending = previousPending;
406
+ throw error;
407
+ }
408
+ return true;
409
+ }
410
+ async submit(eventId, event) {
411
+ const state = this.state;
412
+ try {
413
+ const admitted = await this.controlPlane.submitInbound(event);
414
+ const wasHeld = state.pending.some((entry) => entry.eventId === eventId && entry.held === true);
415
+ // The streak reset and the settle share ONE write: a split would let a
416
+ // crash (or a failed second write) leave disk with pending:[] and the
417
+ // pre-reset streak, so the first transient refusal after a restart
418
+ // would immediately re-hold instead of paying the first-occurrence
419
+ // drop (#17432 R1-2).
420
+ const previousPending = state.pending;
421
+ const previousRecent = state.recent;
422
+ const previousRefusals = state.instanceRefusals;
423
+ const previousStalled = this.instanceStalled;
424
+ state.pending = state.pending.filter((entry) => entry.eventId !== eventId);
425
+ state.recent = [...state.recent, eventId].slice(-RECENT_LIMIT);
426
+ // The stall logic reads the POST-settle pending: the lift arm must not
427
+ // see the held claim this settle is removing.
428
+ if (!admitted.replayed && wasHeld) {
429
+ state.instanceRefusals = 0;
430
+ this.instanceStalled = false;
431
+ }
432
+ else {
433
+ this.liftStallWhenNothingHeld();
434
+ }
435
+ try {
436
+ this.persist();
437
+ this.loggedSettleFailure = false;
438
+ }
439
+ catch (error) {
440
+ // The admission answer arrived but the settle never reached disk.
441
+ // Roll back everything the settle touched so the next tick re-drives
442
+ // the identical event into the idempotent replayed answer; a
443
+ // half-settled memory state would drop the claim from this process's
444
+ // re-drive while disk still holds it (#17173 R10).
445
+ state.pending = previousPending;
446
+ state.recent = previousRecent;
447
+ state.instanceRefusals = previousRefusals;
448
+ this.instanceStalled = previousStalled;
449
+ // Latched like the other outage lines: the rollback keeps the claim
450
+ // pending, so every tick re-drives it and an unlatched line would
451
+ // re-log per claim per tick (#17432 R1-1).
452
+ if (!this.loggedSettleFailure) {
453
+ this.loggedSettleFailure = true;
454
+ this.log(`Managed DingTalk could not persist the admission of ${eventId}: ${persistErrorText(error)}; it re-drives on the next tick.`);
455
+ }
456
+ return;
457
+ }
458
+ }
459
+ catch (error) {
460
+ const status = error.status;
461
+ const code = error.code;
462
+ if (this.isRegistrationRefusal(error)) {
463
+ this.registeredGeneration = 0;
464
+ return;
465
+ }
466
+ if (typeof status === 'number' &&
467
+ (status === 400 ||
468
+ status === 403 ||
469
+ status === 409 ||
470
+ (status === 404 && INSTANCE_SCOPED_REFUSALS.has(String(code))))) {
471
+ if (INSTANCE_SCOPED_REFUSALS.has(String(code))) {
472
+ state.instanceRefusals = (state.instanceRefusals ?? 0) + 1;
473
+ const entry = state.pending.find((p) => p.eventId === eventId);
474
+ if (entry?.held ||
475
+ state.instanceRefusals > INSTANCE_REFUSAL_DROP_LIMIT) {
476
+ if (!entry?.held) {
477
+ state.pending = state.pending.map((p) => p.eventId === eventId ? { ...p, held: true } : p);
478
+ try {
479
+ this.persist();
480
+ }
481
+ catch (error) {
482
+ // The hold stays armed in memory for this process; a restart
483
+ // before the write lands re-arms it after one refusal, which
484
+ // is the bounded first-occurrence tradeoff, never a loss.
485
+ this.log(`Managed DingTalk could not persist the held claim ${eventId}: ${persistErrorText(error)}; the stall stays armed in memory.`);
486
+ }
487
+ }
488
+ // Log only on the transition: a stalled adapter re-probes the held
489
+ // claim every tick, and re-emitting the line would drown the log.
490
+ if (!this.instanceStalled) {
491
+ this.instanceStalled = true;
492
+ this.log(`Managed DingTalk stopped admitting: every message is refused with ${status} ${String(code)}; check the instance's --workspace and --actor flags.`);
493
+ }
494
+ return;
495
+ }
496
+ }
497
+ this.log(`Managed DingTalk admission of ${eventId} was refused (${status}); the message is skipped.`);
498
+ state.pending = state.pending.filter((p) => p.eventId !== eventId);
499
+ state.recent = [...state.recent, eventId].slice(-RECENT_LIMIT);
500
+ this.liftStallWhenNothingHeld();
501
+ try {
502
+ this.persist();
503
+ }
504
+ catch (error) {
505
+ // The drop is already applied in memory; disk keeps the claim, so a
506
+ // restart re-drives it into the same deterministic refusal and drops
507
+ // it again. Never abort the batch over the failed write.
508
+ this.log(`Managed DingTalk could not persist the refused admission of ${eventId}: ${persistErrorText(error)}; a restart re-drives it into the same refusal.`);
509
+ }
510
+ return;
511
+ }
512
+ // A lost answer or a transient refusal: the claim, with its persisted
513
+ // event, stays in pending so the next tick re-drives the identical
514
+ // event, never a rebuilt one.
515
+ }
516
+ }
517
+ /**
518
+ * The stall exists to be lifted by the held claim's probe: when the last
519
+ * held claim leaves without proving the binding — dropped on a per-message
520
+ * verdict or settled by a replayed answer — no probe remains, and a flag
521
+ * kept armed would gate every later tick. The refusal streak is NOT reset
522
+ * here: only the held claim's fresh admission proves the binding, so the
523
+ * next instance-scoped refusal re-holds without a new first-occurrence drop.
524
+ */
525
+ liftStallWhenNothingHeld() {
526
+ if (this.instanceStalled &&
527
+ !this.state.pending.some((entry) => entry.held === true)) {
528
+ this.instanceStalled = false;
529
+ this.log('Managed DingTalk admission resumed; no claim remains held, and the refusal streak still stands for the next instance-scoped refusal.');
530
+ }
531
+ }
532
+ async resubmitPending() {
533
+ const state = this.state;
534
+ if (!state)
535
+ return;
536
+ // Probe held claims first: the stall lifts only on a held claim's fresh
537
+ // admission, and push order lets an earlier claim whose answer never
538
+ // comes shadow the one probe per tick — wedging admission across
539
+ // restarts. The sort is stable: unheld claims keep their push order.
540
+ const ordered = [...state.pending].sort((a, b) => Number(b.held === true) - Number(a.held === true));
541
+ for (const entry of ordered) {
542
+ if (!this.running)
543
+ return;
544
+ if (!this.senderAllowed(entry.event.senderId)) {
545
+ // The policy moved on since the claim: the persisted event drops
546
+ // visibly rather than drive a Session the current policy forbids.
547
+ this.log(`Managed DingTalk event ${entry.eventId} is refused by the current sender policy; its claim drops.`);
548
+ state.pending = state.pending.filter((p) => p.eventId !== entry.eventId);
549
+ this.liftStallWhenNothingHeld();
550
+ try {
551
+ this.persist();
552
+ }
553
+ catch (error) {
554
+ // Same shape as the refusal drop: memory applied, disk keeps the
555
+ // claim, a restart re-drives it into the same policy refusal.
556
+ this.log(`Managed DingTalk could not persist the policy drop of ${entry.eventId}: ${persistErrorText(error)}; a restart re-drives it into the same refusal.`);
557
+ }
558
+ continue;
559
+ }
560
+ await this.submit(entry.eventId, entry.event);
561
+ if (this.registeredGeneration === 0 || this.instanceStalled)
562
+ return;
563
+ }
564
+ }
565
+ isRegistrationRefusal(error) {
566
+ const status = error.status;
567
+ const code = error.code;
568
+ return ((status === 404 && String(code) === CHANNEL_NOT_FOUND) ||
569
+ (status === 409 &&
570
+ (code === 'channel_generation_unregistered' ||
571
+ code === 'channel_disconnected')));
572
+ }
573
+ async ensureRegistered(state) {
574
+ if (this.registeredGeneration === state.generation)
575
+ return;
576
+ try {
577
+ await this.controlPlane.register({
578
+ platform: 'dingtalk',
579
+ accountId: this.settings.clientId,
580
+ accountGeneration: state.generation,
581
+ policy: this.policy,
582
+ });
583
+ this.registeredGeneration = state.generation;
584
+ }
585
+ catch (error) {
586
+ this.registeredGeneration = 0;
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 email reference guards the phase the same way.
595
+ if (!this.running || !this.state)
596
+ return;
597
+ let claimed;
598
+ try {
599
+ claimed = await this.controlPlane.claimDeliveries(CLAIM_BATCH);
600
+ }
601
+ catch (error) {
602
+ if (this.isRegistrationRefusal(error)) {
603
+ this.registeredGeneration = 0;
604
+ return;
605
+ }
606
+ throw error;
607
+ }
608
+ for (const delivery of claimed) {
609
+ if (!this.running)
610
+ return;
611
+ await this.send(delivery);
612
+ }
613
+ }
614
+ /**
615
+ * The single own-key read of the webhook cache, shared by the admission
616
+ * gate and the send path so the two cannot drift (#17173 round 5).
617
+ * Own-key membership, not truthiness: a conversationId naming an
618
+ * Object.prototype member ('constructor', 'toString', ...) must not
619
+ * resolve the inherited value on an empty cache (#17173 R2-2). Cached
620
+ * values are non-empty by the state validator, so undefined ⇔ absent.
621
+ */
622
+ cachedWebhook(conversationId) {
623
+ const webhooks = this.state.webhooks;
624
+ return Object.hasOwn(webhooks, conversationId)
625
+ ? webhooks[conversationId]
626
+ : undefined;
627
+ }
628
+ /**
629
+ * Record a conversation's webhook as the most recently seen. Reinsert at the
630
+ * end so the overflow evicts the least-recently-seen key, not the
631
+ * first-inserted one (#17173 R1-20). defineProperty writes an own key even
632
+ * for '__proto__', which a plain assignment would silently discard through
633
+ * the inherited setter (#17173 R3-5).
634
+ */
635
+ touchWebhook(conversationId, value) {
636
+ const state = this.state;
637
+ delete state.webhooks[conversationId];
638
+ Object.defineProperty(state.webhooks, conversationId, {
639
+ value,
640
+ enumerable: true,
641
+ writable: true,
642
+ configurable: true,
643
+ });
644
+ const keys = Object.keys(state.webhooks);
645
+ if (keys.length > WEBHOOK_LIMIT)
646
+ delete state.webhooks[keys[0]];
647
+ this.persist();
648
+ }
649
+ async send(delivery) {
650
+ const state = this.state;
651
+ const context = delivery.replyContext;
652
+ const conversationId = context?.conversationId;
653
+ const webhook = (conversationId ? this.cachedWebhook(conversationId) : undefined) ??
654
+ context?.sessionWebhook;
655
+ if (!conversationId ||
656
+ !webhook ||
657
+ !this.senderAllowed(context?.senderId ?? '')) {
658
+ // One delivery's unreportable rejection receipt must never abort the
659
+ // claimed batch: the deliveries behind it were already moved to sending
660
+ // server-side and would settle unknown (lost) if the tick escaped here.
661
+ // The rejection itself stays unreported — the control plane's lease
662
+ // reconciliation settles that one delivery — while the rest of the batch
663
+ // still sends.
664
+ try {
665
+ await this.controlPlane.receipt(delivery.deliveryId, {
666
+ outcome: 'rejected',
667
+ });
668
+ }
669
+ catch (error) {
670
+ if (this.isRegistrationRefusal(error)) {
671
+ this.registeredGeneration = 0;
672
+ return;
673
+ }
674
+ this.log(`Managed DingTalk rejection receipt for ${delivery.deliveryId} could not be reported (${String(error)}); the rest of the batch still sends.`);
675
+ }
676
+ return;
677
+ }
678
+ for (const segment of delivery.segments) {
679
+ if (!this.running)
680
+ return;
681
+ const messageId = randomUUID();
682
+ const previousOutbound = state.outbound;
683
+ state.outbound = [
684
+ ...state.outbound,
685
+ {
686
+ deliveryId: delivery.deliveryId,
687
+ ordinal: segment.ordinal,
688
+ messageId,
689
+ },
690
+ ].slice(-MANAGED_OUTBOUND_LIMIT);
691
+ try {
692
+ this.persist();
693
+ }
694
+ catch (error) {
695
+ // The ledger entry is the double-send guard: without it on disk, a
696
+ // crash after the webhook send would re-send on restart. Roll back
697
+ // and abandon this delivery before the side effect; the lease
698
+ // reconciler settles it unknown (#17173 R10).
699
+ state.outbound = previousOutbound;
700
+ this.log(`Managed DingTalk could not persist the outbound ledger for ${delivery.deliveryId}: ${persistErrorText(error)}; the send is abandoned and the lease reconciler settles it.`);
701
+ return;
702
+ }
703
+ let outcome;
704
+ try {
705
+ await this.deps.sendWebhook(webhook, segment.text);
706
+ outcome = {
707
+ outcome: 'accepted',
708
+ ordinal: segment.ordinal,
709
+ providerMessageId: messageId,
710
+ acceptedAt: (this.deps.now ?? Date.now)(),
711
+ };
712
+ }
713
+ catch (error) {
714
+ const definitive = error.definitive;
715
+ // A definitively refused webhook (expired/invalid) is dead: evict it
716
+ // so the admission gate stops admitting frames that can only be
717
+ // answered into a dead target — the next frame must re-commit a fresh
718
+ // webhook. Only evict the entry this send actually used; a fresher
719
+ // webhook committed mid-send stays (#17173 round 5). The receipt
720
+ // persist below carries the eviction to disk.
721
+ if (definitive &&
722
+ conversationId &&
723
+ this.cachedWebhook(conversationId) === webhook) {
724
+ delete state.webhooks[conversationId];
725
+ // The eviction is load-bearing for admission; make it visible.
726
+ // Only the conversation id is logged — the webhook is a bearer
727
+ // capability and the provider errmsg is not trusted text.
728
+ this.log(`Managed DingTalk evicted the cached webhook for conversation ${conversationId} after a definitive send refusal; the next frame must commit a fresh webhook.`);
729
+ }
730
+ outcome = definitive ? { outcome: 'rejected' } : { outcome: 'unknown' };
731
+ }
732
+ const entry = state.outbound.find((candidate) => candidate.deliveryId === delivery.deliveryId &&
733
+ candidate.ordinal === segment.ordinal);
734
+ if (entry)
735
+ entry.receipt = outcome;
736
+ try {
737
+ this.persist();
738
+ }
739
+ catch (error) {
740
+ // The send already happened: report the outcome to the control plane
741
+ // even if the local write failed — the server-side settle is the
742
+ // durable record, and the orphan re-drive replays the in-memory
743
+ // receipt until the local write lands (#17173 R10).
744
+ this.log(`Managed DingTalk could not persist the receipt for ${delivery.deliveryId}: ${persistErrorText(error)}; it is still reported and re-driven locally.`);
745
+ }
746
+ try {
747
+ await this.controlPlane.receipt(delivery.deliveryId, outcome);
748
+ }
749
+ catch (error) {
750
+ // One delivery's unreportable receipt never aborts the claimed
751
+ // batch: the entry stays outbound with the outcome persisted, so
752
+ // every later tick re-drives exactly this receipt — never the
753
+ // webhook send. Its remaining segments wait behind the settled
754
+ // one, the same ordering the !accepted arm already owns.
755
+ this.log(`Managed DingTalk receipt for ${delivery.deliveryId} could not be reported (${String(error)}); it re-drives on the next tick.`);
756
+ return;
757
+ }
758
+ state.outbound = state.outbound.filter((candidate) => !(candidate.deliveryId === delivery.deliveryId &&
759
+ candidate.ordinal === segment.ordinal));
760
+ try {
761
+ this.persist();
762
+ }
763
+ catch (error) {
764
+ // The receipt is already reported; disk keeps the entry, so the next
765
+ // tick's orphan re-drive replays the receipt and removes it again.
766
+ this.log(`Managed DingTalk could not persist the settled segment of ${delivery.deliveryId}: ${persistErrorText(error)}; the orphan re-drive removes it on the next tick.`);
767
+ }
768
+ if (outcome.outcome !== 'accepted')
769
+ return;
770
+ }
771
+ }
772
+ async reportOrphanedOutbound() {
773
+ const state = this.state;
774
+ if (!state)
775
+ return;
776
+ for (const entry of [...state.outbound]) {
777
+ if (!this.running)
778
+ return;
779
+ // A segment whose send produced a persisted receipt replays that
780
+ // receipt — the control plane may already hold it (its answer was
781
+ // lost) and settles idempotently. Only a segment whose send never
782
+ // produced an outcome settles unknown.
783
+ try {
784
+ await this.controlPlane.receipt(entry.deliveryId, entry.receipt ?? { outcome: 'unknown' });
785
+ }
786
+ catch (error) {
787
+ const status = error.status;
788
+ const code = error.code;
789
+ // The instance row is gone — keep the entry and reset the
790
+ // generation: the next tick re-registers first, then the re-driven
791
+ // receipt settles or meets the deterministic drop below.
792
+ if (this.isRegistrationRefusal(error)) {
793
+ this.registeredGeneration = 0;
794
+ this.log(`Managed DingTalk receipt for ${entry.deliveryId} was refused as not registered (${String(status)} ${String(code)}); it re-drives after the next tick re-registers.`);
795
+ return;
796
+ }
797
+ // A deterministic refusal never converges on re-drive, and a held
798
+ // entry runs before every outbox pull: it would stall every later
799
+ // delivery. Drop it visibly; the lease reconciler records the
800
+ // delivery unknown.
801
+ if (!(status === 400 ||
802
+ status === 403 ||
803
+ status === 409 ||
804
+ (status === 404 && code === 'delivery_not_found'))) {
805
+ throw error;
806
+ }
807
+ this.log(`Managed DingTalk receipt for ${entry.deliveryId} was refused (${String(status)}); it is dropped.`);
808
+ }
809
+ state.outbound = state.outbound.filter((candidate) => candidate !== entry);
810
+ try {
811
+ this.persist();
812
+ }
813
+ catch (error) {
814
+ // Disk keeps the entry; the next tick replays the same idempotent
815
+ // receipt and retries the removal. Never abort the remaining orphans.
816
+ this.log(`Managed DingTalk could not persist the orphan removal of ${entry.deliveryId}: ${persistErrorText(error)}; it re-drives on the next tick.`);
817
+ }
818
+ }
819
+ }
820
+ persist() {
821
+ // Once the lock is compromised the state file belongs to another process;
822
+ // never rewrite it, even from an in-flight tick's post-await persist.
823
+ if (this.ownershipLost)
824
+ return;
825
+ if (this.state)
826
+ this.store.save(this.state);
827
+ }
828
+ stop() {
829
+ this.running = false;
830
+ this.abort?.abort();
831
+ try {
832
+ this.stream?.disconnect();
833
+ }
834
+ catch {
835
+ // The stream may already be closed; stopping is best-effort.
836
+ }
837
+ }
838
+ async release() {
839
+ const releaseLock = this.releaseLock;
840
+ this.releaseLock = undefined;
841
+ if (releaseLock)
842
+ await releaseLock().catch(() => undefined);
843
+ }
844
+ }
845
+ function str(value) {
846
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
847
+ }
848
+ // The store rethrows a fixed sentence shared with the email channel; the fs
849
+ // error rides on `cause`. Log the cause so ENOSPC, EACCES and a read-only
850
+ // mount stay distinguishable (#17432 R1-3).
851
+ function persistErrorText(error) {
852
+ return String(error.cause ?? error);
853
+ }
854
+ function extractText(parsed) {
855
+ const msgtype = str(parsed['msgtype']);
856
+ if (msgtype && msgtype !== 'text')
857
+ return undefined;
858
+ const text = parsed['text'];
859
+ if (text && typeof text === 'object') {
860
+ const content = text['content'];
861
+ if (typeof content === 'string' && content.trim())
862
+ return content.trim();
863
+ }
864
+ return undefined;
865
+ }
866
+ //# sourceMappingURL=managed-dingtalk-adapter.js.map