@onlyflows/servicenow-mcp 2.3.0-dev.1 → 2.3.0-dev.2

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +258 -0
  2. package/README.md +141 -7
  3. package/dist/call-metrics.d.ts +42 -0
  4. package/dist/call-metrics.d.ts.map +1 -0
  5. package/dist/call-metrics.js +89 -0
  6. package/dist/call-metrics.js.map +1 -0
  7. package/dist/client.d.ts +14 -2
  8. package/dist/client.d.ts.map +1 -1
  9. package/dist/client.js +40 -10
  10. package/dist/client.js.map +1 -1
  11. package/dist/encoded-query-policy.d.ts +9 -0
  12. package/dist/encoded-query-policy.d.ts.map +1 -1
  13. package/dist/encoded-query-policy.js +19 -1
  14. package/dist/encoded-query-policy.js.map +1 -1
  15. package/dist/http-runtime.js +16 -0
  16. package/dist/http-runtime.js.map +1 -1
  17. package/dist/metadata-cache.d.ts +97 -7
  18. package/dist/metadata-cache.d.ts.map +1 -1
  19. package/dist/metadata-cache.js +283 -21
  20. package/dist/metadata-cache.js.map +1 -1
  21. package/dist/setup-prompts.js +1 -1
  22. package/dist/setup-prompts.js.map +1 -1
  23. package/dist/setup.d.ts.map +1 -1
  24. package/dist/setup.js +10 -1
  25. package/dist/setup.js.map +1 -1
  26. package/dist/structured-query.d.ts +61 -2
  27. package/dist/structured-query.d.ts.map +1 -1
  28. package/dist/structured-query.js +376 -35
  29. package/dist/structured-query.js.map +1 -1
  30. package/dist/tools/codesearch.d.ts.map +1 -1
  31. package/dist/tools/codesearch.js +24 -4
  32. package/dist/tools/codesearch.js.map +1 -1
  33. package/dist/tools/flow-view-module.js +1 -1
  34. package/dist/tools/flow-view-module.js.map +1 -1
  35. package/dist/tools/get-module.js +1 -1
  36. package/dist/tools/get-module.js.map +1 -1
  37. package/dist/tools/index.d.ts.map +1 -1
  38. package/dist/tools/index.js +24 -11
  39. package/dist/tools/index.js.map +1 -1
  40. package/dist/tools/query-module.d.ts.map +1 -1
  41. package/dist/tools/query-module.js +205 -59
  42. package/dist/tools/query-module.js.map +1 -1
  43. package/dist/tools/result-envelope.d.ts +311 -0
  44. package/dist/tools/result-envelope.d.ts.map +1 -1
  45. package/dist/tools/result-envelope.js +314 -31
  46. package/dist/tools/result-envelope.js.map +1 -1
  47. package/dist/tools/schema-module.d.ts.map +1 -1
  48. package/dist/tools/schema-module.js +1 -1
  49. package/dist/tools/schema-module.js.map +1 -1
  50. package/dist/tools/truncation-hint.d.ts +125 -0
  51. package/dist/tools/truncation-hint.d.ts.map +1 -0
  52. package/dist/tools/truncation-hint.js +298 -0
  53. package/dist/tools/truncation-hint.js.map +1 -0
  54. package/dist/version.d.ts +1 -1
  55. package/dist/version.js +1 -1
  56. package/docs/CLIENT-SETUP.md +11 -1
  57. package/docs/PRODUCTION-SECURITY.md +17 -1
  58. package/package.json +1 -1
  59. package/server.json +2 -2
@@ -4,6 +4,8 @@ exports.productionToolOutputSchemas = exports.ENVELOPE_HINT_KEY = exports.result
4
4
  exports.withStructuredResultEnvelope = withStructuredResultEnvelope;
5
5
  exports.isProductionToolName = isProductionToolName;
6
6
  exports.registerEnvelopeTextRenderer = registerEnvelopeTextRenderer;
