@onlyflows/servicenow-mcp 2.2.0-dev.6 → 2.2.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 (269) hide show
  1. package/.env.example +6 -3
  2. package/CHANGELOG.md +404 -0
  3. package/README.md +580 -104
  4. package/dist/atf-form.d.ts +3 -15
  5. package/dist/atf-form.d.ts.map +1 -1
  6. package/dist/atf-policy.d.ts +1 -1
  7. package/dist/atf-policy.d.ts.map +1 -1
  8. package/dist/atf-policy.js +2 -0
  9. package/dist/atf-policy.js.map +1 -1
  10. package/dist/atf-result-cache.d.ts +23 -59
  11. package/dist/atf-result-cache.d.ts.map +1 -1
  12. package/dist/auth.d.ts +1 -0
  13. package/dist/auth.d.ts.map +1 -1
  14. package/dist/auth.js +17 -0
  15. package/dist/auth.js.map +1 -1
  16. package/dist/batch-limits.d.ts +18 -0
  17. package/dist/batch-limits.d.ts.map +1 -0
  18. package/dist/batch-limits.js +21 -0
  19. package/dist/batch-limits.js.map +1 -0
  20. package/dist/bounded-input.d.ts +49 -0
  21. package/dist/bounded-input.d.ts.map +1 -0
  22. package/dist/bounded-input.js +81 -0
  23. package/dist/bounded-input.js.map +1 -0
  24. package/dist/client.d.ts +25 -0
  25. package/dist/client.d.ts.map +1 -1
  26. package/dist/client.js +92 -18
  27. package/dist/client.js.map +1 -1
  28. package/dist/credential-tables.d.ts +32 -0
  29. package/dist/credential-tables.d.ts.map +1 -0
  30. package/dist/credential-tables.js +58 -0
  31. package/dist/credential-tables.js.map +1 -0
  32. package/dist/encoded-query-policy.d.ts +11 -0
  33. package/dist/encoded-query-policy.d.ts.map +1 -1
  34. package/dist/encoded-query-policy.js +18 -2
  35. package/dist/encoded-query-policy.js.map +1 -1
  36. package/dist/execution-context.d.ts +14 -0
  37. package/dist/execution-context.d.ts.map +1 -1
  38. package/dist/execution-context.js +8 -0
  39. package/dist/execution-context.js.map +1 -1
  40. package/dist/field-policy.d.ts +115 -3
  41. package/dist/field-policy.d.ts.map +1 -1
  42. package/dist/field-policy.js +909 -97
  43. package/dist/field-policy.js.map +1 -1
  44. package/dist/hidden-values.d.ts +225 -0
  45. package/dist/hidden-values.d.ts.map +1 -0
  46. package/dist/hidden-values.js +748 -0
  47. package/dist/hidden-values.js.map +1 -0
  48. package/dist/html-response.d.ts +34 -0
  49. package/dist/html-response.d.ts.map +1 -0
  50. package/dist/html-response.js +72 -0
  51. package/dist/html-response.js.map +1 -0
  52. package/dist/http-entrypoint.d.ts.map +1 -1
  53. package/dist/http-entrypoint.js +7 -0
  54. package/dist/http-entrypoint.js.map +1 -1
  55. package/dist/http-runtime.d.ts.map +1 -1
  56. package/dist/http-runtime.js +8 -0
  57. package/dist/http-runtime.js.map +1 -1
  58. package/dist/incident-journal-policy.d.ts +27 -5
  59. package/dist/incident-journal-policy.d.ts.map +1 -1
  60. package/dist/incident-journal-policy.js +34 -21
  61. package/dist/incident-journal-policy.js.map +1 -1
  62. package/dist/index.js +7 -0
  63. package/dist/index.js.map +1 -1
  64. package/dist/json-shape-limits.d.ts +71 -0
  65. package/dist/json-shape-limits.d.ts.map +1 -0
  66. package/dist/json-shape-limits.js +131 -0
  67. package/dist/json-shape-limits.js.map +1 -0
  68. package/dist/metadata-cache.d.ts +84 -21
  69. package/dist/metadata-cache.d.ts.map +1 -1
  70. package/dist/metadata-cache.js +316 -196
  71. package/dist/metadata-cache.js.map +1 -1
  72. package/dist/policy-card.d.ts +146 -0
  73. package/dist/policy-card.d.ts.map +1 -0
  74. package/dist/policy-card.js +420 -0
  75. package/dist/policy-card.js.map +1 -0
  76. package/dist/profile-manager.d.ts +19 -3
  77. package/dist/profile-manager.d.ts.map +1 -1
  78. package/dist/profile-manager.js +89 -4
  79. package/dist/profile-manager.js.map +1 -1
  80. package/dist/record-identifier-policy.d.ts +2 -8
  81. package/dist/record-identifier-policy.d.ts.map +1 -1
  82. package/dist/risky-grants.d.ts +25 -0
  83. package/dist/risky-grants.d.ts.map +1 -0
  84. package/dist/risky-grants.js +77 -0
  85. package/dist/risky-grants.js.map +1 -0
  86. package/dist/server.d.ts.map +1 -1
  87. package/dist/server.js +26 -5
  88. package/dist/server.js.map +1 -1
  89. package/dist/setup-prompts.js +1 -0
  90. package/dist/setup-prompts.js.map +1 -1
  91. package/dist/setup.d.ts +1 -1
  92. package/dist/setup.d.ts.map +1 -1
  93. package/dist/setup.js +305 -59
  94. package/dist/setup.js.map +1 -1
  95. package/dist/stdio-runtime.d.ts +15 -0
  96. package/dist/stdio-runtime.d.ts.map +1 -1
  97. package/dist/stdio-runtime.js +60 -0
  98. package/dist/stdio-runtime.js.map +1 -1
  99. package/dist/structured-query.d.ts +100 -115
  100. package/dist/structured-query.d.ts.map +1 -1
  101. package/dist/structured-query.js +138 -17
  102. package/dist/structured-query.js.map +1 -1
  103. package/dist/table-policy.d.ts +41 -4
  104. package/dist/table-policy.d.ts.map +1 -1
  105. package/dist/table-policy.js +82 -10
  106. package/dist/table-policy.js.map +1 -1
  107. package/dist/tool-error.d.ts +34 -0
  108. package/dist/tool-error.d.ts.map +1 -1
  109. package/dist/tool-error.js +109 -1
  110. package/dist/tool-error.js.map +1 -1
  111. package/dist/tool-table-access.d.ts.map +1 -1
  112. package/dist/tool-table-access.js +35 -5
  113. package/dist/tool-table-access.js.map +1 -1
  114. package/dist/tools/aggregate.d.ts +13 -19
  115. package/dist/tools/aggregate.d.ts.map +1 -1
  116. package/dist/tools/aggregate.js +4 -5
  117. package/dist/tools/aggregate.js.map +1 -1
  118. package/dist/tools/all-fields-cap.d.ts.map +1 -1
  119. package/dist/tools/all-fields-cap.js +32 -45
  120. package/dist/tools/all-fields-cap.js.map +1 -1
  121. package/dist/tools/atf-author-module.d.ts +29 -14
  122. package/dist/tools/atf-author-module.d.ts.map +1 -1
  123. package/dist/tools/atf-author-module.js +11 -5
  124. package/dist/tools/atf-author-module.js.map +1 -1
  125. package/dist/tools/atf-contracts.d.ts +135 -829
  126. package/dist/tools/atf-contracts.d.ts.map +1 -1
  127. package/dist/tools/atf-shared.js +2 -2
  128. package/dist/tools/atf-shared.js.map +1 -1
  129. package/dist/tools/atf-step-catalog.d.ts +16 -15
  130. package/dist/tools/atf-step-catalog.d.ts.map +1 -1
  131. package/dist/tools/atf-step-catalog.js +181 -10
  132. package/dist/tools/atf-step-catalog.js.map +1 -1
  133. package/dist/tools/atf.d.ts +8 -24
  134. package/dist/tools/atf.d.ts.map +1 -1
  135. package/dist/tools/atf.js +2 -2
  136. package/dist/tools/atf.js.map +1 -1
  137. package/dist/tools/attach.d.ts +6 -22
  138. package/dist/tools/attach.d.ts.map +1 -1
  139. package/dist/tools/batch.d.ts +18 -71
  140. package/dist/tools/batch.d.ts.map +1 -1
  141. package/dist/tools/batch.js +566 -100
  142. package/dist/tools/batch.js.map +1 -1
  143. package/dist/tools/catalog.d.ts +2 -2
  144. package/dist/tools/catalog.d.ts.map +1 -1
  145. package/dist/tools/catalog.js +7 -1
  146. package/dist/tools/catalog.js.map +1 -1
  147. package/dist/tools/codesearch.d.ts +1 -13
  148. package/dist/tools/codesearch.d.ts.map +1 -1
  149. package/dist/tools/create-module.d.ts +9 -14
  150. package/dist/tools/create-module.d.ts.map +1 -1
  151. package/dist/tools/create-module.js +4 -8
  152. package/dist/tools/create-module.js.map +1 -1
  153. package/dist/tools/delete.d.ts +1 -9
  154. package/dist/tools/delete.d.ts.map +1 -1
  155. package/dist/tools/delete.js +2 -3
  156. package/dist/tools/delete.js.map +1 -1
  157. package/dist/tools/discover.d.ts +6 -14
  158. package/dist/tools/discover.d.ts.map +1 -1
  159. package/dist/tools/flow-view-contracts.d.ts +1023 -0
  160. package/dist/tools/flow-view-contracts.d.ts.map +1 -0
  161. package/dist/tools/flow-view-contracts.js +570 -0
  162. package/dist/tools/flow-view-contracts.js.map +1 -0
  163. package/dist/tools/flow-view-graph.d.ts +86 -0
  164. package/dist/tools/flow-view-graph.d.ts.map +1 -0
  165. package/dist/tools/flow-view-graph.js +993 -0
  166. package/dist/tools/flow-view-graph.js.map +1 -0
  167. package/dist/tools/flow-view-gzip.d.ts +52 -0
  168. package/dist/tools/flow-view-gzip.d.ts.map +1 -0
  169. package/dist/tools/flow-view-gzip.js +179 -0
  170. package/dist/tools/flow-view-gzip.js.map +1 -0
  171. package/dist/tools/flow-view-mermaid.d.ts +37 -0
  172. package/dist/tools/flow-view-mermaid.d.ts.map +1 -0
  173. package/dist/tools/flow-view-mermaid.js +337 -0
  174. package/dist/tools/flow-view-mermaid.js.map +1 -0
  175. package/dist/tools/flow-view-module.d.ts +61 -0
  176. package/dist/tools/flow-view-module.d.ts.map +1 -0
  177. package/dist/tools/flow-view-module.js +378 -0
  178. package/dist/tools/flow-view-module.js.map +1 -0
  179. package/dist/tools/flow-view-policy.d.ts +106 -0
  180. package/dist/tools/flow-view-policy.d.ts.map +1 -0
  181. package/dist/tools/flow-view-policy.js +462 -0
  182. package/dist/tools/flow-view-policy.js.map +1 -0
  183. package/dist/tools/flow-view-renderers.d.ts +68 -0
  184. package/dist/tools/flow-view-renderers.d.ts.map +1 -0
  185. package/dist/tools/flow-view-renderers.js +513 -0
  186. package/dist/tools/flow-view-renderers.js.map +1 -0
  187. package/dist/tools/flow-view-table.d.ts +115 -0
  188. package/dist/tools/flow-view-table.d.ts.map +1 -0
  189. package/dist/tools/flow-view-table.js +1002 -0
  190. package/dist/tools/flow-view-table.js.map +1 -0
  191. package/dist/tools/get-module.d.ts +36 -42
  192. package/dist/tools/get-module.d.ts.map +1 -1
  193. package/dist/tools/health.d.ts +9 -6
  194. package/dist/tools/health.d.ts.map +1 -1
  195. package/dist/tools/incident-journal-module.d.ts +8 -7
  196. package/dist/tools/incident-journal-module.d.ts.map +1 -1
  197. package/dist/tools/index.d.ts +4 -4
  198. package/dist/tools/index.d.ts.map +1 -1
  199. package/dist/tools/index.js +118 -18
  200. package/dist/tools/index.js.map +1 -1
  201. package/dist/tools/markdown.d.ts +27 -0
  202. package/dist/tools/markdown.d.ts.map +1 -1
  203. package/dist/tools/markdown.js +104 -1
  204. package/dist/tools/markdown.js.map +1 -1
  205. package/dist/tools/nl.d.ts +1 -11
  206. package/dist/tools/nl.d.ts.map +1 -1
  207. package/dist/tools/profile.d.ts +1 -1
  208. package/dist/tools/profile.d.ts.map +1 -1
  209. package/dist/tools/profile.js +20 -1
  210. package/dist/tools/profile.js.map +1 -1
  211. package/dist/tools/query-module.d.ts +59 -71
  212. package/dist/tools/query-module.d.ts.map +1 -1
  213. package/dist/tools/query-module.js +28 -7
  214. package/dist/tools/query-module.js.map +1 -1
  215. package/dist/tools/record-write-shared.d.ts.map +1 -1
  216. package/dist/tools/record-write-shared.js +20 -2
  217. package/dist/tools/record-write-shared.js.map +1 -1
  218. package/dist/tools/relationships.d.ts +6 -22
  219. package/dist/tools/relationships.d.ts.map +1 -1
  220. package/dist/tools/result-envelope.d.ts +2255 -1357
  221. package/dist/tools/result-envelope.d.ts.map +1 -1
  222. package/dist/tools/result-envelope.js +24 -2
  223. package/dist/tools/result-envelope.js.map +1 -1
  224. package/dist/tools/schema-module.d.ts +36 -21
  225. package/dist/tools/schema-module.d.ts.map +1 -1
  226. package/dist/tools/schema-module.js +106 -65
  227. package/dist/tools/schema-module.js.map +1 -1
  228. package/dist/tools/script.d.ts +1 -11
  229. package/dist/tools/script.d.ts.map +1 -1
  230. package/dist/tools/syslog.d.ts +11 -18
  231. package/dist/tools/syslog.d.ts.map +1 -1
  232. package/dist/tools/syslog.js +2 -3
  233. package/dist/tools/syslog.js.map +1 -1
  234. package/dist/tools/table-hierarchy.d.ts +35 -0
  235. package/dist/tools/table-hierarchy.d.ts.map +1 -0
  236. package/dist/tools/table-hierarchy.js +74 -0
  237. package/dist/tools/table-hierarchy.js.map +1 -0
  238. package/dist/tools/tool-module.d.ts +40 -15
  239. package/dist/tools/tool-module.d.ts.map +1 -1
  240. package/dist/tools/tool-module.js +755 -205
  241. package/dist/tools/tool-module.js.map +1 -1
  242. package/dist/tools/update-module.d.ts +11 -17
  243. package/dist/tools/update-module.d.ts.map +1 -1
  244. package/dist/tools/update-module.js +10 -12
  245. package/dist/tools/update-module.js.map +1 -1
  246. package/dist/unknown-filter-fields.d.ts +52 -0
  247. package/dist/unknown-filter-fields.d.ts.map +1 -0
  248. package/dist/unknown-filter-fields.js +87 -0
  249. package/dist/unknown-filter-fields.js.map +1 -0
  250. package/dist/version.d.ts +1 -1
  251. package/dist/version.d.ts.map +1 -1
  252. package/dist/version.js +1 -1
  253. package/dist/version.js.map +1 -1
  254. package/dist/write-value-policy.d.ts +20 -12
  255. package/dist/write-value-policy.d.ts.map +1 -1
  256. package/dist/write-value-policy.js +179 -67
  257. package/dist/write-value-policy.js.map +1 -1
  258. package/docs/ADDING-TOOLS.md +22 -13
  259. package/docs/CLIENT-SETUP.md +110 -52
  260. package/docs/CROSS-CLIENT-RELEASE-MATRIX.md +2 -2
  261. package/docs/FLOW-VIEW.md +214 -0
  262. package/docs/PRODUCTION-SECURITY.md +218 -25
  263. package/docs/RELEASE-VALIDATION.md +2 -2
  264. package/docs/TESTING-OAUTH.md +1 -1
  265. package/docs/V2-MIGRATION.md +404 -30
  266. package/package.json +20 -6
  267. package/scripts/release-validate.mjs +56 -0
  268. package/server.json +22 -0
  269. package/tools/inspector/package-lock.json +163 -201
