@onlyflows/servicenow-mcp 2.2.0-dev.6 → 2.2.0

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 (244) hide show
  1. package/.env.example +6 -3
  2. package/CHANGELOG.md +286 -0
  3. package/README.md +504 -101
  4. package/dist/atf-form.d.ts +3 -15
  5. package/dist/atf-form.d.ts.map +1 -1
  6. package/dist/atf-result-cache.d.ts +23 -59
  7. package/dist/atf-result-cache.d.ts.map +1 -1
  8. package/dist/auth.d.ts +1 -0
  9. package/dist/auth.d.ts.map +1 -1
  10. package/dist/auth.js +17 -0
  11. package/dist/auth.js.map +1 -1
  12. package/dist/batch-limits.d.ts +18 -0
  13. package/dist/batch-limits.d.ts.map +1 -0
  14. package/dist/batch-limits.js +21 -0
  15. package/dist/batch-limits.js.map +1 -0
  16. package/dist/bounded-input.d.ts +49 -0
  17. package/dist/bounded-input.d.ts.map +1 -0
  18. package/dist/bounded-input.js +81 -0
  19. package/dist/bounded-input.js.map +1 -0
  20. package/dist/client.d.ts +25 -0
  21. package/dist/client.d.ts.map +1 -1
  22. package/dist/client.js +92 -18
  23. package/dist/client.js.map +1 -1
  24. package/dist/encoded-query-policy.d.ts +11 -0
  25. package/dist/encoded-query-policy.d.ts.map +1 -1
  26. package/dist/encoded-query-policy.js +10 -1
  27. package/dist/encoded-query-policy.js.map +1 -1
  28. package/dist/field-policy.d.ts +82 -3
  29. package/dist/field-policy.d.ts.map +1 -1
  30. package/dist/field-policy.js +609 -80
  31. package/dist/field-policy.js.map +1 -1
  32. package/dist/html-response.d.ts +34 -0
  33. package/dist/html-response.d.ts.map +1 -0
  34. package/dist/html-response.js +72 -0
  35. package/dist/html-response.js.map +1 -0
  36. package/dist/http-runtime.d.ts.map +1 -1
  37. package/dist/http-runtime.js +8 -0
  38. package/dist/http-runtime.js.map +1 -1
  39. package/dist/incident-journal-policy.d.ts +27 -5
  40. package/dist/incident-journal-policy.d.ts.map +1 -1
  41. package/dist/incident-journal-policy.js +34 -21
  42. package/dist/incident-journal-policy.js.map +1 -1
  43. package/dist/json-shape-limits.d.ts +71 -0
  44. package/dist/json-shape-limits.d.ts.map +1 -0
  45. package/dist/json-shape-limits.js +131 -0
  46. package/dist/json-shape-limits.js.map +1 -0
  47. package/dist/metadata-cache.d.ts +46 -21
  48. package/dist/metadata-cache.d.ts.map +1 -1
  49. package/dist/metadata-cache.js +228 -195
  50. package/dist/metadata-cache.js.map +1 -1
  51. package/dist/policy-card.d.ts +131 -0
  52. package/dist/policy-card.d.ts.map +1 -0
  53. package/dist/policy-card.js +409 -0
  54. package/dist/policy-card.js.map +1 -0
  55. package/dist/profile-manager.d.ts +7 -3
  56. package/dist/profile-manager.d.ts.map +1 -1
  57. package/dist/profile-manager.js +66 -3
  58. package/dist/profile-manager.js.map +1 -1
  59. package/dist/record-identifier-policy.d.ts +2 -8
  60. package/dist/record-identifier-policy.d.ts.map +1 -1
  61. package/dist/risky-grants.d.ts +25 -0
  62. package/dist/risky-grants.d.ts.map +1 -0
  63. package/dist/risky-grants.js +77 -0
  64. package/dist/risky-grants.js.map +1 -0
  65. package/dist/server.d.ts.map +1 -1
  66. package/dist/server.js +26 -5
  67. package/dist/server.js.map +1 -1
  68. package/dist/setup-prompts.js +1 -0
  69. package/dist/setup-prompts.js.map +1 -1
  70. package/dist/setup.d.ts +1 -1
  71. package/dist/setup.d.ts.map +1 -1
  72. package/dist/setup.js +300 -58
  73. package/dist/setup.js.map +1 -1
  74. package/dist/stdio-runtime.d.ts +15 -0
  75. package/dist/stdio-runtime.d.ts.map +1 -1
  76. package/dist/stdio-runtime.js +60 -0
  77. package/dist/stdio-runtime.js.map +1 -1
  78. package/dist/structured-query.d.ts +100 -115
  79. package/dist/structured-query.d.ts.map +1 -1
  80. package/dist/structured-query.js +132 -16
  81. package/dist/structured-query.js.map +1 -1
  82. package/dist/table-policy.d.ts +10 -4
  83. package/dist/table-policy.d.ts.map +1 -1
  84. package/dist/table-policy.js +1 -1
  85. package/dist/table-policy.js.map +1 -1
  86. package/dist/tool-error.d.ts +18 -0
  87. package/dist/tool-error.d.ts.map +1 -1
  88. package/dist/tool-error.js +69 -0
  89. package/dist/tool-error.js.map +1 -1
  90. package/dist/tool-table-access.d.ts.map +1 -1
  91. package/dist/tool-table-access.js +32 -2
  92. package/dist/tool-table-access.js.map +1 -1
  93. package/dist/tools/aggregate.d.ts +13 -19
  94. package/dist/tools/aggregate.d.ts.map +1 -1
  95. package/dist/tools/aggregate.js +2 -3
  96. package/dist/tools/aggregate.js.map +1 -1
  97. package/dist/tools/all-fields-cap.d.ts.map +1 -1
  98. package/dist/tools/all-fields-cap.js +3 -38
  99. package/dist/tools/all-fields-cap.js.map +1 -1
  100. package/dist/tools/atf-author-module.d.ts +28 -7
  101. package/dist/tools/atf-author-module.d.ts.map +1 -1
  102. package/dist/tools/atf-author-module.js +4 -2
  103. package/dist/tools/atf-author-module.js.map +1 -1
  104. package/dist/tools/atf-contracts.d.ts +135 -829
  105. package/dist/tools/atf-contracts.d.ts.map +1 -1
  106. package/dist/tools/atf-shared.js +2 -2
  107. package/dist/tools/atf-shared.js.map +1 -1
  108. package/dist/tools/atf-step-catalog.d.ts +3 -7
  109. package/dist/tools/atf-step-catalog.d.ts.map +1 -1
  110. package/dist/tools/atf-step-catalog.js +12 -5
  111. package/dist/tools/atf-step-catalog.js.map +1 -1
  112. package/dist/tools/atf.d.ts +8 -24
  113. package/dist/tools/atf.d.ts.map +1 -1
  114. package/dist/tools/atf.js +2 -2
  115. package/dist/tools/atf.js.map +1 -1
  116. package/dist/tools/attach.d.ts +6 -22
  117. package/dist/tools/attach.d.ts.map +1 -1
  118. package/dist/tools/batch.d.ts +18 -71
  119. package/dist/tools/batch.d.ts.map +1 -1
  120. package/dist/tools/batch.js +544 -96
  121. package/dist/tools/batch.js.map +1 -1
  122. package/dist/tools/catalog.d.ts +2 -2
  123. package/dist/tools/catalog.d.ts.map +1 -1
  124. package/dist/tools/catalog.js +7 -1
  125. package/dist/tools/catalog.js.map +1 -1
  126. package/dist/tools/codesearch.d.ts +1 -13
  127. package/dist/tools/codesearch.d.ts.map +1 -1
  128. package/dist/tools/create-module.d.ts +9 -14
  129. package/dist/tools/create-module.d.ts.map +1 -1
  130. package/dist/tools/create-module.js +4 -8
  131. package/dist/tools/create-module.js.map +1 -1
  132. package/dist/tools/delete.d.ts +1 -9
  133. package/dist/tools/delete.d.ts.map +1 -1
  134. package/dist/tools/delete.js +2 -3
  135. package/dist/tools/delete.js.map +1 -1
  136. package/dist/tools/discover.d.ts +6 -14
  137. package/dist/tools/discover.d.ts.map +1 -1
  138. package/dist/tools/flow-view-contracts.d.ts +1023 -0
  139. package/dist/tools/flow-view-contracts.d.ts.map +1 -0
  140. package/dist/tools/flow-view-contracts.js +570 -0
  141. package/dist/tools/flow-view-contracts.js.map +1 -0
  142. package/dist/tools/flow-view-graph.d.ts +86 -0
  143. package/dist/tools/flow-view-graph.d.ts.map +1 -0
  144. package/dist/tools/flow-view-graph.js +993 -0
  145. package/dist/tools/flow-view-graph.js.map +1 -0
  146. package/dist/tools/flow-view-gzip.d.ts +52 -0
  147. package/dist/tools/flow-view-gzip.d.ts.map +1 -0
  148. package/dist/tools/flow-view-gzip.js +179 -0
  149. package/dist/tools/flow-view-gzip.js.map +1 -0
  150. package/dist/tools/flow-view-mermaid.d.ts +37 -0
  151. package/dist/tools/flow-view-mermaid.d.ts.map +1 -0
  152. package/dist/tools/flow-view-mermaid.js +337 -0
  153. package/dist/tools/flow-view-mermaid.js.map +1 -0
  154. package/dist/tools/flow-view-module.d.ts +61 -0
  155. package/dist/tools/flow-view-module.d.ts.map +1 -0
  156. package/dist/tools/flow-view-module.js +378 -0
  157. package/dist/tools/flow-view-module.js.map +1 -0
  158. package/dist/tools/flow-view-policy.d.ts +106 -0
  159. package/dist/tools/flow-view-policy.d.ts.map +1 -0
  160. package/dist/tools/flow-view-policy.js +461 -0
  161. package/dist/tools/flow-view-policy.js.map +1 -0
  162. package/dist/tools/flow-view-renderers.d.ts +68 -0
  163. package/dist/tools/flow-view-renderers.d.ts.map +1 -0
  164. package/dist/tools/flow-view-renderers.js +513 -0
  165. package/dist/tools/flow-view-renderers.js.map +1 -0
  166. package/dist/tools/flow-view-table.d.ts +115 -0
  167. package/dist/tools/flow-view-table.d.ts.map +1 -0
  168. package/dist/tools/flow-view-table.js +1002 -0
  169. package/dist/tools/flow-view-table.js.map +1 -0
  170. package/dist/tools/get-module.d.ts +36 -42
  171. package/dist/tools/get-module.d.ts.map +1 -1
  172. package/dist/tools/health.d.ts +9 -6
  173. package/dist/tools/health.d.ts.map +1 -1
  174. package/dist/tools/incident-journal-module.d.ts +8 -7
  175. package/dist/tools/incident-journal-module.d.ts.map +1 -1
  176. package/dist/tools/index.d.ts +4 -4
  177. package/dist/tools/index.d.ts.map +1 -1
  178. package/dist/tools/index.js +43 -6
  179. package/dist/tools/index.js.map +1 -1
  180. package/dist/tools/markdown.d.ts +27 -0
  181. package/dist/tools/markdown.d.ts.map +1 -1
  182. package/dist/tools/markdown.js +104 -1
  183. package/dist/tools/markdown.js.map +1 -1
  184. package/dist/tools/nl.d.ts +1 -11
  185. package/dist/tools/nl.d.ts.map +1 -1
  186. package/dist/tools/profile.d.ts +1 -1
  187. package/dist/tools/profile.d.ts.map +1 -1
  188. package/dist/tools/profile.js +19 -1
  189. package/dist/tools/profile.js.map +1 -1
  190. package/dist/tools/query-module.d.ts +59 -71
  191. package/dist/tools/query-module.d.ts.map +1 -1
  192. package/dist/tools/query-module.js +2 -2
  193. package/dist/tools/query-module.js.map +1 -1
  194. package/dist/tools/record-write-shared.d.ts.map +1 -1
  195. package/dist/tools/record-write-shared.js +19 -2
  196. package/dist/tools/record-write-shared.js.map +1 -1
  197. package/dist/tools/relationships.d.ts +6 -22
  198. package/dist/tools/relationships.d.ts.map +1 -1
  199. package/dist/tools/result-envelope.d.ts +2255 -1357
  200. package/dist/tools/result-envelope.d.ts.map +1 -1
  201. package/dist/tools/result-envelope.js +24 -2
  202. package/dist/tools/result-envelope.js.map +1 -1
  203. package/dist/tools/schema-module.d.ts +36 -21
  204. package/dist/tools/schema-module.d.ts.map +1 -1
  205. package/dist/tools/schema-module.js +106 -65
  206. package/dist/tools/schema-module.js.map +1 -1
  207. package/dist/tools/script.d.ts +1 -11
  208. package/dist/tools/script.d.ts.map +1 -1
  209. package/dist/tools/syslog.d.ts +11 -18
  210. package/dist/tools/syslog.d.ts.map +1 -1
  211. package/dist/tools/syslog.js +2 -3
  212. package/dist/tools/syslog.js.map +1 -1
  213. package/dist/tools/table-hierarchy.d.ts +35 -0
  214. package/dist/tools/table-hierarchy.d.ts.map +1 -0
  215. package/dist/tools/table-hierarchy.js +74 -0
  216. package/dist/tools/table-hierarchy.js.map +1 -0
  217. package/dist/tools/tool-module.d.ts +40 -15
  218. package/dist/tools/tool-module.d.ts.map +1 -1
  219. package/dist/tools/tool-module.js +755 -205
  220. package/dist/tools/tool-module.js.map +1 -1
  221. package/dist/tools/update-module.d.ts +11 -17
  222. package/dist/tools/update-module.d.ts.map +1 -1
  223. package/dist/tools/update-module.js +10 -12
  224. package/dist/tools/update-module.js.map +1 -1
  225. package/dist/version.d.ts +1 -1
  226. package/dist/version.d.ts.map +1 -1
  227. package/dist/version.js +1 -1
  228. package/dist/version.js.map +1 -1
  229. package/dist/write-value-policy.d.ts +20 -12
  230. package/dist/write-value-policy.d.ts.map +1 -1
  231. package/dist/write-value-policy.js +179 -67
  232. package/dist/write-value-policy.js.map +1 -1
  233. package/docs/ADDING-TOOLS.md +22 -13
  234. package/docs/CLIENT-SETUP.md +110 -52
  235. package/docs/CROSS-CLIENT-RELEASE-MATRIX.md +2 -2
  236. package/docs/FLOW-VIEW.md +214 -0
  237. package/docs/PRODUCTION-SECURITY.md +154 -25
  238. package/docs/RELEASE-VALIDATION.md +2 -2
  239. package/docs/TESTING-OAUTH.md +1 -1
  240. package/docs/V2-MIGRATION.md +404 -30
  241. package/package.json +20 -6
  242. package/scripts/release-validate.mjs +56 -0
  243. package/server.json +22 -0
  244. package/tools/inspector/package-lock.json +163 -201
