File size: 20,301 Bytes
5cb63c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
/**
 * Presentation limit adapters for channel outbound payloads.
 *
 * Splits text and reshapes portable controls to match per-channel limits.
 */
import { normalizeStringEntries } from "@openclaw/normalization-core/string-normalization";
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
import {
  renderMessagePresentationChartFallbackText,
  renderMessagePresentationControlFallbackLabel,
  renderMessagePresentationTableFallbackText,
  resolveMessagePresentationActionValue,
  resolveMessagePresentationButtonAction,
  resolveMessagePresentationOptionAction,
} from "../../../interactive/payload.js";
import type {
  MessagePresentation,
  MessagePresentationBlock,
  MessagePresentationButton,
  MessagePresentationOption,
} from "../../../interactive/payload.js";
import type { ChannelPresentationCapabilities } from "../outbound.types.js";

type ActionLimits = NonNullable<NonNullable<ChannelPresentationCapabilities["limits"]>["actions"]>;
type SelectLimits = NonNullable<NonNullable<ChannelPresentationCapabilities["limits"]>["selects"]>;
type TextLimits = NonNullable<NonNullable<ChannelPresentationCapabilities["limits"]>["text"]>;
type ActionBudget = {
  remainingActions?: number;
  remainingRows?: number;
  maxActionsPerRow?: number;
};
type ButtonCandidate = {
  original: MessagePresentationButton;
  adapted?: MessagePresentationButton;
};
type SelectCandidate = {
  original: MessagePresentationOption;
  adapted?: MessagePresentationOption;
};
type ButtonSelection = ReadonlySet<MessagePresentationButton> | undefined;

const PRESENTATION_FALLBACK_CONTINUATION = Symbol.for(
  "openclaw.presentation.fallback-continuation",
);

function positiveInteger(value: number | undefined): number | undefined {
  return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
}

function truncateText(value: string, maxLength: number | undefined): string {
  const limit = positiveInteger(maxLength);
  if (!limit || value.length <= limit) {
    return value;
  }
  // A code point uses at most two UTF-16 units; later units cannot affect this prefix.
  return Array.from(value.slice(0, limit * 2))
    .slice(0, limit)
    .join("");
}

function truncateUtf8Bytes(value: string, limit: number): string {
  let bytes = 0;
  let result = "";
  for (const char of value) {
    const nextBytes = utf8ByteLength(char);
    if (bytes + nextBytes > limit) {
      break;
    }
    bytes += nextBytes;
    result += char;
  }
  return result;
}

function truncatePresentationText(value: string, limits: TextLimits | undefined): string {
  const limit = positiveInteger(limits?.maxLength);
  if (!limit) {
    return value;
  }
  if (limits?.encoding === "utf8-bytes") {
    return truncateUtf8Bytes(value, limit);
  }
  if (limits?.encoding === "utf16-units") {
    return truncateUtf16Safe(value, limit);
  }
  return truncateText(value, limit);
}

function splitPresentationText(value: string, limits: TextLimits | undefined): string[] {
  const limit = positiveInteger(limits?.maxLength);
  if (!limit || truncatePresentationText(value, limits) === value) {
    return [value];
  }
  const chunks: string[] = [];
  let remaining = value;
  while (remaining) {
    const prefix = truncatePresentationText(remaining, limits);
    if (!prefix || prefix === remaining) {
      chunks.push(remaining);
      break;
    }
    // Keep complete fallback lines together when possible. Retain the newline
    // itself so concatenating the blocks reconstructs every authored character.
    const newlineIndex = prefix.lastIndexOf("\n");
    const splitIndex = newlineIndex > 0 ? newlineIndex + 1 : prefix.length;
    chunks.push(remaining.slice(0, splitIndex));
    remaining = remaining.slice(splitIndex);
  }
  return chunks;
}

function presentationTextBlocks(params: {
  blockType: "context" | "text";
  text: string;
  limits?: TextLimits;
  continuation?: boolean;
}): Array<{ type: "context" | "text"; text: string }> {
  return splitPresentationText(params.text, params.limits).map((text, index) => {
    const block = { type: params.blockType, text };
    if (index > 0 || params.continuation) {
      // Native fallback renderers must reassemble split fragments without inserting paragraph breaks.
      Object.defineProperty(block, PRESENTATION_FALLBACK_CONTINUATION, { value: true });
    }
    return block;
  });
}