@@ -2,13 +2,19 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.schema = exports.definition = void 0;
4
4
  exports.handler = handler;
5
+ const node_buffer_1 = require("node:buffer");
5
6
  const zod_1 = require("zod");
7
+ const client_js_1 = require("../client.js");
8
+ const batch_limits_js_1 = require("../batch-limits.js");
9
+ const metadata_cache_js_1 = require("../metadata-cache.js");
6
10
  const encoded_query_policy_js_1 = require("../encoded-query-policy.js");
7
11
  const field_policy_js_1 = require("../field-policy.js");
8
- const incident_journal_policy_js_1 = require("../incident-journal-policy.js");
9
12
  const utils_js_1 = require("../utils.js");
13
+ const unknown_filter_fields_js_1 = require("../unknown-filter-fields.js");
10
14
  const servicenow_identifiers_js_1 = require("../servicenow-identifiers.js");
11
15
  const structured_query_js_1 = require("../structured-query.js");
16
+ const tool_error_js_1 = require("../tool-error.js");
17
+ const write_value_policy_js_1 = require("../write-value-policy.js");
12
18
  const structuredWriteQuerySchema = structured_query_js_1.structuredQuerySchema.refine((query) => query.filter !== undefined, { message: "Batch mutations require structured_query.filter" });