@@ -21,20 +21,32 @@ exports.snapshotToolModuleCatalog = snapshotToolModuleCatalog;
21
21
  const node_util_1 = require("node:util");
22
22
  const zod_1 = require("zod");
23
23
  const encoded_query_policy_js_1 = require("../encoded-query-policy.js");
24
- /**
25
- * Required on every published tool. Trimming makes whitespace-only selectors
26
- * invalid and ensures profile lookup uses the exact value clients discover.
27
- */
28
- exports.profileNameSchema = zod_1.z
29
- .string()
30
- .trim()
31
- .min(1, "profile must not be empty")
32
- .max(128, "profile must not exceed 128 characters")
33
- .describe("Configured ServiceNow profile name (required; no default fallback).");
34
24
  const ISSUED_INPUT_SCHEMAS = new WeakSet();
35
25
  const ISSUED_OUTPUT_SCHEMAS = new WeakSet();
36
26
  const ISSUED_SCHEMA_SNAPSHOTS = new WeakMap();
37
27
  const HARDENED_SCHEMA_NODES = new WeakSet();
28
+ /**
29
+ * Process-wide: each source zod node maps to the one hardened rebuild made
30
+ * from it. Tools share source schemas (every output envelope embeds the same
31
+ * result metadata), and without this every tool rebuilt and froze its own
32
+ * copy. Two consequences, both intended:
33
+ *
34
+ * - The first issuance wins. A source schema changed after it was first
35
+ * hardened is not read again, so no issued schema, earlier or later, sees
36
+ * the change; issued graphs stay inert to their sources.
37
+ * - Reuse skips the rebuild but not the budgets. A graph that reuses a
38
+ * hardened subgraph is charged for every value in it that the graph has not
39
+ * already counted, exactly as a fresh traversal would have counted it, and
40
+ * the subgraph's height is checked at the depth it is reached (see
41
+ * {@link HARDENED_SUBGRAPHS} and `chargeReusedSubgraph`).
42
+ */
43
+ const HARDENED_FROM_SOURCE = new WeakMap();
44
+ /**
45
+ * Budget records for every hardened zod node, so the nodes reachable from a
46
+ * reused subgraph, and what a fresh traversal would have charged for each,
47
+ * can be recovered without traversing it again.
48
+ */
49
+ const HARDENED_SUBGRAPHS = new WeakMap();
38
50
  const MAX_TOOL_SCHEMA_FIELDS = 128;
39
51
  const MAX_SCHEMA_GRAPH_DEPTH = 128;
40
52
  const MAX_SCHEMA_GRAPH_NODES = 10_000;
@@ -46,29 +58,86 @@ const INTRINSIC_MAP_ITERATOR_NEXT = Object.getPrototypeOf(new Map().entries()).n
46
58
  const INTRINSIC_SET_SIZE = Object.getOwnPropertyDescriptor(Set.prototype, "size")?.get;
47
59
  const INTRINSIC_SET_VALUES = Set.prototype.values;
48
60
  const INTRINSIC_SET_ITERATOR_NEXT = Object.getPrototypeOf(new Set().values()).next;
