@onlyflows/servicenow-mcp 2.3.0 → 2.4.0-rc.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.
Files changed (131) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +206 -22
  3. package/dist/atf-result-cache.d.ts +2 -2
  4. package/dist/call-metrics.d.ts +11 -1
  5. package/dist/call-metrics.d.ts.map +1 -1
  6. package/dist/call-metrics.js +2 -0
  7. package/dist/call-metrics.js.map +1 -1
  8. package/dist/client.d.ts +10 -0
  9. package/dist/client.d.ts.map +1 -1
  10. package/dist/client.js +31 -3
  11. package/dist/client.js.map +1 -1
  12. package/dist/execution-context.d.ts +3 -3
  13. package/dist/execution-context.d.ts.map +1 -1
  14. package/dist/execution-context.js +7 -2
  15. package/dist/execution-context.js.map +1 -1
  16. package/dist/field-policy.d.ts +8 -0
  17. package/dist/field-policy.d.ts.map +1 -1
  18. package/dist/field-policy.js +239 -46
  19. package/dist/field-policy.js.map +1 -1
  20. package/dist/hidden-values.d.ts +368 -21
  21. package/dist/hidden-values.d.ts.map +1 -1
  22. package/dist/hidden-values.js +1050 -101
  23. package/dist/hidden-values.js.map +1 -1
  24. package/dist/http-observability.js +3 -1
  25. package/dist/http-observability.js.map +1 -1
  26. package/dist/inert-text.d.ts +27 -0
  27. package/dist/inert-text.d.ts.map +1 -0
  28. package/dist/inert-text.js +57 -0
  29. package/dist/inert-text.js.map +1 -0
  30. package/dist/policy-card.d.ts +1 -1
  31. package/dist/policy-card.d.ts.map +1 -1
  32. package/dist/policy-card.js +3 -1
  33. package/dist/policy-card.js.map +1 -1
  34. package/dist/setup-prompts.js +1 -0
  35. package/dist/setup-prompts.js.map +1 -1
  36. package/dist/setup.js +6 -0
  37. package/dist/setup.js.map +1 -1
  38. package/dist/tool-error.d.ts +39 -3
  39. package/dist/tool-error.d.ts.map +1 -1
  40. package/dist/tool-error.js +101 -2
  41. package/dist/tool-error.js.map +1 -1
  42. package/dist/tool-table-access.d.ts.map +1 -1
  43. package/dist/tool-table-access.js +5 -0
  44. package/dist/tool-table-access.js.map +1 -1
  45. package/dist/tools/aggregate.d.ts +8 -0
  46. package/dist/tools/aggregate.d.ts.map +1 -1
  47. package/dist/tools/aggregate.js +70 -11
  48. package/dist/tools/aggregate.js.map +1 -1
  49. package/dist/tools/atf-contracts.d.ts +9 -9
  50. package/dist/tools/catalog.d.ts +2 -2
  51. package/dist/tools/catalog.d.ts.map +1 -1
  52. package/dist/tools/catalog.js +9 -0
  53. package/dist/tools/catalog.js.map +1 -1
  54. package/dist/tools/envelope-text-fit.d.ts +20 -0
  55. package/dist/tools/envelope-text-fit.d.ts.map +1 -0
  56. package/dist/tools/envelope-text-fit.js +33 -0
  57. package/dist/tools/envelope-text-fit.js.map +1 -0
  58. package/dist/tools/flow-view-mermaid.d.ts.map +1 -1
  59. package/dist/tools/flow-view-mermaid.js +6 -13
  60. package/dist/tools/flow-view-mermaid.js.map +1 -1
  61. package/dist/tools/flow-view-module.js +1 -1
  62. package/dist/tools/get-module.js +1 -1
  63. package/dist/tools/history-contracts.d.ts +198 -0
  64. package/dist/tools/history-contracts.d.ts.map +1 -0
  65. package/dist/tools/history-contracts.js +317 -0
  66. package/dist/tools/history-contracts.js.map +1 -0
  67. package/dist/tools/history-module.d.ts +158 -0
  68. package/dist/tools/history-module.d.ts.map +1 -0
  69. package/dist/tools/history-module.js +937 -0
  70. package/dist/tools/history-module.js.map +1 -0
  71. package/dist/tools/history-renderers.d.ts +32 -0
  72. package/dist/tools/history-renderers.d.ts.map +1 -0
  73. package/dist/tools/history-renderers.js +154 -0
  74. package/dist/tools/history-renderers.js.map +1 -0
  75. package/dist/tools/index.d.ts +3 -3
  76. package/dist/tools/index.d.ts.map +1 -1
  77. package/dist/tools/index.js +31 -14
  78. package/dist/tools/index.js.map +1 -1
  79. package/dist/tools/platform-view-contracts.d.ts +4 -4
  80. package/dist/tools/platform-view-contracts.d.ts.map +1 -1
  81. package/dist/tools/platform-view-contracts.js +3 -0
  82. package/dist/tools/platform-view-contracts.js.map +1 -1
  83. package/dist/tools/platform-view-evaluate.d.ts +7 -2
  84. package/dist/tools/platform-view-evaluate.d.ts.map +1 -1
  85. package/dist/tools/platform-view-evaluate.js +44 -130
  86. package/dist/tools/platform-view-evaluate.js.map +1 -1
  87. package/dist/tools/platform-view-module.d.ts +12 -3
  88. package/dist/tools/platform-view-module.d.ts.map +1 -1
  89. package/dist/tools/platform-view-module.js +61 -16
  90. package/dist/tools/platform-view-module.js.map +1 -1
  91. package/dist/tools/platform-view-payload.d.ts +101 -0
  92. package/dist/tools/platform-view-payload.d.ts.map +1 -0
  93. package/dist/tools/platform-view-payload.js +302 -0
  94. package/dist/tools/platform-view-payload.js.map +1 -0
  95. package/dist/tools/platform-view-update-sets.d.ts +129 -0
  96. package/dist/tools/platform-view-update-sets.d.ts.map +1 -0
  97. package/dist/tools/platform-view-update-sets.js +1060 -0
  98. package/dist/tools/platform-view-update-sets.js.map +1 -0
  99. package/dist/tools/query-module.js +1 -1
  100. package/dist/tools/relationships-map.d.ts +59 -0
  101. package/dist/tools/relationships-map.d.ts.map +1 -0
  102. package/dist/tools/relationships-map.js +162 -0
  103. package/dist/tools/relationships-map.js.map +1 -0
  104. package/dist/tools/relationships-renderer.d.ts +22 -0
  105. package/dist/tools/relationships-renderer.d.ts.map +1 -0
  106. package/dist/tools/relationships-renderer.js +90 -0
  107. package/dist/tools/relationships-renderer.js.map +1 -0
  108. package/dist/tools/relationships.d.ts +37 -2
  109. package/dist/tools/relationships.d.ts.map +1 -1
  110. package/dist/tools/relationships.js +602 -183
  111. package/dist/tools/relationships.js.map +1 -1
  112. package/dist/tools/result-envelope.d.ts +314 -15
  113. package/dist/tools/result-envelope.d.ts.map +1 -1
  114. package/dist/tools/result-envelope.js +120 -19
  115. package/dist/tools/result-envelope.js.map +1 -1
  116. package/dist/tools/syslog.d.ts +1 -1
  117. package/dist/tools/table-hierarchy.d.ts +17 -0
  118. package/dist/tools/table-hierarchy.d.ts.map +1 -1
  119. package/dist/tools/table-hierarchy.js +41 -0
  120. package/dist/tools/table-hierarchy.js.map +1 -1
  121. package/dist/version.d.ts +1 -1
  122. package/dist/version.d.ts.map +1 -1
  123. package/dist/version.js +1 -1
  124. package/dist/version.js.map +1 -1
  125. package/docs/CLIENT-SETUP.md +2 -2
  126. package/docs/CROSS-CLIENT-RELEASE-MATRIX.md +2 -2
  127. package/docs/PRODUCTION-SECURITY.md +145 -2
  128. package/docs/RELEASE-VALIDATION.md +2 -2
  129. package/docs/TESTING-OAUTH.md +1 -1
  130. package/package.json +2 -2
  131. package/server.json +2 -2