7
+ exports.withoutCallMetadata = withoutCallMetadata;
8
+ exports.withCallMetadata = withCallMetadata;
7
9
  exports.envelopeCompatibilityResult = envelopeCompatibilityResult;
8
10
  exports.finalizeEnvelopeResult = finalizeEnvelopeResult;
9
11
  const atf_contracts_js_1 = require("./atf-contracts.js");
@@ -13,6 +15,7 @@ const batch_limits_js_1 = require("../batch-limits.js");
13
15
  const field_policy_js_1 = require("../field-policy.js");
14
16
  const utils_js_1 = require("../utils.js");
15
17
  const markdown_js_1 = require("./markdown.js");
18
+ const truncation_hint_js_1 = require("./truncation-hint.js");
16
19
  const tool_module_js_1 = require("./tool-module.js");
17
20
  exports.DEFAULT_RESULT_RECORD_LIMIT = 1_000;
18
21
  exports.DEFAULT_RESULT_BYTE_LIMIT = utils_js_1.MAX_RESPONSE_BYTES_DEFAULT;
@@ -34,11 +37,18 @@ const offsetPaginationSchema = zod_1.z
34
37
  })
35
38
  .strict()
36
39
  .superRefine((value, context) => {
40
+ // has_more means rows exist that this response did not contain. Normally
41
+ // next_offset points at the first of them. When rows were dropped for
42
+ // size and not one fit, no offset can advance: `recovery` then marks that
43
+ // the request itself must change, and next_offset is left out.
37
44
  if (value.has_more &&
38
- (value.next_offset === undefined || value.next_offset <= value.offset)) {
45
+ (value.next_offset === undefined
46
+ ? value.recovery === undefined
47
+ : value.next_offset <= value.offset)) {
39
48
  context.addIssue({
40
49
  code: zod_1.z.ZodIssueCode.custom,
41
- message: "next_offset must advance beyond offset when has_more is true",
50
+ message: "next_offset must advance beyond offset when has_more is true, " +
51
+ "unless recovery says the request must change",
42
52
  path: ["next_offset"],
43
53
  });
44
54
  }
@@ -55,6 +65,29 @@ exports.resultPaginationSchema = zod_1.z.union([
55
65
  zod_1.z.object({ mode: zod_1.z.literal("none") }).strict(),
56
66
  offsetPaginationSchema,
57
67
  ]);
68
+ /**
69
+ * What a call reports about itself (see `call-metrics.ts`): one compact
70
+ * definition, shared by every tool's output schema. `metadata.cache` and
71
+ * `metadata.timing` are both optional: a handler builds its envelope without
72
+ * them and the dispatcher adds them, and `cache` is absent when the call made
73
+ * no cacheable read.
74
+ */
75
+ // Validation still bounds these to safe integers; only the advertised
76
+ // `maximum` (2^53 - 1, 81 characters per tool in `tools/list`) is left out,
77
+ // since no duration comes near it. The undefined meta value removes the key.
78
+ const wholeMilliseconds = nonNegativeInteger.meta({ maximum: undefined });
79
+ const callTimingSchema = zod_1.z
80
+ .object({
81
+ total_ms: wholeMilliseconds,
82
+ upstream_ms: wholeMilliseconds,
83
+ watermark_ms: wholeMilliseconds,
84
+ })
85
+ .strict();
86
+ const callMetadataShape = {
87
+ cache: zod_1.z.enum(["hit", "miss", "bypass", "mixed"]).optional(),
88
+ timing: callTimingSchema.optional(),
89
+ };
90
+ const callMetadataSchema = zod_1.z.object(callMetadataShape).strict();
58
91
  exports.resultMetadataSchema = zod_1.z
59
92
  .object({
60
93
  kind: zod_1.z.enum(["single", "collection", "operation"]),
@@ -77,6 +110,7 @@ exports.resultMetadataSchema = zod_1.z
77
110
  dropped_records: nonNegativeInteger.optional(),
78
111
  })
79
112
  .strict(),
113
+ ...callMetadataShape,
80
114
  })