function utf8ByteLength(value: string): number {
  return Buffer.byteLength(value, "utf8");
}

function fitsByteLimit(value: string | undefined, maxBytes: number | undefined): boolean {
  const limit = positiveInteger(maxBytes);
  return !value || !limit || utf8ByteLength(value) <= limit;
}

function fallbackListBlocks(params: {
  blockType: "context" | "text";
  heading: string;
  labels: readonly string[];
  limits?: TextLimits;
}): MessagePresentationBlock[] {
  const labels = normalizeStringEntries(params.labels);
  if (labels.length === 0) {
    return [];
  }
  // Action labels are operator-visible content; split like chart/table fallbacks instead of dropping them.
  return presentationTextBlocks({
    blockType: params.blockType,
    text: `${params.heading}:\n${labels.map((label) => `- ${label}`).join("\n")}`,
    limits: params.limits,
  });
}

function createActionBudget(limits: ActionLimits | undefined): ActionBudget {
  return {
    remainingActions: positiveInteger(limits?.maxActions),
    remainingRows: positiveInteger(limits?.maxRows),
    maxActionsPerRow: positiveInteger(limits?.maxActionsPerRow),
  };
}

function buttonCapacity(budget: ActionBudget): number | undefined {
  if (budget.remainingActions === 0 || budget.remainingRows === 0) {
    return 0;
  }
  const rowCapacity =
    budget.remainingRows && budget.maxActionsPerRow
      ? budget.remainingRows * budget.maxActionsPerRow
      : undefined;
  if (budget.remainingActions !== undefined && rowCapacity !== undefined) {
    return Math.min(budget.remainingActions, rowCapacity);
  }
  return budget.remainingActions ?? rowCapacity;
}

function consumeButtonBudget(budget: ActionBudget, count: number): void {
  if (count <= 0) {
    return;
  }
  if (budget.remainingActions !== undefined) {
    budget.remainingActions = Math.max(0, budget.remainingActions - count);
  }
  if (budget.remainingRows !== undefined) {
    const perRow = budget.maxActionsPerRow ?? count;
    budget.remainingRows = Math.max(0, budget.remainingRows - Math.ceil(count / perRow));
  }
}

function chunkButtons(
  buttons: readonly MessagePresentationButton[],
  maxActionsPerRow: number | undefined,
): MessagePresentationButton[][] {
  const rowSize = positiveInteger(maxActionsPerRow);
  if (!rowSize) {
    return buttons.length > 0 ? [[...buttons]] : [];
  }
  const rows: MessagePresentationButton[][] = [];
  for (let index = 0; index < buttons.length; index += rowSize) {
    rows.push(buttons.slice(index, index + rowSize));
  }
  return rows;
}

function hasActionSlotBudget(budget: ActionBudget): boolean {
  return budget.remainingActions !== 0 && budget.remainingRows !== 0;
}

function consumeSelectBudget(budget: ActionBudget, count = 1): void {
  if (budget.remainingActions !== undefined) {
    budget.remainingActions = Math.max(0, budget.remainingActions - count);
  }
  if (budget.remainingRows !== undefined) {
    budget.remainingRows = Math.max(0, budget.remainingRows - count);
  }
}

function adaptButton(
  button: MessagePresentationButton,
  limits: ActionLimits | undefined,
): MessagePresentationButton | undefined {
  const hasExplicitAction = button.action !== undefined;
  const action = resolveMessagePresentationButtonAction(button);
  if (!action) {
    return undefined;
  }
  const actionValue = resolveMessagePresentationActionValue(action);
  const actionFits = actionValue === undefined || fitsByteLimit(actionValue, limits?.maxValueBytes);
  const legacyValueFits = fitsByteLimit(button.value, limits?.maxValueBytes);
  if (
    (hasExplicitAction ? !actionFits : action.type === "callback" && !legacyValueFits) ||
    (button.disabled === true && limits?.supportsDisabled !== true)
  ) {
    return undefined;
  }
  const adapted: MessagePresentationButton = {
    ...button,
    label: truncateText(button.label, limits?.maxLabelLength),
  };
  if (!legacyValueFits) {
    delete adapted.value;
  }
  if (limits?.supportsStyles === false) {
    delete adapted.style;
  }
  return adapted;
}

