@qwen-code/channel-dingtalk 0.28.0 → 0.28.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.
@@ -77,6 +77,18 @@ export class DingtalkInteractiveCardClient {
77
77
  : 'DingTalk card delivery failed'}`, false);
78
78
  }
79
79
  }
80
+ if (this.options.strictResponses) {
81
+ // createAndDeliver has a delivery step that can fail independently of the
82
+ // HTTP 200: require an entry that positively reports success. A missing or
83
+ // empty deliverResults is no proof of delivery, so it is ambiguous (R1-2).
84
+ const proved = Array.isArray(deliveries) &&
85
+ deliveries.some((entry) => entry !== null &&
86
+ typeof entry === 'object' &&
87
+ entry.success === true);
88
+ if (!proved) {
89
+ throw new DingtalkCardRequestError(`${input.templateId}: DingTalk card delivery was not confirmed; the outcome is unknown.`, true);
90
+ }
91
+ }
80
92
  }
81
93
  async openOrUpdateStream(input) {
82
94
  await this.request('/v1.0/card/streaming', 'PUT', {
@@ -119,7 +131,13 @@ export class DingtalkInteractiveCardClient {
119
131
  const detail = (await response.text().catch(() => '')).slice(0, 300);
120
132
  throw new DingtalkCardRequestError(`DingTalk Card OpenAPI ${method} ${path} failed${templateId ? ` for ${templateId}` : ''}: HTTP ${response.status}${detail ? ` ${detail}` : ''}`, isRetryableDingtalkStatus(response.status));
121
133
  }
122
- return response.json().catch(() => undefined);
134
+ const parsed = await response.json().catch(() => undefined);
135
+ if (this.options.strictResponses && parsed == null) {
136
+ // A 200 whose body cannot be read proves nothing about delivery; in
137
+ // strict mode that is ambiguous, not a silent success (R1-2).
138
+ throw new DingtalkCardRequestError(`DingTalk Card OpenAPI ${method} ${path} answered without a readable body; the outcome is unknown.`, true);
139
+ }
140
+ return parsed;
123
141
  }
124
142
  }
125
143
  }
@@ -1 +1 @@
1
- {"version":3,"file":"interactive-card-client.js","sourceRoot":"","sources":["../src/interactive-card-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEz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right 2026 Qwen Team
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
- import type { ManagedChannelPolicy, ManagedChannelControlPlane } from '@qwen-code/channel-base';
6
+ import type { ManagedChannelCapabilities, ManagedChannelPolicy, ManagedChannelControlPlane } from '@qwen-code/channel-base';
7
7
  export type { ManagedReceipt } from './managed-state.js';
8
8
  /** What a reply needs, committed with the input and echoed by the outbox. */
9
9
  export interface DingtalkReplyContext {
@@ -35,6 +35,23 @@ export interface DingtalkWebhookFailure extends Error {
35
35
  export interface ManagedDingtalkAdapterDeps {
36
36
  readonly createStreamClient: (settings: DingtalkSettings, onMessage: (messageId: string, data: string) => boolean) => ManagedDingtalkStreamClient;
37
37
  readonly sendWebhook: (webhook: string, text: string) => Promise<void>;
38
+ /**
39
+ * Render one segment into the delivery's provider-native card (H5e).
40
+ * `create` selects createAndDeliver versus a full-snapshot updateInstance
41
+ * edit. Failures carry `.definitive` exactly like sendWebhook, so the
42
+ * adapter's rejected/unknown arm is surface-agnostic. Optional: an adapter
43
+ * without card deps keeps the text path.
44
+ */
45
+ readonly sendCardSegment?: (input: {
46
+ outTrackId: string;
47
+ templateId: string;
48
+ target: {
49
+ chatId: string;
50
+ isGroup: boolean;
51
+ };
52
+ body: string;
53
+ create: boolean;
54
+ }) => Promise<void>;
38
55
  readonly lock: (directory: string, onCompromised: () => void) => Promise<() => Promise<void>>;
39
56
  readonly now?: () => number;
40
57
  readonly log?: (line: string) => void;
@@ -48,10 +65,29 @@ export interface ManagedDingtalkAdapterOptions {
48
65
  /** Off, the caller drives `tick()` itself (tests); on by default. */
49
66
  readonly pollLoop?: boolean;
50
67
  }
68
+ export declare const MANAGED_CARD_CONTENT_LIMIT = 20000;
69
+ /**
70
+ * The deterministic provider-side handle of one delivery's card. A pure
71
+ * function of the delivery identity, so a restart re-derives the same handle
72
+ * and never creates a second card, while a resend (a new deliveryId) gets its
73
+ * own. 45 characters, inside the provider's 64-character outTrackId bound; the
74
+ * prefix mirrors the Legacy qwen-status-/qwen-result- convention.
75
+ */
76
+ export declare function managedCardOutTrackId(deliveryId: string): string;
77
+ /**
78
+ * The operator-authored card template id from the channel config, or undefined
79
+ * when absent or unusable. Reuses the credential rule (validCredential) rather
80
+ * than restating its CR/LF/NUL predicate, so the next hardening of that rule
81
+ * lands in one copy (R1-10); a copy-paste artifact cannot reach the card API.
82
+ */
83
+ export declare function dingtalkCardTemplateId(config: Readonly<Record<string, unknown>>): string | undefined;
51
84
  export declare function dingtalkSettings(config: Readonly<Record<string, unknown>>): DingtalkSettings;
52
85
  export declare class ManagedDingtalkAdapter {
53
86
  readonly settings: DingtalkSettings;
54
87
  readonly policy: ManagedChannelPolicy;
88
+ /** H5e: DingTalk renders one delivery as one card, edited per segment. */
89
+ readonly capabilities: ManagedChannelCapabilities;
90
+ private readonly cardTemplateId?;
55
91
  private readonly store;
56
92
  private readonly controlPlane;
57
93
  private readonly deps;
@@ -112,6 +148,25 @@ export declare class ManagedDingtalkAdapter {
112
148
  * the inherited setter (#17173 R3-5).
113
149
  */
114
150
  private touchWebhook;
151
+ /**
152
+ * Decide the surface for one segment (H5e). Card mode engages only when the
153
+ * adapter declares cards, a template is configured and the deps provide the
154
+ * card send. The first segment creates the card; later segments edit it with
155
+ * the accumulated body. An overflow — or a missing progress entry for a
156
+ * non-first segment, which is what makes eviction safe — falls back to text
157
+ * rather than re-creating a card the provider may already hold.
158
+ */
159
+ private cardDecision;
160
+ /** Own-key read of one delivery's card progress, never an inherited member. */
161
+ private cardProgress;
162
+ /**
163
+ * Record a delivery's card progress as most-recently-touched, evicting the
164
+ * least-recently-touched entry over the bound (the touchWebhook discipline:
165
+ * delete, redefine as an own enumerable key, evict the first key). An evicted
166
+ * in-flight delivery is safe — cardDecision reads its absence as text.
167
+ */
168
+ private touchCardProgress;
169
+ private pruneCardProgress;
115
170
  private send;
116
171
  private reportOrphanedOutbound;
117
172
  private persist;
@@ -1 +1 @@
1
- {"version":3,"file":"managed-dingtalk-adapter.d.ts","sourceRoot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CAAC,iBAAiB;YAQX,IAAI;YAwNJ,sBAAsB;IAyEpC,OAAO,CAAC,OAAO;IAOf,OAAO,CAAC,IAAI;YAUE,OAAO;CAKtB"}
@@ -3,10 +3,10 @@
3
3
  * Copyright 2026 Qwen Team
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
- import { randomUUID } from 'node:crypto';
6
+ import { createHash, randomUUID } from 'node:crypto';
7
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';
8
+ import { fitInboundText, MANAGED_OUTBOUND_LIMIT, resolvePrivatePolicy, } from '@qwen-code/channel-base';
9
+ import { MANAGED_CARD_PROGRESS_LIMIT, MANAGED_DINGTALK_PENDING_LIMIT, ManagedDingtalkStateStore, RECENT_LIMIT, WEBHOOK_LIMIT, } from './managed-state.js';
10
10
  const CLAIM_BATCH = 16;
11
11
  const DEFAULT_POLL_INTERVAL = 2_000;
12
12
  // Shared by the clamp and the operator-facing diagnostic so a bound change
@@ -22,13 +22,50 @@ const INSTANCE_SCOPED_REFUSALS = new Set([
22
22
  ]);
23
23
  const INSTANCE_REFUSAL_DROP_LIMIT = 1;
24
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;
25
+ // H5e of #12827: the card body bound, in UTF-16 units, mirroring the Legacy
26
+ // status card's CONTENT_LIMIT. A ledger segment can be 48 KiB of UTF-8 and a
27
+ // reply up to 64 of them, so a card cannot carry every reply; the overflow
28
+ // falls back to the text path rather than truncating content the receipts
29
+ // would then claim as delivered.
30
+ export const MANAGED_CARD_CONTENT_LIMIT = 20_000;
31
+ /**
32
+ * The deterministic provider-side handle of one delivery's card. A pure
33
+ * function of the delivery identity, so a restart re-derives the same handle
34
+ * and never creates a second card, while a resend (a new deliveryId) gets its
35
+ * own. 45 characters, inside the provider's 64-character outTrackId bound; the
36
+ * prefix mirrors the Legacy qwen-status-/qwen-result- convention.
37
+ */
38
+ export function managedCardOutTrackId(deliveryId) {
39
+ return `qwen-managed-${createHash('sha256')
40
+ .update(deliveryId)
41
+ .digest('hex')
42
+ .slice(0, 32)}`;
43
+ }
44
+ /**
45
+ * The operator-authored card template id from the channel config, or undefined
46
+ * when absent or unusable. Reuses the credential rule (validCredential) rather
47
+ * than restating its CR/LF/NUL predicate, so the next hardening of that rule
48
+ * lands in one copy (R1-10); a copy-paste artifact cannot reach the card API.
49
+ */
50
+ export function dingtalkCardTemplateId(config) {
51
+ const raw = config['cardTemplateId'];
52
+ if (!validCredential(raw))
53
+ return undefined;
54
+ return raw.trim();
55
+ }
56
+ /**
57
+ * The settled delivery state a receipt answer surfaces, if any. The control
58
+ * plane returns the delivery view (carrying `state`); a double that does not
59
+ * surface it resolves to undefined, which reads as "not provably terminal".
60
+ */
61
+ function settledDeliveryState(settled) {
62
+ if (settled && typeof settled === 'object') {
63
+ const state = settled.state;
64
+ if (typeof state === 'string')
65
+ return state;
66
+ }
67
+ return undefined;
68
+ }
32
69
  export function dingtalkSettings(config) {
33
70
  const clientId = config['clientId'];
34
71
  const clientSecret = config['clientSecret'];
@@ -57,6 +94,9 @@ function validCredential(value) {
57
94
  export class ManagedDingtalkAdapter {
58
95
  settings;
59
96
  policy;
97
+ /** H5e: DingTalk renders one delivery as one card, edited per segment. */
98
+ capabilities = { cards: true };
99
+ cardTemplateId;
60
100
  store;
61
101
  controlPlane;
62
102
  deps;
@@ -77,6 +117,7 @@ export class ManagedDingtalkAdapter {
77
117
  loggedSettleFailure = false;
78
118
  constructor(options) {
79
119
  this.settings = dingtalkSettings(options.config);
120
+ this.cardTemplateId = dingtalkCardTemplateId(options.config);
80
121
  const senderPolicy = resolvePrivatePolicy(options.config);
81
122
  if (senderPolicy === 'pairing') {
82
123
  // The managed policy shape has no pairing arm; silently coercing it to
@@ -94,7 +135,7 @@ export class ManagedDingtalkAdapter {
94
135
  : [],
95
136
  dispatchMode: options.config['dispatchMode'] === 'steer' ? 'steer' : 'followup',
96
137
  };
97
- this.store = new ManagedDingtalkStateStore(options.name, options.cwd, this.settings.clientId);
138
+ this.store = new ManagedDingtalkStateStore(options.name, options.cwd, this.settings.clientId, options.controlPlane.destinationKey ?? '');
98
139
  this.controlPlane = options.controlPlane;
99
140
  this.deps = options.deps;
100
141
  this.log =
@@ -106,6 +147,15 @@ export class ManagedDingtalkAdapter {
106
147
  if (this.settings.pollIntervalRewritten) {
107
148
  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
149
  }
150
+ // A configured-but-unusable template id silently disables cards forever;
151
+ // announce the refusal once (the fact, not the value) so "cards never
152
+ // appear" has a diagnosable cause, like the pollInterval rewrite above.
153
+ // Non-fatal: without a usable template the adapter stays on the text path
154
+ // (R1-10).
155
+ if (options.config['cardTemplateId'] !== undefined &&
156
+ this.cardTemplateId === undefined) {
157
+ this.log('Managed DingTalk cardTemplateId is configured but unusable (not a non-empty string, or it contains CR/LF/NUL); cards are disabled and replies use the text path.');
158
+ }
109
159
  this.pollLoop = options.pollLoop ?? true;
110
160
  }
111
161
  get stateFile() {
@@ -131,7 +181,40 @@ export class ManagedDingtalkAdapter {
131
181
  throw new Error('DingTalk state is owned by another process; managed adapter not started.');
132
182
  }
133
183
  try {
134
- this.state = this.store.load() ?? {
184
+ const loaded = this.store.load();
185
+ // The upgrade to per-registration ledgers strands the legacy
186
+ // managed-state.json: make the drop explicit, never silent. Detect it
187
+ // even when a keyed ledger already exists — a rollback to the
188
+ // pre-upgrade build can stage fresh legacy claims after the upgrade
189
+ // (R2-6). The legacy ledger is not adopted — that would replay one
190
+ // registration's pending into another. It is archived only once the
191
+ // start succeeds (below), so a failed first start leaves the file for a
192
+ // rollback to recover (R3-2).
193
+ const legacy = this.store.strandedLegacyLedger();
194
+ if (legacy) {
195
+ // An unreadable legacy is not an empty one: its counts are unknown and
196
+ // any claims it held are stranded (R3-1). Name the inbound and outbound
197
+ // consequences separately so an outbound-only strand does not report
198
+ // lost inbound messages, and a quiescent 0/0 legacy reports no loss
199
+ // (R2-1).
200
+ const pendingLabel = legacy.readable ? legacy.pending : 'unknown';
201
+ const outboundLabel = legacy.readable ? legacy.outbound : 'unknown';
202
+ let consequence = '';
203
+ if (!legacy.readable) {
204
+ consequence =
205
+ ' Its contents could not be read, so any staged-but-unadmitted claims it held are stranded.';
206
+ }
207
+ else {
208
+ if (legacy.pending > 0)
209
+ consequence +=
210
+ ' Its staged-but-unadmitted claims were acked to the provider and are lost.';
211
+ if (legacy.outbound > 0)
212
+ consequence +=
213
+ ' Its un-receipted outbound segments were dropped, so their delivery status is unknown.';
214
+ }
215
+ this.log(`Managed DingTalk upgraded to per-registration ledgers; the legacy ledger ${legacy.path} (${pendingLabel} pending, ${outboundLabel} outbound) is stranded and not replayed.${consequence}`);
216
+ }
217
+ this.state = loaded ?? {
135
218
  version: 1,
136
219
  generation: 1,
137
220
  pending: [],
@@ -163,6 +246,20 @@ export class ManagedDingtalkAdapter {
163
246
  // adapter the CLI would then park on.
164
247
  if (!this.running || this.ownershipLost)
165
248
  throw new Error('Managed DingTalk adapter stopped during connection.');
249
+ // The start succeeded, so archive the reported legacy: a static legacy is
250
+ // not re-announced on every later start, and a second registration of the
251
+ // entry is not told the first registration's claims were its own (R2-6).
252
+ // A failed start above leaves it untouched for a rollback to recover
253
+ // (R3-2); the notice then simply repeats on the retry.
254
+ if (legacy) {
255
+ const archived = this.store.archiveStrandedLegacy();
256
+ // The notice above names the legacy path, which this rename moves; name
257
+ // the archived path too so an operator following the notice can still
258
+ // find the preserved claims instead of hitting ENOENT (R4-1).
259
+ if (archived) {
260
+ this.log(`Managed DingTalk archived the legacy ledger to ${archived}; the claims it held are preserved there for inspection.`);
261
+ }
262
+ }
166
263
  if (this.pollLoop)
167
264
  this.loop = this.runLoop();
168
265
  }
@@ -653,6 +750,84 @@ export class ManagedDingtalkAdapter {
653
750
  delete state.webhooks[keys[0]];
654
751
  this.persist();
655
752
  }
753
+ /**
754
+ * Decide the surface for one segment (H5e). Card mode engages only when the
755
+ * adapter declares cards, a template is configured and the deps provide the
756
+ * card send. The first segment creates the card; later segments edit it with
757
+ * the accumulated body. An overflow — or a missing progress entry for a
758
+ * non-first segment, which is what makes eviction safe — falls back to text
759
+ * rather than re-creating a card the provider may already hold.
760
+ */
761
+ cardDecision(deliveryId, segment) {
762
+ if (!this.capabilities.cards ||
763
+ !this.cardTemplateId ||
764
+ !this.deps.sendCardSegment) {
765
+ return { render: 'text' };
766
+ }
767
+ const progress = this.cardProgress(deliveryId);
768
+ if (progress?.mode === 'text')
769
+ return { render: 'text' };
770
+ if (segment.ordinal === 0) {
771
+ if (segment.text.length > MANAGED_CARD_CONTENT_LIMIT) {
772
+ return { render: 'text', fallback: progress };
773
+ }
774
+ return {
775
+ render: 'card',
776
+ outTrackId: managedCardOutTrackId(deliveryId),
777
+ body: segment.text,
778
+ create: !progress,
779
+ };
780
+ }
781
+ if (progress?.mode === 'card') {
782
+ const body = progress.body + segment.text;
783
+ if (body.length > MANAGED_CARD_CONTENT_LIMIT) {
784
+ return { render: 'text', fallback: progress };
785
+ }
786
+ return {
787
+ render: 'card',
788
+ outTrackId: progress.outTrackId,
789
+ body,
790
+ create: false,
791
+ };
792
+ }
793
+ return { render: 'text' };
794
+ }
795
+ /** Own-key read of one delivery's card progress, never an inherited member. */
796
+ cardProgress(deliveryId) {
797
+ const cards = this.state.cards;
798
+ return cards && Object.hasOwn(cards, deliveryId)
799
+ ? cards[deliveryId]
800
+ : undefined;
801
+ }
802
+ /**
803
+ * Record a delivery's card progress as most-recently-touched, evicting the
804
+ * least-recently-touched entry over the bound (the touchWebhook discipline:
805
+ * delete, redefine as an own enumerable key, evict the first key). An evicted
806
+ * in-flight delivery is safe — cardDecision reads its absence as text.
807
+ */
808
+ touchCardProgress(deliveryId, progress) {
809
+ const state = this.state;
810
+ const cards = state.cards ?? {};
811
+ delete cards[deliveryId];
812
+ Object.defineProperty(cards, deliveryId, {
813
+ value: progress,
814
+ enumerable: true,
815
+ writable: true,
816
+ configurable: true,
817
+ });
818
+ const keys = Object.keys(cards);
819
+ if (keys.length > MANAGED_CARD_PROGRESS_LIMIT)
820
+ delete cards[keys[0]];
821
+ state.cards = cards;
822
+ }
823
+ pruneCardProgress(deliveryId) {
824
+ const cards = this.state.cards;
825
+ if (cards && Object.hasOwn(cards, deliveryId)) {
826
+ delete cards[deliveryId];
827
+ if (Object.keys(cards).length === 0)
828
+ this.state.cards = undefined;
829
+ }
830
+ }
656
831
  async send(delivery) {
657
832
  const state = this.state;
658
833
  const context = delivery.replyContext;
@@ -662,6 +837,16 @@ export class ManagedDingtalkAdapter {
662
837
  if (!conversationId ||
663
838
  !webhook ||
664
839
  !this.senderAllowed(context?.senderId ?? '')) {
840
+ // The delivery is rejected terminally; drop any card body it retained
841
+ // from earlier segments (deferred round-3). Persist best-effort so the
842
+ // prune is durable even though the rejection receipt may stay unreported.
843
+ this.pruneCardProgress(delivery.deliveryId);
844
+ try {
845
+ this.persist();
846
+ }
847
+ catch (error) {
848
+ this.log(`Managed DingTalk could not persist the card prune for ${delivery.deliveryId}: ${persistErrorText(error)}.`);
849
+ }
665
850
  // One delivery's unreportable rejection receipt must never abort the
666
851
  // claimed batch: the deliveries behind it were already moved to sending
667
852
  // server-side and would settle unknown (lost) if the tick escaped here.
@@ -685,8 +870,16 @@ export class ManagedDingtalkAdapter {
685
870
  for (const segment of delivery.segments) {
686
871
  if (!this.running)
687
872
  return;
688
- const messageId = randomUUID();
873
+ const card = this.cardDecision(delivery.deliveryId, segment);
874
+ // A card segment's provider handle is the card's outTrackId — the durable
875
+ // key that resolves it for editing — shared by every segment rendered
876
+ // into the same card. A text segment keeps a local id, as before.
877
+ const messageId = card.render === 'card' ? card.outTrackId : randomUUID();
689
878
  const previousOutbound = state.outbound;
879
+ // touchCardProgress mutates the live map in place, so the rollback
880
+ // snapshot must be a copy — a bare reference would already carry the
881
+ // new entry when the persist fails.
882
+ const previousCards = state.cards && { ...state.cards };
690
883
  state.outbound = [
691
884
  ...state.outbound,
692
885
  {
@@ -695,21 +888,53 @@ export class ManagedDingtalkAdapter {
695
888
  messageId,
696
889
  },
697
890
  ].slice(-MANAGED_OUTBOUND_LIMIT);
891
+ if (card.render === 'card') {
892
+ this.touchCardProgress(delivery.deliveryId, {
893
+ outTrackId: card.outTrackId,
894
+ body: card.body,
895
+ mode: 'card',
896
+ });
897
+ }
898
+ else if (card.fallback) {
899
+ // The overflow switch is persisted so the whole tail stays text after
900
+ // the first segment that no longer fits, in order, across a restart.
901
+ // The accumulated body is never read again once mode is text, so drop
902
+ // it rather than re-serialising up to 20 000 dead units on every later
903
+ // persist (R3-1). The validator still requires a string body.
904
+ this.touchCardProgress(delivery.deliveryId, {
905
+ ...card.fallback,
906
+ body: '',
907
+ mode: 'text',
908
+ });
909
+ }
698
910
  try {
699
911
  this.persist();
700
912
  }
701
913
  catch (error) {
702
914
  // 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).
915
+ // crash after the send would re-send on restart. Roll back both the
916
+ // outbound entry and the card progress and abandon this delivery
917
+ // before the side effect; the lease reconciler settles it unknown
918
+ // (#17173 R10).
706
919
  state.outbound = previousOutbound;
920
+ state.cards = previousCards;
707
921
  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
922
  return;
709
923
  }
710
924
  let outcome;
711
925
  try {
712
- await this.deps.sendWebhook(webhook, segment.text);
926
+ if (card.render === 'card') {
927
+ await this.deps.sendCardSegment({
928
+ outTrackId: card.outTrackId,
929
+ templateId: this.cardTemplateId,
930
+ target: { chatId: context.senderId, isGroup: false },
931
+ body: card.body,
932
+ create: card.create,
933
+ });
934
+ }
935
+ else {
936
+ await this.deps.sendWebhook(webhook, segment.text);
937
+ }
713
938
  outcome = {
714
939
  outcome: 'accepted',
715
940
  ordinal: segment.ordinal,
@@ -724,8 +949,10 @@ export class ManagedDingtalkAdapter {
724
949
  // answered into a dead target — the next frame must re-commit a fresh
725
950
  // webhook. Only evict the entry this send actually used; a fresher
726
951
  // webhook committed mid-send stays (#17173 round 5). The receipt
727
- // persist below carries the eviction to disk.
728
- if (definitive &&
952
+ // persist below carries the eviction to disk. A card refusal is the
953
+ // card API's verdict, not the webhook's, so it never evicts the webhook.
954
+ if (card.render === 'text' &&
955
+ definitive &&
729
956
  conversationId &&
730
957
  this.cachedWebhook(conversationId) === webhook) {
731
958
  delete state.webhooks[conversationId];
@@ -734,8 +961,20 @@ export class ManagedDingtalkAdapter {
734
961
  // capability and the provider errmsg is not trusted text.
735
962
  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
963
  }
964
+ if (card.render === 'card' && definitive) {
965
+ // A definitive card refusal settles the delivery rejected; make it
966
+ // diagnosable. Log the fact, not the provider errmsg (untrusted text).
967
+ this.log(`Managed DingTalk card send for ${delivery.deliveryId} was definitively refused; the delivery is rejected.`);
968
+ }
737
969
  outcome = definitive ? { outcome: 'rejected' } : { outcome: 'unknown' };
738
970
  }
971
+ if (outcome.outcome !== 'accepted') {
972
+ // The delivery is terminal server-side once this receipt lands; no
973
+ // later segment renders into its card. Drop the progress so the map
974
+ // does not retain a dead delivery's body. The receipt persist below
975
+ // carries the prune to disk.
976
+ this.pruneCardProgress(delivery.deliveryId);
977
+ }
739
978
  const entry = state.outbound.find((candidate) => candidate.deliveryId === delivery.deliveryId &&
740
979
  candidate.ordinal === segment.ordinal);
741
980
  if (entry)
@@ -750,8 +989,9 @@ export class ManagedDingtalkAdapter {
750
989
  // receipt until the local write lands (#17173 R10).
751
990
  this.log(`Managed DingTalk could not persist the receipt for ${delivery.deliveryId}: ${persistErrorText(error)}; it is still reported and re-driven locally.`);
752
991
  }
992
+ let settled;
753
993
  try {
754
- await this.controlPlane.receipt(delivery.deliveryId, outcome);
994
+ settled = await this.controlPlane.receipt(delivery.deliveryId, outcome);
755
995
  }
756
996
  catch (error) {
757
997
  // One delivery's unreportable receipt never aborts the claimed
@@ -762,6 +1002,13 @@ export class ManagedDingtalkAdapter {
762
1002
  this.log(`Managed DingTalk receipt for ${delivery.deliveryId} could not be reported (${String(error)}); it re-drives on the next tick.`);
763
1003
  return;
764
1004
  }
1005
+ // A `delivered` receipt proves the whole delivery terminal: drop its card
1006
+ // body now rather than retaining it on disk until 64 newer card deliveries
1007
+ // evict it (R1-4). The removal persist below carries the prune to disk.
1008
+ if (outcome.outcome === 'accepted' &&
1009
+ settledDeliveryState(settled) === 'delivered') {
1010
+ this.pruneCardProgress(delivery.deliveryId);
1011
+ }
765
1012
  state.outbound = state.outbound.filter((candidate) => !(candidate.deliveryId === delivery.deliveryId &&
766
1013
  candidate.ordinal === segment.ordinal));
767
1014
  try {
@@ -787,8 +1034,11 @@ export class ManagedDingtalkAdapter {
787
1034
  // receipt — the control plane may already hold it (its answer was
788
1035
  // lost) and settles idempotently. Only a segment whose send never
789
1036
  // produced an outcome settles unknown.
1037
+ const replay = entry.receipt ?? { outcome: 'unknown' };
1038
+ let settled;
1039
+ let dropped = false;
790
1040
  try {
791
- await this.controlPlane.receipt(entry.deliveryId, entry.receipt ?? { outcome: 'unknown' });
1041
+ settled = await this.controlPlane.receipt(entry.deliveryId, replay);
792
1042
  }
793
1043
  catch (error) {
794
1044
  const status = error.status;
@@ -812,6 +1062,17 @@ export class ManagedDingtalkAdapter {
812
1062
  throw error;
813
1063
  }
814
1064
  this.log(`Managed DingTalk receipt for ${entry.deliveryId} was refused (${String(status)}); it is dropped.`);
1065
+ dropped = true;
1066
+ }
1067
+ // A replayed non-accepted receipt (or a delivered one) settles the
1068
+ // delivery terminal: drop its card body so a post-restart settle does not
1069
+ // retain it on disk (R1-4). A deterministically dropped entry is terminal
1070
+ // too even if its replayed receipt was accepted (deferred round-3). The
1071
+ // removal persist below carries the prune.
1072
+ if (dropped ||
1073
+ replay.outcome !== 'accepted' ||
1074
+ settledDeliveryState(settled) === 'delivered') {
1075
+ this.pruneCardProgress(entry.deliveryId);
815
1076
  }
816
1077
  state.outbound = state.outbound.filter((candidate) => candidate !== entry);
817
1078
  try {
@@ -870,40 +1131,4 @@ function extractText(parsed) {
870
1131
  }
871
1132
  return undefined;
872
1133
  }
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
1134
  //# sourceMappingURL=managed-dingtalk-adapter.js.map