@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
@@ -1,13 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.schema = exports.definition = void 0;
3
+ exports.ARGUMENT_BOUNDS = exports.TRAVERSAL_LIMITS = exports.schema = exports.definition = void 0;
4
4
  exports.handler = handler;
5
+ exports.traverseRelationships = traverseRelationships;
5
6
  const zod_1 = require("zod");
7
+ const inert_text_js_1 = require("../inert-text.js");
8
+ const tool_error_js_1 = require("../tool-error.js");
9
+ const client_js_1 = require("../client.js");
6
10
  const utils_js_1 = require("../utils.js");
11
+ const field_policy_js_1 = require("../field-policy.js");
7
12
  const servicenow_identifiers_js_1 = require("../servicenow-identifiers.js");
13
+ const relationships_map_js_1 = require("./relationships-map.js");
8
14
  exports.definition = {
9
15
  name: "sn_relationships",
10
- description: "Traverse CMDB CI relationships (graph walk). Supports upstream, downstream, or both directions with configurable depth. Use for impact analysis and dependency mapping.",
16
+ description: "Traverse CMDB CI relationships breadth first: each CI once, at its shortest depth, upstream, downstream or both. Lists only CIs the profile can read. A limit that stops the walk sets meta.traversal_truncated and warns, naming the CIs not fully read. For impact analysis and dependency mapping.",
11
17
  annotations: {
12
18
  title: "Traverse CI relationships",
13
19
  readOnlyHint: true,
@@ -17,7 +23,7 @@ exports.definition = {
17
23
  },
18
24
  };
19
25
  exports.schema = zod_1.z.object({
20
- ci_name: zod_1.z.string().optional().describe("Name of the CI to start from (resolved via cmdb_ci name field)"),
26
+ ci_name: zod_1.z.string().optional().describe("Name of the CI to start from (several matches: pass sys_id instead)"),
21
27
  sys_id: servicenow_identifiers_js_1.serviceNowSysIdSchema.optional().describe("32-hex sys_id of the CI to start from (alternative to ci_name)"),
22
28
  depth: zod_1.z.number().int().min(1).max(5).optional().describe("How many levels deep to traverse (1-5, default from SN_REL_DEPTH or 3)"),
23
29
  limit: zod_1.z.number().int().min(1).max(1000).optional().default(100).describe("Maximum relationships to return (default 100, max 1000)"),
@@ -26,217 +32,630 @@ exports.schema = zod_1.z.object({
26
32
  type: zod_1.z.string().optional().describe("Filter by relationship type name (substring match)"),
27
33
  class: zod_1.z.string().optional().describe("Filter displayed CIs by class name (substring match)"),
28
34
  impact: zod_1.z.boolean().optional().default(false).describe("Impact analysis mode -- walks upstream only"),
35
+ max_response_bytes: zod_1.z
36
+ .number()
37
+ .int()
38
+ .min(utils_js_1.MAX_RESPONSE_BYTES_MIN)
39
+ .max(utils_js_1.MAX_RESPONSE_BYTES_MAX)
40
+ .optional()
41
+ .default(utils_js_1.MAX_RESPONSE_BYTES_DEFAULT)
42
+ .describe("Byte budget (default 100000, min 1000, max 1000000); list and map are cut to fit"),
43
+ map: zod_1.z.boolean().optional().default(false).describe("Also return nodes, edges (with types) and a Mermaid diagram"),
29
44
  });
30
- async function handler(args, client, config, _context) {
31
- try {
32
- if (!args.ci_name && !args.sys_id) {
33
- return (0, utils_js_1.err)("Either ci_name or sys_id is required");
45
+ exports.TRAVERSAL_LIMITS = Object.freeze({
46
+ /**
47
+ * Upstream requests of one call, root lookup, relationship pages and CI
48
+ * reads together. A batched walk needs about one request per 50 CIs of a
49
+ * level: at the other limits' worst case, about 45 in all.
50
+ */
51
+ maxRequests: 50,
52
+ /** Of those, the requests kept back for reading the CIs a level finds. */
53
+ ciReadReserve: 15,
54
+ /** Distinct CIs read, the start CI aside. */
55
+ maxCis: 1_000,
56
+ /** Relationship rows read, duplicates (a row read from each end) included. */
57
+ maxRelationshipRows: 2_000,
58
+ /** Rows per relationship page. */
59
+ relationshipPage: 500,
60
+ /** CIs per relationship query (both directions: 2 x 50 sys_ids in the URL). */
61
+ relationshipChunk: 50,
62
+ /** CIs per `cmdb_ci` read. */
63
+ ciChunk: 100,
64
+ /** Matches an ambiguous `ci_name` error lists. */
65
+ ambiguousListed: 5,
66
+ /** CIs named in a warning. */
67
+ namedInWarning: 5,
68
+ /**
69
+ * The client allows 1 MiB of upstream JSON per call, all requests together.
70
+ * The walk keeps its own estimate of what it has read and stops short of it:
71
+ * this much for relationship rows, and this much for CI reads.
72
+ */
73
+ relationshipBytes: 640 * 1024,
74
+ ciBytes: 180 * 1024,
75
+ /** Share of `max_response_bytes` the map (nodes, edges and diagram) may take; the list gets the rest. */
76
+ mapShare: 0.48,
77
+ });
78
+ /** Longest `ci_name`, `type` and `class` a call may carry, in characters. */
79
+ exports.ARGUMENT_BOUNDS = Object.freeze({ ci_name: 255, type: 255, class: 80 });
80
+ const RELATED_TO = "Related to";
81
+ const SYS_ID_FIELD = "sys_id";
82
+ /** The fields of `table`, of those named, that the profile can read. */
83
+ function readableAmong(table, names) {
84
+ const readable = [];
85
+ for (const name of names) {
86
+ try {
87
+ (0, field_policy_js_1.resolveReadableFields)(table, { fields: name });
88
+ readable.push(name);
34
89
  }
35
- const maxDepth = Math.min(Math.max(args.depth ?? config.relDepth, 1), 5);
36
- let direction = args.direction;
37
- if (args.impact)
38
- direction = "upstream";
39
- // ── Resolve root CI ──
40
- let rootId;
41
- let rootName;
42
- let rootClass;
43
- if (args.sys_id) {
44
- const ciResp = await client.get(`/api/now/table/cmdb_ci/${(0, servicenow_identifiers_js_1.serviceNowSysIdPathSegment)(args.sys_id)}`, {
45
- sysparm_fields: "sys_id,name,sys_class_name",
46
- sysparm_display_value: "true",
47
- });
48
- if (!ciResp.result?.name) {
49
- return (0, utils_js_1.err)(`CI not found with sys_id: ${args.sys_id}`);
50
- }
51
- rootId = (0, servicenow_identifiers_js_1.normalizeServiceNowSysId)(args.sys_id);
52
- rootName = ciResp.result.name;
53
- rootClass = ciResp.result.sys_class_name;
90
+ catch (error) {
91
+ if (!(0, field_policy_js_1.isFieldPolicyError)(error))
92
+ throw error;
54
93
  }
55
- else {
56
- const ciResp = await client.get("/api/now/table/cmdb_ci", {
57
- sysparm_query: `name=${(0, utils_js_1.escapeQueryValue)(args.ci_name)}^ORDERBYsys_id`,
58
- sysparm_fields: "sys_id,name,sys_class_name",
59
- sysparm_display_value: "true",
60
- sysparm_limit: "5",
61
- });
62
- const results = ciResp.result || [];
63
- if (results.length === 0) {
64
- return (0, utils_js_1.err)(`CI not found: ${args.ci_name}`);
65
- }
66
- rootId = results[0].sys_id;
67
- rootName = results[0].name;
68
- rootClass = results[0].sys_class_name;
69
- }
70
- // ── Traverse ──
71
- const visited = new Set([rootId]);
72
- const classCache = new Map([[rootId, rootClass]]);
73
- const allRels = [];
74
- const warnings = [];
75
- const traversalTarget = args.offset + args.limit + 1;
76
- const maxTraversalRequests = 2_001;
77
- let traversalRequests = 0;
78
- let traversalTruncated = false;
79
- async function getClass(id) {
80
- if (classCache.has(id))
81
- return classCache.get(id);
82
- try {
83
- const safeId = (0, servicenow_identifiers_js_1.normalizeServiceNowSysId)(id);
84
- const resp = await client.get(`/api/now/table/cmdb_ci/${(0, servicenow_identifiers_js_1.serviceNowSysIdPathSegment)(safeId)}`, {
85
- sysparm_fields: "sys_class_name",
86
- sysparm_display_value: "true",
87
- });
88
- const cls = resp.result?.sys_class_name || "unknown";
89
- classCache.set(id, cls);
90
- return cls;
91
- }
92
- catch {
93
- classCache.set(id, "unknown");
94
- return "unknown";
95
- }
94
+ }
95
+ return readable;
96
+ }
97
+ function extractValue(field) {
98
+ if (!field)
99
+ return "";
100
+ if (typeof field === "string")
101
+ return field;
102
+ if (typeof field === "object" && field !== null) {
103
+ const f = field;
104
+ if (f.value && typeof f.value === "string")
105
+ return f.value;
106
+ if (f.link && typeof f.link === "string") {
107
+ // Extract sys_id from link URL
108
+ const parts = f.link.split("/");
109
+ return parts[parts.length - 1] ?? "";
96
110
  }
97
- function extractValue(field) {
98
- if (!field)
99
- return "";
100
- if (typeof field === "string")
101
- return field;
102
- if (typeof field === "object" && field !== null) {
103
- const f = field;
104
- if (f.value && typeof f.value === "string")
105
- return f.value;
106
- if (f.link && typeof f.link === "string") {
107
- // Extract sys_id from link URL
108
- const parts = f.link.split("/");
109
- return parts[parts.length - 1];
110
- }
111
- }
111
+ }
112
+ return "";
113
+ }
114
+ function extractDisplay(field) {
115
+ if (!field)
116
+ return "";
117
+ if (typeof field === "string") {
118
+ // If it's a 32-char hex string, it's a sys_id not a display value
119
+ if (/^[a-f0-9]{32}$/.test(field))
112
120
  return "";
121
+ return field;
122
+ }
123
+ if (typeof field === "object" && field !== null) {
124
+ const f = field;
125
+ if (f.display_value && typeof f.display_value === "string")
126
+ return f.display_value;
127
+ }
128
+ return "";
129
+ }
130
+ /** The relationship row's sys_id; `display_value=all` returns it as a value object. */
131
+ function relationshipId(field) {
132
+ const value = extractValue(field);
133
+ return /^[0-9a-f]{32}$/u.test(value) ? value : undefined;
134
+ }
135
+ function rowsOf(response) {
136
+ const result = typeof response === "object" && response !== null
137
+ ? response.result
138
+ : undefined;
139
+ return Array.isArray(result) ? result : [];
140
+ }
141
+ function recordOf(value) {
142
+ return typeof value === "object" && value !== null && !Array.isArray(value)
143
+ ? value
144
+ : undefined;
145
+ }
146
+ function chunks(items, size) {
147
+ const out = [];
148
+ for (let index = 0; index < items.length; index += size) {
149
+ out.push(items.slice(index, index + size));
150
+ }
151
+ return out;
152
+ }
153
+ /**
154
+ * The start CI does not exist, or is not readable. A result the handler marks
155
+ * as an error reaches the caller only as a generic failure, so this is the
156
+ * trusted error that says what happened.
157
+ */
158
+ function ciNotFound() {
159
+ return (0, tool_error_js_1.createToolError)("not_found", "retry_after_correction");
160
+ }
161
+ function quantity(count, singular, plural = `${singular}s`) {
162
+ return `${count} ${count === 1 ? singular : plural}`;
163
+ }
164
+ async function handler(args, client, config, _context) {
165
+ return traverseRelationships(args, client, config, exports.TRAVERSAL_LIMITS);
166
+ }
167
+ /** The traversal with its bounds given, for tests that exercise each one. */
168
+ async function traverseRelationships(args, client, config, limits) {
169
+ if (!args.ci_name && !args.sys_id) {
170
+ throw (0, tool_error_js_1.createStartCiRequiredError)();
171
+ }
172
+ const maxDepth = Math.min(Math.max(args.depth ?? config.relDepth, 1), 5);
173
+ let direction = args.direction;
174
+ if (args.impact)
175
+ direction = "upstream";
176
+ const wantDown = direction !== "upstream";
177
+ const wantUp = direction !== "downstream";
178
+ // ── Field policy: both ends of a relationship must be readable ──
179
+ // Lengths are bound here, not in the schema, to keep the tool's description small.
180
+ if (args.ci_name !== undefined && args.ci_name.length > exports.ARGUMENT_BOUNDS.ci_name) {
181
+ throw (0, tool_error_js_1.createArgumentTooLongError)("ci_name", exports.ARGUMENT_BOUNDS.ci_name);
182
+ }
183
+ if (args.type !== undefined && args.type.length > exports.ARGUMENT_BOUNDS.type) {
184
+ throw (0, tool_error_js_1.createArgumentTooLongError)("type", exports.ARGUMENT_BOUNDS.type);
185
+ }
186
+ if (args.class !== undefined && args.class.length > exports.ARGUMENT_BOUNDS.class) {
187
+ throw (0, tool_error_js_1.createArgumentTooLongError)("class", exports.ARGUMENT_BOUNDS.class);
188
+ }
189
+ // Refuse before any request, and show only what the profile can read.
190
+ // Both ends and the type of a relationship, and the sys_id of a CI, are what
191
+ // a walk is made of: without them there is nothing to walk or to show.
192
+ (0, field_policy_js_1.resolveReadableFields)("cmdb_rel_ci", { fields: "parent,child,type" });
193
+ (0, field_policy_js_1.resolveReadableFields)("cmdb_ci", { fields: SYS_ID_FIELD });
194
+ const relIdReadable = readableAmong("cmdb_rel_ci", [SYS_ID_FIELD]).length > 0;
195
+ const relFields = [...(relIdReadable ? [SYS_ID_FIELD] : []), "parent", "child", "type"];
196
+ const relSelection = (0, field_policy_js_1.resolveReadableFields)("cmdb_rel_ci", { fields: relFields.join(",") });
197
+ const ciShown = readableAmong("cmdb_ci", ["name", "sys_class_name"]);
198
+ const nameShown = ciShown.includes("name");
199
+ const classShown = ciShown.includes("sys_class_name");
200
+ if (args.ci_name)
201
+ (0, field_policy_js_1.resolveReadableFields)("cmdb_ci", { fields: "name", purpose: "query" });
202
+ if (args.class)
203
+ (0, field_policy_js_1.resolveReadableFields)("cmdb_ci", { fields: "sys_class_name", purpose: "query" });
204
+ const ciFields = [SYS_ID_FIELD, ...ciShown].join(",");
205
+ const ciSelection = (0, field_policy_js_1.resolveReadableFields)("cmdb_ci", { fields: ciFields });
206
+ // ── Request accounting: every upstream request this call makes ──
207
+ let requests = 0;
208
+ const warnings = [];
209
+ async function request(path, params) {
210
+ requests += 1;
211
+ return client.get(path, params);
212
+ }
213
+ /** What the profile may see of one `cmdb_ci` row. */
214
+ function viewOf(row) {
215
+ const shown = recordOf((0, field_policy_js_1.filterReadableRecord)(row, ciSelection));
216
+ const name = shown?.name;
217
+ const cls = shown?.sys_class_name;
218
+ return {
219
+ ...(nameShown ? { name: typeof name === "string" && name !== "" ? name : undefined } : {}),
220
+ ...(classShown ? { class: typeof cls === "string" && cls !== "" ? cls : "unknown" } : {}),
221
+ };
222
+ }
223
+ // ── Resolve the start CI ──
224
+ let rootId;
225
+ let rootView;
226
+ if (args.sys_id) {
227
+ const response = await request(`/api/now/table/cmdb_ci/${(0, servicenow_identifiers_js_1.serviceNowSysIdPathSegment)(args.sys_id)}`, {
228
+ sysparm_fields: ciFields,
229
+ sysparm_display_value: "true",
230
+ });
231
+ const row = recordOf(response?.result);
232
+ if (!row || (!row.sys_id && !row.name))
233
+ throw ciNotFound();
234
+ rootId = (0, servicenow_identifiers_js_1.normalizeServiceNowSysId)(args.sys_id);
235
+ rootView = viewOf(row);
236
+ }
237
+ else {
238
+ const response = await request("/api/now/table/cmdb_ci", {
239
+ sysparm_query: `name=${(0, utils_js_1.escapeQueryValue)(args.ci_name)}^ORDERBYsys_id`,
240
+ sysparm_fields: ciFields,
241
+ sysparm_display_value: "true",
242
+ sysparm_limit: String(limits.ambiguousListed + 1),
243
+ });
244
+ const matches = rowsOf(response).map(recordOf).filter((row) => row !== undefined);
245
+ if (matches.length === 0)
246
+ throw ciNotFound();
247
+ if (matches.length > 1) {
248
+ throw (0, tool_error_js_1.createAmbiguousCiNameError)(args.ci_name, matches.slice(0, limits.ambiguousListed).map((row) => {
249
+ const view = viewOf(row);
250
+ return {
251
+ sys_id: String(row.sys_id ?? ""),
252
+ ...(view.name === undefined ? {} : { name: view.name }),
253
+ ...(view.class === undefined ? {} : { class: view.class }),
254
+ };
255
+ }), matches.length > limits.ambiguousListed);
113
256
  }
114
- function extractDisplay(field) {
115
- if (!field)
116
- return "";
117
- if (typeof field === "string") {
118
- // If it's a 32-char hex string, it's a sys_id not a display value
119
- if (/^[a-f0-9]{32}$/.test(field))
120
- return "";
121
- return field;
122
- }
123
- if (typeof field === "object" && field !== null) {
124
- const f = field;
125
- if (f.display_value && typeof f.display_value === "string")
126
- return f.display_value;
127
- }
128
- return "";
257
+ const row = matches[0];
258
+ try {
259
+ rootId = (0, servicenow_identifiers_js_1.normalizeServiceNowSysId)(row.sys_id);
129
260
  }
130
- async function traverse(currentId, currentDepth) {
131
- if (currentDepth > maxDepth || allRels.length >= traversalTarget)
132
- return;
133
- if (traversalRequests >= maxTraversalRequests) {
134
- traversalTruncated = true;
261
+ catch {
262
+ throw ciNotFound();
263
+ }
264
+ rootView = viewOf(row);
265
+ }
266
+ // ── Traverse, level by level ──
267
+ const known = new Map([[rootId, rootView]]);
268
+ const unreadable = new Set();
269
+ const notRead = new Set();
270
+ const listed = [];
271
+ /** Relationships among readable CIs, by row sys_id, for the map. */
272
+ const edges = new Map();
273
+ const leftOut = new Set();
274
+ const skippedVia = new Set();
275
+ const wantedShown = args.offset + args.limit;
276
+ let shownCount = 0;
277
+ let rowsRead = 0;
278
+ let relBytes = 0;
279
+ let ciBytes = 0;
280
+ let ciRequested = 0;
281
+ let stop;
282
+ let ciStop;
283
+ let invalidIdentifier = false;
284
+ const matchesClass = (view) => !args.class || (view.class ?? "").toLowerCase().includes(args.class.toLowerCase());
285
+ const matchesType = (type) => !args.type || type.toLowerCase().includes(args.type.toLowerCase());
286
+ /** How many rows the next relationship page may ask for, or the cap that forbids one. */
287
+ function nextPage(wanted) {
288
+ if (requests + 1 > limits.maxRequests - limits.ciReadReserve)
289
+ return { cap: "requests" };
290
+ const rowsLeft = limits.maxRelationshipRows - rowsRead;
291
+ if (rowsLeft < 1)
292
+ return { cap: "relationship_rows" };
293
+ const perRow = rowsRead > 0 ? Math.max(relBytes / rowsRead, 100) : 250;
294
+ const byBytes = Math.floor((limits.relationshipBytes - relBytes) / (perRow * 1.25));
295
+ if (byBytes < 10)
296
+ return { cap: "response_bytes" };
297
+ // Ask for about twice the CIs still needed, so a short page is rare.
298
+ const asked = Math.min(limits.relationshipPage, Math.max(wanted * 2, 100));
299
+ return { limit: Math.min(asked, rowsLeft, byBytes) };
300
+ }
301
+ /** The type filter goes in the query too; `escapeQueryValue` keeps the value one literal. */
302
+ const typeCondition = args.type ? `^type.nameLIKE${(0, utils_js_1.escapeQueryValue)(args.type)}` : "";
303
+ let frontier = [rootId];
304
+ for (let depth = 1; depth <= maxDepth && frontier.length > 0; depth += 1) {
305
+ // A level is read only as far as the page asked for needs: the CIs are
306
+ // found in the order of the frontier's chunks, then of the relationship
307
+ // rows, so what one call reads is a prefix of what a longer one reads.
308
+ const inFrontier = new Set(frontier);
309
+ const chunked = chunks(frontier, limits.relationshipChunk);
310
+ const cursor = { chunk: 0, offset: 0 };
311
+ const found = new Map();
312
+ const pending = [];
313
+ let pendingStart = 0;
314
+ const levelEdges = [];
315
+ const readOrder = [];
316
+ let levelShown = 0;
317
+ let rowsDone = false;
318
+ let levelReadStopped;
319
+ const needed = () => wantedShown + 1 - (shownCount + levelShown);
320
+ async function fetchPage(wanted) {
321
+ const page = nextPage(wanted);
322
+ if ("cap" in page) {
323
+ stop = { cap: page.cap, depth, unread: frontier.slice(cursor.chunk * limits.relationshipChunk) };
324
+ rowsDone = true;
135
325
  return;
136
326
  }
137
- traversalRequests += 1;
138
- let relResp;
327
+ const ids = chunked[cursor.chunk].join(",");
328
+ const condition = wantDown && wantUp ? `parentIN${ids}^ORchildIN${ids}` : wantDown ? `parentIN${ids}` : `childIN${ids}`;
329
+ let response;
139
330
  try {
140
- const safeId = (0, utils_js_1.escapeQueryValue)((0, servicenow_identifiers_js_1.normalizeServiceNowSysId)(currentId));
141
- relResp = await client.get("/api/now/table/cmdb_rel_ci", {
142
- sysparm_query: `parent=${safeId}^ORchild=${safeId}^ORDERBYsys_id`,
143
- sysparm_fields: "parent,child,type",
144
- sysparm_display_value: "all",
145
- sysparm_limit: "100",
146
- });
331
+ response = await request("/api/now/table/cmdb_rel_ci", (0, utils_js_1.buildTableParams)({
332
+ query: `${condition}${typeCondition}^ORDERBYsys_id`,
333
+ // The ends come back as bare sys_ids, and the type's own name by
334
+ // a dot-walk of `type`: no display value of a CI is ever asked for.
335
+ fields: [...relFields, "type.name"].join(","),
336
+ limit: page.limit,
337
+ offset: cursor.offset,
338
+ displayValue: "false",
339
+ noCount: true,
340
+ }));
147
341
  }
148
342
  catch (error) {
149
- // A failed hop truncates the walk -- report, don't hide
150
- warnings.push(`cmdb_rel_ci (traversal at depth ${currentDepth}): ${(0, utils_js_1.formatError)(error)}`);
343
+ if ((0, client_js_1.isServiceNowRequestCancellation)(error))
344
+ throw error;
345
+ const unread = frontier.slice(cursor.chunk * limits.relationshipChunk);
346
+ if ((0, client_js_1.isServiceNowResponseTooLarge)(error)) {
347
+ stop = { cap: "response_bytes", depth, unread };
348
+ }
349
+ else {
350
+ // A failed hop truncates the walk -- report, don't hide
351
+ warnings.push(`cmdb_rel_ci (traversal at depth ${depth}): ${(0, utils_js_1.formatError)(error)}`);
352
+ stop = { cap: "error", depth, unread };
353
+ }
354
+ rowsDone = true;
151
355
  return;
152
356
  }
153
- const records = relResp.result || [];
154
- const seen = new Set();
155
- for (const rec of records) {
156
- if (allRels.length >= traversalTarget) {
157
- traversalTruncated = true;
158
- break;
159
- }
160
- let parentId;
161
- let childId;
357
+ relBytes += (0, utils_js_1.serializedBytes)(response);
358
+ const raw = rowsOf(response);
359
+ const filtered = (0, field_policy_js_1.filterReadableRecord)(raw, relSelection);
360
+ const rows = Array.isArray(filtered) ? filtered : [];
361
+ const received = raw.length;
362
+ rowsRead += received;
363
+ for (const [position, entry] of rows.entries()) {
364
+ const row = recordOf(entry);
365
+ if (!row)
366
+ continue;
367
+ // Rows keep their order and count, so the raw row at the same place carries the type's name.
368
+ const typeName = rows.length === raw.length ? recordOf(raw[position])?.["type.name"] : undefined;
369
+ let parent;
370
+ let child;
162
371
  try {
163
- parentId = (0, servicenow_identifiers_js_1.normalizeServiceNowSysId)(extractValue(rec.parent));
164
- childId = (0, servicenow_identifiers_js_1.normalizeServiceNowSysId)(extractValue(rec.child));
372
+ parent = (0, servicenow_identifiers_js_1.normalizeServiceNowSysId)(extractValue(row.parent));
373
+ child = (0, servicenow_identifiers_js_1.normalizeServiceNowSysId)(extractValue(row.child));
165
374
  }
166
375
  catch {
167
- warnings.push("cmdb_rel_ci returned an invalid relationship identifier");
376
+ invalidIdentifier = true;
168
377
  continue;
169
378
  }
170
- const parentName = extractDisplay(rec.parent);
171
- const childName = extractDisplay(rec.child);
172
- const typeName = extractDisplay(rec.type) || "Related to";
173
- let otherId;
174
- let otherName;
175
- let relDir;
176
- if (parentId === currentId) {
177
- otherId = childId;
178
- otherName = childName;
179
- relDir = "downstream";
379
+ const rel = {
380
+ id: relationshipId(row.sys_id),
381
+ parent,
382
+ child,
383
+ type: (typeof typeName === "string" && typeName !== "" ? typeName : extractDisplay(row.type)) || RELATED_TO,
384
+ };
385
+ if (rel.parent === rel.child || !matchesType(rel.type))
386
+ continue;
387
+ const reached = [];
388
+ if (wantDown && inFrontier.has(rel.parent)) {
389
+ reached.push({ other: rel.child, direction: "downstream", via: rel.parent });
180
390
  }
181
- else if (childId === currentId) {
182
- otherId = parentId;
183
- otherName = parentName;
184
- relDir = "upstream";
391
+ if (wantUp && inFrontier.has(rel.child)) {
392
+ reached.push({ other: rel.parent, direction: "upstream", via: rel.child });
185
393
  }
186
- else {
394
+ if (reached.length === 0)
187
395
  continue;
396
+ levelEdges.push({ key: rel.id ?? `${rel.parent}>${rel.child}>${rel.type}`, row: rel });
397
+ for (const entry of reached) {
398
+ if (known.has(entry.other) || unreadable.has(entry.other) || notRead.has(entry.other) || found.has(entry.other)) {
399
+ continue;
400
+ }
401
+ const fresh = { sys_id: entry.other, type: rel.type, direction: entry.direction, via: entry.via };
402
+ found.set(entry.other, fresh);
403
+ pending.push(fresh);
188
404
  }
189
- if (otherId === currentId)
190
- continue;
191
- if (direction !== "both" && relDir !== direction)
192
- continue;
193
- if (args.type && !typeName.toLowerCase().includes(args.type.toLowerCase()))
405
+ }
406
+ if (received < page.limit) {
407
+ cursor.chunk += 1;
408
+ cursor.offset = 0;
409
+ if (cursor.chunk >= chunked.length)
410
+ rowsDone = true;
411
+ }
412
+ else {
413
+ cursor.offset += received;
414
+ }
415
+ }
416
+ while (needed() > 0) {
417
+ const waiting = () => pending.length - pendingStart;
418
+ // Read relationship rows until they name the CIs still needed.
419
+ while (!rowsDone && waiting() < needed())
420
+ await fetchPage(needed() - waiting());
421
+ if (waiting() === 0)
422
+ break;
423
+ // Read the CIs, from cmdb_ci, under the profile's field policy.
424
+ // Relationship rows are not domain separated, so nothing shown about a
425
+ // CI comes from them: a CI this read does not return is not shown, and
426
+ // is not walked through.
427
+ const size = Math.min(limits.ciChunk, args.class ? waiting() : Math.min(waiting(), needed()));
428
+ const group = pending.slice(pendingStart, pendingStart + size);
429
+ if (limits.maxCis - ciRequested < 1)
430
+ levelReadStopped = "cis";
431
+ else if (requests + 1 > limits.maxRequests)
432
+ levelReadStopped = "requests";
433
+ else if (ciBytes >= limits.ciBytes)
434
+ levelReadStopped = "response_bytes";
435
+ if (levelReadStopped !== undefined)
436
+ break;
437
+ const take = group.slice(0, limits.maxCis - ciRequested);
438
+ pendingStart += take.length;
439
+ ciRequested += take.length;
440
+ let response;
441
+ try {
442
+ response = await request("/api/now/table/cmdb_ci", (0, utils_js_1.buildTableParams)({
443
+ query: `sys_idIN${take.map((entry) => entry.sys_id).join(",")}`,
444
+ fields: ciFields,
445
+ limit: take.length,
446
+ displayValue: "true",
447
+ noCount: true,
448
+ }));
449
+ }
450
+ catch (error) {
451
+ if ((0, client_js_1.isServiceNowRequestCancellation)(error))
452
+ throw error;
453
+ if ((0, client_js_1.isServiceNowResponseTooLarge)(error)) {
454
+ levelReadStopped = "response_bytes";
455
+ }
456
+ else {
457
+ warnings.push(`cmdb_ci (reading CIs at depth ${depth}): ${(0, utils_js_1.formatError)(error)}`);
458
+ levelReadStopped = "error";
459
+ }
460
+ for (const entry of take) {
461
+ notRead.add(entry.sys_id);
462
+ skippedVia.add(entry.via);
463
+ }
464
+ break;
465
+ }
466
+ ciBytes += (0, utils_js_1.serializedBytes)(response);
467
+ const returned = new Map();
468
+ for (const entry of rowsOf(response)) {
469
+ const row = recordOf(entry);
470
+ if (!row)
194
471
  continue;
195
- const pairKey = `${otherId}:${relDir}`;
196
- if (seen.has(pairKey))
472
+ try {
473
+ returned.set((0, servicenow_identifiers_js_1.normalizeServiceNowSysId)(row.sys_id), row);
474
+ }
475
+ catch {
476
+ // A row without a usable sys_id cannot be matched to a relationship.
477
+ }
478
+ }
479
+ for (const entry of take) {
480
+ const row = returned.get(entry.sys_id);
481
+ if (!row) {
482
+ unreadable.add(entry.sys_id);
197
483
  continue;
198
- seen.add(pairKey);
199
- const otherClass = await getClass(otherId);
200
- // Apply class filter for display only
201
- if (!args.class || otherClass.toLowerCase().includes(args.class.toLowerCase())) {
202
- allRels.push({
203
- name: otherName || otherId,
204
- class: otherClass,
205
- type: typeName,
206
- direction: relDir,
207
- sys_id: otherId,
208
- depth: currentDepth,
209
- });
210
484
  }
211
- // Recurse
212
- if (currentDepth < maxDepth && !visited.has(otherId)) {
213
- visited.add(otherId);
214
- await traverse(otherId, currentDepth + 1);
485
+ const view = viewOf(row);
486
+ known.set(entry.sys_id, view);
487
+ readOrder.push(entry);
488
+ if (matchesClass(view))
489
+ levelShown += 1;
490
+ }
491
+ }
492
+ // CIs found that a cap kept from being read, when the page still needed them.
493
+ if (levelReadStopped !== undefined) {
494
+ const missed = pending.slice(pendingStart).filter((entry) => !notRead.has(entry.sys_id));
495
+ for (const entry of missed) {
496
+ notRead.add(entry.sys_id);
497
+ skippedVia.add(entry.via);
498
+ }
499
+ ciStop = {
500
+ cap: levelReadStopped,
501
+ depth,
502
+ count: [...notRead].filter((id) => found.has(id)).length,
503
+ };
504
+ }
505
+ // Relationships among CIs the profile can read; the others are counted.
506
+ for (const { key, row } of levelEdges) {
507
+ const ends = [row.parent, row.child];
508
+ if (ends.some((id) => unreadable.has(id))) {
509
+ leftOut.add(key);
510
+ }
511
+ else if (ends.every((id) => known.has(id))) {
512
+ if (!edges.has(key)) {
513
+ edges.set(key, {
514
+ ...(row.id === undefined || !relIdReadable ? {} : { sys_id: row.id }),
515
+ parent: row.parent,
516
+ child: row.child,
517
+ type: row.type,
518
+ rank: depth,
519
+ });
215
520
  }
216
521
  }
217
522
  }
218
- await traverse(rootId, 1);
219
- const page = allRels.slice(args.offset, args.offset + args.limit);
220
- return (0, utils_js_1.ok)((0, utils_js_1.withWarnings)({
221
- root: { name: rootName, class: rootClass, sys_id: rootId },
222
- relationships: page,
223
- meta: {
224
- depth: maxDepth,
225
- direction,
226
- total: allRels.length,
227
- offset: args.offset,
228
- limit: args.limit,
229
- has_more: args.offset + page.length < allRels.length,
230
- ...(args.offset + page.length < allRels.length
231
- ? { next_offset: args.offset + page.length }
523
+ for (const entry of readOrder) {
524
+ const view = known.get(entry.sys_id);
525
+ listed.push({
526
+ sys_id: entry.sys_id,
527
+ ...(view.name === undefined ? {} : { name: view.name }),
528
+ ...(view.class === undefined ? {} : { class: view.class }),
529
+ depth,
530
+ type: entry.type,
531
+ direction: entry.direction,
532
+ via: entry.via,
533
+ });
534
+ }
535
+ shownCount += levelShown;
536
+ if (stop !== undefined || ciStop !== undefined)
537
+ break;
538
+ // The page asked for is full, with one more CI known to exist: deeper
539
+ // levels would only add CIs after it.
540
+ if (shownCount > wantedShown)
541
+ break;
542
+ frontier = readOrder.map((entry) => entry.sys_id);
543
+ }
544
+ // ── Report ──
545
+ // A CI is named by its policy-filtered name, made inert and in quotes, or by its sys_id.
546
+ const labelOf = (id) => {
547
+ const name = (0, inert_text_js_1.quotedInertText)(known.get(id)?.name, 60);
548
+ return name === "" ? id : `"${name}"`;
549
+ };
550
+ const namedList = (ids) => {
551
+ const unique = [...new Set(ids)];
552
+ const named = unique.slice(0, limits.namedInWarning).map(labelOf);
553
+ const more = unique.length - named.length;
554
+ return `${named.join(", ")}${more > 0 ? ` and ${more} more` : ""}`;
555
+ };
556
+ const capText = {
557
+ requests: `the ${limits.maxRequests}-request limit`,
558
+ relationship_rows: `the ${limits.maxRelationshipRows}-relationship-row limit`,
559
+ response_bytes: "the response size limit",
560
+ cis: `the ${limits.maxCis}-CI limit`,
561
+ error: "an error",
562
+ };
563
+ let truncatedBy;
564
+ if (stop) {
565
+ truncatedBy = {
566
+ cap: stop.cap,
567
+ ...(stop.cap === "requests"
568
+ ? { max: limits.maxRequests }
569
+ : stop.cap === "relationship_rows"
570
+ ? { max: limits.maxRelationshipRows }
571
+ : {}),
572
+ depth: stop.depth,
573
+ unread_cis: stop.unread.length,
574
+ };
575
+ warnings.push(`Relationships of ${quantity(stop.unread.length, "CI")} at depth ${stop.depth} were not fully read, ` +
576
+ `stopped by ${capText[stop.cap]}: ${namedList(stop.unread)}. ` +
577
+ "Their relationships and the CIs beyond them may be missing; narrow the walk with a lower depth, a type, or a nearer start CI.");
578
+ }
579
+ else if (ciStop) {
580
+ truncatedBy = {
581
+ cap: ciStop.cap,
582
+ ...(ciStop.cap === "requests"
583
+ ? { max: limits.maxRequests }
584
+ : ciStop.cap === "cis"
585
+ ? { max: limits.maxCis }
232
586
  : {}),
233
- traversal_truncated: traversalTruncated,
234
- traversal_requests: traversalRequests,
235
- },
236
- }, warnings));
587
+ depth: ciStop.depth,
588
+ unread_cis: ciStop.count,
589
+ };
590
+ }
591
+ if (ciStop && ciStop.count > 0) {
592
+ warnings.push(`${quantity(ciStop.count, "CI")} found at depth ${ciStop.depth} could not be read, stopped by ${capText[ciStop.cap]}, ` +
593
+ `so ${ciStop.count === 1 ? "it is" : "they are"} left out, with the CIs beyond. ` +
594
+ `They are related to: ${namedList([...skippedVia])}.`);
595
+ }
596
+ if (leftOut.size > 0) {
597
+ warnings.push(leftOut.size === 1
598
+ ? "1 relationship leads to a CI this profile can't read; it is left out."
599
+ : `${leftOut.size} relationships lead to CIs this profile can't read; they are left out.`);
237
600
  }
238
- catch (error) {
239
- throw error;
601
+ if (invalidIdentifier) {
602
+ warnings.push("cmdb_rel_ci returned an invalid relationship identifier");
603
+ }
604
+ const shown = listed
605
+ .filter((entry) => matchesClass({ ...(entry.class === undefined ? {} : { class: entry.class }) }))
606
+ .map((entry) => ({
607
+ ...(nameShown ? { name: entry.name ?? entry.sys_id } : {}),
608
+ ...(entry.class === undefined ? {} : { class: entry.class }),
609
+ type: entry.type,
610
+ direction: entry.direction,
611
+ sys_id: entry.sys_id,
612
+ via: entry.via,
613
+ depth: entry.depth,
614
+ }));
615
+ const page = shown.slice(args.offset, args.offset + args.limit);
616
+ const hasMore = args.offset + page.length < shown.length;
617
+ const data = {
618
+ root: {
619
+ ...(rootView.name === undefined ? {} : { name: rootView.name }),
620
+ ...(rootView.class === undefined ? {} : { class: rootView.class }),
621
+ sys_id: rootId,
622
+ },
623
+ relationships: page,
624
+ meta: {
625
+ depth: maxDepth,
626
+ direction,
627
+ total: shown.length,
628
+ offset: args.offset,
629
+ limit: args.limit,
630
+ has_more: hasMore,
631
+ ...(hasMore ? { next_offset: args.offset + page.length } : {}),
632
+ traversal_truncated: truncatedBy !== undefined,
633
+ traversal_requests: requests,
634
+ ...(truncatedBy === undefined ? {} : { truncated_by: truncatedBy }),
635
+ ...(leftOut.size > 0 ? { unreadable_relationships: leftOut.size } : {}),
636
+ },
637
+ };
638
+ if (args.map) {
639
+ const node = (entry) => ({
640
+ sys_id: entry.sys_id,
641
+ ...(entry.name === undefined ? {} : { name: entry.name }),
642
+ ...(entry.class === undefined ? {} : { class: entry.class }),
643
+ depth: entry.depth,
644
+ });
645
+ const pageIds = new Set(page.map((entry) => entry.sys_id));
646
+ const inPage = listed.filter((entry) => pageIds.has(entry.sys_id));
647
+ const map = (0, relationships_map_js_1.buildRelationshipMap)(node({ sys_id: rootId, ...(rootView.name === undefined ? {} : { name: rootView.name }), ...(rootView.class === undefined ? {} : { class: rootView.class }), depth: 0 }), inPage.map(node), [...edges.values()]
648
+ .sort((a, b) => a.rank - b.rank || ((a.sys_id ?? "") < (b.sys_id ?? "") ? -1 : (a.sys_id ?? "") > (b.sys_id ?? "") ? 1 : 0))
649
+ .map(({ rank: _rank, ...edge }) => edge), Math.floor(args.max_response_bytes * limits.mapShare));
650
+ data.nodes = map.nodes;
651
+ data.edges = map.edges;
652
+ data.diagram = map.diagram;
653
+ if (map.omitted_nodes > 0) {
654
+ data.meta.map_omitted_cis = map.omitted_nodes;
655
+ warnings.push(`The map holds the first ${map.nodes.length} of ${map.nodes.length + map.omitted_nodes} CIs to fit the response budget; ` +
656
+ "lower limit, or page with offset, for the rest.");
657
+ }
240
658
  }
659
+ return (0, utils_js_1.ok)((0, utils_js_1.withWarnings)(data, warnings));
241
660
  }
242
661
  //# sourceMappingURL=relationships.js.map