function adaptButtonsBlock(
  block: Extract<MessagePresentationBlock, { type: "buttons" }>,
  limits: ActionLimits | undefined,
  budget: ActionBudget,
  fallbackBlockType: "context" | "text",
  buttonSelection: ButtonSelection,
  textLimits?: TextLimits,
): MessagePresentationBlock[] {
  const capacity = buttonCapacity(budget);
  const candidates: ButtonCandidate[] = block.buttons.map((button) => ({
    original: button,
    adapted: adaptButton(button, limits),
  }));
  const renderableCandidates = candidates.filter(
    (candidate): candidate is ButtonCandidate & { adapted: MessagePresentationButton } =>
      Boolean(candidate.adapted),
  );
  const eligibleCandidates = buttonSelection
    ? renderableCandidates.filter((candidate) => buttonSelection.has(candidate.original))
    : renderableCandidates;
  const selectedCandidates =
    capacity !== undefined && eligibleCandidates.length > capacity
      ? eligibleCandidates
          .map((candidate, index) => ({ candidate, index }))
          .toSorted((left, right) => {
            const priorityDelta =
              (right.candidate.adapted.priority ?? 0) - (left.candidate.adapted.priority ?? 0);
            return priorityDelta || left.index - right.index;
          })
          .slice(0, capacity)
          .map((entry) => entry.candidate)
      : eligibleCandidates;
  const selected = new Set<ButtonCandidate>(selectedCandidates);
  const buttons = selectedCandidates.map((candidate) => candidate.adapted);
  const droppedLabels = candidates
    .filter((candidate) => !candidate.adapted || !selected.has(candidate))
    .map((candidate) => renderMessagePresentationControlFallbackLabel(candidate.original));
  consumeButtonBudget(budget, buttons.length);
  const fallback = fallbackListBlocks({
    blockType: fallbackBlockType,
    heading: "Actions",
    labels: droppedLabels,
    limits: textLimits,
  });
  if (buttons.length === 0) {
    return fallback;
  }
  const blocks: MessagePresentationBlock[] = chunkButtons(buttons, limits?.maxActionsPerRow).map(
    (row) => ({
      type: "buttons",
      buttons: row,
    }),
  );
  blocks.push(...fallback);
  return blocks;
}

function adaptOption(
  option: MessagePresentationOption,
  limits: SelectLimits | undefined,
): MessagePresentationOption | undefined {
  const hasExplicitAction = option.action !== undefined;
  const action = resolveMessagePresentationOptionAction(option);
  if (!action) {
    return undefined;
  }
  const actionValue = resolveMessagePresentationActionValue(action);
  const actionFits = actionValue === undefined || fitsByteLimit(actionValue, limits?.maxValueBytes);
  const legacyValueFits = fitsByteLimit(option.value, limits?.maxValueBytes);
  if (hasExplicitAction ? !actionFits : !legacyValueFits) {
    return undefined;
  }
  const adapted: MessagePresentationOption = {
    ...option,
    label: truncateText(option.label, limits?.maxLabelLength),
  };
  if (!legacyValueFits) {
    delete adapted.value;
  }
  return adapted;
}