@@ -0,0 +1,937 @@
1
+ "use strict";
2
+ /**
3
+ * `sn_history`: one record's history, newest first: its audited field
4
+ * changes (`sys_audit`), its comments and work notes (`sys_journal_field`)
5
+ * and the flows that ran on it (`sys_flow_context`).
6
+ *
7
+ * Access plan (`historyAccessPlan`), decided before any read:
8
+ * - the record's table, with `sys_id` and `sys_class_name` readable under
9
+ * field policy (otherwise the call is refused before it reads anything);
10
+ * - `sys_db_object` and `sys_dictionary`, for the class's field types, when
11
+ * the profile may read them. Without them every value is withheld;
12
+ * - each source the profile may read, decided on its own as `sn_codesearch`
13
+ * decides its code tables: a source whose table is not granted (including a
14
+ * named-only table under `"*"`, or a target not bound to this tool), or
15
+ * whose key columns field policy hides, is reported `not_granted` and left
16
+ * out of the plan. The call fails only when a source the caller named
17
+ * explicitly is refused, or when no source is left.
18
+ * The mirror tables (`sys_history_line`, `sys_audit_delete`,
19
+ * `sys_email`) are never read.
20
+ *
21
+ * Reads, at most six per page (four once the class's types are memoized):
22
+ * 1. the record (`GET <table>/<sys_id>`, `sys_id,sys_class_name`). A record
23
+ * that is missing or that the instance refuses is `not_found`; a record
24
+ * whose class is not `table` is refused with the class to call with;
25
+ * 2. the class's extension chain (`sys_db_object`) and every dictionary row
26
+ * of that chain (`sys_dictionary`), uncached and then kept for an hour in
27
+ * the per-credential memo, so a warm call skips both. Skipped as well when
28
+ * no source on the page needs types. The chain counts only when it is
29
+ * known to end at a table that extends nothing;
30
+ * 3. each planned source, newest first, `limit + 1` rows, uncached. The
31
+ * journal and flow reads run with step 2; the audit read follows it, so
32
+ * its query leaves out the chain's journal fields. A source whose page is
33
+ * too large for the client is asked again for half the rows, down to one
34
+ * row; past that it alone is `too_large` and the others still answer.
35
+ *
36
+ * Every source row must carry the record's class and sys_id in its key
37
+ * columns, or it is dropped (`omitted.mismatch`). Then, in order:
38
+ * (a) an audit row for a journal-typed field (by the dictionary type found
39
+ * walking up the class's chain, never by name) is left out of the audit
40
+ * query, and dropped if it comes back anyway: journal text, and whether
41
+ * there is any, comes only through the journal source and its own grant.
42
+ * Without types, the platform's journal field names are left out the same
43
+ * way unless the call reads the journal source;
44
+ * (b) a row whose field the profile may not read on the class (field policy,
45
+ * a sensitive name, a type the call hides, or a column that field policy
46
+ * keeps closed, such as a record payload or a process command line) is
47
+ * dropped (`omitted.unreadable`), unnamed;
48
+ * (c) a value whose field is hidden by type, sits on a credential table or
49
+ * has an unknown type is withheld (`value_hidden`). This uses the shared
50
+ * type helper over the dictionary rows of step 2, so an unreadable
51
+ * dictionary withholds every value.
52
+ * Values are cut at 2,000 characters; references stay raw sys_ids. No row is
53
+ * cached.
54
+ *
55
+ * Paging: each source has its own position, `encodeTailCursor` bound to the
56
+ * record, the source and the filters (`historyCursorFilter`). The newest
57
+ * `limit` events of all sources are returned; a source's cursor stands at
58
+ * the last of its rows this page consumed, so a page never skips or repeats.
59
+ *
60
+ * A page where every source that still has entries is `too_large` carries a
61
+ * `hint` (`STUCK_PAGE_HINT`): repeating the call unchanged would not move on.
62
+ *
63
+ * Registered in `catalog.ts`; its output schema and byte limit are its
64
+ * result-envelope entries.
65
+ *
66
+ * @module tools/history-module
67
+ */
68
+ Object.defineProperty(exports, "__esModule", { value: true });
69
+ exports.historyToolModule = exports.FITTED_WARNING = exports.STUCK_PAGE_HINT = exports.TOO_LARGE_WARNING = exports.VALUES_NOT_READABLE_WARNING = exports.INVALID_CURSOR_HINT = exports.WRONG_CLASS_HINT = exports.MIN_SOURCE_READ_ROWS = exports.MAX_HISTORY_DICTIONARY_ROWS = exports.JOURNAL_FIELD_NAMES = void 0;
70
+ exports.isRecordContentColumn = isRecordContentColumn;
71
+ exports.historyAccessPlan = historyAccessPlan;
72
+ exports.classTypesWarning = classTypesWarning;
73
+ exports.auditExclusions = auditExclusions;
74
+ exports.sourceQuery = sourceQuery;
75
+ exports.resolveHistoryAccess = resolveHistoryAccess;
76
+ const client_js_1 = require("../client.js");
77
+ const field_policy_js_1 = require("../field-policy.js");
78
+ const hidden_values_js_1 = require("../hidden-values.js");
79
+ const metadata_cache_js_1 = require("../metadata-cache.js");
80
+ const servicenow_identifiers_js_1 = require("../servicenow-identifiers.js");
81
+ const table_policy_js_1 = require("../table-policy.js");
82
+ const tool_error_js_1 = require("../tool-error.js");
83
+ const utils_js_1 = require("../utils.js");
84
+ const history_contracts_js_1 = require("./history-contracts.js");
85
+ const result_envelope_js_1 = require("./result-envelope.js");
86
+ const syslog_cursor_js_1 = require("./syslog-cursor.js");
87
+ const table_hierarchy_js_1 = require("./table-hierarchy.js");
88
+ const tool_module_js_1 = require("./tool-module.js");
89
+ const TOOL = "sn_history";
90
+ const TABLE_PATH = "/api/now/table/";
91
+ const L = history_contracts_js_1.HISTORY_LIMITS;
92
+ /** Dictionary types whose values are journal text. */
93
+ const JOURNAL_TYPES = new Set(["journal", "journal_input", "journal_list"]);
94
+ /**
95
+ * The platform's own journal fields, by name. Used only to leave rows out when
96
+ * the types cannot be read and the journal source is not in the call: a name
97
+ * never makes a row visible.
98
+ */
99
+ exports.JOURNAL_FIELD_NAMES = Object.freeze(["comments", "comments_and_work_notes", "work_notes"]);
100
+ /** Depth of the class chain walked for field types. */
101
+ const MAX_HIERARCHY_DEPTH = 12;
102
+ /** A dictionary read that returns this many rows may be cut short, so its types are unavailable. */
103
+ exports.MAX_HISTORY_DICTIONARY_ROWS = 5_000;
104
+ /** Bytes kept back from `max_response_bytes` for the envelope around `data`. */
105
+ const ENVELOPE_RESERVE_BYTES = 2_000;
106
+ /** The highest sys_id: a position at the end of one second, for a source this page did not reach. */
107
+ const END_OF_SECOND = "f".repeat(32);
108
+ /** A position before every row: where a source that returned nothing yet starts again. */
109
+ const BEFORE_ALL = Object.freeze({ timestamp: "9999-12-31 23:59:59", sysId: END_OF_SECOND });
110
+ /** The fewest rows a source read asks for after a response was too large: one row and the look-ahead. */
111
+ exports.MIN_SOURCE_READ_ROWS = 2;
112
+ const TABLE_NAME = /^[a-z][a-z0-9_]{0,79}$/u;
113
+ const WRONG_CLASS_HINT = (recordClass) => `This record's class is ${recordClass}. Call again with table: ${recordClass}.`;
114
+ exports.WRONG_CLASS_HINT = WRONG_CLASS_HINT;
115
+ exports.INVALID_CURSOR_HINT = "The cursor was returned for another record, source or filter. Repeat the call that returned it with " +
116
+ "the same arguments, or leave cursor out to start from the newest entry.";
117
+ const VALUES_NOT_READABLE_WARNING = (source) => `Field policy hides the ${source} value columns, so no ${source} values are shown.`;
118
+ exports.VALUES_NOT_READABLE_WARNING = VALUES_NOT_READABLE_WARNING;
119
+ const TOO_LARGE_WARNING = (source) => `The newest ${source} entries were too large to return, so ${source} was skipped on this page. ` +
120
+ "Repeat the call with include_values: false or a narrower since/until to read them.";
121
+ exports.TOO_LARGE_WARNING = TOO_LARGE_WARNING;
122
+ /**
123
+ * Every source with entries left was too large to read on this page, so
124
+ * repeating the call with the same arguments returns the same page. The
125
+ * limit is the client's per-response cap, which `max_response_bytes` does
126
+ * not change.
127
+ */
128
+ const STUCK_PAGE_HINT = (sources) => `Paging on with the same arguments will not progress: ${sources.join(", ")} ` +
129
+ `${sources.length === 1 ? "is" : "are"} too large to read. Use include_values: false, a narrower ` +
130
+ `since/until, or leave ${sources.length === 1 ? "that source" : "them"} out of sources.`;
131
+ exports.STUCK_PAGE_HINT = STUCK_PAGE_HINT;
132
+ exports.FITTED_WARNING = "Fewer events than limit fit max_response_bytes; the rest follow with next_cursor.";
133
+ function read(table) {
134
+ return Object.freeze({ operation: "read", table });
135
+ }
136
+ /** Whether every one of `fields` is readable on `table` under the call's field policy. */
137
+ function canRead(table, fields) {
138
+ try {
139
+ (0, field_policy_js_1.resolveReadableFields)(table, { fields: fields.join(",") });
140
+ return true;
141
+ }
142
+ catch (error) {
143
+ if ((0, field_policy_js_1.isFieldPolicyError)(error))
144
+ return false;
145
+ throw error;
146
+ }
147
+ }
148
+ /**
149
+ * True for a column that field policy keeps closed on `table` (a record
150
+ * payload or a process command line; see `explicitReadColumns`). History
151
+ * never shows such a column, even where a profile opened it for reading: its
152
+ * audit rows are dropped and it cannot be named in `fields`. A table that
153
+ * extends one with such columns has them too, wherever its chain is known.
154
+ */
155
+ function isRecordContentColumn(table, field) {
156
+ return (0, field_policy_js_1.explicitReadColumns)(table)?.has(field) === true;
157
+ }
158
+ /**
159
+ * The call's access plan. It throws (and so refuses the call before any read)
160
+ * when the record cannot be identified under field policy, when `fields`
161
+ * names a field the profile may not read, when a source the caller named is
162
+ * refused, or when no source is left. Every other refusal narrows the plan.
163
+ *
164
+ * Pure apart from the policy it consults: the dispatcher runs it inside the
165
+ * call's field-policy and type scopes, and the handler runs it again there,
166
+ * so both see the same plan.
167
+ */
168
+ function historyAccessPlan(args, tableAccess) {
169
+ const table = args.table;
170
+ // The class is read before anything else; a profile that may not read
171
+ // it gets nothing, rather than a history keyed to a guessed class.
172
+ (0, field_policy_js_1.resolveReadableFields)(table, { fields: "sys_id,sys_class_name" });
173
+ if (args.fields !== undefined) {
174
+ (0, field_policy_js_1.resolveReadableFields)(table, { fields: args.fields.join(",") });
175
+ const content = args.fields.find((field) => isRecordContentColumn(table, field));
176
+ if (content !== undefined)
177
+ throw new field_policy_js_1.FieldPolicyError("unreadable_field", { table, field: content });
178
+ }
179
+ let dictionary = false;
180
+ try {
181
+ (0, table_policy_js_1.authorizeTableAccess)(tableAccess, read("sys_db_object"), TOOL);
182
+ (0, table_policy_js_1.authorizeTableAccess)(tableAccess, read("sys_dictionary"), TOOL);
183
+ dictionary = canRead("sys_db_object", history_contracts_js_1.HISTORY_HIERARCHY_FIELDS) && canRead("sys_dictionary", history_contracts_js_1.HISTORY_DICTIONARY_FIELDS);
184
+ }
185
+ catch (error) {
186
+ if (!(0, table_policy_js_1.isTablePolicyError)(error))
187
+ throw error;
188
+ }
189
+ const auditFlag = dictionary && canRead("sys_dictionary", [history_contracts_js_1.HISTORY_DICTIONARY_AUDIT_FIELD]);
190
+ const explicit = args.sources !== undefined;
191
+ const asked = args.sources ?? history_contracts_js_1.HISTORY_SOURCES;
192
+ const sources = [];
193
+ let firstDenial;
194
+ for (const source of asked) {
195
+ const spec = history_contracts_js_1.HISTORY_SOURCE_SPECS[source];
196
+ try {
197
+ (0, table_policy_js_1.authorizeTableAccess)(tableAccess, read(spec.table), TOOL);
198
+ (0, field_policy_js_1.resolveReadableFields)(spec.table, { fields: spec.keys.join(",") });
199
+ }
200
+ catch (error) {
201
+ if (!(0, table_policy_js_1.isTablePolicyError)(error) && !(0, field_policy_js_1.isFieldPolicyError)(error))
202
+ throw error;
203
+ if (explicit)
204
+ throw error;
205
+ firstDenial ??= error;
206
+ sources.push(Object.freeze({ source, spec, granted: false, fields: [], user: false, values: false, valuesHidden: false }));
207
+ continue;
208
+ }
209
+ const user = canRead(spec.table, [spec.user]);
210
+ const valuesReadable = spec.values.length > 0 && canRead(spec.table, spec.values);
211
+ const values = args.include_values && valuesReadable;
212
+ const extras = spec.extras.filter((field) => canRead(spec.table, [field]));
213
+ sources.push(Object.freeze({
214
+ source,
215
+ spec,
216
+ granted: true,
217
+ fields: Object.freeze([...spec.keys, ...(user ? [spec.user] : []), ...(values ? spec.values : []), ...extras]),
218
+ user,
219
+ values,
220
+ valuesHidden: args.include_values && spec.values.length > 0 && !valuesReadable,
221
+ }));
222
+ }
223
+ if (!sources.some((entry) => entry.granted)) {
224
+ if ((0, field_policy_js_1.isFieldPolicyError)(firstDenial))
225
+ throw firstDenial;
226
+ throw new table_policy_js_1.TablePolicyError({
227
+ reason: "none_granted",
228
+ operation: "read",
229
+ tool: TOOL,
230
+ tables: history_contracts_js_1.HISTORY_SOURCES.map((source) => history_contracts_js_1.HISTORY_SOURCE_SPECS[source].table),
231
+ });
232
+ }
233
+ const tables = [
234
+ table,
235
+ ...(dictionary ? ["sys_db_object", "sys_dictionary"] : []),
236
+ ...sources.filter((entry) => entry.granted).map((entry) => entry.spec.table),
237
+ ];
238
+ return Object.freeze({
239
+ table,
240
+ dictionary,
241
+ auditFlag,
242
+ sources: Object.freeze(sources),
243
+ requests: Object.freeze([...new Set(tables)].map(read)),
244
+ });
245
+ }
246
+ // ---------------------------------------------------------------------------
247
+ // Reading
248
+ // ---------------------------------------------------------------------------
249
+ function inOwnScope(signal, operation) {
250
+ return signal instanceof AbortSignal ? (0, client_js_1.runWithServiceNowRequestSignal)(signal, operation) : operation();
251
+ }
252
+ function rowsOf(response) {
253
+ const result = response?.result;
254
+ return Array.isArray(result)
255
+ ? result.filter((row) => typeof row === "object" && row !== null && !Array.isArray(row))
256
+ : [];
257
+ }
258
+ /** A stored value as text: a string, or the `value` of a `{value, display_value}` pair. */
259
+ function stored(value) {
260
+ if (typeof value === "string")
261
+ return value;
262
+ if (typeof value === "number" && Number.isFinite(value))
263
+ return String(value);
264
+ if (typeof value === "boolean")
265
+ return String(value);
266
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
267
+ const inner = value.value;
268
+ if (typeof inner === "string")
269
+ return inner;
270
+ }
271
+ return undefined;
272
+ }
273
+ function key(value) {
274
+ return (stored(value) ?? "").trim().toLowerCase();
275
+ }
276
+ const CONTROL_CHARACTERS = /[\u0000-\u001F\u007F-\u009F]/gu;
277
+ /** Cut at `max` code units without splitting a surrogate pair. */
278
+ function cut(value, max) {
279
+ if (value.length <= max)
280
+ return { text: value, cut: false };
281
+ let end = max;
282
+ const last = value.charCodeAt(end - 1);
283
+ if (last >= 0xd800 && last <= 0xdbff)
284
+ end -= 1;
285
+ return { text: value.slice(0, end), cut: true };
286
+ }
287
+ /** A short instance string on one line, or undefined when empty. */
288
+ function shortText(value, max) {
289
+ const raw = stored(value);
290
+ if (raw === undefined)
291
+ return undefined;
292
+ const flat = raw.replace(CONTROL_CHARACTERS, " ").trim();
293
+ return flat === "" ? undefined : cut(flat, max).text;
294
+ }
295
+ function errorCategory(error) {
296
+ return (0, tool_error_js_1.trustedToolErrorDescriptor)(error)?.category;
297
+ }
298
+ /** The Table API's answer for a table that does not exist: an `upstream` error with no reason. */
299
+ function isMissingTable(error) {
300
+ const descriptor = (0, tool_error_js_1.trustedToolErrorDescriptor)(error);
301
+ return descriptor?.category === "upstream" && descriptor.retry === "do_not_retry" && descriptor.reason === undefined;
302
+ }
303
+ /**
304
+ * The record's class. A missing record, one the instance refuses to show and
305
+ * a table the instance does not have are all `not_found`, so the answer says
306
+ * nothing about a record the caller cannot see. An empty class means the
307
+ * table is not extended: the class is the table.
308
+ */
309
+ async function readRecordClass(ops, args, signal) {
310
+ let response;
311
+ try {
312
+ response = await inOwnScope(signal, () => ops.get(`${TABLE_PATH}${args.table}/${(0, servicenow_identifiers_js_1.serviceNowSysIdPathSegment)(args.sys_id)}`, {
313
+ sysparm_fields: "sys_id,sys_class_name",
314
+ sysparm_display_value: "false",
315
+ sysparm_exclude_reference_link: "true",
316
+ }));
317
+ }
318
+ catch (error) {
319
+ if ((0, client_js_1.isServiceNowRequestCancellation)(error) || signal?.aborted)
320
+ throw error;
321
+ const category = errorCategory(error);
322
+ if (category === "not_found" || category === "authorization" || isMissingTable(error)) {
323
+ throw (0, tool_error_js_1.createToolError)("not_found", "do_not_retry");
324
+ }
325
+ throw error;
326
+ }
327
+ const result = response?.result;
328
+ const row = Array.isArray(result) ? result[0] : result;
329
+ if (typeof row !== "object" || row === null || key(row.sys_id) !== args.sys_id) {
330
+ throw (0, tool_error_js_1.createToolError)("not_found", "do_not_retry");
331
+ }
332
+ const recordClass = key(row.sys_class_name);
333
+ if (recordClass === "")
334
+ return args.table;
335
+ // Only a valid table name is ever repeated or put in a query.
336
+ if (!TABLE_NAME.test(recordClass))
337
+ throw (0, tool_error_js_1.createToolError)("upstream", "do_not_retry");
338
+ return recordClass;
339
+ }
340
+ /** This profile's plan does not read sys_db_object and sys_dictionary: a cause of this server's own policy. */
341
+ const POLICY_WHY = Object.freeze({
342
+ failure: Object.freeze({ kind: "policy", table: "sys_dictionary" }),
343
+ });
344
+ /** The types of a call whose profile does not read them: one value, shared. */
345
+ const POLICY_TYPES = unavailableTypes(POLICY_WHY);
346
+ /** The warning for a class whose types are not known, worded from its cause. */
347
+ function classTypesWarning(why) {
348
+ return (0, hidden_values_js_1.fieldTypesProblemText)({ surface: "history", ...(why ?? {}) });
349
+ }
350
+ function unavailableTypes(why, auditEnabled = null) {
351
+ return Object.freeze({
352
+ types: (0, hidden_values_js_1.fieldTypesUnavailable)(why.failure ?? (why.problem?.kind === "read" ? why.problem.failure : undefined)),
353
+ auditEnabled,
354
+ why,
355
+ });
356
+ }
357
+ const CLASS_TYPES_MEMO_PREFIX = "sn_history:class-types:v1:";
358
+ function isClassTypesEntry(candidate) {
359
+ if (typeof candidate !== "object" || candidate === null)
360
+ return false;
361
+ const entry = candidate;
362
+ return Array.isArray(entry.chain) && Array.isArray(entry.rows) && typeof entry.complete === "boolean" && typeof entry.full === "boolean";
363
+ }
364
+ function isClassTypesFailure(candidate) {
365
+ return typeof candidate === "object" && candidate !== null && "failed" in candidate && "read" in candidate;
366
+ }
367
+ function failureTypes(failure) {
368
+ return unavailableTypes({ failure: failure.failed, read: failure.read });
369
+ }
370
+ function typesOf(entry, recordClass) {
371
+ if (entry.full)
372
+ return unavailableTypes({ failure: Object.freeze({ kind: "incomplete" }), read: "sys_dictionary" });
373
+ if (!entry.complete) {
374
+ // The class's own row is not readable: the instance showed this user no
375
+ // sys_db_object row for it. Otherwise the chain stops short at a table.
376
+ if (entry.gap === "no_row") {
377
+ return unavailableTypes({ failure: Object.freeze({ kind: "refused", status: 200 }), read: "sys_db_object" }, entry.auditEnabled);
378
+ }
379
+ return unavailableTypes({
380
+ problem: Object.freeze({
381
+ kind: "chain",
382
+ at: entry.chain[entry.chain.length - 1] ?? recordClass,
383
+ gap: entry.gap ?? "malformed",
384
+ }),
385
+ }, entry.auditEnabled);
386
+ }
387
+ return {
388
+ types: (0, hidden_values_js_1.fieldTypesFromRows)(entry.rows, { [recordClass]: { tables: entry.chain, complete: true } }, { complete: true }),
389
+ auditEnabled: entry.auditEnabled,
390
+ };
391
+ }
392
+ /**
393
+ * The class's field types: its chain, then every dictionary row of the chain,
394
+ * each field typed by its nearest definition (`incident.work_notes` is
395
+ * defined on `task`).
396
+ *
397
+ * The reads go straight to the instance, and what they find is kept in the
398
+ * metadata cache's per-credential memo for an hour (the type-hiding memo's
399
+ * time), as `loadFieldTypes` does: a warm call reads nothing here, and a wide
400
+ * chain never pays for a `sys_dictionary` watermark. Concurrent calls for one
401
+ * class share one read. A read that times out or returns a 5xx the client does
402
+ * not retry itself is made once more after a short pause; any failure is not kept and
403
+ * gives the `unavailable` state, with its cause. A full page or a chain that
404
+ * stops short is kept for 30 seconds and gives it too, with its cause. A
405
+ * cancellation rethrows.
406
+ *
407
+ * The chain is only trusted when the shared reader reports it complete: it
408
+ * ends at a table whose stored parent reference and parent name are both
409
+ * empty. A chain that may stop short (no row, a parent whose row did not come
410
+ * back, or one longer than the read) could hide that the class extends a
411
+ * credential table, so its types are `unavailable` too.
412
+ */
413
+ async function readClassTypes(services, recordClass, plan, signal) {
414
+ if (!plan.dictionary)
415
+ return POLICY_TYPES;
416
+ const memo = (0, metadata_cache_js_1.derivedMetadataMemo)(services);
417
+ const memoKey = `${CLASS_TYPES_MEMO_PREFIX}${plan.auditFlag ? "audit" : "plain"}:${recordClass}`;
418
+ const known = memo?.get(memoKey);
419
+ if (isClassTypesEntry(known))
420
+ return typesOf(known, recordClass);
421
+ const pending = memo?.pending(memoKey);
422
+ if (pending !== undefined) {
423
+ try {
424
+ const shared = await pending;
425
+ if (isClassTypesEntry(shared))
426
+ return typesOf(shared, recordClass);
427
+ if (isClassTypesFailure(shared))
428
+ return failureTypes(shared);
429
+ }
430
+ catch {
431
+ // That call was cancelled; read for this one.
432
+ }
433
+ }
434
+ const read = readClassTypesEntry((0, metadata_cache_js_1.uncachedOperations)(services), recordClass, plan, signal);
435
+ const entry = await (memo === undefined ? read : memo.track(memoKey, read));
436
+ if (isClassTypesFailure(entry))
437
+ return failureTypes(entry);
438
+ memo?.set(memoKey, entry, 128 + JSON.stringify(entry).length, entry.complete && !entry.full ? hidden_values_js_1.FIELD_TYPES_TTL_MS : hidden_values_js_1.FIELD_TYPES_UNAVAILABLE_TTL_MS);
439
+ return typesOf(entry, recordClass);
440
+ }
441
+ /** One uncached read of the chain and its dictionary rows; a failure says which read and why. */
442
+ async function readClassTypesEntry(reader, recordClass, plan, signal) {
443
+ let reading = "sys_db_object";
444
+ try {
445
+ const { tables: chain, complete, gap } = await (0, hidden_values_js_1.retryTransientOnce)(() => inOwnScope(signal, () => (0, table_hierarchy_js_1.resolveTableChain)(reader, recordClass, MAX_HIERARCHY_DEPTH, false)), { signal });
446
+ reading = "sys_dictionary";
447
+ const fields = [...history_contracts_js_1.HISTORY_DICTIONARY_FIELDS, ...(plan.auditFlag ? [history_contracts_js_1.HISTORY_DICTIONARY_AUDIT_FIELD] : [])];
448
+ const response = await (0, hidden_values_js_1.retryTransientOnce)(() => inOwnScope(signal, () => reader.get(`${TABLE_PATH}sys_dictionary`, {
449
+ sysparm_query: `nameIN${chain.join(",")}^ORDERBYname^ORDERBYelement`,
450
+ sysparm_fields: fields.join(","),
451
+ sysparm_limit: String(exports.MAX_HISTORY_DICTIONARY_ROWS),
452
+ sysparm_display_value: "false",
453
+ sysparm_exclude_reference_link: "true",
454
+ })), { signal });
455
+ const rows = rowsOf(response);
456
+ if (rows.length >= exports.MAX_HISTORY_DICTIONARY_ROWS) {
457
+ return Object.freeze({ chain, rows: [], auditEnabled: null, complete: false, full: true });
458
+ }
459
+ const dictionaryRows = [];
460
+ let auditEnabled = null;
461
+ for (const row of rows) {
462
+ const table = key(row.name);
463
+ const element = key(row.element);
464
+ const type = key(row.internal_type);
465
+ if (!chain.includes(table) || type === "")
466
+ continue;
467
+ if (element === "") {
468
+ if (table === recordClass && type === "collection" && plan.auditFlag) {
469
+ const flag = key(row[history_contracts_js_1.HISTORY_DICTIONARY_AUDIT_FIELD]);
470
+ auditEnabled = flag === "true" ? true : flag === "false" ? false : null;
471
+ }
472
+ continue;
473
+ }
474
+ dictionaryRows.push(Object.freeze({ table, element, internal_type: type }));
475
+ }
476
+ return Object.freeze({
477
+ chain: Object.freeze([...chain]),
478
+ rows: Object.freeze(dictionaryRows),
479
+ auditEnabled,
480
+ complete,
481
+ ...(complete || gap === undefined ? {} : { gap }),
482
+ full: false,
483
+ });
484
+ }
485
+ catch (error) {
486
+ if ((0, client_js_1.isServiceNowRequestCancellation)(error) || signal?.aborted)
487
+ throw error;
488
+ return Object.freeze({ failed: (0, hidden_values_js_1.classifyReadFailure)(error), read: reading });
489
+ }
490
+ }
491
+ /**
492
+ * The audit fields the audit read leaves out, so journal rows never reach a
493
+ * page, its cursors, `has_more` or its counts: every journal-typed field of
494
+ * the class's chain when the types are known. Without types, the platform's
495
+ * journal field names, unless the call also reads the journal source (then
496
+ * those rows are shown without values, as every audit row is).
497
+ */
498
+ function auditExclusions(types, recordClass, journalInCall) {
499
+ if (types.state === "available") {
500
+ const all = types.tables.get(recordClass)?.allTypes;
501
+ return [...(all ?? new Map())]
502
+ .filter(([, type]) => JOURNAL_TYPES.has(type))
503
+ .map(([field]) => field)
504
+ .sort();
505
+ }
506
+ return journalInCall ? [] : exports.JOURNAL_FIELD_NAMES;
507
+ }
508
+ /** The encoded query of one source's page: position first, then the record, then the filters. */
509
+ function sourceQuery(spec, recordClass, args, position,
510
+ /** Field names the source must not return (journal fields, for the audit log). */
511
+ exclude = []) {
512
+ const parts = [];
513
+ if (position !== undefined) {
514
+ // Newest first, strictly before (T, I): `<=T` and (`<T` or `sys_id<I`).
515
+ // `^OR` binds to the clause before it, so the record filter that follows
516
+ // applies to both branches.
517
+ parts.push(`sys_created_on<=${position.timestamp}`, `sys_created_on<${position.timestamp}^ORsys_id<${position.sysId}`);
518
+ }
519
+ parts.push(`${spec.classColumn}=${recordClass}`, `${spec.idColumn}=${args.sys_id}`);
520
+ if (args.fields !== undefined && spec.fieldColumn !== undefined)
521
+ parts.push(`${spec.fieldColumn}IN${args.fields.join(",")}`);
522
+ if (exclude.length > 0 && spec.fieldColumn !== undefined)
523
+ parts.push(`${spec.fieldColumn}NOT IN${exclude.join(",")}`);
524
+ if (args.since !== undefined)
525
+ parts.push(`sys_created_on>=${args.since}`);
526
+ if (args.until !== undefined)
527
+ parts.push(`sys_created_on<=${args.until}`);
528
+ return `${parts.join("^")}^ORDERBYDESCsys_created_on^ORDERBYDESCsys_id`;
529
+ }
530
+ /**
531
+ * One source's page. A response too large for the client is asked again for
532
+ * half the rows, down to one row and the look-ahead; if even that is too
533
+ * large, the source alone is `too_large` and the other sources still answer.
534
+ * Each attempt runs in its own response scope.
535
+ */
536
+ async function readSource(ops, plan, recordClass, args, signal, exclude = []) {
537
+ if (!plan.granted)
538
+ return { status: "not_granted" };
539
+ const position = args.cursor?.[plan.source];
540
+ // A follow-up page reads only the sources its cursor names: the others are finished.
541
+ if (args.cursor !== undefined && position === undefined)
542
+ return { status: "done" };
543
+ const query = sourceQuery(plan.spec, recordClass, args, position, exclude);
544
+ let asked = args.limit + 1;
545
+ for (;;) {
546
+ try {
547
+ const response = await inOwnScope(signal, () => ops.get(`${TABLE_PATH}${plan.spec.table}`, {
548
+ sysparm_query: query,
549
+ sysparm_fields: plan.fields.join(","),
550
+ sysparm_limit: String(asked),
551
+ sysparm_display_value: "false",
552
+ sysparm_exclude_reference_link: "true",
553
+ }));
554
+ return { status: "ok", rows: rowsOf(response), asked };
555
+ }
556
+ catch (error) {
557
+ if ((0, client_js_1.isServiceNowRequestCancellation)(error) || signal?.aborted)
558
+ throw error;
559
+ if ((0, client_js_1.isServiceNowResponseTooLarge)(error)) {
560
+ if (asked <= exports.MIN_SOURCE_READ_ROWS)
561
+ return { status: "too_large" };
562
+ asked = Math.max(exports.MIN_SOURCE_READ_ROWS, Math.floor(asked / 2));
563
+ continue;
564
+ }
565
+ if (errorCategory(error) === "authorization")
566
+ return { status: "denied" };
567
+ if (isMissingTable(error))
568
+ return { status: "unavailable" };
569
+ throw error;
570
+ }
571
+ }
572
+ }
573
+ function judgeRow(plan, row, judge) {
574
+ const spec = plan.spec;
575
+ // A row about another record is never shown, whatever the query said.
576
+ if (key(row[spec.classColumn]) !== judge.recordClass || key(row[spec.idColumn]) !== judge.sysId) {
577
+ return { omitted: "mismatch" };
578
+ }
579
+ const time = stored(row.sys_created_on);
580
+ const user = plan.user ? shortText(row[spec.user], L.MAX_USER_CHARS) : undefined;
581
+ if (plan.source === "flows") {
582
+ const name = shortText(row.name, L.MAX_FLOW_NAME_CHARS);
583
+ const state = shortText(row.state, L.MAX_FLOW_STATE_CHARS);
584
+ const test = key(row.is_test_run);
585
+ const flow = {
586
+ ...(name === undefined ? {} : { name }),
587
+ ...(state === undefined ? {} : { state }),
588
+ ...(test === "true" ? { test: true } : test === "false" ? { test: false } : {}),
589
+ };
590
+ return { event: { time, source: "flows", ...(user === undefined ? {} : { user }), flow } };
591
+ }
592
+ const field = key(row[spec.fieldColumn]);
593
+ // (a) Journal text never comes through the audit log, by the field's type.
594
+ if (plan.source === "audit") {
595
+ if (judge.excluded.has(field))
596
+ return null;
597
+ if (judge.types.state === "available") {
598
+ const type = judge.types.tables.get(judge.recordClass)?.allTypes?.get(field);
599
+ if (type !== undefined && JOURNAL_TYPES.has(type))
600
+ return null;
601
+ }
602
+ }
603
+ // (b) The field must be one the profile may read on the class.
604
+ if (!judge.readable(field))
605
+ return { omitted: "unreadable" };
606
+ const event = { time, source: plan.source, field, ...(user === undefined ? {} : { user }) };
607
+ if (plan.valuesHidden)
608
+ return { event: { ...event, value_hidden: true } };
609
+ if (!plan.values)
610
+ return { event };
611
+ // (c) Values by type and table, through the shared helper.
612
+ if ((0, hidden_values_js_1.classifyField)(judge.types, judge.recordClass, field) !== "visible")
613
+ return { event: { ...event, value_hidden: true } };
614
+ let truncated = false;
615
+ const value = (column) => {
616
+ const raw = stored(row[column]);
617
+ if (raw === undefined || raw === "")
618
+ return undefined;
619
+ const shown = cut(raw, L.MAX_VALUE_CHARS);
620
+ truncated ||= shown.cut;
621
+ return shown.text;
622
+ };
623
+ const values = plan.source === "audit"
624
+ ? { old: value("oldvalue"), new: value("newvalue") }
625
+ : { new: value("value") };
626
+ return {
627
+ event: {
628
+ ...event,
629
+ ...(values.old === undefined ? {} : { old: values.old }),
630
+ ...(values.new === undefined ? {} : { new: values.new }),
631
+ ...(truncated ? { value_truncated: true } : {}),
632
+ },
633
+ };
634
+ }
635
+ /**
636
+ * A source's rows as candidates, newest first. Of `asked` rows, the last is
637
+ * the look-ahead: it only says more exist, so at most `asked - 1` (and at most
638
+ * `limit`) rows are candidates.
639
+ */
640
+ function candidatesOf(plan, rows, limit, judge) {
641
+ const order = history_contracts_js_1.HISTORY_SOURCES.indexOf(plan.source);
642
+ const positioned = rows.map((row) => {
643
+ const timestamp = stored(row.sys_created_on);
644
+ const sysId = key(row.sys_id);
645
+ // A row without a position cannot be paged past: fail closed, as the log tail does.
646
+ if (!(0, syslog_cursor_js_1.isStoredTimestamp)(timestamp) || !(0, syslog_cursor_js_1.isSysId)(sysId))
647
+ throw (0, tool_error_js_1.createToolError)("upstream", "do_not_retry");
648
+ return { row, position: { timestamp, sysId } };
649
+ });
650
+ positioned.sort((a, b) => compareNewestFirst(a.position, b.position));
651
+ const candidates = [];
652
+ for (const { row, position } of positioned.slice(0, limit)) {
653
+ const judged = judgeRow(plan, row, judge);
654
+ candidates.push({ source: plan.source, order, position, ...(judged ?? {}) });
655
+ }
656
+ return { candidates, full: rows.length > limit };
657
+ }
658
+ function compareNewestFirst(a, b) {
659
+ if (a.timestamp !== b.timestamp)
660
+ return a.timestamp > b.timestamp ? -1 : 1;
661
+ if (a.sysId !== b.sysId)
662
+ return a.sysId > b.sysId ? -1 : 1;
663
+ return 0;
664
+ }
665
+ /** Newest first across sources: time, then source order, then sys_id. */
666
+ function compareMerged(a, b) {
667
+ if (a.position.timestamp !== b.position.timestamp)
668
+ return a.position.timestamp > b.position.timestamp ? -1 : 1;
669
+ return a.order - b.order || compareNewestFirst(a.position, b.position);
670
+ }
671
+ /**
672
+ * Walk all sources' candidates newest first and take at most `emitLimit`
673
+ * events. A dropped row is consumed as it is passed, so a page of dropped rows
674
+ * still moves the cursor on; the walk stops at the first event past the limit.
675
+ *
676
+ * A source that has rows past its candidates (`full`) bounds the walk: its
677
+ * next row is unknown and may be newer than anything after its last
678
+ * candidate, so the walk never passes that candidate. Each page therefore
679
+ * holds a prefix of the whole history in its one order, and consumes at least
680
+ * one row while any source has one.
681
+ */
682
+ function walkPage(all, emitLimit, full) {
683
+ const merged = [...all].sort(compareMerged);
684
+ let end = merged.length;
685
+ for (const source of full) {
686
+ let last = -1;
687
+ merged.forEach((candidate, index) => {
688
+ if (candidate.source === source)
689
+ last = index;
690
+ });
691
+ if (last >= 0)
692
+ end = Math.min(end, last + 1);
693
+ }
694
+ const events = [];
695
+ const omitted = { unreadable: 0, mismatch: 0 };
696
+ const perSource = new Map();
697
+ for (const source of history_contracts_js_1.HISTORY_SOURCES)
698
+ perSource.set(source, { returned: 0, consumed: 0 });
699
+ let cutAt;
700
+ for (const candidate of merged.slice(0, end)) {
701
+ const state = perSource.get(candidate.source);
702
+ if (candidate.event !== undefined) {
703
+ if (events.length >= emitLimit)
704
+ break;
705
+ events.push(candidate.event);
706
+ state.returned += 1;
707
+ }
708
+ else if (candidate.omitted !== undefined) {
709
+ omitted[candidate.omitted] += 1;
710
+ }
711
+ state.consumed += 1;
712
+ state.last = candidate.position;
713
+ cutAt = candidate.position;
714
+ }
715
+ return { events, omitted, perSource, ...(cutAt === undefined ? {} : { cut: cutAt }) };
716
+ }
717
+ // ---------------------------------------------------------------------------
718
+ // Handler
719
+ // ---------------------------------------------------------------------------
720
+ function historyResult(args, data) {
721
+ return (0, result_envelope_js_1.envelopeCompatibilityResult)(TOOL, args, (0, utils_js_1.ok)(data));
722
+ }
723
+ function dataBytes(data) {
724
+ return Buffer.byteLength(JSON.stringify(data), "utf8");
725
+ }
726
+ async function handleHistory(rawArgs, services) {
727
+ let args;
728
+ try {
729
+ args = (0, history_contracts_js_1.canonicalHistoryArgs)(rawArgs);
730
+ }
731
+ catch (error) {
732
+ if (error instanceof history_contracts_js_1.HistoryArgumentError)
733
+ throw (0, tool_error_js_1.createToolError)("conflict", "retry_after_correction");
734
+ throw error;
735
+ }
736
+ // A window that ends before it starts: the caller can correct it.
737
+ if (args.since !== undefined && args.until !== undefined && args.since > args.until) {
738
+ throw (0, tool_error_js_1.createToolError)("conflict", "retry_after_correction");
739
+ }
740
+ const plan = historyAccessPlan(args, services.policy.tableAccess);
741
+ const record = { table: args.table, sys_id: args.sys_id };
742
+ // A cursor is checked before any read: it must have been issued for this
743
+ // record, this source and these filters.
744
+ for (const source of history_contracts_js_1.HISTORY_SOURCES) {
745
+ const position = args.cursor?.[source];
746
+ if (position !== undefined && position.filter !== (0, history_contracts_js_1.historyCursorFilter)(args, args.table, source)) {
747
+ return historyResult(args, { status: "invalid_cursor", record, hint: exports.INVALID_CURSOR_HINT });
748
+ }
749
+ }
750
+ const signal = services.context?.signal;
751
+ const ops = (0, metadata_cache_js_1.uncachedOperations)(services.serviceNow);
752
+ // 1. The record's class.
753
+ const recordClass = await readRecordClass(ops, args, signal);
754
+ if (recordClass !== args.table) {
755
+ return historyResult(args, { status: "wrong_class", record, hint: (0, exports.WRONG_CLASS_HINT)(recordClass) });
756
+ }
757
+ // 2 and 3: the class's field types, and every source's page. The journal
758
+ // and flow reads start with the types; the audit read waits for them, to
759
+ // leave journal fields out of its query.
760
+ const journalInCall = plan.sources.some((source) => source.source === "journal" && source.granted);
761
+ // Types are needed only by a source this page reads that has audit rows
762
+ // to judge or journal values to show; a flows-only page skips them.
763
+ const live = (source) => source.granted && (args.cursor === undefined || args.cursor[source.source] !== undefined);
764
+ const needsTypes = plan.sources.some((source) => live(source) && (source.source === "audit" || (source.source === "journal" && source.values)));
765
+ const typesRead = needsTypes
766
+ ? readClassTypes(services.serviceNow, recordClass, plan, signal)
767
+ : Promise.resolve(POLICY_TYPES);
768
+ const [classTypes, reads] = await Promise.all([
769
+ typesRead,
770
+ Promise.all(plan.sources.map((source) => source.source === "audit" && source.granted
771
+ ? typesRead.then((types) => readSource(ops, source, recordClass, args, signal, auditExclusions(types.types, recordClass, journalInCall)))
772
+ : readSource(ops, source, recordClass, args, signal))),
773
+ ]);
774
+ const excluded = new Set(auditExclusions(classTypes.types, recordClass, journalInCall));
775
+ const readableMemo = new Map();
776
+ const judge = {
777
+ recordClass,
778
+ sysId: args.sys_id,
779
+ types: classTypes.types,
780
+ excluded,
781
+ readable: (field) => {
782
+ let known = readableMemo.get(field);
783
+ if (known === undefined) {
784
+ known = TABLE_NAME.test(field) && !isRecordContentColumn(recordClass, field) && canRead(recordClass, [field]);
785
+ readableMemo.set(field, known);
786
+ }
787
+ return known;
788
+ },
789
+ };
790
+ const all = [];
791
+ const full = new Set();
792
+ plan.sources.forEach((source, index) => {
793
+ const result = reads[index];
794
+ if (result.status !== "ok")
795
+ return;
796
+ const page = candidatesOf(source, result.rows, Math.min(args.limit, result.asked - 1), judge);
797
+ all.push(...page.candidates);
798
+ if (page.full)
799
+ full.add(source.source);
800
+ });
801
+ const warnings = [];
802
+ if (needsTypes && args.include_values && classTypes.types.state !== "available") {
803
+ warnings.push(classTypesWarning(classTypes.why));
804
+ }
805
+ for (const source of plan.sources) {
806
+ if (source.granted && source.valuesHidden)
807
+ warnings.push((0, exports.VALUES_NOT_READABLE_WARNING)(source.source));
808
+ }
809
+ plan.sources.forEach((source, index) => {
810
+ if (reads[index].status === "too_large")
811
+ warnings.push((0, exports.TOO_LARGE_WARNING)(source.source));
812
+ });
813
+ const build = (emitLimit) => {
814
+ const walk = walkPage(all, emitLimit, full);
815
+ const sources = {};
816
+ const nextCursor = {};
817
+ plan.sources.forEach((source, index) => {
818
+ const result = reads[index];
819
+ const filter = (0, history_contracts_js_1.historyCursorFilter)(args, recordClass, source.source);
820
+ if (result.status === "too_large") {
821
+ // Nothing of it was read, so it starts again where it was: its own
822
+ // position, or before every row. Its rows may then follow newer rows
823
+ // of the other sources on later pages, but none is skipped.
824
+ sources[source.source] = { status: "too_large", returned: 0, has_more: true };
825
+ nextCursor[source.source] = (0, syslog_cursor_js_1.encodeTailCursor)({ ...(args.cursor?.[source.source] ?? BEFORE_ALL), filter });
826
+ return;
827
+ }
828
+ if (result.status !== "ok") {
829
+ sources[source.source] = { status: result.status, returned: 0, has_more: false };
830
+ return;
831
+ }
832
+ const state = walk.perSource.get(source.source);
833
+ const candidates = all.filter((candidate) => candidate.source === source.source).length;
834
+ const hasMore = state.consumed < candidates || full.has(source.source);
835
+ sources[source.source] = { status: "ok", returned: state.returned, has_more: hasMore };
836
+ if (!hasMore)
837
+ return;
838
+ // The last row this page consumed; for a source it did not reach, the
839
+ // position it was given, or the end of the second the page stopped in.
840
+ const position = state.last ?? args.cursor?.[source.source] ?? (walk.cut === undefined ? undefined : { timestamp: walk.cut.timestamp, sysId: END_OF_SECOND });
841
+ if (position === undefined)
842
+ return;
843
+ const cursor = { ...position, filter };
844
+ nextCursor[source.source] = (0, syslog_cursor_js_1.encodeTailCursor)(cursor);
845
+ });
846
+ // The sources with entries left; if every one is too large, the next
847
+ // page would read the same thing and fail the same way.
848
+ const pending = history_contracts_js_1.HISTORY_SOURCES.filter((source) => sources[source]?.has_more === true);
849
+ const stuck = pending.length > 0 && pending.every((source) => sources[source].status === "too_large");
850
+ return {
851
+ status: "ok",
852
+ record,
853
+ audit_enabled: classTypes.auditEnabled,
854
+ events: walk.events,
855
+ sources: sources,
856
+ omitted: walk.omitted,
857
+ not_recorded: [...history_contracts_js_1.NOT_RECORDED],
858
+ ...(Object.keys(nextCursor).length > 0 ? { next_cursor: nextCursor } : {}),
859
+ ...(stuck ? { hint: (0, exports.STUCK_PAGE_HINT)(pending) } : {}),
860
+ ...(warnings.length > 0 ? { warnings: [...warnings] } : {}),
861
+ };
862
+ };
863
+ // Fit `max_response_bytes`: keep the newest events that fit, and let the
864
+ // cursors carry the rest. One event is always kept, without its values if
865
+ // they alone are too large, so a page always moves on.
866
+ // The result envelope holds the result to the same `max_response_bytes`.
867
+ const budget = Math.max(0, args.max_response_bytes - ENVELOPE_RESERVE_BYTES);
868
+ let data = build(args.limit);
869
+ if (dataBytes(data) > budget && (data.events?.length ?? 0) > 0) {
870
+ const events = data.events;
871
+ const base = dataBytes({ ...data, events: [], warnings: [...(data.warnings ?? []), exports.FITTED_WARNING] });
872
+ let used = base;
873
+ let fit = 0;
874
+ for (const event of events) {
875
+ used += dataBytes(event) + 1;
876
+ if (used > budget)
877
+ break;
878
+ fit += 1;
879
+ }
880
+ warnings.push(exports.FITTED_WARNING);
881
+ data = build(Math.max(1, fit));
882
+ if (fit === 0) {
883
+ const first = { ...data.events[0] };
884
+ if (first.old !== undefined || first.new !== undefined) {
885
+ delete first.old;
886
+ delete first.new;
887
+ first.value_truncated = true;
888
+ }
889
+ data = { ...data, events: [first] };
890
+ }
891
+ }
892
+ return historyResult(args, data);
893
+ }
894
+ // ---------------------------------------------------------------------------
895
+ // Module
896
+ // ---------------------------------------------------------------------------
897
+ const schema = (0, tool_module_js_1.withRequiredProfile)(history_contracts_js_1.historyInputSchema);
898
+ /** The plan for one call, as the dispatcher authorizes it. */
899
+ function resolveHistoryAccess(candidate, tableAccess) {
900
+ const input = schema.parse(candidate);
901
+ const args = (0, history_contracts_js_1.canonicalHistoryArgs)(input);
902
+ const plan = historyAccessPlan(args, tableAccess);
903
+ return Object.freeze({
904
+ args: Object.freeze({ ...input }),
905
+ requests: plan.requests,
906
+ });
907
+ }
908
+ exports.historyToolModule = (0, tool_module_js_1.defineServiceNowToolModule)({
909
+ runtime: "servicenow",
910
+ definition: {
911
+ name: TOOL,
912
+ description: history_contracts_js_1.HISTORY_DESCRIPTION,
913
+ annotations: {
914
+ title: "View record history",
915
+ readOnlyHint: true,
916
+ destructiveHint: false,
917
+ idempotentHint: true,
918
+ openWorldHint: true,
919
+ },
920
+ },
921
+ inputSchema: schema,
922
+ outputSchema: result_envelope_js_1.productionToolOutputSchemas.sn_history,
923
+ requirements: {
924
+ permissions: ["read"],
925
+ tables: {
926
+ kind: "dynamic",
927
+ names: history_contracts_js_1.HISTORY_FIXED_TABLES,
928
+ description: "The record's own table (its class), plus the history sources the profile may read",
929
+ },
930
+ apis: ["table"],
931
+ fieldPolicies: ["read"],
932
+ capabilities: ["record:history"],
933
+ },
934
+ resolveAccess: (candidate, policy) => resolveHistoryAccess(candidate, policy.tableAccess),
935
+ handler: handleHistory,
936
+ });
937
+ //# sourceMappingURL=history-module.js.map