61
+ /**
62
+ * The zod constructors a schema graph may be rebuilt with: every classic
63
+ * schema class and every core check class. A node whose internals name any
64
+ * other constructor is refused, so hardening never runs a constructor that a
65
+ * caller supplied.
66
+ */
67
+ const ZOD_NODE_CONSTRUCTORS = new Set([...Object.values(zod_1.z), ...Object.values(zod_1.z.core)].filter((candidate) => typeof candidate === "function" &&
68
+ Object.hasOwn(candidate, "init") &&
69
+ typeof candidate.name === "string"));
70
+ /**
71
+ * The definition keys zod itself installs as getters: an object's `shape`
72
+ * (built on first read) and a default's `defaultValue` (a fresh copy per
73
+ * parse). Any other accessor in a definition is refused.
74
+ */
75
+ const ZOD_DEFINITION_ACCESSOR_KEYS = new Set([
76
+ "shape",
77
+ "defaultValue",
78
+ ]);
79
+ const NO_ACCESSORS = new Set();
80
+ /**
81
+ * Container types whose parse zod's memoizer wraps at construction. On its
82
+ * first call the wrapper checks whether the schema can recurse and, when it
83
+ * cannot, writes the unwrapped parse back onto the node's internals. That
84
+ * write is made before freezing (see `settleMemoizedParse`).
85
+ */
86
+ const MEMOIZED_CONTAINER_TYPES = new Set([
87
+ "array",
88
+ "object",
89
+ "tuple",
90
+ "record",
91
+ "map",
92
+ "set",
93
+ ]);
94
+ /**
95
+ * Required on every published tool. Trimming makes whitespace-only selectors
96
+ * invalid and ensures profile lookup uses the exact value clients discover.
97
+ * Hardened once here, so every issued schema shares this exact node.
98
+ */
99
+ exports.profileNameSchema = hardenSchemaGraph(zod_1.z
100
+ .string()
101
+ .trim()
102
+ .min(1, "profile must not be empty")
103
+ .max(128, "profile must not exceed 128 characters")
104
+ .describe("Configured ServiceNow profile name (required; no default fallback)."));
49
105
  /** Compose tool-local fields with the exact shared profile selector. */
50
106
  function withRequiredProfile(toolSchema) {
51
107
  const source = snapshotUntrustedObjectSchema(toolSchema, "tool-local input schema");
52
- const normalized = zod_1.z.object({
53
- ...source.shape,
54
- profile: exports.profileNameSchema,
55
- });
108
+ const shape = { ...source.shape, profile: exports.profileNameSchema };
56
109
  const composed = source.unknownKeys === "strict"
57
- ? normalized.strict(encoded_query_policy_js_1.ENCODED_QUERY_MIGRATION_MESSAGE)
58
- : normalized.strip();
110
+ ? strictInputObject(shape)
111
+ : stripInputObject(shape);
59
112
  return issueSchema(composed, "input");
60
113
  }
61
114
  /** Compose module output fields with the coordinator-owned profile envelope. */
62
115
  function withResolvedProfileOutput(outputSchema) {
63
116
  const source = snapshotUntrustedObjectSchema(outputSchema, "tool-local output schema");
64
- const normalized = zod_1.z
65
- .object({
66
- ...source.shape,
67
- profile: exports.profileNameSchema,
68
- })
69
- .strict();
117
+ const normalized = zod_1.z.strictObject({ ...source.shape, profile: exports.profileNameSchema });
70
118
  return issueSchema(normalized, "output");
71
119
  }
120
+ /**
121
+ * A strict input object whose unknown-key issue carries the encoded-query
122
+ * migration hint, as zod 3's `.strict(message)` did. Every other issue keeps
123
+ * zod's own message: the map answers only `unrecognized_keys`.
124
+ */
125
+ function strictInputObject(shape) {
126
+ return zod_1.z.strictObject(shape, encoded_query_policy_js_1.ENCODED_QUERY_STRICT_OBJECT_PARAMS);
127
+ }
128
+ /**
129
+ * A stripping input object that still tells clients it takes no other keys.
130
+ *
131
+ * Unknown keys are dropped, not rejected, at parse; clients have always been
132
+ * told `additionalProperties: false` for these tools, which the registration
133
+ * preflight requires. zod 3's converter emitted that for a stripping object;
134
+ * zod 4's emits it only for a strict one, and copies a node's metadata into
135
+ * its JSON Schema, so the keyword is carried as metadata. Parsing is
136
+ * unaffected.
137
+ */
138
+ function stripInputObject(shape) {
139
+ return zod_1.z.object(shape).meta({ additionalProperties: false });
140
+ }
72
141
  /** Base output envelope used until a module declares additional structured data. */
73
142
  exports.profileOutputSchema = withResolvedProfileOutput(zod_1.z.object({}));