function adaptSelectBlock(
  block: Extract<MessagePresentationBlock, { type: "select" }>,
  limits: SelectLimits | undefined,
  budget: ActionBudget,
  fallbackBlockType: "context" | "text",
  textLimits?: TextLimits,
): MessagePresentationBlock[] {
  const candidates: SelectCandidate[] = block.options.map((option) => ({
    original: option,
    adapted: adaptOption(option, limits),
  }));
  const renderableCandidates = candidates.filter(
    (candidate): candidate is SelectCandidate & { adapted: MessagePresentationOption } =>
      Boolean(candidate.adapted),
  );
  const maxOptions = positiveInteger(limits?.maxOptions);
  const selectedCandidates = maxOptions
    ? renderableCandidates.slice(0, maxOptions)
    : renderableCandidates;
  const selected = new Set<SelectCandidate>(selectedCandidates);
  const options = selectedCandidates.map((candidate) => candidate.adapted);
  const canRenderSelect = options.length > 0 && hasActionSlotBudget(budget);
  const fallback = fallbackListBlocks({
    blockType: fallbackBlockType,
    heading: block.placeholder ?? "Options",
    labels: (canRenderSelect
      ? candidates.filter((candidate) => !candidate.adapted || !selected.has(candidate))
      : candidates
    ).map((candidate) => renderMessagePresentationControlFallbackLabel(candidate.original)),
    limits: textLimits,
  });
  if (!canRenderSelect) {
    return fallback;
  }
  consumeSelectBudget(budget);
  const blocks: MessagePresentationBlock[] = [
    {
      type: "select",
      ...(block.placeholder
        ? { placeholder: truncateText(block.placeholder, limits?.maxLabelLength) }
        : {}),
      options,
    },
  ];
  blocks.push(...fallback);
  return blocks;
}

function countRenderableSelectBlocks(
  blocks: readonly MessagePresentationBlock[],
  capabilities: ChannelPresentationCapabilities | undefined,
  limits: SelectLimits | undefined,
): number {
  if (capabilities?.selects === false) {
    return 0;
  }
  let count = 0;
  for (const block of blocks) {
    // A valid maxOptions is at least one, so one accepted option reserves the slot.
    if (block.type === "select" && block.options.some((option) => adaptOption(option, limits))) {
      count += 1;
    }
  }
  return count;
}

function createGlobalButtonSelection(params: {
  presentation: MessagePresentation;
  capabilities: ChannelPresentationCapabilities | undefined;
  limits: ActionLimits | undefined;
  selectLimits: SelectLimits | undefined;
}): ButtonSelection {
  if (params.capabilities?.buttons === false) {
    return undefined;
  }
  const reservationBudget = createActionBudget(params.limits);
  consumeSelectBudget(
    reservationBudget,
    countRenderableSelectBlocks(
      params.presentation.blocks,
      params.capabilities,
      params.selectLimits,
    ),
  );
  // Without a per-row size, row-only limits follow authored block order rather than preselecting buttons.
  const capacity =
    reservationBudget.remainingRows === 0 && reservationBudget.maxActionsPerRow === undefined
      ? reservationBudget.remainingActions
      : buttonCapacity(reservationBudget);
  if (capacity === undefined) {
    return undefined;
  }
  const candidates = params.presentation.blocks.flatMap((block) => {
    if (block.type !== "buttons") {
      return [];
    }
    return block.buttons
      .map((button) => ({
        original: button,
        adapted: adaptButton(button, params.limits),
      }))
      .filter(
        (
          candidate,
        ): candidate is {
          original: MessagePresentationButton;
          adapted: MessagePresentationButton;
        } => Boolean(candidate.adapted),
      );
  });
  if (candidates.length <= capacity) {
    return undefined;
  }
  return new Set(
    candidates
      .map((candidate, index) => ({ candidate, index }))
      .toSorted((left, right) => {
        const priorityDelta =
          (right.candidate.adapted.priority ?? 0) - (left.candidate.adapted.priority ?? 0);
        return priorityDelta || left.index - right.index;
      })
      .slice(0, capacity)
      .map((entry) => entry.candidate.original),
  );
}

/**
 * Adapt a portable presentation to the target channel's advertised capabilities.
 *
 * Unsupported controls are downgraded to text/context fallback blocks where possible, and
 * controls honor channel limits while authored and fallback text retain every character.
 */
