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