74
143
  exports.SILENT_TOOL_MODULE_LOGGER = Object.freeze({
@@ -87,40 +156,36 @@ function snapshotUntrustedObjectSchema(candidate, label) {
87
156
  node_util_1.types.isProxy(candidate)) {
88
157
  throw new TypeError(`${label} must provide a non-proxy object shape`);
89
158
  }
90
- const definitionDescriptor = Object.getOwnPropertyDescriptor(candidate, "_def");
91
- if (!definitionDescriptor || !("value" in definitionDescriptor)) {
159
+ const internals = ownDataValue(candidate, "_zod");
160
+ if (typeof internals !== "object" ||
161
+ internals === null ||
162
+ node_util_1.types.isProxy(internals)) {
92
163
  throw new TypeError(`${label} definition must be a data property`);
93
164
  }
94
- const definition = definitionDescriptor.value;
165
+ const definition = ownDataValue(internals, "def");
95
166
  if (typeof definition !== "object" ||
96
167
  definition === null ||
97
168
  node_util_1.types.isProxy(definition) ||
98
169
  Object.getPrototypeOf(definition) !== Object.prototype) {
99
170
  throw new TypeError(`${label} definition must be a plain data object`);
100
171
  }
101
- const typeDescriptor = Object.getOwnPropertyDescriptor(definition, "typeName");
102
- const shapeDescriptor = Object.getOwnPropertyDescriptor(definition, "shape");
103
- const unknownKeysDescriptor = Object.getOwnPropertyDescriptor(definition, "unknownKeys");
172
+ const typeDescriptor = Object.getOwnPropertyDescriptor(definition, "type");
104
173
  const catchallDescriptor = Object.getOwnPropertyDescriptor(definition, "catchall");
105
- if (!typeDescriptor ||
174
+ const catchall = catchallDescriptor && "value" in catchallDescriptor
175
+ ? catchallDescriptor.value
176
+ : undefined;
177
+ if (ownDataValue(internals, "constr") !== zod_1.z.ZodObject ||
178
+ !typeDescriptor ||
106
179
  !("value" in typeDescriptor) ||
107
- typeDescriptor.value !== zod_1.z.ZodFirstPartyTypeKind.ZodObject ||
108
- !shapeDescriptor ||
109
- !("value" in shapeDescriptor) ||
110
- typeof shapeDescriptor.value !== "function" ||
111
- !unknownKeysDescriptor ||
112
- !("value" in unknownKeysDescriptor) ||
113
- (unknownKeysDescriptor.value !== "strip" &&
114
- unknownKeysDescriptor.value !== "strict") ||
115
- !catchallDescriptor ||
116
- !("value" in catchallDescriptor) ||
117
- !(catchallDescriptor.value instanceof zod_1.z.ZodNever) ||
118
- node_util_1.types.isProxy(catchallDescriptor.value)) {
180
+ typeDescriptor.value !== "object" ||
181
+ (catchallDescriptor !== undefined && !("value" in catchallDescriptor)) ||
182
+ (catchall !== undefined && !isZodNeverNode(catchall))) {
119
183
  throw new TypeError(`${label} definition is unsupported`);
120
184
  }
185
+ const unknownKeys = catchall === undefined ? "strip" : "strict";
121
186
  let shapeCandidate;
122
187
  try {
123
- shapeCandidate = Reflect.apply(shapeDescriptor.value, undefined, []);
188
+ shapeCandidate = readDefinitionShape(definition);
124
189
  }
125
190
  catch {
126
191
  throw new TypeError(`${label} shape could not be materialized`);
@@ -151,9 +216,7 @@ function snapshotUntrustedObjectSchema(candidate, label) {
151
216
  throw new TypeError(`${label} shape must contain only data fields`);
152
217
  }
153
218
  const field = descriptor.value;
154
- if (typeof field !== "object" ||
155
- field === null ||
156
- node_util_1.types.isProxy(field)) {
219
+ if (!isZodSchemaNode(field)) {
157
220
  throw new TypeError(`${label} contains an invalid field schema`);
158
221
  }
159
222
  shape[key] = field;
@@ -168,20 +231,49 @@ function snapshotUntrustedObjectSchema(candidate, label) {
168
231
  catch {
169
232
  throw new TypeError(`${label} fields could not be safely validated`);
170
233
  }
171
- return Object.freeze({
172
- shape: shapeSnapshot,
173
- unknownKeys: unknownKeysDescriptor.value,
174
- });
234
+ return Object.freeze({ shape: shapeSnapshot, unknownKeys });
235
+ }
236
+ /** The value of an own data property, or undefined for an accessor or absence. */
237
+ function ownDataValue(target, key) {
238
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
239
+ return descriptor && "value" in descriptor ? descriptor.value : undefined;
240
+ }
241
+ /**
242
+ * Read an object definition's shape. zod 4 installs `shape` as a getter that
243
+ * builds the shape on first read, so that getter (and only that key's getter)
244
+ * is run once here; a data property is read directly.
245
+ */
246
+ function readDefinitionShape(definition) {
247
+ const descriptor = Object.getOwnPropertyDescriptor(definition, "shape");
248
+ if (!descriptor)
249
+ throw new TypeError("object definition has no shape");
250
+ if ("value" in descriptor)
251
+ return descriptor.value;
252
+ if (typeof descriptor.get !== "function") {
253
+ throw new TypeError("object definition shape is not readable");
254
+ }
255
+ return Reflect.apply(descriptor.get, definition, []);
256
+ }
257
+ function isZodNeverNode(value) {
258
+ if (!isZodSchemaNode(value))
259
+ return false;
260
+ const internals = ownDataValue(value, "_zod");
261
+ if (typeof internals !== "object" || internals === null)
262
+ return false;
263
+ const definition = ownDataValue(internals, "def");
264
+ return (typeof definition === "object" &&
265
+ definition !== null &&
266
+ ownDataValue(definition, "type") === "never");
175
267
  }
176
- function issueSchema(schema, kind) {
177
- hardenSchemaGraph(schema);
178
- const shape = Object.freeze({ ...schema.shape });
268
+ function issueSchema(source, kind) {
269
+ const schema = hardenSchemaGraph(source);
270
+ const definition = schema._zod.def;
179
271
  const snapshot = Object.freeze({
180
- definition: schema._def,
181
- shape,
272
+ definition,
273
+ shape: Object.freeze({ ...schema.shape }),
182
274
  parse: schema.parse,
183
275
  safeParse: schema.safeParse,
184
- unknownKeys: schema._def.unknownKeys,
276
+ unknownKeys: isZodNeverNode(definition.catchall) ? "strict" : "strip",
185
277
  });
186
278
  ISSUED_SCHEMA_SNAPSHOTS.set(schema, snapshot);
187
279
  (kind === "input" ? ISSUED_INPUT_SCHEMAS : ISSUED_OUTPUT_SCHEMAS).add(schema);
@@ -193,7 +285,7 @@ function issuedSchemaSnapshot(schema, kind) {
193
285
  if (node_util_1.types.isProxy(schema) ||
194
286
  !issued.has(schema) ||
195
287
  !snapshot ||
196
- schema._def !== snapshot.definition ||
288
+ schema._zod.def !== snapshot.definition ||
197
289
  schema.parse !== snapshot.parse ||
198
290
  schema.safeParse !== snapshot.safeParse) {
199
291
  throw new TypeError(`tool ${kind} schema is not an issued contract-normalized schema`);
@@ -210,127 +302,501 @@ function issuedSchemaSnapshot(schema, kind) {
210
302
  /** Clone an issued top-level schema so later source-catalog mutation is inert. */
211
303
  function snapshotIssuedToolSchema(schema, kind) {
212
304
  const snapshot = issuedSchemaSnapshot(schema, kind);
213
- const normalized = zod_1.z.object({ ...snapshot.shape });
214
- const cloned = snapshot.unknownKeys === "strict"
215
- ? normalized.strict(kind === "input" ? encoded_query_policy_js_1.ENCODED_QUERY_MIGRATION_MESSAGE : undefined)
216
- : normalized.strip();
217
- hardenSchemaGraph(cloned);
218
- return cloned;
305
+ const shape = { ...snapshot.shape };
306
+ const cloned = snapshot.unknownKeys === "strip"
307
+ ? stripInputObject(shape)
308
+ : kind === "input"
309
+ ? strictInputObject(shape)
310
+ : zod_1.z.strictObject(shape);
311
+ return hardenSchemaGraph(cloned);
219
312
  }
220
313
  /**
221
- * Make every parse-relevant value reachable from a normalized schema stable.
222
- * Zod definitions are replaced with contract-owned copies before the schema
223
- * node is frozen, so references to an earlier definition become inert. The
224
- * traversal is deliberately bounded and rejects accessors, proxies, and
225
- * mutable exotic containers rather than attempting to execute them.
314
+ * Rebuild a schema graph from contract-owned, frozen definitions and return
315
+ * the rebuilt root.
316
+ *
317
+ * zod 4 parses through closures that each node's constructor creates over the
318
+ * definition it was given, so swapping a definition after construction would
319
+ * not reach parsing. Instead every node, checks included, is constructed anew
320
+ * from a frozen copy of its definition, and that copy is the only state its
321
+ * closures can see. References a caller kept to the source graph (its
322
+ * definitions, checks, regexes or collections) are therefore inert. Each
323
+ * rebuilt node then has its lazily derived state computed and its prototype
324
+ * members pinned as own values, and is frozen. The traversal is deliberately
325
+ * bounded and rejects accessors, proxies, foreign constructors, lazy
326
+ * (recursive) nodes and mutable exotic containers rather than attempting to
327
+ * execute them.
226
328
  */
227
329
  function hardenSchemaGraph(schema) {
228
330
  const state = {
229
331
  seen: new WeakMap(),
230
332
  depth: 0,
333
+ maxDepth: 0,
334
+ frames: [],
335
+ local: new WeakMap(),
336
+ building: new WeakMap(),
231
337
  nodes: 0,
232
338
  ownKeys: 0,
233
339
  };
234
- hardenZodSchemaNode(schema, state);
340
+ try {
341
+ return hardenZodNode(schema, state);
342
+ }
343
+ catch (error) {
344
+ throw error instanceof TypeError
345
+ ? error
346
+ : new TypeError("tool schema graph could not be hardened");
347
+ }
348
+ }
349
+ /** The allowlisted constructor a genuine zod node was built by, or undefined. */
350
+ function zodNodeConstructor(value) {
351
+ if (typeof value !== "object" ||
352
+ value === null ||
353
+ node_util_1.types.isProxy(value)) {
354
+ return undefined;
355
+ }
356
+ const internals = ownDataValue(value, "_zod");
357
+ if (typeof internals !== "object" ||
358
+ internals === null ||
359
+ node_util_1.types.isProxy(internals)) {
360
+ return undefined;
361
+ }
362
+ const constructor = ownDataValue(internals, "constr");
363
+ if (!ZOD_NODE_CONSTRUCTORS.has(constructor))
364
+ return undefined;
365
+ return value instanceof constructor
366
+ ? constructor
367
+ : undefined;
235
368
  }
236
- function hardenZodSchemaNode(schema, state) {
237
- if (node_util_1.types.isProxy(schema)) {
369
+ function hardenZodNode(node, state) {
370
+ if (node_util_1.types.isProxy(node)) {
238
371
  throw new TypeError("tool schema graph must not contain a Proxy");
239
372
  }
240
- if (HARDENED_SCHEMA_NODES.has(schema))
241
- return schema;
242
- const seen = state.seen.get(schema);
243
- if (seen)
244
- return seen;
245
- enterSchemaGraphValue(state, schema);
246
- state.seen.set(schema, schema);
247
- const definitionDescriptor = Object.getOwnPropertyDescriptor(schema, "_def");
373
+ const reused = HARDENED_SCHEMA_NODES.has(node)
374
+ ? node
375
+ : (HARDENED_FROM_SOURCE.get(node) ?? state.seen.get(node));
376
+ if (reused !== undefined) {
377
+ // Already counted in this graph, or built by an earlier one.
378
+ if (state.seen.has(reused))
379
+ noteSeenSubgraph(state, reused);
380
+ else
381
+ chargeReusedSubgraph(state, reused);
382
+ if (reused !== node)
383
+ state.seen.set(node, reused);
384
+ return reused;
385
+ }
386
+ const constructor = zodNodeConstructor(node);
387
+ if (!constructor) {
388
+ throw new TypeError("tool schema graph contains an unsupported schema node");
389
+ }
390
+ return measureSubgraph(state, () => rebuildZodNode(node, constructor, state), true);
391
+ }
392
+ function rebuildZodNode(node, constructor, state) {
393
+ const internals = ownDataValue(node, "_zod");
394
+ const definitionDescriptor = Object.getOwnPropertyDescriptor(internals, "def");
248
395
  if (!definitionDescriptor ||
249
396
  !("value" in definitionDescriptor) ||
250
- (!definitionDescriptor.configurable && !definitionDescriptor.writable)) {
397
+ typeof definitionDescriptor.value !== "object" ||
398
+ definitionDescriptor.value === null) {
399
+ throw new TypeError("tool schema graph definition must be a data property");
400
+ }
401
+ const sourceDefinition = definitionDescriptor.value;
402
+ // measureSubgraph pushed this node's frame; the only in-progress node a
403
+ // build may reach again is the one recorded here (see noteSeenSubgraph).
404
+ const frame = state.frames.at(-1);
405
+ enterSchemaGraphValue(state, node);
406
+ try {
407
+ if (constructor === zod_1.z.core.$ZodCheck) {
408
+ // A bare check (from .superRefine() or .check(fn)) gets its behaviour
409
+ // assigned after construction, and its closure refers to the check
410
+ // itself, so it cannot be rebuilt from its definition. It is frozen in
411
+ // place instead: a reference kept to it, or to its definition, can no
412
+ // longer change it.
413
+ state.seen.set(node, node);
414
+ frame.node = node;
415
+ sealCheckDefinitionInPlace(sourceDefinition, state);
416
+ sealRebuiltZodNode(node, state);
417
+ HARDENED_SCHEMA_NODES.add(node);
418
+ return node;
419
+ }
420
+ if (ownDataValue(sourceDefinition, "type") === "lazy") {
421
+ // zod 4 resolves a lazy target by writing it onto the definition and
422
+ // the node on first use, which a frozen graph cannot allow. A lazy node
423
+ // is also the way to build a recursive schema (shape getters are
424
+ // refused as accessors; a cycle closed through metadata is refused by
425
+ // noteSeenSubgraph and noteSeenValue). No tool schema is recursive, so
426
+ // lazy nodes are refused rather than half supported.
427
+ throw new TypeError("tool schema graph does not support lazy (recursive) schemas");
428
+ }
429
+ const definition = cloneSchemaDefinition(sourceDefinition, state);
430
+ const assigned = new Map(Reflect.ownKeys(definition).map((key) => [key, definition[key]]));
431
+ const rebuilt = new constructor(definition);
432
+ state.seen.set(node, rebuilt);
433
+ // A rebuilt node reached again through its own members is itself.
434
+ state.seen.set(rebuilt, rebuilt);
435
+ frame.node = rebuilt;
436
+ sealSchemaDefinition(definition, assigned, state);
437
+ copySchemaMetadata(node, rebuilt, state);
438
+ sealRebuiltZodNode(rebuilt, state);
439
+ HARDENED_SCHEMA_NODES.add(rebuilt);
440
+ // Only a completely sealed rebuild is shared; a failure above leaves
441
+ // nothing behind for the next graph.
442
+ HARDENED_FROM_SOURCE.set(node, rebuilt);
443
+ return rebuilt;
444
+ }
445
+ finally {
251
446
  leaveSchemaGraphValue(state);
252
- throw new TypeError("tool schema graph contains an immutable foreign definition");
253
447
  }
448
+ }
449
+ /**
450
+ * Build a hardened value and record what it charged and reached. A non-zod
451
+ * value gets a per-graph record of its own charge and its direct links. A zod
452
+ * node's process-wide record (see {@link HARDENED_SUBGRAPHS}) is computed from
453
+ * those when the node is finished, by walking its whole value closure.
454
+ */
455
+ function measureSubgraph(state, build, isZodNode,
456
+ /** For a non-zod value, the source being cloned (tracked while in progress). */
457
+ source) {
458
+ const startNodes = state.nodes;
459
+ const startOwnKeys = state.ownKeys;
460
+ const startDepth = state.depth;
461
+ const outerMaxDepth = state.maxDepth;
462
+ const parent = state.frames.at(-1);
463
+ const frame = {
464
+ zodFrame: parent?.zodFrame,
465
+ node: undefined,
466
+ childNodes: 0,
467
+ childOwnKeys: 0,
468
+ values: [],
469
+ zods: [],
470
+ boundTo: undefined,
471
+ };
472
+ if (isZodNode)
473
+ frame.zodFrame = frame;
474
+ state.maxDepth = startDepth;
475
+ state.frames.push(frame);
476
+ if (source !== undefined)
477
+ state.building.set(source, frame);
478
+ let hardened;
479
+ let height;
254
480
  try {
255
- const definition = cloneSchemaDefinition(schema, definitionDescriptor.value, state);
256
- Object.defineProperty(schema, "_def", {
257
- value: definition,
258
- enumerable: definitionDescriptor.enumerable,
259
- writable: false,
260
- configurable: false,
481
+ hardened = build();
482
+ height = state.maxDepth - startDepth;
483
+ }
484
+ finally {
485
+ if (source !== undefined)
486
+ state.building.delete(source);
487
+ state.frames.pop();
488
+ state.maxDepth = Math.max(outerMaxDepth, state.maxDepth);
489
+ }
490
+ const nodes = state.nodes - startNodes;
491
+ const ownKeys = state.ownKeys - startOwnKeys;
492
+ const ownNodes = nodes - frame.childNodes;
493
+ const ownOwnKeys = ownKeys - frame.childOwnKeys;
494
+ if (isZodNode) {
495
+ if (!HARDENED_SUBGRAPHS.has(hardened)) {
496
+ HARDENED_SUBGRAPHS.set(hardened, zodNodeRecord(state, hardened, frame, ownNodes, ownOwnKeys, height));
497
+ }
498
+ if (parent) {
499
+ parent.childNodes += nodes;
500
+ parent.childOwnKeys += ownKeys;
501
+ parent.zods.push(hardened);
502
+ }
503
+ return hardened;
504
+ }
505
+ if (!state.local.has(hardened)) {
506
+ state.local.set(hardened, {
507
+ nodes: ownNodes,
508
+ ownKeys: ownOwnKeys,
509
+ height,
510
+ values: frame.values,
511
+ zods: frame.zods,
512
+ boundTo: frame.boundTo,
261
513
  });
262
- initializeZodParseCaches(schema);
263
- hardenSchemaOwnProperties(schema, state);
264
- shadowZodPrototypeBehavior(schema);
265
- Object.freeze(schema);
266
- HARDENED_SCHEMA_NODES.add(schema);
267
- return schema;
268
514
  }
269
- catch (error) {
270
- throw error instanceof TypeError
271
- ? error
272
- : new TypeError("tool schema graph could not be hardened");
515
+ if (parent) {
516
+ parent.childNodes += nodes;
517
+ parent.childOwnKeys += ownKeys;
518
+ parent.values.push(hardened);
519
+ if (parent.zodFrame !== parent)
520
+ parent.boundTo ??= frame.boundTo;
273
521
  }
274
- finally {
275
- leaveSchemaGraphValue(state);
522
+ return hardened;
523
+ }
524
+ /**
525
+ * A finished zod node's record: its own charge plus that of every non-zod
526
+ * value in its closure (the values reachable from it without passing through
527
+ * another zod node), and the zod nodes that closure reaches. Every value in
528
+ * the closure has a record by now, because it was built in this graph and
529
+ * finished before this node did; one that has not is still being built by an
530
+ * enclosing node and closes a cycle. A value bound to a cycle through another
531
+ * node, or another node still being built, likewise means a cycle. Either
532
+ * case is refused, so a finished record never leaves anything out.
533
+ */
534
+ function zodNodeRecord(state, hardened, frame, ownNodes, ownOwnKeys, height) {
535
+ let nodes = ownNodes;
536
+ let ownKeys = ownOwnKeys;
537
+ const children = new Set(frame.zods);
538
+ const visited = new Set();
539
+ const pending = [...frame.values];
540
+ while (pending.length > 0) {
541
+ const value = pending.pop();
542
+ if (visited.has(value))
543
+ continue;
544
+ visited.add(value);
545
+ const record = state.local.get(value);
546
+ if (record === undefined)
547
+ throw schemaGraphCycle();
548
+ if (record.boundTo !== undefined && record.boundTo !== hardened)
549
+ throw schemaGraphCycle();
550
+ nodes += record.nodes;
551
+ ownKeys += record.ownKeys;
552
+ for (const child of record.zods)
553
+ children.add(child);
554
+ for (const next of record.values)
555
+ pending.push(next);
556
+ }
557
+ children.delete(hardened);
558
+ for (const child of children) {
559
+ if (!HARDENED_SUBGRAPHS.has(child))
560
+ throw schemaGraphCycle();
561
+ }
562
+ return Object.freeze({
563
+ nodes,
564
+ ownKeys,
565
+ height,
566
+ children: Object.freeze([...children]),
567
+ });
568
+ }
569
+ /** Record a depth reached through a subgraph, failing past the bound. */
570
+ function reachSchemaGraphDepth(state, depth) {
571
+ if (depth > state.maxDepth)
572
+ state.maxDepth = depth;
573
+ if (depth > MAX_SCHEMA_GRAPH_DEPTH) {
574
+ throw new TypeError("tool schema graph traversal budget exceeded");
276
575
  }
277
576
  }
278
- function cloneSchemaDefinition(schema, candidate, state) {
279
- if (typeof candidate !== "object" ||
280
- candidate === null ||
281
- node_util_1.types.isProxy(candidate) ||
577
+ /**
578
+ * The error for a graph with a cycle that runs through more than one node.
579
+ * Metadata and check parameters are attached after a node is constructed, so
580
+ * they can point back at an enclosing value or node even though lazy nodes
581
+ * are refused and accessors are not followed. A node reaching itself is
582
+ * allowed, and charged in full; any other cycle is refused, because a node
583
+ * inside it could not be given a complete record.
584
+ */
585
+ function schemaGraphCycle() {
586
+ return new TypeError("tool schema graph contains a cycle");
587
+ }
588
+ /** The node the innermost zod frame is building, if it exists yet. */
589
+ function nodeBeingBuilt(state) {
590
+ return state.frames.at(-1)?.zodFrame?.node;
591
+ }
592
+ /**
593
+ * Bind the value being built (and so every value enclosing it up to its zod
594
+ * node) to that node: it reached the node while the node was being built.
595
+ */
596
+ function bindToNodeBeingBuilt(state) {
597
+ const frame = state.frames.at(-1);
598
+ if (frame !== undefined && frame.zodFrame !== frame)
599
+ frame.boundTo ??= frame.zodFrame?.node;
600
+ }
601
+ /**
602
+ * A zod node reached again within the graph that already counted it: no new
603
+ * charge, as before, but its height is checked at this depth too and it is
604
+ * linked from the value or node being built. A node with no record is still
605
+ * being built; reaching it is allowed only from within its own build, and
606
+ * binds the reaching values to it. Reaching any other node still being built
607
+ * is a cycle and is refused.
608
+ */
609
+ function noteSeenSubgraph(state, hardened) {
610
+ const record = HARDENED_SUBGRAPHS.get(hardened);
611
+ if (record === undefined) {
612
+ if (hardened !== nodeBeingBuilt(state))
613
+ throw schemaGraphCycle();
614
+ bindToNodeBeingBuilt(state);
615
+ return;
616
+ }
617
+ reachSchemaGraphDepth(state, state.depth + record.height);
618
+ state.frames.at(-1)?.zods.push(hardened);
619
+ }
620
+ /**
621
+ * A cloned non-zod value reached again within this graph: no new charge to
622
+ * the graph, its height is checked at this depth, and it is linked from the
623
+ * value or node being built, whose record will then include it. A value bound
624
+ * to a cycle through another node may not be reached from this one. A value
625
+ * still being built may be reached again only from within the same zod
626
+ * node's build, which binds the reaching values to that node; from another
627
+ * node it is a cycle. Both are refused.
628
+ */
629
+ function noteSeenValue(state, source, hardened) {
630
+ const frame = state.frames.at(-1);
631
+ const record = state.local.get(hardened);
632
+ if (record === undefined) {
633
+ const building = state.building.get(source);
634
+ if (building === undefined) {
635
+ throw new TypeError("tool schema graph reuses a value with no recorded budget");
636
+ }
637
+ if (building.zodFrame !== frame?.zodFrame)
638
+ throw schemaGraphCycle();
639
+ bindToNodeBeingBuilt(state);
640
+ frame?.values.push(hardened);
641
+ return;
642
+ }
643
+ if (record.boundTo !== undefined) {
644
+ if (record.boundTo !== nodeBeingBuilt(state))
645
+ throw schemaGraphCycle();
646
+ bindToNodeBeingBuilt(state);
647
+ }
648
+ reachSchemaGraphDepth(state, state.depth + record.height);
649
+ frame?.values.push(hardened);
650
+ }
651
+ /**
652
+ * A hardened subgraph built by an earlier graph. Every node in it that this
653
+ * graph has not counted yet is charged its recorded nodes and own keys,
654
+ * which covers everything a fresh traversal of it would have charged, and its
655
+ * height is checked at the depth it is reached. The walk follows the recorded
656
+ * links only; it does not touch the frozen nodes.
657
+ */
658
+ function chargeReusedSubgraph(state, hardened) {
659
+ const record = HARDENED_SUBGRAPHS.get(hardened);
660
+ if (record === undefined) {
661
+ throw new TypeError("tool schema graph reuses a node with no recorded budget");
662
+ }
663
+ reachSchemaGraphDepth(state, state.depth + record.height);
664
+ let nodes = 0;
665
+ let ownKeys = 0;
666
+ const pending = [hardened];
667
+ while (pending.length > 0) {
668
+ const value = pending.pop();
669
+ if (state.seen.has(value))
670
+ continue;
671
+ const valueRecord = HARDENED_SUBGRAPHS.get(value);
672
+ if (valueRecord === undefined) {
673
+ throw new TypeError("tool schema graph reuses a node with no recorded budget");
674
+ }
675
+ state.seen.set(value, value);
676
+ nodes += valueRecord.nodes;
677
+ ownKeys += valueRecord.ownKeys;
678
+ for (const child of valueRecord.children)
679
+ pending.push(child);
680
+ }
681
+ state.nodes += nodes;
682
+ state.ownKeys += ownKeys;
683
+ if (state.nodes > MAX_SCHEMA_GRAPH_NODES) {
684
+ throw new TypeError("tool schema graph traversal budget exceeded");
685
+ }
686
+ if (state.ownKeys > MAX_SCHEMA_GRAPH_OWN_KEYS) {
687
+ throw new TypeError("tool schema graph property budget exceeded");
688
+ }
689
+ const parent = state.frames.at(-1);
690
+ if (parent) {
691
+ parent.childNodes += nodes;
692
+ parent.childOwnKeys += ownKeys;
693
+ parent.zods.push(hardened);
694
+ }
695
+ }
696
+ function cloneSchemaDefinition(candidate, state) {
697
+ if (node_util_1.types.isProxy(candidate) ||
282
698
  (Object.getPrototypeOf(candidate) !== Object.prototype &&
283
699
  Object.getPrototypeOf(candidate) !== null)) {
284
700
  throw new TypeError("tool schema graph definitions must be plain data objects");
285
701
  }
286
- const existing = state.seen.get(candidate);
287
- if (existing)
288
- return existing;
289
702
  enterSchemaGraphValue(state, candidate);
290
- const descriptors = boundedDataDescriptors(candidate, state, "definition");
291
- const clone = Object.create(Object.getPrototypeOf(candidate));
292
- state.seen.set(candidate, clone);
293
703
  try {
704
+ const descriptors = boundedDataDescriptors(candidate, state, "definition", ZOD_DEFINITION_ACCESSOR_KEYS);
705
+ const clone = Object.create(Object.getPrototypeOf(candidate));
294
706
  for (const key of Reflect.ownKeys(descriptors)) {
295
707
  const descriptor = descriptors[key];
296
- let value = descriptor.value;
297
- if (schema instanceof zod_1.z.ZodObject && key === "shape") {
298
- if (typeof value !== "function") {
299
- throw new TypeError("tool schema graph has an invalid object shape");
300
- }
301
- const shape = materializeZodShape(value, state);
302
- value = Object.freeze(() => shape);
708
+ let value;
709
+ if ("value" in descriptor) {
710
+ value = descriptor.value;
303
711
  }
304
- else if (schema instanceof zod_1.z.ZodLazy && key === "getter") {
305
- if (typeof value !== "function") {
306
- throw new TypeError("tool schema graph has an invalid lazy getter");
712
+ else {
713
+ try {
714
+ value = Reflect.apply(descriptor.get, candidate, []);
307
715
  }
308
- const lazyTarget = Reflect.apply(value, undefined, []);
309
- if (!isZodSchemaNode(lazyTarget)) {
310
- throw new TypeError("tool schema graph lazy getter returned an invalid schema");
716
+ catch {
717
+ throw new TypeError("tool schema graph definition getter could not be read");
311
718
  }
312
- const stableTarget = hardenZodSchemaNode(lazyTarget, state);
313
- value = Object.freeze(() => stableTarget);
314
- }
315
- else {
316
- value = cloneAndHardenGraphValue(value, state);
317
719
  }
318
- Object.defineProperty(clone, key, immutableDataDescriptor(descriptor, value));
720
+ value =
721
+ key === "shape"
722
+ ? materializeZodShape(value, state)
723
+ : cloneAndHardenGraphValue(value, state);
724
+ // Left writable until the node is constructed: zod constructors fill
725
+ // in definition defaults (a number format, a format's pattern) and an
726
+ // object's constructor reinstalls `shape` as its own getter. The
727
+ // definition is sealed right after construction.
728
+ Object.defineProperty(clone, key, {
729
+ value,
730
+ enumerable: descriptor.enumerable ?? true,
731
+ writable: true,
732
+ configurable: true,
733
+ });
319
734
  }
320
- return Object.freeze(clone);
735
+ return clone;
321
736
  }
322
737
  finally {
323
738
  leaveSchemaGraphValue(state);
324
739
  }
325
740
  }
326
- function materializeZodShape(shapeFactory, state) {
327
- let candidate;
741
+ /** Freeze a bare check's own definition where it is, hardening its values. */
742
+ function sealCheckDefinitionInPlace(definition, state) {
743
+ if (node_util_1.types.isProxy(definition) ||
744
+ Object.getPrototypeOf(definition) !== Object.prototype) {
745
+ throw new TypeError("tool schema graph definitions must be plain data objects");
746
+ }
747
+ enterSchemaGraphValue(state, definition);
328
748
  try {
329
- candidate = Reflect.apply(shapeFactory, undefined, []);
749
+ boundedDataDescriptors(definition, state, "definition");
750
+ sealSchemaDefinition(definition, new Map(), state);
330
751
  }
331
- catch {
332
- throw new TypeError("tool schema graph object shape could not be materialized");
752
+ finally {
753
+ leaveSchemaGraphValue(state);
333
754
  }
755
+ }
756
+ /**
757
+ * Freeze a rebuilt definition once its node is constructed. Any getter the
758
+ * constructor installed (an object's `shape`, which copies the frozen shape
759
+ * on first read) is read once so it settles as data, and the copy is frozen.
760
+ * A value the constructor added or replaced (a format's default pattern) is
761
+ * hardened like any other; the values cloned in are already hardened.
762
+ */
763
+ function sealSchemaDefinition(definition, assigned, state) {
764
+ for (const key of Reflect.ownKeys(definition)) {
765
+ const descriptor = Object.getOwnPropertyDescriptor(definition, key);
766
+ if (!descriptor)
767
+ continue;
768
+ let value;
769
+ if ("value" in descriptor) {
770
+ value = descriptor.value;
771
+ }
772
+ else {
773
+ value = Reflect.get(definition, key);
774
+ if (key !== "shape") {
775
+ throw new TypeError("tool schema graph definition gained an unexpected accessor");
776
+ }
777
+ }
778
+ if (key === "shape") {
779
+ if (typeof value !== "object" ||
780
+ value === null ||
781
+ node_util_1.types.isProxy(value) ||
782
+ Object.getPrototypeOf(value) !== Object.prototype) {
783
+ throw new TypeError("tool schema graph object shape must be a plain data object");
784
+ }
785
+ Object.freeze(value);
786
+ }
787
+ else if (!assigned.has(key) || assigned.get(key) !== value) {
788
+ value = cloneAndHardenGraphValue(value, state);
789
+ }
790
+ Object.defineProperty(definition, key, {
791
+ value,
792
+ enumerable: descriptor.enumerable ?? true,
793
+ writable: false,
794
+ configurable: false,
795
+ });
796
+ }
797
+ Object.freeze(definition);
798
+ }
799
+ function materializeZodShape(candidate, state) {
334
800
  if (typeof candidate !== "object" ||
335
801
  candidate === null ||
336
802
  Array.isArray(candidate) ||
@@ -340,9 +806,9 @@ function materializeZodShape(shapeFactory, state) {
340
806
  throw new TypeError("tool schema graph object shape must be a plain data object");
341
807
  }
342
808
  enterSchemaGraphValue(state, candidate);
343
- const descriptors = boundedDataDescriptors(candidate, state, "object shape");
344
- const shape = Object.create(null);
345
809
  try {
810
+ const descriptors = boundedDataDescriptors(candidate, state, "object shape");
811
+ const shape = {};
346
812
  for (const key of Reflect.ownKeys(descriptors)) {
347
813
  if (typeof key !== "string") {
348
814
  throw new TypeError("tool schema graph object shape has a symbol field");
@@ -351,65 +817,124 @@ function materializeZodShape(shapeFactory, state) {
351
817
  if (!isZodSchemaNode(field)) {
352
818
  throw new TypeError("tool schema graph object shape has an invalid field");
353
819
  }
354
- shape[key] = hardenZodSchemaNode(field, state);
820
+ Object.defineProperty(shape, key, {
821
+ value: hardenZodNode(field, state),
822
+ enumerable: true,
823
+ writable: false,
824
+ configurable: false,
825
+ });
355
826
  }
356
- return Object.freeze({ ...shape });
827
+ return Object.freeze(shape);
357
828
  }
358
829
  finally {
359
830
  leaveSchemaGraphValue(state);
360
831
  }
361
832
  }
362
- function initializeZodParseCaches(schema) {
363
- if (schema instanceof zod_1.z.ZodObject) {
364
- const shape = schema._def.shape();
365
- Object.defineProperty(schema, "_cached", {
366
- value: { shape, keys: Object.keys(shape) },
367
- enumerable: false,
368
- writable: true,
369
- configurable: true,
370
- });
833
+ /**
834
+ * zod 4 keeps a description in its global metadata registry, keyed by node,
835
+ * so the rebuilt node is registered with a frozen copy of the source's.
836
+ */
837
+ function copySchemaMetadata(source, rebuilt, state) {
838
+ const metadata = zod_1.z.globalRegistry.get(source);
839
+ if (metadata === undefined)
371
840
  return;
372
- }
373
- if (schema instanceof zod_1.z.ZodEnum) {
374
- Object.defineProperty(schema, "_cache", {
375
- value: new Set(schema._def.values),
376
- enumerable: false,
377
- writable: true,
378
- configurable: true,
379
- });
841
+ zod_1.z.globalRegistry.add(rebuilt, cloneAndHardenGraphValue(metadata, state));
842
+ }
843
+ /**
844
+ * Make a freshly rebuilt node immutable without breaking zod's own lazy
845
+ * state. zod 4 derives some internals on first read and binds prototype
846
+ * methods to the instance on first access, writing each onto the object, so
847
+ * freezing first would turn that write into a TypeError mid-parse. Every
848
+ * derived internal is therefore computed and every prototype member
849
+ * materialized first, Set/Map state is swapped for immutable facades, and only
850
+ * then is the node frozen. Prototype members stay pinned as own properties, so
851
+ * a later change to a zod prototype cannot reach an issued node.
852
+ */
853
+ function sealRebuiltZodNode(node, state) {
854
+ const internals = ownDataValue(node, "_zod");
855
+ settleMemoizedParse(internals);
856
+ materializeDerivedMembers(internals, true);
857
+ hardenOwnMembers(internals, state, new Set(["constr", "version"]));
858
+ Object.freeze(internals);
859
+ materializeDerivedMembers(node);
860
+ hardenOwnMembers(node, state, new Set(["_zod"]));
861
+ Object.freeze(node);
862
+ }
863
+ /**
864
+ * Let zod's memoizer settle a container's parse before the node is frozen.
865
+ * The wrapper decides on its first call whether the schema can recurse and,
866
+ * if not, restores the plain parse onto the internals; on a frozen node that
867
+ * write would throw mid-parse. Each memoized container rejects a non-object
868
+ * input before reaching any child or user function, so parsing `undefined`
869
+ * here only makes that decision.
870
+ */
871
+ function settleMemoizedParse(internals) {
872
+ const definition = ownDataValue(internals, "def");
873
+ if (!MEMOIZED_CONTAINER_TYPES.has(ownDataValue(definition, "type")))
380
874
  return;
875
+ const parse = ownDataValue(internals, "parse");
876
+ if (typeof parse !== "function") {
877
+ throw new TypeError("tool schema graph container has no parse function");
381
878
  }
382
- if (schema instanceof zod_1.z.ZodNativeEnum) {
383
- const values = schema._def.values;
384
- const validValues = Object.keys(values)
385
- .filter((key) => typeof values[String(values[key])] !== "number")
386
- .map((key) => values[key]);
387
- Object.defineProperty(schema, "_cache", {
388
- value: new Set(validValues),
389
- enumerable: false,
390
- writable: true,
391
- configurable: true,
392
- });
393
- }
879
+ Reflect.apply(parse, internals, [{ value: undefined, issues: [] }, {}]);
394
880
  }
395
- function hardenSchemaOwnProperties(schema, state) {
396
- const descriptors = boundedDataDescriptors(schema, state, "schema node");
397
- for (const key of Reflect.ownKeys(descriptors)) {
398
- if (key === "_def")
881
+ /**
882
+ * Harden every own member of a rebuilt node or its internals before the
883
+ * caller freezes it (freezing pins each member non-writable and
884
+ * non-configurable). Object data is replaced by its frozen clone or facade
885
+ * and functions are frozen; an accessor (a live zod getter pinned from the
886
+ * prototype) keeps its frozen functions. Members named in `shared` are zod
887
+ * module values every schema points at, and are left as they are. Only the
888
+ * members traversed count toward the property budget: the rest were created
889
+ * by zod's constructors from the bounded, cloned definition.
890
+ */
891
+ function hardenOwnMembers(target, state, shared) {
892
+ for (const key of Reflect.ownKeys(target)) {
893
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
894
+ if (!descriptor)
399
895
  continue;
400
- const descriptor = descriptors[key];
401
- const value = cloneAndHardenGraphValue(descriptor.value, state);
402
- if (!descriptor.configurable &&
403
- !descriptor.writable &&
404
- value !== descriptor.value) {
405
- throw new TypeError("tool schema graph contains immutable foreign state");
896
+ if (!("value" in descriptor)) {
897
+ if (descriptor.get)
898
+ Object.freeze(descriptor.get);
899
+ if (descriptor.set)
900
+ Object.freeze(descriptor.set);
901
+ continue;
902
+ }
903
+ const value = descriptor.value;
904
+ if (shared.has(key) || value === null)
905
+ continue;
906
+ if (typeof value === "function") {
907
+ Object.freeze(value);
908
+ continue;
909
+ }
910
+ if (typeof value !== "object")
911
+ continue;
912
+ state.ownKeys += 1;
913
+ if (state.ownKeys > MAX_SCHEMA_GRAPH_OWN_KEYS) {
914
+ throw new TypeError("tool schema graph property budget exceeded");
915
+ }
916
+ const hardened = cloneAndHardenGraphValue(value, state);
917
+ if (hardened !== value) {
918
+ if (!descriptor.configurable && !descriptor.writable) {
919
+ throw new TypeError("tool schema graph contains immutable foreign state");
920
+ }
921
+ Object.defineProperty(target, key, { value: hardened });
406
922
  }
407
- Object.defineProperty(schema, key, immutableDataDescriptor(descriptor, value));
408
923
  }
409
924
  }
410
- /** Shadow parse-relevant prototype behavior before freezing the node. */
411
- function shadowZodPrototypeBehavior(schema) {
412
- let prototype = Object.getPrototypeOf(schema);
925
+ /**
926
+ * Read every prototype getter of `target` once, so zod's lazily derived
927
+ * members land as own data, then pin any member still inherited (a method
928
+ * value, or a getter that stays live, such as `description`, which reads the
929
+ * registry on each access) as an own property.
930
+ *
931
+ * On a node's internals every prototype getter is a memoizing derivation, and
932
+ * one that resolved through a recursion break stays unmemoized (zod retries
933
+ * it later by writing to the internals). There the value read now, with the
934
+ * graph complete, is pinned as data instead, so no later read writes.
935
+ */
936
+ function materializeDerivedMembers(target, pinGettersAsData = false) {
937
+ let prototype = Object.getPrototypeOf(target);
413
938
  let levels = 0;
414
939
  while (prototype && prototype !== Object.prototype) {
415
940
  levels += 1;
@@ -417,7 +942,7 @@ function shadowZodPrototypeBehavior(schema) {
417
942
  throw new TypeError("tool schema graph has an unsupported prototype chain");
418
943
  }
419
944
  for (const key of Reflect.ownKeys(prototype)) {
420
- if (key === "constructor" || Object.hasOwn(schema, key))
945
+ if (key === "constructor" || Object.hasOwn(target, key))
421
946
  continue;
422
947
  const descriptor = Object.getOwnPropertyDescriptor(prototype, key);
423
948
  if (!descriptor)
@@ -425,26 +950,40 @@ function shadowZodPrototypeBehavior(schema) {
425
950
  if ("value" in descriptor) {
426
951
  if (typeof descriptor.value !== "function")
427
952
  continue;
428
- Object.freeze(descriptor.value);
429
- Object.defineProperty(schema, key, {
953
+ Object.defineProperty(target, key, {
430
954
  value: descriptor.value,
431
955
  enumerable: descriptor.enumerable,
432
956
  writable: false,
433
- configurable: false,
957
+ configurable: true,
434
958
  });
959
+ continue;
435
960
  }
436
- else {
437
- if (descriptor.get)
438
- Object.freeze(descriptor.get);
439
- if (descriptor.set)
440
- Object.freeze(descriptor.set);
441
- Object.defineProperty(schema, key, {
442
- get: descriptor.get,
443
- set: descriptor.set,
961
+ if (pinGettersAsData) {
962
+ const value = Reflect.get(target, key);
963
+ if (Object.hasOwn(target, key))
964
+ continue;
965
+ Object.defineProperty(target, key, {
966
+ value,
444
967
  enumerable: descriptor.enumerable,
445
- configurable: false,
968
+ writable: false,
969
+ configurable: true,
446
970
  });
971
+ continue;
972
+ }
973
+ try {
974
+ Reflect.get(target, key);
975
+ }
976
+ catch {
977
+ // A getter that cannot run for this node is pinned unread below.
447
978
  }
979
+ if (Object.hasOwn(target, key))
980
+ continue;
981
+ Object.defineProperty(target, key, {
982
+ get: descriptor.get,
983
+ set: descriptor.set,
984
+ enumerable: descriptor.enumerable,
985
+ configurable: true,
986
+ });
448
987
  }
449
988
  prototype = Object.getPrototypeOf(prototype);
450
989
  }
@@ -457,11 +996,17 @@ function cloneAndHardenGraphValue(value, state) {
457
996
  if (node_util_1.types.isProxy(value)) {
458
997
  throw new TypeError("tool schema graph must not contain a Proxy");
459
998
  }
460
- if (isZodSchemaNode(value))
461
- return hardenZodSchemaNode(value, state);
999
+ if (zodNodeConstructor(value))
1000
+ return hardenZodNode(value, state);
462
1001
  const existing = state.seen.get(value);
463
- if (existing)
1002
+ if (existing) {
1003
+ noteSeenValue(state, value, existing);
464
1004
  return existing;
1005
+ }
1006
+ return measureSubgraph(state, () => cloneFreshGraphValue(value, state), false, value);
1007
+ }
1008
+ /** Clone and freeze one non-zod value not yet seen in this graph. */
1009
+ function cloneFreshGraphValue(value, state) {
465
1010
  if (typeof value === "function") {
466
1011
  Object.freeze(value);
467
1012
  state.seen.set(value, value);
@@ -595,7 +1140,9 @@ function cloneAndFreezeSet(value, initialSize, state) {
595
1140
  }
596
1141
  }
597
1142
  function intrinsicMapSize(value) {
598
- if (!INTRINSIC_MAP_SIZE)
1143
+ // isMap reads the internal slot, so it cannot be spoofed and, unlike the
1144
+ // intrinsic getter on a non-Map, does not throw for every plain object.
1145
+ if (!INTRINSIC_MAP_SIZE || !node_util_1.types.isMap(value))
599
1146
  return undefined;
600
1147
  try {
601
1148
  const size = Reflect.apply(INTRINSIC_MAP_SIZE, value, []);
@@ -608,7 +1155,7 @@ function intrinsicMapSize(value) {
608
1155
  }
609
1156
  }
610
1157
  function intrinsicSetSize(value) {
611
- if (!INTRINSIC_SET_SIZE)
1158
+ if (!INTRINSIC_SET_SIZE || !node_util_1.types.isSet(value))
612
1159
  return undefined;
613
1160
  try {
614
1161
  const size = Reflect.apply(INTRINSIC_SET_SIZE, value, []);
@@ -761,7 +1308,7 @@ function immutableBoundMethod(method, receiver) {
761
1308
  configurable: false,
762
1309
  };
763
1310
  }
764
- function boundedDataDescriptors(value, state, label) {
1311
+ function boundedDataDescriptors(value, state, label, allowedAccessors = NO_ACCESSORS) {
765
1312
  const descriptors = Object.getOwnPropertyDescriptors(value);
766
1313
  const keys = Reflect.ownKeys(descriptors);
767
1314
  if (keys.length > MAX_SCHEMA_CONTAINER_KEYS) {
@@ -772,7 +1319,11 @@ function boundedDataDescriptors(value, state, label) {
772
1319
  throw new TypeError("tool schema graph property budget exceeded");
773
1320
  }
774
1321
  for (const key of keys) {
775
- if (!("value" in descriptors[key])) {
1322
+ const descriptor = descriptors[key];
1323
+ if (!("value" in descriptor) &&
1324
+ (!allowedAccessors.has(key) ||
1325
+ typeof descriptor.get !== "function" ||
1326
+ node_util_1.types.isProxy(descriptor.get))) {
776
1327
  throw new TypeError(`tool schema graph ${label} must not contain accessors`);
777
1328
  }
778
1329
  }
@@ -792,6 +1343,8 @@ function enterSchemaGraphValue(state, value) {
792
1343
  }
793
1344
  state.depth += 1;
794
1345
  state.nodes += 1;
1346
+ if (state.depth > state.maxDepth)
1347
+ state.maxDepth = state.depth;
795
1348
  if (state.depth > MAX_SCHEMA_GRAPH_DEPTH ||
796
1349
  state.nodes > MAX_SCHEMA_GRAPH_NODES) {
797
1350
  state.depth -= 1;
@@ -802,10 +1355,7 @@ function leaveSchemaGraphValue(state) {
802
1355
  state.depth -= 1;
803
1356
  }
804
1357
  function isZodSchemaNode(value) {
805
- return (typeof value === "object" &&
806
- value !== null &&
807
- !node_util_1.types.isProxy(value) &&
808
- value instanceof zod_1.z.ZodType);
1358
+ return zodNodeConstructor(value) !== undefined && value instanceof zod_1.z.ZodType;
809
1359
  }
810
1360
  /** Define, validate, snapshot, and freeze a profile-resolved tool module. */
811
1361
  function defineServiceNowToolModule(candidate) {
@@ -941,7 +1491,7 @@ function validateProfileSchema(name, kind, schema, requireStrict) {
941
1491
  if (!schema ||
942
1492
  !issued ||
943
1493
  schema.shape.profile !== exports.profileNameSchema ||
944
- (requireStrict && schema._def.unknownKeys !== "strict")) {
1494
+ (requireStrict && issued.unknownKeys !== "strict")) {
945
1495
  throw new TypeError(`${name}: ${kind} schema must use the shared required profile schema and be an issued contract-normalized Zod object${requireStrict ? " in strict mode" : ""}`);
946
1496
  }
947
1497
  }