13
19
  exports.definition = {
14
20
  name: "sn_batch",
@@ -24,44 +30,42 @@ exports.definition = {
24
30
  },
25
31
  };
26
32
  exports.schema = zod_1.z
27
- .object({
33
+ .strictObject({
28
34
  table: zod_1.z.string().describe("ServiceNow table name"),
29
35
  structured_query: structuredWriteQuerySchema.describe("Required policy-authorized structured filter selecting records. Raw encoded queries are prohibited."),
30
36
  action: zod_1.z
31
37
  .enum(["update", "delete"])
32
38
  .describe("Operation to perform: update or delete"),
33
39
  fields: zod_1.z
34
- .record(zod_1.z.unknown())
40
+ .record(zod_1.z.string(), zod_1.z.unknown())
35
41
  .optional()
36
42
  .describe('JSON fields to set on each record (required for update action). e.g. {"state":"7","close_notes":"Bulk closed"}'),
37
43
  limit: zod_1.z
38
44
  .number()
39
45
  .int()
40
46
  .min(1)
41
- .max(10_000)
47
+ .max(batch_limits_js_1.BATCH_LIMITS.maxLimit)
42
48
  .optional()
43
- .default(200)
49
+ .default(batch_limits_js_1.BATCH_LIMITS.defaultLimit)
44
50
  .describe("Max records to affect (default 200, safety cap 10000)"),
45
51
  confirm: zod_1.z
46
52
  .boolean()
47
53
  .optional()
48
54
  .default(false)
49
55
  .describe("Set to true to actually execute. Default is dry-run."),
50
- })
51
- .strict(encoded_query_policy_js_1.ENCODED_QUERY_MIGRATION_MESSAGE);
52
- async function handler(args, client, _config, _context) {
56
+ }, encoded_query_policy_js_1.ENCODED_QUERY_STRICT_OBJECT_PARAMS);
57
+ async function handler(args, client, _config, context) {
53
58
  try {
54
59
  (0, encoded_query_policy_js_1.rejectRawEncodedWrite)(args.query);
55
- // The append-only journal discipline is uniform across every write path.
56
- // Without this, sn_batch was the one way to set comments/work_notes as
57
- // generic fields, which is exactly what makes the journal audit trail
58
- // meaningless. Matches sn_create and sn_update.
59
- (0, incident_journal_policy_js_1.rejectGenericIncidentJournalFields)(args.fields);
60
60
  if (args.action === "update" && !args.fields) {
61
61
  return (0, utils_js_1.err)("--fields is required for update action");
62
62
  }
63
+ // The same field and value policy as sn_create and sn_update, including
64
+ // the journal bounds for comments/work_notes. Preflight already applied
65
+ // it; repeating it keeps a direct handler call equally bounded, and the
66
+ // canonical strings are what goes upstream.
63
67
  const writableFields = args.action === "update"
64
- ? (0, field_policy_js_1.validateWritableFields)(args.table, args.fields)
68
+ ? (0, write_value_policy_js_1.prepareWriteFieldValues)("update", args.table, args.fields)
65
69
  : undefined;
66
70
  const readableFields = (0, field_policy_js_1.preparedReadableFields)(args, args.table) ??
67
71
  (0, field_policy_js_1.resolveReadableFields)(args.table, { fields: "sys_id" });
@@ -69,26 +73,53 @@ async function handler(args, client, _config, _context) {
69
73
  if (structuredPlan.structuredQuery.filter === undefined) {
70
74
  throw new encoded_query_policy_js_1.EncodedQueryPolicyError("encoded_write_prohibited");
71
75
  }
72
- const limit = Math.min(args.limit, 10000);
73
- // Step 1: Query matching records (sys_id only)
74
- const resp = await client.get(`/api/now/table/${args.table}`, {
75
- sysparm_fields: "sys_id",
76
- sysparm_limit: String(limit),
77
- sysparm_query: structuredPlan.encodedQuery,
78
- });
76
+ const limit = Math.min(args.limit, batch_limits_js_1.BATCH_LIMITS.maxLimit);
77
+ // Step 1: Query matching records (sys_id only). These are the records the
78
+ // run will change, so they come from the instance on every run, never
79
+ // from the metadata cache: a cached answer can be stale within the
80
+ // watermark's gaps, and would update or delete records that no longer
81
+ // match.
82
+ // The filter's own fields ride along so the rows show whether the table
83
+ // has them (see unknown-filter-fields.ts).
84
+ const echo = (0, unknown_filter_fields_js_1.echoFilterFields)("sys_id", structuredPlan.referencedFields);
85
+ let resp;
86
+ try {
87
+ resp = await (0, metadata_cache_js_1.uncachedOperations)(client).get(`/api/now/table/${args.table}`, {
88
+ sysparm_fields: echo.sysparmFields,
89
+ sysparm_limit: String(limit),
90
+ sysparm_query: structuredPlan.encodedQuery,
91
+ });
92
+ }
93
+ catch (error) {
94
+ if ((0, unknown_filter_fields_js_1.isFilterEchoTooLarge)(error, echo))
95
+ throw (0, tool_error_js_1.createFilterFieldsTooLargeError)();
96
+ throw error;
97
+ }
98
+ // Refused here, before the sample, the target list or any other request.
99
+ const missingField = (0, unknown_filter_fields_js_1.firstMissingFilterField)(resp.result, echo.probe);
100
+ if (missingField !== undefined)
101
+ throw (0, tool_error_js_1.createUnknownFilterFieldError)(missingField);
79
102
  const filtered = (0, field_policy_js_1.filterReadableRecord)(resp.result || [], readableFields);
80
103
  const results = Array.isArray(filtered)
81
104
  ? (filtered.filter((record) => typeof record === "object" && record !== null && !Array.isArray(record)))
82
105
  : [];
83
- const matched = results.length;
106
+ const targets = targetSysIds(results);
107
+ const matched = targets.sysIds.length + targets.invalid;
84
108
  // Step 2: Dry-run?
85
109
  if (!args.confirm) {
110
+ const sample = await dryRunSample(client, args.table, targets.sysIds, (0, field_policy_js_1.resolveReadableFields)(args.table, { fields: "all" }), context?.signal);
86
111
  return (0, utils_js_1.ok)({
87
112
  action: args.action,
88
113
  table: args.table,
89
114
  matched,
90
115
  dry_run: true,
91
116
  message: "Dry run — no changes made. Set confirm to true to execute.",
117
+ ...(sample.length === 0 ? {} : { sample }),
118
+ // Names only, never values: the values are the caller's own input.
119
+ ...(writableFields === undefined
120
+ ? {}
121
+ : { fields_to_write: Object.keys(writableFields) }),
122
+ note: DRY_RUN_NOTE,
92
123
  });
93
124
  }
94
125
  if (matched === 0) {
@@ -100,125 +131,560 @@ async function handler(args, client, _config, _context) {
100
131
  failed: 0,
101
132
  });
102
133
  }
103
- // Step 3: Execute through ServiceNow REST Batch API where available.
104
- // If the instance rejects /api/now/v1/batch, fall back to the serial table
105
- // API path so the public tool behavior stays compatible.
106
- const execution = await executeBatchMutation(client, args.table, args.action, results, writableFields);
107
- const { processed, failed } = execution;
134
+ // Step 3: Execute through the ServiceNow REST Batch API. Serial Table API
135
+ // calls are used only when the instance refused a batch request before
136
+ // running any of it, so no change is ever sent twice.
137
+ const execution = await executeBatchMutation(client, args.table, args.action, targets, writableFields,
138
+ // A direct handler call may pass no context; it then keeps the single
139
+ // budget of whatever scope it runs in.
140
+ context?.signal);
141
+ const { processed, failed, message } = execution;
108
142
  return (0, utils_js_1.ok)({
109
143
  action: args.action,
110
144
  table: args.table,
111
145
  matched,
112
146
  processed,
113
147
  failed,
148
+ ...(message === undefined ? {} : { message }),
114
149
  });
115
150
  }
116
151
  catch (error) {
117
152
  throw error;
118
153
  }
119
154
  }
120
- const REST_BATCH_CHUNK_SIZE = 50;
121
- async function executeBatchMutation(client, table, action, records, fields) {
155
+ /** Records a dry run shows. */
156
+ const DRY_RUN_SAMPLE_SIZE = batch_limits_js_1.BATCH_LIMITS.dryRunSampleSize;
157
+ /** Longest display value a sample row carries. */
158
+ const DRY_RUN_DISPLAY_MAX_CHARS = 120;
159
+ /** Readable fields that identify a record to a person, in order of preference. */
160
+ const DRY_RUN_DISPLAY_FIELDS = Object.freeze([
161
+ "number",
162
+ "name",
163
+ "short_description",
164
+ "title",
165
+ ]);
166
+ const DRY_RUN_SAMPLE_DEADLINE_MS = 5_000;
167
+ const DRY_RUN_NOTE = "The sample is a preview of the first matches, not a list of what will change. " +
168
+ "Running again with confirm true re-runs the query, so it can match different " +
169
+ "records than this dry run did.";
170
+ /**
171
+ * The one extra read a dry run makes: at most DRY_RUN_SAMPLE_SIZE records,
172
+ * addressed by the sys_ids the lookup already returned, so the preview shows
173
+ * rows from that same result rather than a second evaluation of the filter.
174
+ * It asks only for sys_id and one display field the profile may read, and the
175
+ * rows pass the same readable-field filter as the lookup. It is skipped when
176
+ * nothing matched, and a failed response yields no sample rather than failing
177
+ * the dry run: the count is already in hand.
178
+ */
179
+ async function dryRunSample(client, table, sysIds, readable, signal) {
180
+ const ids = sysIds.slice(0, DRY_RUN_SAMPLE_SIZE);
181
+ if (ids.length === 0)
182
+ return [];
183
+ const readableAll = (0, field_policy_js_1.isAllFieldSelection)(readable);
184
+ // A hidden-typed field is never the display field: it is not even asked for.
185
+ const hidden = (0, field_policy_js_1.typeHiddenFieldNames)(table);
186
+ const allows = (field) => !hidden.has(field) && (readableAll || readable.includes(field));
187
+ if (!allows("sys_id"))
188
+ return [];
189
+ const displayField = DRY_RUN_DISPLAY_FIELDS.find(allows);
190
+ const selection = (0, field_policy_js_1.readableSelectionForTable)(table, displayField === undefined ? ["sys_id"] : ["sys_id", displayField]);
191
+ let response;
122
192
  try {
123
- return await executeRestBatchMutation(client, table, action, records, fields);
193
+ // A short deadline: the count is already in hand, so a slow instance
194
+ // costs the preview, never the dry run.
195
+ const deadline = AbortSignal.timeout(DRY_RUN_SAMPLE_DEADLINE_MS);
196
+ response = await inOwnResponseBudget(signal === undefined ? deadline : AbortSignal.any([signal, deadline]), () => (0, metadata_cache_js_1.uncachedOperations)(client).get(`/api/now/table/${table}`, {
197
+ sysparm_fields: selection.join(","),
198
+ sysparm_limit: String(DRY_RUN_SAMPLE_SIZE),
199
+ sysparm_query: `sys_idIN${ids.join(",")}`,
200
+ }));
124
201
  }
125
- catch {
126
- return executeSerialMutation(client, table, action, records, fields);
202
+ catch (error) {
203
+ // A cancelled call stays cancelled; any other failure only drops the preview.
204
+ if (signal?.aborted)
205
+ throw error;
206
+ return [];
127
207
  }
208
+ const filtered = (0, field_policy_js_1.filterReadableRecord)(Array.isArray(response?.result) ? response.result : [], selection);
209
+ const rows = [];
210
+ // Only rows for the sys_ids asked for, each once: the sample must come from
211
+ // the matched set, whatever the instance answers.
212
+ const requested = new Set(ids);
213
+ const shown = new Set();
214
+ for (const record of Array.isArray(filtered) ? filtered : []) {
215
+ const item = plainRecord(record);
216
+ if (item === undefined)
217
+ continue;
218
+ let sysId;
219
+ try {
220
+ sysId = (0, servicenow_identifiers_js_1.serviceNowSysIdPathSegment)(item.sys_id);
221
+ }
222
+ catch {
223
+ continue;
224
+ }
225
+ if (!requested.has(sysId) || shown.has(sysId))
226
+ continue;
227
+ shown.add(sysId);
228
+ const display = displayField === undefined ? undefined : displayText(item[displayField]);
229
+ rows.push(display === undefined ? { sys_id: sysId } : { sys_id: sysId, display });
230
+ if (rows.length === DRY_RUN_SAMPLE_SIZE)
231
+ break;
232
+ }
233
+ return rows;
128
234
  }
129
- async function executeRestBatchMutation(client, table, action, records, fields) {
235
+ /** A display value is text; a reference object contributes its own display text. */
236
+ function displayText(candidate) {
237
+ const reference = plainRecord(candidate);
238
+ const value = typeof candidate === "string"
239
+ ? candidate
240
+ : typeof reference?.display_value === "string"
241
+ ? reference.display_value
242
+ : undefined;
243
+ if (value === undefined || value === "")
244
+ return undefined;
245
+ return value.length > DRY_RUN_DISPLAY_MAX_CHARS
246
+ ? `${value.slice(0, DRY_RUN_DISPLAY_MAX_CHARS)}…`
247
+ : value;
248
+ }
249
+ const REST_BATCH_CHUNK_SIZE = batch_limits_js_1.BATCH_LIMITS.restBatchChunkSize;
250
+ const REST_BATCH_PATH = "/api/now/v1/batch";
251
+ /**
252
+ * Target size of one batch request body. ServiceNow caps REST request
253
+ * payloads (about 10 MB by default), and an oversized batch that is refused
254
+ * has an unknown outcome, so a chunk holds fewer records when values are
255
+ * large. A request stays under this size unless one record's fields alone
256
+ * exceed about 3 MiB of JSON; such a record is sent one per request, because
257
+ * a chunk never holds fewer than one record.
258
+ */
259
+ const MAX_BATCH_REQUEST_BYTES = 4 * 1024 * 1024;
260
+ /**
261
+ * Upper bound on the JSON one `rest_requests` entry adds besides its body and
262
+ * table name: id, method, url, headers and exclude_response_headers.
263
+ */
264
+ const REST_BATCH_REQUEST_OVERHEAD_BYTES = 300;
265
+ /**
266
+ * A sub-request that returns a 5xx or 408 inside a readable batch response
267
+ * is unconfirmed and never retried, but the run continues: the instance is
268
+ * answering, and every other record is still sent at most once. Past this
269
+ * many unconfirmed records in one run, the run stops and reports the rest as
270
+ * not sent, because that many server errors suggest an unhealthy instance.
271
+ */
272
+ const MAX_UNCONFIRMED_SUB_REQUESTS = 10;
273
+ /**
274
+ * Failure categories that mean ServiceNow refused a batch request before
275
+ * running any request in it, and that serial calls can work around: the
276
+ * Batch API is missing or not permitted for this credential. Only these fall
277
+ * back to serial calls. Any other failure, and every 2xx response, can follow
278
+ * a batch ServiceNow already applied in whole or in part. Replaying it would
279
+ * apply a change twice, which for a journal field is a duplicate entry.
280
+ *
281
+ * A rate limit (429) also means nothing ran, but it is not in the set: serial
282
+ * calls would add one request per record to the limit the instance is
283
+ * enforcing. The run stops instead and reports the Retry-After hint.
284
+ */
285
+ const BATCH_REFUSED_BEFORE_PROCESSING = new Set(["authentication", "authorization", "not_found"]);
286
+ /** Per-request headers, as the documented Batch API takes them. */
287
+ const JSON_BODY_HEADERS = Object.freeze([
288
+ Object.freeze({ name: "Content-Type", value: "application/json" }),
289
+ Object.freeze({ name: "Accept", value: "application/json" }),
290
+ ]);
291
+ const JSON_ACCEPT_HEADERS = Object.freeze([
292
+ Object.freeze({ name: "Accept", value: "application/json" }),
293
+ ]);
294
+ /**
295
+ * Validate and de-duplicate the sys_ids the lookup returned. The lookup can
296
+ * name a record more than once; each record is changed at most once per run,
297
+ * so a journal entry is never appended twice to it.
298
+ */
299
+ function targetSysIds(records) {
300
+ const unique = new Set();
301
+ let invalid = 0;
302
+ for (const record of records) {
303
+ try {
304
+ unique.add((0, servicenow_identifiers_js_1.serviceNowSysIdPathSegment)(record.sys_id));
305
+ }
306
+ catch {
307
+ invalid += 1;
308
+ }
309
+ }
310
+ return { sysIds: [...unique], invalid };
311
+ }
312
+ /**
313
+ * Apply one update or delete to every matched record through the documented
314
+ * REST Batch API (`POST /api/now/v1/batch`), up to 50 requests per batch and
315
+ * at most MAX_BATCH_REQUEST_BYTES per request body.
316
+ *
317
+ * Request: `rest_requests[]` with `id`, `method`, `url`, `headers` as
318
+ * name/value pairs, and a base64-encoded `body`. Response:
319
+ * `serviced_requests[]` with `id` and `status_code`, plus
320
+ * `unserviced_requests[]` with the ids ServiceNow did not run.
321
+ *
322
+ * A batch request is never replayed. Serial Table API calls replace it only
323
+ * when ServiceNow refused the request before running any of it.
324
+ *
325
+ * The run stops, reporting the rest as not sent, when a batch request fails
326
+ * or its response cannot be read or attributed, when every serviced
327
+ * sub-request in a batch returns a server error, or when more than
328
+ * MAX_UNCONFIRMED_SUB_REQUESTS records are unconfirmed. An isolated
329
+ * sub-request server error is reported as unconfirmed and the run continues.
330
+ */
331
+ async function executeBatchMutation(client, table, action, targets, fields, signal) {
130
332
  let processed = 0;
131
- let failed = 0;
132
- for (let offset = 0; offset < records.length; offset += REST_BATCH_CHUNK_SIZE) {
133
- const chunk = records.slice(offset, offset + REST_BATCH_CHUNK_SIZE);
134
- const restRequests = chunk.map((record, index) => {
135
- const sysId = (0, servicenow_identifiers_js_1.serviceNowSysIdPathSegment)(record.sys_id);
136
- return {
137
- id: String(offset + index + 1),
138
- method: action === "update" ? "PATCH" : "DELETE",
139
- url: `/api/now/table/${table}/${sysId}`,
140
- ...(action === "update" ? { body: fields ?? {} } : {}),
141
- };
142
- });
143
- const response = await client.post("/api/now/v1/batch", {
144
- batch_request_id: `sn_batch_${Date.now()}_${offset}`,
145
- rest_requests: restRequests,
146
- });
147
- const statuses = extractBatchStatuses(response);
148
- if (statuses.length !== chunk.length) {
149
- throw new TypeError("REST Batch response did not include per-request statuses");
333
+ let failed = targets.invalid;
334
+ let unserviced = 0;
335
+ let unconfirmed = 0;
336
+ let serverErrors = 0;
337
+ const { sysIds } = targets;
338
+ const body = action === "update" ? encodeBatchBody(fields ?? {}) : undefined;
339
+ const chunkSize = batchChunkSize(table, body);
340
+ for (let offset = 0; offset < sysIds.length; offset += chunkSize) {
341
+ const chunk = sysIds.slice(offset, offset + chunkSize);
342
+ const requests = chunk.map((sysId, index) => restBatchRequest(table, action, sysId, String(offset + index + 1), body));
343
+ let response;
344
+ try {
345
+ response = await inOwnResponseBudget(signal, () => client.post(REST_BATCH_PATH, {
346
+ batch_request_id: `sn_batch_${Date.now()}_${offset}`,
347
+ rest_requests: requests,
348
+ }));
349
+ }
350
+ catch (error) {
351
+ const descriptor = (0, tool_error_js_1.trustedToolErrorDescriptor)(error);
352
+ if (descriptor !== undefined &&
353
+ BATCH_REFUSED_BEFORE_PROCESSING.has(descriptor.category)) {
354
+ // Nothing in this batch ran. The records from here on go through the
355
+ // Table API one at a time; earlier batches are confirmed and are not
356
+ // sent again.
357
+ const serial = await executeSerialMutation(client, table, action, sysIds.slice(offset), fields, signal);
358
+ return batchResult({
359
+ ...serial,
360
+ processed: processed + serial.processed,
361
+ failed: failed + serial.failed,
362
+ unserviced,
363
+ unconfirmed: unconfirmed + serial.unconfirmed,
364
+ serverErrors,
365
+ });
366
+ }
367
+ if (descriptor?.category === "rate_limit") {
368
+ // Nothing in this batch ran, and the client already retried it.
369
+ return batchResult({
370
+ processed,
371
+ failed,
372
+ unserviced,
373
+ unconfirmed,
374
+ serverErrors,
375
+ notSent: sysIds.length - offset,
376
+ rateLimited: { retryAfterSeconds: descriptor.retryAfterSeconds },
377
+ });
378
+ }
379
+ // The request may have reached ServiceNow and been applied.
380
+ return batchResult({
381
+ processed,
382
+ failed,
383
+ unserviced,
384
+ unconfirmed: unconfirmed + chunk.length,
385
+ serverErrors,
386
+ notSent: sysIds.length - offset - chunk.length,
387
+ });
388
+ }
389
+ const outcome = chunkOutcome(response, requests.map(({ id }) => id));
390
+ processed += outcome.processed;
391
+ failed += outcome.failed;
392
+ unserviced += outcome.unserviced;
393
+ unconfirmed += outcome.serverErrors + outcome.unattributed;
394
+ serverErrors += outcome.serverErrors;
395
+ const serviced = outcome.processed + outcome.failed - outcome.unserviced + outcome.serverErrors;
396
+ const stoppedOn = outcome.unattributed > 0
397
+ ? "unreadable_response"
398
+ : outcome.serverErrors > 0 && outcome.serverErrors === serviced
399
+ ? "server_errors"
400
+ : unconfirmed > MAX_UNCONFIRMED_SUB_REQUESTS
401
+ ? "unconfirmed_limit"
402
+ : undefined;
403
+ if (stoppedOn !== undefined) {
404
+ return batchResult({
405
+ processed,
406
+ failed,
407
+ unserviced,
408
+ unconfirmed,
409
+ serverErrors,
410
+ notSent: sysIds.length - offset - chunk.length,
411
+ stoppedOn,
412
+ });
150
413
  }
151
- for (const status of statuses) {
152
- if (status >= 200 && status < 300)
414
+ }
415
+ return batchResult({
416
+ processed,
417
+ failed,
418
+ unserviced,
419
+ unconfirmed,
420
+ serverErrors,
421
+ notSent: 0,
422
+ });
423
+ }
424
+ /**
425
+ * Run one upstream request with its own response-byte budget, bound to the
426
+ * tool call's cancellation signal.
427
+ *
428
+ * A single per-call budget would cut a large run short: the sys_id lookup and
429
+ * every batch response draw on it, so a 10,000-record update would stop after
430
+ * about 3,400 records. Each response is still capped by the client, and is
431
+ * parsed and dropped before the next request, so memory stays bounded by one
432
+ * chunk. Without a signal (a direct handler call) the request runs in the
433
+ * caller's scope.
434
+ */
435
+ function inOwnResponseBudget(signal, operation) {
436
+ return signal instanceof AbortSignal
437
+ ? (0, client_js_1.runWithServiceNowRequestSignal)(signal, operation)
438
+ : operation();
439
+ }
440
+ /** Up to 50 records, fewer when the encoded body is large. */
441
+ function batchChunkSize(table, body) {
442
+ const perRequestBytes = (body?.length ?? 0) + table.length + REST_BATCH_REQUEST_OVERHEAD_BYTES;
443
+ return Math.max(1, Math.min(REST_BATCH_CHUNK_SIZE, Math.floor(MAX_BATCH_REQUEST_BYTES / perRequestBytes)));
444
+ }
445
+ function restBatchRequest(table, action, sysId, id, body) {
446
+ if (action === "update") {
447
+ return {
448
+ id,
449
+ method: "PATCH",
450
+ // Only sys_id comes back per record, which keeps each batch response
451
+ // small and its parse cheap.
452
+ url: `/api/now/table/${table}/${sysId}?sysparm_fields=sys_id`,
453
+ headers: JSON_BODY_HEADERS,
454
+ exclude_response_headers: true,
455
+ body,
456
+ };
457
+ }
458
+ return {
459
+ id,
460
+ method: "DELETE",
461
+ url: `/api/now/table/${table}/${sysId}`,
462
+ headers: JSON_ACCEPT_HEADERS,
463
+ exclude_response_headers: true,
464
+ };
465
+ }
466
+ /** Base64 text is ASCII, so its length is its byte count. */
467
+ function encodeBatchBody(fields) {
468
+ return node_buffer_1.Buffer.from(JSON.stringify(fields), "utf8").toString("base64");
469
+ }
470
+ /**
471
+ * Count one batch response against the ids that were sent. An id ServiceNow
472
+ * neither serviced nor listed as unserviced is unattributed, and so is an id
473
+ * reported more than once, because its result cannot be attributed.
474
+ *
475
+ * A sub-request answered with a 5xx or a 408 is a server error. It is
476
+ * reported as unconfirmed, matching the serial path: a server error can
477
+ * follow a change that was partly applied (ServiceNow does not roll back a
478
+ * journal insert when a later business rule fails), so it must not read as
479
+ * "failed, safe to re-run".
480
+ */
481
+ function chunkOutcome(response, ids) {
482
+ const requested = new Set(ids);
483
+ const statuses = new Map();
484
+ const notServiced = new Set();
485
+ const root = plainRecord(response);
486
+ const serviced = root?.serviced_requests;
487
+ if (Array.isArray(serviced)) {
488
+ for (const entry of serviced) {
489
+ const item = plainRecord(entry);
490
+ if (item === undefined)
491
+ continue;
492
+ const id = batchRequestId(item.id);
493
+ if (id === undefined || !requested.has(id))
494
+ continue;
495
+ statuses.set(id, statuses.has(id) ? undefined : statusCode(item.status_code));
496
+ }
497
+ }
498
+ const unservicedEntries = root?.unserviced_requests;
499
+ if (Array.isArray(unservicedEntries)) {
500
+ for (const entry of unservicedEntries) {
501
+ const id = batchRequestId(entry) ?? batchRequestId(plainRecord(entry)?.id);
502
+ if (id !== undefined && requested.has(id) && !statuses.has(id)) {
503
+ notServiced.add(id);
504
+ }
505
+ }
506
+ }
507
+ let processed = 0;
508
+ let failed = 0;
509
+ let serverErrors = 0;
510
+ let unattributed = 0;
511
+ for (const id of ids) {
512
+ const status = statuses.get(id);
513
+ if (status !== undefined) {
514
+ if (status >= 200 && status < 300) {
153
515
  processed += 1;
154
- else
516
+ }
517
+ else if (status >= 500 || status === 408) {
518
+ serverErrors += 1;
519
+ }
520
+ else {
155
521
  failed += 1;
522
+ }
523
+ }
524
+ else if (notServiced.has(id)) {
525
+ failed += 1;
526
+ }
527
+ else {
528
+ unattributed += 1;
156
529
  }
157
530
  }
158
- return { processed, failed };
531
+ return {
532
+ processed,
533
+ failed,
534
+ unserviced: notServiced.size,
535
+ serverErrors,
536
+ unattributed,
537
+ };
159
538
  }
160
- function extractBatchStatuses(response) {
161
- const root = unwrapBatchResponse(response);
162
- if (!Array.isArray(root))
163
- return [];
164
- return root
165
- .map((entry) => {
166
- if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
167
- return undefined;
168
- }
169
- const record = entry;
170
- const status = record.status_code ?? record.status ?? record.http_status;
171
- return typeof status === "number" && Number.isSafeInteger(status)
172
- ? status
173
- : typeof status === "string" && /^(?:0|[1-9]\d*)$/u.test(status)
174
- ? Number(status)
175
- : undefined;
176
- })
177
- .filter((status) => status !== undefined);
178
- }
179
- function unwrapBatchResponse(response) {
180
- if (typeof response !== "object" || response === null || Array.isArray(response)) {
181
- return response;
182
- }
183
- const record = response;
184
- const result = record.result;
185
- if (Array.isArray(record.rest_requests))
186
- return record.rest_requests;
187
- if (Array.isArray(record.responses))
188
- return record.responses;
189
- if (Array.isArray(result))
190
- return result;
191
- if (typeof result === "object" && result !== null && !Array.isArray(result)) {
192
- const nested = result;
193
- if (Array.isArray(nested.rest_requests))
194
- return nested.rest_requests;
195
- if (Array.isArray(nested.responses))
196
- return nested.responses;
539
+ function batchResult(tally) {
540
+ const notes = [];
541
+ if (tally.unconfirmed > 0) {
542
+ const serverErrors = tally.serverErrors ?? 0;
543
+ notes.push(`ServiceNow did not confirm the outcome for ${tally.unconfirmed} record(s)` +
544
+ (serverErrors === 0
545
+ ? ". "
546
+ : `; ${serverErrors} of them returned a server error (HTTP 5xx or ` +
547
+ "408), which can follow a partly applied change. ") +
548
+ "They may have been changed. The run has not retried them. A journal " +
549
+ "write (comments, work_notes) is never re-sent, but when records are " +
550
+ "sent one at a time, other fields may have been sent up to three " +
551
+ "times by the HTTP client's retry on a transient error. Check them " +
552
+ "before running the batch again.");
553
+ }
554
+ if (tally.stoppedOn === "server_errors") {
555
+ notes.push("Every serviced record in one batch returned a server error, so nothing " +
556
+ "more was sent.");
557
+ }
558
+ else if (tally.stoppedOn === "unconfirmed_limit") {
559
+ notes.push(`More than ${MAX_UNCONFIRMED_SUB_REQUESTS} records had an unconfirmed ` +
560
+ "outcome, so nothing more was sent.");
561
+ }
562
+ if (tally.authenticationFailed === true) {
563
+ notes.push("ServiceNow rejected the credentials (HTTP 401), so nothing more was sent.");
564
+ }
565
+ if (tally.rateLimited !== undefined) {
566
+ const retryAfter = tally.rateLimited.retryAfterSeconds;
567
+ notes.push("ServiceNow rate-limited the request (HTTP 429), so nothing more was sent." +
568
+ (retryAfter === undefined ? "" : ` Retry after ${retryAfter} seconds.`));
569
+ }
570
+ if (tally.notSent > 0) {
571
+ notes.push(`The remaining ${tally.notSent} record(s) were not sent and are counted as failed.`);
572
+ }
573
+ if (tally.unserviced > 0) {
574
+ notes.push(`ServiceNow did not process ${tally.unserviced} record(s) because a batch ` +
575
+ "reached a size or time limit. They are counted as failed.");
576
+ }
577
+ return {
578
+ processed: tally.processed,
579
+ failed: tally.failed + tally.notSent,
580
+ ...(notes.length === 0 ? {} : { message: notes.join(" ") }),
581
+ };
582
+ }
583
+ function plainRecord(candidate) {
584
+ return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate)
585
+ ? candidate
586
+ : undefined;
587
+ }
588
+ function batchRequestId(candidate) {
589
+ if (typeof candidate === "string" && candidate !== "")
590
+ return candidate;
591
+ if (typeof candidate === "number" && Number.isSafeInteger(candidate)) {
592
+ return String(candidate);
197
593
  }
198
594
  return undefined;
199
595
  }
200
- async function executeSerialMutation(client, table, action, records, fields) {
596
+ function statusCode(candidate) {
597
+ const status = typeof candidate === "number"
598
+ ? candidate
599
+ : typeof candidate === "string" && /^[1-5][0-9]{2}$/u.test(candidate)
600
+ ? Number(candidate)
601
+ : undefined;
602
+ return status !== undefined &&
603
+ Number.isSafeInteger(status) &&
604
+ status >= 100 &&
605
+ status <= 599
606
+ ? status
607
+ : undefined;
608
+ }
609
+ /**
610
+ * One Table API call per record, each with its own response budget. The run
611
+ * stops at the first failure whose outcome is unknown, at a rate limit, or at
612
+ * an authentication failure (a 401 the client could not refresh); the records
613
+ * after it are reported as not sent. Sending them would only repeat the same
614
+ * rejection, and repeated failed logins can trip an account lockout.
615
+ */
616
+ async function executeSerialMutation(client, table, action, sysIds, fields, signal) {
201
617
  let processed = 0;
202
618
  let failed = 0;
203
- for (const record of records) {
619
+ for (const [index, sysId] of sysIds.entries()) {
620
+ const path = `/api/now/table/${table}/${sysId}`;
204
621
  try {
205
- const sysId = (0, servicenow_identifiers_js_1.serviceNowSysIdPathSegment)(record.sys_id);
206
622
  if (action === "update") {
207
- await client.patch(`/api/now/table/${table}/${sysId}`, fields);
623
+ await inOwnResponseBudget(signal, () => client.patch(path, fields));
208
624
  processed += 1;
209
625
  }
210
626
  else {
211
- const delResp = await client.delete(`/api/now/table/${table}/${sysId}`);
627
+ const delResp = await inOwnResponseBudget(signal, () => client.delete(path));
212
628
  if (delResp.status === 204 || delResp.status === 200)
213
629
  processed += 1;
214
630
  else
215
631
  failed += 1;
216
632
  }
217
633
  }
218
- catch {
634
+ catch (error) {
635
+ const notSent = sysIds.length - index - 1;
636
+ const descriptor = (0, tool_error_js_1.trustedToolErrorDescriptor)(error);
637
+ if (descriptor?.category === "rate_limit") {
638
+ return {
639
+ processed,
640
+ failed: failed + 1,
641
+ unserviced: 0,
642
+ unconfirmed: 0,
643
+ notSent,
644
+ rateLimited: { retryAfterSeconds: descriptor.retryAfterSeconds },
645
+ };
646
+ }
647
+ if (descriptor?.category === "authentication") {
648
+ // Rejected before processing, so this record failed definitely.
649
+ return {
650
+ processed,
651
+ failed: failed + 1,
652
+ unserviced: 0,
653
+ unconfirmed: 0,
654
+ notSent,
655
+ authenticationFailed: true,
656
+ };
657
+ }
658
+ if (!serialFailureIsDefinite(descriptor)) {
659
+ return { processed, failed, unserviced: 0, unconfirmed: 1, notSent };
660
+ }
219
661
  failed += 1;
220
662
  }
221
663
  }
222
- return { processed, failed };
664
+ return { processed, failed, unserviced: 0, unconfirmed: 0, notSent: 0 };
665
+ }
666
+ /**
667
+ * True when a single-record PATCH or DELETE failed with a status that means
668
+ * ServiceNow did not apply it, and the run can continue with the next record.
669
+ * For these methods the client classifies a 4xx it has no category for as
670
+ * `upstream` with `do_not_retry`, and a 5xx or connection failure as
671
+ * `upstream` with `retry_if_safe_and_idempotent`. A 5xx, a timeout, a
672
+ * connection failure, or an unreadable or over-budget response may follow an
673
+ * applied write, so its outcome is unknown. Authentication and rate-limit
674
+ * failures stop the run before this is consulted.
675
+ */
676
+ function serialFailureIsDefinite(descriptor) {
677
+ if (descriptor === undefined)
678
+ return false;
679
+ switch (descriptor.category) {
680
+ case "authorization":
681
+ case "not_found":
682
+ case "conflict":
683
+ return true;
684
+ case "upstream":
685
+ return descriptor.retry === "do_not_retry";
686
+ default:
687
+ return false;
688
+ }
223
689
  }
224
690
  //# sourceMappingURL=batch.js.map