export function adaptMessagePresentationForChannel(params: {
  presentation: MessagePresentation;
  capabilities?: ChannelPresentationCapabilities;
}): MessagePresentation {
  const capabilities = params.capabilities;
  const limits = params.capabilities?.limits;
  const actionBudget = createActionBudget(limits?.actions);
  const fallbackBlockType = capabilities?.context === false ? "text" : "context";
  const buttonSelection = createGlobalButtonSelection({
    presentation: params.presentation,
    capabilities,
    limits: limits?.actions,
    selectLimits: limits?.selects,
  });
  const titleBlocks = params.presentation.title
    ? presentationTextBlocks({
        blockType: "text",
        text: params.presentation.title,
        limits: limits?.text,
      })
    : [];
  const blocks: MessagePresentationBlock[] = titleBlocks.slice(1);
  for (const block of params.presentation.blocks) {
    if (block.type === "text" || block.type === "context") {
      blocks.push(
        ...presentationTextBlocks({
          blockType: block.type === "context" ? fallbackBlockType : "text",
          text: block.text,
          limits: limits?.text,
          continuation:
            Object.getOwnPropertyDescriptor(block, PRESENTATION_FALLBACK_CONTINUATION)?.value ===
            true,
        }),
      );
      continue;
    }
    if (block.type === "chart" && capabilities?.charts !== true) {
      blocks.push(
        ...presentationTextBlocks({
          blockType: fallbackBlockType,
          text: renderMessagePresentationChartFallbackText(block),
          limits: limits?.text,
        }),
      );
      continue;
    }
    if (block.type === "table" && capabilities?.tables !== true) {
      blocks.push(
        ...presentationTextBlocks({
          blockType: fallbackBlockType,
          text: renderMessagePresentationTableFallbackText(block),
          limits: limits?.text,
        }),
      );
      continue;
    }
    if (block.type === "buttons") {
      if (capabilities?.buttons === false) {
        blocks.push(
          ...fallbackListBlocks({
            blockType: fallbackBlockType,
            heading: "Actions",
            labels: block.buttons.map(renderMessagePresentationControlFallbackLabel),
            limits: limits?.text,
          }),
        );
        continue;
      }
      blocks.push(
        ...adaptButtonsBlock(
          block,
          limits?.actions,
          actionBudget,
          fallbackBlockType,
          buttonSelection,
          limits?.text,
        ),
      );
      continue;
    }
    if (block.type === "select") {
      if (capabilities?.selects === false) {
        blocks.push(
          ...fallbackListBlocks({
            blockType: fallbackBlockType,
            heading: block.placeholder ?? "Options",
            labels: block.options.map(renderMessagePresentationControlFallbackLabel),
            limits: limits?.text,
          }),
        );
        continue;
      }
      blocks.push(
        ...adaptSelectBlock(block, limits?.selects, actionBudget, fallbackBlockType, limits?.text),
      );
      continue;
    }
    if (block.type === "divider" && capabilities?.divider === false) {
      continue;
    }
    blocks.push(block);
  }
  return {
    ...params.presentation,
    ...(params.presentation.title ? { title: titleBlocks[0]?.text } : {}),
    blocks,
  };
}

/** Return the subset of buttons that can still be rendered under action limits. */
export function applyPresentationActionLimits(
  buttons: readonly MessagePresentationButton[],
  capabilities?: ChannelPresentationCapabilities,
): MessagePresentationButton[] {
  const block = adaptButtonsBlock(
    { type: "buttons", buttons: [...buttons] },
    capabilities?.limits?.actions,
    createActionBudget(capabilities?.limits?.actions),
    capabilities?.context === false ? "text" : "context",
    undefined,
    capabilities?.limits?.text,
  );
  return block.flatMap((entry) => (entry.type === "buttons" ? entry.buttons : []));
}

/** Resolve an action page size that leaves room for reserved actions on the target channel. */
export function presentationPageSize(
  capabilities?: ChannelPresentationCapabilities,
  reservedActions = 0,
  maxPageSize = Number.POSITIVE_INFINITY,
): number {
  const capacity = buttonCapacity(createActionBudget(capabilities?.limits?.actions));
  const remaining = Math.max(0, (capacity ?? maxPageSize) - Math.max(0, reservedActions));
  return Math.max(1, Math.min(remaining || 1, maxPageSize));
}