81
115
  .strict();
82
116
  function withStructuredResultEnvelope(dataSchema) {
@@ -550,7 +584,28 @@ function synchronizeRecordCount(data, count) {
550
584
  }
551
585
  }
552
586
  }
553
- function synchronizePagingFields(data, pagination, truncation, depth = 0) {
587
+ /**
588
+ * The truncation hint a tool wrote, if `data` carries one this module's
589
+ * parser accepts, looked for where {@link synchronizePagingFields} restates it.
590
+ */
591
+ function truncationHintParts(data, depth = 0) {
592
+ if (typeof data !== "object" || data === null || Array.isArray(data) || depth > 3) {
593
+ return undefined;
594
+ }
595
+ const record = data;
596
+ if (typeof record.hint === "string" && Object.hasOwn(record, "dropped_records")) {
597
+ const parts = (0, truncation_hint_js_1.parseTruncationHint)(record.hint);
598
+ if (parts !== undefined)
599
+ return parts;
600
+ }
601
+ for (const wrapper of ["meta", "request", "result"]) {
602
+ const parts = truncationHintParts(record[wrapper], depth + 1);
603
+ if (parts !== undefined)
604
+ return parts;
605
+ }
606
+ return undefined;
607
+ }
608
+ function synchronizePagingFields(data, pagination, truncation, depth = 0, neededBytes, capBytes, allBytes, withoutAdvice, widestHint) {
554
609
  if (pagination.mode !== "offset" ||
555
610
  typeof data !== "object" ||
556
611
  data === null ||
@@ -571,13 +626,25 @@ function synchronizePagingFields(data, pagination, truncation, depth = 0) {
571
626
  target.has_more = pagination.has_more;
572
627
  }
573
628
  if (pagination.has_more && pagination.next_offset !== undefined) {
574
- if (Object.hasOwn(target, "next_offset")) {
629
+ // A tool that reports has_more reports where to continue, even when
630
+ // the fit created the continuation (rows dropped for size).
631
+ if (Object.hasOwn(target, "next_offset") || Object.hasOwn(target, "has_more")) {
575
632
  target.next_offset = pagination.next_offset;
576
633
  }
577
634
  }
578
635
  else if (Object.hasOwn(target, "next_offset")) {
579
636
  delete target.next_offset;
580
637
  }
638
+ if (pagination.has_more && typeof target.hint === "string") {
639
+ // The tool wrote its continuation from the page it fetched; if the fit
640
+ // dropped rows, the first row not returned is where to continue.
641
+ target.hint = (0, truncation_hint_js_1.restateContinuationHint)(target.hint, {
642
+ offset: pagination.offset,
643
+ ...(pagination.next_offset === undefined
644
+ ? {}
645
+ : { nextOffset: pagination.next_offset }),
646
+ });
647
+ }
581
648
  if (Object.hasOwn(target, "truncated")) {
582
649
  target.truncated = truncation.truncated;
583
650
  }
@@ -587,6 +654,20 @@ function synchronizePagingFields(data, pagination, truncation, depth = 0) {
587
654
  }
588
655
  else {
589
656
  target.dropped_records = truncation.dropped_records;
657
+ // A tool that explains the drop in a hint wrote it before this fit
658
+ // dropped more rows. Restate it from the final counts and
659
+ // continuation so the text agrees with the fields beside it.
660
+ if (typeof target.hint === "string") {
661
+ target.hint = (0, truncation_hint_js_1.refreshTruncationHint)(target.hint, {
662
+ dropped: truncation.dropped_records,
663
+ returned: pagination.returned,
664
+ ...(neededBytes === undefined ? {} : { neededBytes }),
665
+ ...(allBytes === undefined ? {} : { allBytes }),
666
+ ...(withoutAdvice === true ? { withoutAdvice } : {}),
667
+ ...(widestHint === true ? { widest: true } : {}),
668
+ ...(capBytes === undefined ? {} : { capBytes }),
669
+ });
670
+ }
590
671
  }
591
672
  }
592
673
  };
@@ -595,9 +676,65 @@ function synchronizePagingFields(data, pagination, truncation, depth = 0) {
595
676
  synchronizeObject(record.meta);
596
677
  }
597
678
  for (const wrapper of ["request", "result"]) {
598
- synchronizePagingFields(record[wrapper], pagination, truncation, depth + 1);
679
+ synchronizePagingFields(record[wrapper], pagination, truncation, depth + 1, neededBytes, capBytes, allBytes, withoutAdvice, widestHint);
599
680
  }
600
681
  }
682
+ /**
683
+ * Remove `metadata.cache` and `metadata.timing` from a handler's result. Only
684
+ * the dispatcher reports them, from what it observed, so a value a handler
685
+ * sets is never passed on, whether or not the dispatcher adds its own.
686
+ */
687
+ function withoutCallMetadata(result) {
688
+ const content = result.structuredContent;
689
+ if (typeof content !== "object" || content === null)
690
+ return result;
691
+ const metadata = content.metadata;
692
+ if (typeof metadata !== "object" || metadata === null)
693
+ return result;
694
+ const rest = { ...metadata };
695
+ delete rest.cache;
696
+ delete rest.timing;
697
+ return { ...result, structuredContent: { ...content, metadata: rest } };
698
+ }
699
+ /**
700
+ * Add what the call reports about itself to a finished result's envelope
701
+ * metadata. The two fields are not counted against the result's byte limit.
702
+ *
703
+ * They are diagnostics, so they never cost the caller anything: the result is
704
+ * fitted to its limit first, exactly as before, with the fit, the paging
705
+ * fields and the truncation hint knowing nothing about them, and the fields
706
+ * are added after. A successful response therefore carries them always, on the
707
+ * calls where the timing matters most (a truncated one is often fitted to
708
+ * within a few bytes of the limit), and may exceed the limit by their size,
709
+ * under 100 bytes. A result that is not an envelope comes back untouched.
710
+ */
711
+ function withCallMetadata(handlerResult, snapshot) {
712
+ // Whatever the handler put in the two fields never survives, fitted or not.
713
+ const result = withoutCallMetadata(handlerResult);
714
+ const content = result.structuredContent;
715
+ if (typeof content !== "object" || content === null)
716
+ return result;
717
+ const metadata = content.metadata;
718
+ if (typeof metadata !== "object" || metadata === null)
719
+ return result;
720
+ // Only an envelope has limits; anything else is not this function's to annotate.
721
+ const maxBytes = metadata.limits?.max_bytes;
722
+ if (typeof maxBytes !== "number")
723
+ return result;
724
+ const added = callMetadataSchema.safeParse({
725
+ ...(snapshot.cache === undefined ? {} : { cache: snapshot.cache }),
726
+ timing: snapshot.timing,
727
+ });
728
+ if (!added.success)
729
+ return result;
730
+ return {
731
+ ...result,
732
+ structuredContent: {
733
+ ...content,
734
+ metadata: { ...metadata, ...added.data },
735
+ },
736
+ };
737
+ }
601
738
  function envelopeCompatibilityResult(name, args, result) {
602
739
  if (result.isError)
603
740
  return result;
@@ -616,14 +753,23 @@ function envelopeCompatibilityResult(name, args, result) {
616
753
  const explicitNextOffset = numericObjectField(data, "next_offset");
617
754
  const legacyTruncated = booleanObjectField(data, "truncated") === true;
618
755
  const priorDropped = numericObjectField(data, "dropped_records") ?? 0;
756
+ // A tool that dropped rows for size says so (truncated, dropped_records):
757
+ // rows exist that its response does not hold, so there is more to fetch.
758
+ const droppedForSize = collection && legacyTruncated && priorDropped > 0;
619
759
  let hasMore = collection &&
620
760
  (originalCount > returned ||
621
761
  explicitHasMore === true ||
762
+ droppedForSize ||
622
763
  (explicitHasMore === undefined && returned >= limit));
623
764
  let nextOffset;
624
765
  let recovery = legacyTruncated ? "adjust_request_and_retry_same_offset" : undefined;
625
766
  if (hasMore) {
626
- if (explicitNextOffset !== undefined && explicitNextOffset > offset) {
767
+ if (droppedForSize && returned > 0) {
768
+ // The rows returned are a prefix of the window, so the first row not
769
+ // returned is the one to continue at; nothing is skipped.
770
+ nextOffset = offset + returned;
771
+ }
772
+ else if (explicitNextOffset !== undefined && explicitNextOffset > offset) {
627
773
  nextOffset = explicitNextOffset;
628
774
  }
629
775
  else if (originalCount > returned && returned > 0) {
@@ -635,6 +781,11 @@ function envelopeCompatibilityResult(name, args, result) {
635
781
  // the effective limit prevents ACL-filtered windows from being replayed.
636
782
  nextOffset = offset + limit;
637
783
  }
784
+ else if (droppedForSize) {
785
+ // Not one row fit: has_more stays true, no offset can advance, and the
786
+ // request has to change.
787
+ recovery = "adjust_request_and_retry_same_offset";
788
+ }
638
789
  else {
639
790
  hasMore = false;
640
791
  recovery = "adjust_request_and_retry_same_offset";
@@ -689,13 +840,20 @@ function isMutableEnvelope(candidate) {
689
840
  }
690
841
  function renderEnvelopeText(envelope) {
691
842
  const pagination = envelope.metadata.pagination;
843
+ const noRowFit = pagination.mode === "offset" && pagination.returned === 0;
692
844
  const continuation = pagination.mode === "offset" && pagination.has_more
693
- ? ` More records are available at offset ${pagination.next_offset}.`
845
+ ? pagination.next_offset !== undefined
846
+ ? ` More records are available at offset ${pagination.next_offset}.`
847
+ : noRowFit
848
+ ? " More records are available, but none fit."
849
+ : " More records are available; this result has no offset to continue at."
694
850
  : "";
695
851
  const recovery = pagination.mode === "offset" && pagination.recovery !== undefined
696
- ? pagination.has_more
697
- ? ` To recover records dropped from the current window, adjust the request and retry offset ${pagination.offset}; use offset ${pagination.next_offset} only to resume after the consumed window.`
698
- : ` No automatic post-window continuation is available; adjust the request and retry offset ${pagination.offset}.`
852
+ ? pagination.has_more && pagination.next_offset !== undefined
853
+ ? ` Rows were dropped from the current window; next_offset is the first row not returned, or adjust the request and retry offset ${pagination.offset} to get them in one response.`
854
+ : noRowFit
855
+ ? ` No row fit; adjust the request (fewer fields, a lower limit or a higher max_response_bytes) and retry offset ${pagination.offset}.`
856
+ : ` Rows were dropped from the current window; adjust the request (fewer fields, a lower limit or a higher max_response_bytes) and retry offset ${pagination.offset}.`
699
857
  : "";
700
858
  const truncated = envelope.metadata.truncation.truncated
701
859
  ? ` Output was truncated by ${envelope.metadata.truncation.reason}.`
@@ -803,7 +961,7 @@ function renderedEnvelopeText(renderer, envelope, context) {
803
961
  */
804
962
  function finalizeEnvelopeResult(result, tool, options = {}) {
805
963
  envelopeTextRenderersSealed = true;
806
- const summarized = finalizeSummaryResult(result);
964
+ const summarized = finalizeSummaryResult(result, tool, options.maxResponseBytesCap);
807
965
  const renderer = tool === undefined ? undefined : ENVELOPE_TEXT_RENDERERS.get(tool);
808
966
  if (!summarized ||
809
967
  !renderer ||
@@ -827,20 +985,75 @@ function finalizeEnvelopeResult(result, tool, options = {}) {
827
985
  ? rendered
828
986
  : summarized;
829
987
  }
830
- function finalizeSummaryResult(result) {
988
+ /**
989
+ * The `max_response_bytes` to name for the whole window: what the tool
990
+ * measured for all its rows, plus what the envelope adds around them. Null
991
+ * when the tool named none (the window exceeded the maximum on its own) or
992
+ * when the sum exceeds the maximum, so the hint leaves it out.
993
+ */
994
+ function wholeWindowBytes(toolHint, envelopeBytes, current, cap) {
995
+ if (toolHint.allBytes === undefined)
996
+ return null;
997
+ const needed = (0, truncation_hint_js_1.neededResponseBytes)(toolHint.allBytes + envelopeBytes, current, cap);
998
+ return Number.isFinite(needed) ? needed : null;
999
+ }
1000
+ /**
1001
+ * The tools whose `offset` argument is a row offset into the collection they
1002
+ * return, so that `offset + rows returned` is the first row not returned. For
1003
+ * these a fit that drops rows for size can offer that offset as
1004
+ * `next_offset`. Any other collection still reports `has_more`, but with no
1005
+ * offset to give: the request has to change.
1006
+ */
1007
+ const OFFSET_PAGED_TOOLS = new Set([
1008
+ "sn_query",
1009
+ "sn_syslog",
1010
+ "sn_schema",
1011
+ "sn_relationships",
1012
+ "sn_codesearch",
1013
+ "sn_discover",
1014
+ "sn_attach",
1015
+ "sn_atf",
1016
+ ]);
1017
+ /**
1018
+ * Fit the result to its byte limit by dropping whole rows from the tail.
1019
+ * Rows dropped for size mean rows exist that the response does not hold, so
1020
+ * `has_more` is true; the rows returned are a prefix of the window, so a
1021
+ * paged tool continues at `offset + rows returned` and loses nothing, and
1022
+ * when no row fits there is no offset to give. With no `tool` (a caller that
1023
+ * does not say which), the offset is offered as for a paged tool.
1024
+ */
1025
+ function finalizeSummaryResult(result, tool, byteCap = utils_js_1.MAX_RESPONSE_BYTES_MAX) {
1026
+ const offsetPaged = tool === undefined || OFFSET_PAGED_TOOLS.has(tool);
831
1027
  if (!isMutableEnvelope(result.structuredContent))
832
1028
  return result;
833
1029
  const sourceEnvelope = JSON.parse(JSON.stringify(result.structuredContent));
834
1030
  let candidate = candidateResult(result, sourceEnvelope);
835
1031
  const maximum = sourceEnvelope.metadata.limits.max_bytes;
836
- if (resultBytes(candidate) <= maximum)
837
- return candidate;
1032
+ // A tool that dropped rows for size wrote the budget that would hold the
1033
+ // next row from what it could measure, the payload alone. Only here is the
1034
+ // rest of the result known.
1035
+ const toolHint = truncationHintParts(sourceEnvelope.data);
1036
+ if (resultBytes(candidate) <= maximum) {
1037
+ if (toolHint === undefined || !Number.isFinite(toolHint.neededBytes))
1038
+ return candidate;
1039
+ const overhead = resultBytes(candidate) - Buffer.byteLength(JSON.stringify(sourceEnvelope.data), "utf8");
1040
+ const restated = JSON.parse(JSON.stringify(sourceEnvelope));
1041
+ synchronizePagingFields(restated.data, restated.metadata.pagination, restated.metadata.truncation, 0, (0, truncation_hint_js_1.neededResponseBytes)(toolHint.neededBytes + overhead, maximum, byteCap), byteCap, wholeWindowBytes(toolHint, overhead, maximum, byteCap));
1042
+ const restatedCandidate = candidateResult(result, restated);
1043
+ // The larger number can add a digit; if that tips the result over its
1044
+ // limit, fit it like any other result that is too big.
1045
+ if (resultBytes(restatedCandidate) <= maximum)
1046
+ return restatedCandidate;
1047
+ }
838
1048
  const sourceRecords = collectionArray(sourceEnvelope.data);
839
1049
  let envelope = sourceEnvelope;
840
1050
  if (sourceRecords) {
841
1051
  const originalRecordCount = sourceRecords.length;
842
1052
  const priorDropped = sourceEnvelope.metadata.truncation.dropped_records ?? 0;
843
- const envelopeForCount = (count) => {
1053
+ // While fitting, a hint carries the widest form of its byte budget (the
1054
+ // "exceeds the maximum" clause), which is never shorter than a number, so
1055
+ // a result that fits that way still fits with the real number.
1056
+ const envelopeForCount = (count, neededBytes, allBytes, withoutAdvice, widestHint) => {
844
1057
  const probe = JSON.parse(JSON.stringify(sourceEnvelope));
845
1058
  const probeRecords = collectionArray(probe.data);
846
1059
  if (!probeRecords)
@@ -851,36 +1064,106 @@ function finalizeSummaryResult(result) {
851
1064
  if (probe.metadata.pagination.mode === "offset") {
852
1065
  probe.metadata.pagination.returned = count;
853
1066
  if (count < originalRecordCount) {
854
- probe.metadata.pagination.recovery =
855
- "adjust_request_and_retry_same_offset";
1067
+ const paging = probe.metadata.pagination;
1068
+ paging.recovery = "adjust_request_and_retry_same_offset";
1069
+ paging.has_more = true;
1070
+ if (offsetPaged && count > 0) {
1071
+ paging.next_offset = paging.offset + count;
1072
+ }
1073
+ else {
1074
+ delete paging.next_offset;
1075
+ }
856
1076
  }
857
1077
  }
858
1078
  applyByteTruncation(probe, priorDropped + originalRecordCount - count);
859
- synchronizePagingFields(probe.data, probe.metadata.pagination, probe.metadata.truncation);
1079
+ synchronizePagingFields(probe.data, probe.metadata.pagination, probe.metadata.truncation, 0, neededBytes, byteCap, allBytes, withoutAdvice, widestHint);
860
1080
  return probe;
861
1081
  };
862
- let low = 0;
863
- let high = originalRecordCount;
1082
+ const widest = Number.POSITIVE_INFINITY;
1083
+ // The forms the hint can take while fitting, fullest first. The labelled
1084
+ // hint is longer than the bare one was, and at the smallest budgets the
1085
+ // envelope's own metadata leaves room for little more than the counts: the
1086
+ // page figure can go, then the field advice, which is the least that
1087
+ // still names the next row's budget. A narrower form is used only when no
1088
+ // row, not even zero, fits beside the fuller one. Each form's widest text
1089
+ // (the longest any real figures could make it) is what rows are sized
1090
+ // with, and the real text is rendered in the same form, so it is never
1091
+ // longer than the probe. The budget named for the next row is always
1092
+ // measured with the fullest form, so a call at that budget, which takes
1093
+ // the fullest form that fits, returns the row.
1094
+ const forms = toolHint === undefined
1095
+ ? [{ all: widest, withoutAdvice: false }]
1096
+ : [
1097
+ { all: widest, withoutAdvice: false },
1098
+ { all: null, withoutAdvice: false },
1099
+ { all: null, withoutAdvice: true },
1100
+ ];
864
1101
  let best = -1;
865
- while (low <= high) {
866
- const midpoint = Math.floor((low + high) / 2);
867
- const probe = candidateResult(result, envelopeForCount(midpoint));
868
- if (resultBytes(probe) <= maximum) {
869
- best = midpoint;
870
- low = midpoint + 1;
871
- }
872
- else {
873
- high = midpoint - 1;
1102
+ let form = forms[0];
1103
+ for (const candidateForm of forms) {
1104
+ let low = 0;
1105
+ let high = originalRecordCount;
1106
+ let fitted = -1;
1107
+ while (low <= high) {
1108
+ const midpoint = Math.floor((low + high) / 2);
1109
+ const probe = candidateResult(result, envelopeForCount(midpoint, widest, candidateForm.all, candidateForm.withoutAdvice, true));
1110
+ if (resultBytes(probe) <= maximum) {
1111
+ fitted = midpoint;
1112
+ low = midpoint + 1;
1113
+ }
1114
+ else {
1115
+ high = midpoint - 1;
1116
+ }
874
1117
  }
1118
+ // The first form that fits (zero rows is enough) is the one used.
1119
+ form = candidateForm;
1120
+ best = fitted;
1121
+ if (best >= 0)
1122
+ break;
875
1123
  }
876
1124
  // Collections are fitted only by removing complete rows. In particular,
877
1125
  // never shorten a field merely to force one row into the envelope: callers
878
1126
  // can retry this exact window with a narrower projection/larger budget,
879
1127
  // while next_offset (when present) remains the separately authoritative
880
1128
  // post-window resume point.
881
- envelope = envelopeForCount(Math.max(best, 0));
1129
+ const kept = Math.max(best, 0);
1130
+ envelope = envelopeForCount(kept, widest, form.all, form.withoutAdvice, true);
882
1131
  candidate = candidateResult(result, envelope);
883
- return resultBytes(candidate) <= maximum ? candidate : undefined;
1132
+ if (resultBytes(candidate) > maximum)
1133
+ return undefined;
1134
+ if (toolHint === undefined)
1135
+ return candidate;
1136
+ // The rows the tool already dropped are not here to measure, so the whole
1137
+ // window is its payload size, which the tool measured, plus what this
1138
+ // envelope adds around the rows. The envelope of a whole page carries no
1139
+ // truncation fields, so this is never too small.
1140
+ const overhead = resultBytes(candidate) - Buffer.byteLength(JSON.stringify(envelope.data), "utf8");
1141
+ // The budget that would hold one more row is measured here, with the
1142
+ // envelope's own cost in it, not guessed. When the fit dropped nothing
1143
+ // (the tool had already dropped every row, and only a narrower form
1144
+ // fitted) there is no row of ours to add: it is the tool's figure plus
1145
+ // the envelope's cost, as in the first branch.
1146
+ // With no row returned the envelope carries no `next_offset`, which the
1147
+ // first row brings with it, in the data and in the pagination metadata. The
1148
+ // zero-row overhead would then name a budget a few bytes short of one row.
1149
+ const overheadWithARow = (zeroOrMore, rows, base) => {
1150
+ if (rows > 0 || !offsetPaged)
1151
+ return base;
1152
+ const withRow = JSON.parse(JSON.stringify(zeroOrMore));
1153
+ const paging = withRow.metadata.pagination;
1154
+ if (paging.mode !== "offset")
1155
+ return base;
1156
+ paging.returned = 1;
1157
+ paging.next_offset = paging.offset + 1;
1158
+ synchronizePagingFields(withRow.data, withRow.metadata.pagination, withRow.metadata.truncation, 0, undefined, byteCap);
1159
+ return (resultBytes(candidateResult(result, withRow)) -
1160
+ Buffer.byteLength(JSON.stringify(withRow.data), "utf8"));
1161
+ };
1162
+ const needed = kept >= originalRecordCount
1163
+ ? (0, truncation_hint_js_1.neededResponseBytes)(toolHint.neededBytes + overheadWithARow(envelope, kept, overhead), maximum, byteCap)
1164
+ : (0, truncation_hint_js_1.neededResponseBytes)(resultBytes(candidateResult(result, envelopeForCount(kept + 1, widest, forms[0].all, false, true))), maximum, byteCap);
1165
+ const restated = candidateResult(result, envelopeForCount(kept, needed, form.all === null ? null : wholeWindowBytes(toolHint, overhead, maximum, byteCap), form.withoutAdvice));
1166
+ return resultBytes(restated) <= maximum ? restated : candidate;
884
1167
  }
885
1168
  while (resultBytes(candidate) > maximum && truncateLongestString(envelope.data)) {
886
1169
  applyByteTruncation(envelope, envelope.metadata.truncation.dropped_records ?? 0);