@opengeni/tool-gateway 1.2.1-canary.37222965366001 → 1.3.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.
package/dist/errors.d.ts CHANGED
@@ -11,6 +11,10 @@ export declare class ToolGatewayApprovalRequiredError extends Error {
11
11
  readonly code = "approval_required";
12
12
  constructor();
13
13
  }
14
+ export declare class ToolGatewayBlockedError extends Error {
15
+ readonly code = "tool_blocked";
16
+ constructor();
17
+ }
14
18
  export declare class ToolGatewayCatalogIntegrityError extends Error {
15
19
  readonly code = "catalog_integrity_failed";
16
20
  constructor();
package/dist/index.d.ts CHANGED
@@ -15,6 +15,8 @@ export type ToolGatewayDefinition = Omit<ToolGatewayCatalogEntryValue, "codemode
15
15
  codemodePath?: readonly string[];
16
16
  /** Internal authority revision bound into human approval capabilities. */
17
17
  approvalAuthorityDigest?: string;
18
+ /** Executable effect/account identity; excludes unrelated revision changes. */
19
+ effectAuthorityDigest?: string;
18
20
  /** Connection-backed calls must have a side-effect-free provider preflight before approval. */
19
21
  requiresProviderPreflight?: boolean;
20
22
  /** In-process provider preflight; never enters the public catalog or its digest. */
@@ -31,6 +33,11 @@ export type ToolGatewayAuthorization = (input: {
31
33
  call: ToolGatewayCall;
32
34
  entry: ToolGatewayCatalogEntryValue;
33
35
  }) => Promise<void> | void;
36
+ /** A trusted adapter resolves user preferences after schema and access validation. */
37
+ export type ToolGatewayApprovalResolver = (input: {
38
+ call: ToolGatewayCall;
39
+ entry: ToolGatewayCatalogEntryValue;
40
+ }) => Promise<"allow" | "ask" | "block"> | "allow" | "ask" | "block";
34
41
  export type ToolGatewayCall = {
35
42
  operationId: string;
36
43
  catalogDigest: string;
@@ -46,6 +53,11 @@ export type ToolGatewayCallSettlement = {
46
53
  error: unknown;
47
54
  };
48
55
  export type PreparedToolGatewayCallLifecycle = {
56
+ /** Exact durable review created by a trusted policy adapter. */
57
+ waitingForApproval?: {
58
+ requestId: string;
59
+ actionFingerprint: string;
60
+ };
49
61
  /** Cross the side-effect boundary immediately before the executor closure. */
50
62
  begin?: () => Promise<void> | void;
51
63
  /** Settle the side-effect lifecycle after a returned result or thrown failure. */
@@ -73,6 +85,7 @@ type CompiledDefinition = {
73
85
  entry: ToolGatewayCatalogEntryValue;
74
86
  execute: ToolGatewayDefinition["execute"];
75
87
  approvalAuthorityDigest: string | undefined;
88
+ effectAuthorityDigest: string | undefined;
76
89
  preflightCall: ToolGatewayDefinition["preflightCall"];
77
90
  lifecycle: ToolGatewayCallLifecycle | undefined;
78
91
  validateInput: ValidateFunction<unknown>;
@@ -84,6 +97,13 @@ export type PreparedToolGatewayCall = {
84
97
  readonly call: ToolGatewayCall;
85
98
  readonly entry: ToolGatewayCatalogEntryValue;
86
99
  readonly approvalAuthorityDigest: string;
100
+ /** Effective choice; optional for older adapters constructing this interface. */
101
+ readonly approvalDecision?: "allow" | "ask";
102
+ readonly waitingForApproval?: {
103
+ requestId: string;
104
+ actionFingerprint: string;
105
+ };
106
+ readonly effectDigest?: string;
87
107
  execute: () => Promise<ToolGatewayResultValue>;
88
108
  };
89
109
  export declare class PreparedToolGatewayDefinitions {
@@ -93,6 +113,7 @@ export declare class PreparedToolGatewayDefinitions {
93
113
  create(input: {
94
114
  catalogDigest: string;
95
115
  authorize?: ToolGatewayAuthorization;
116
+ resolveApproval?: ToolGatewayApprovalResolver;
96
117
  requireApproval?: (entry: ToolGatewayCatalogEntryValue, caller: ToolGatewayCaller, context: {
97
118
  transportMeta?: Record<string, unknown> | null;
98
119
  }) => boolean;
@@ -108,6 +129,7 @@ export declare class ToolGateway {
108
129
  private readonly authorize;
109
130
  private readonly requireApproval;
110
131
  private readonly confirmModelApproval;
132
+ private readonly resolveApproval?;
111
133
  private readonly byIdentity;
112
134
  private readonly byModelName;
113
135
  constructor(catalogDigest: string, definitions: readonly CompiledDefinition[], authorize: ToolGatewayAuthorization | undefined, requireApproval: ((entry: ToolGatewayCatalogEntryValue, caller: ToolGatewayCaller, context: {
@@ -116,11 +138,13 @@ export declare class ToolGateway {
116
138
  entry: ToolGatewayCatalogEntryValue;
117
139
  modelName: string;
118
140
  subjectId: string;
119
- }) => boolean) | undefined);
141
+ }) => boolean) | undefined, resolveApproval?: ToolGatewayApprovalResolver | undefined);
120
142
  call(input: ToolGatewayCall, context?: ToolGatewayCallContext): Promise<ToolGatewayResultValue>;
121
143
  prepareCall(input: ToolGatewayCall, context?: ToolGatewayCallContext): Promise<PreparedToolGatewayCall>;
122
144
  private prepareCallWithModelApproval;
123
145
  private prepareCallCore;
146
+ /** Binds continuation to one executable operation, independent of unrelated catalog changes. */
147
+ effectDigest(identity: ToolGatewayIdentity): string;
124
148
  callModel(input: ModelToolGatewayCall): Promise<ToolGatewayResultValue>;
125
149
  }
126
150
  export declare function prepareToolGatewayDefinitions(definitions: readonly ToolGatewayDefinition[]): PreparedToolGatewayDefinitions;
@@ -131,6 +155,7 @@ export declare function createWorkspaceToolGateway(input: {
131
155
  definitions: readonly ToolGatewayDefinition[];
132
156
  createdAt?: Date;
133
157
  authorize?: ToolGatewayAuthorization;
158
+ resolveApproval?: ToolGatewayApprovalResolver;
134
159
  requireApproval?: (entry: ToolGatewayCatalogEntryValue, caller: ToolGatewayCaller, context: {
135
160
  transportMeta?: Record<string, unknown> | null;
136
161
  }) => boolean;
package/dist/index.js CHANGED
@@ -13,7 +13,8 @@ import {
13
13
  ToolGatewayCatalog as ToolGatewayCatalog2,
14
14
  ToolGatewayCatalogEntry,
15
15
  ToolGatewayResult,
16
- isToolResultSpilledReceipt
16
+ isToolResultSpilledReceipt,
17
+ executableToolSchema
17
18
  } from "@opengeni/contracts";
18
19
 
19
20
  // src/catalog.ts
@@ -752,6 +753,13 @@ var ToolGatewayApprovalRequiredError = class extends Error {
752
753
  this.name = "ToolGatewayApprovalRequiredError";
753
754
  }
754
755
  };
756
+ var ToolGatewayBlockedError = class extends Error {
757
+ code = "tool_blocked";
758
+ constructor() {
759
+ super("This action is blocked by your tool permissions");
760
+ this.name = "ToolGatewayBlockedError";
761
+ }
762
+ };
755
763
  var ToolGatewayCatalogIntegrityError = class extends Error {
756
764
  code = "catalog_integrity_failed";
757
765
  constructor() {
@@ -1093,16 +1101,18 @@ var PreparedToolGatewayDefinitions = class {
1093
1101
  this.definitions,
1094
1102
  input.authorize,
1095
1103
  input.requireApproval,
1096
- input.confirmModelApproval
1104
+ input.confirmModelApproval,
1105
+ input.resolveApproval
1097
1106
  );
1098
1107
  }
1099
1108
  };
1100
1109
  var ToolGateway = class {
1101
- constructor(catalogDigest, definitions, authorize, requireApproval, confirmModelApproval) {
1110
+ constructor(catalogDigest, definitions, authorize, requireApproval, confirmModelApproval, resolveApproval) {
1102
1111
  this.catalogDigest = catalogDigest;
1103
1112
  this.authorize = authorize;
1104
1113
  this.requireApproval = requireApproval;
1105
1114
  this.confirmModelApproval = confirmModelApproval;
1115
+ this.resolveApproval = resolveApproval;
1106
1116
  for (const definition of definitions) {
1107
1117
  this.byIdentity.set(identityKey(definition.entry.identity), definition);
1108
1118
  this.byModelName.set(definition.entry.modelName, definition);
@@ -1141,13 +1151,13 @@ var ToolGateway = class {
1141
1151
  if (!definition) {
1142
1152
  throw new ToolGatewayToolNotFoundError();
1143
1153
  }
1144
- if (this.requireApproval?.(definition.entry, caller, context)) {
1154
+ if (!this.resolveApproval && this.requireApproval?.(definition.entry, caller, context)) {
1145
1155
  throw new ToolGatewayApprovalRequiredError();
1146
1156
  }
1147
1157
  if (!definition.validateInput(request.arguments)) {
1148
1158
  throw inputValidationError(definition, request.arguments);
1149
1159
  }
1150
- if (caller.kind === "model" && definition.entry.approval === "human" && !modelApprovalConfirmed) {
1160
+ if (caller.kind === "model" && !this.resolveApproval && definition.entry.approval === "human" && !modelApprovalConfirmed) {
1151
1161
  throw new ToolGatewayApprovalRequiredError();
1152
1162
  }
1153
1163
  const call = {
@@ -1161,7 +1171,12 @@ var ToolGateway = class {
1161
1171
  "provider_authorization",
1162
1172
  () => this.authorize?.({ call, entry: definition.entry })
1163
1173
  );
1164
- if (definition.entry.approval === "human") {
1174
+ const approvalDecision = this.resolveApproval ? await this.resolveApproval({ call, entry: definition.entry }) : definition.entry.approval === "human" ? "ask" : "allow";
1175
+ if (approvalDecision === "block") throw new ToolGatewayBlockedError();
1176
+ if (this.resolveApproval && approvalDecision === "ask" && (caller.kind === "model" ? !modelApprovalConfirmed : context.transportMeta?.approvalConfirmed !== true)) {
1177
+ throw new ToolGatewayApprovalRequiredError();
1178
+ }
1179
+ if (approvalDecision === "ask") {
1165
1180
  await measureMcpPhase(
1166
1181
  "preflight",
1167
1182
  () => definition.preflightCall?.({
@@ -1182,6 +1197,9 @@ var ToolGateway = class {
1182
1197
  return {
1183
1198
  call,
1184
1199
  entry: definition.entry,
1200
+ approvalDecision,
1201
+ ...lifecycle?.waitingForApproval ? { waitingForApproval: lifecycle.waitingForApproval } : {},
1202
+ effectDigest: this.effectDigest(request.identity),
1185
1203
  approvalAuthorityDigest: definition.approvalAuthorityDigest ?? digestCanonicalJson({
1186
1204
  version: 1,
1187
1205
  catalogDigest: this.catalogDigest,
@@ -1190,6 +1208,7 @@ var ToolGateway = class {
1190
1208
  execute: async () => measureMcpPhase(
1191
1209
  "execution",
1192
1210
  async () => {
1211
+ if (lifecycle?.waitingForApproval) throw new ToolGatewayApprovalRequiredError();
1193
1212
  await measureMcpPhase("lifecycle_begin", () => lifecycle?.begin?.());
1194
1213
  let result;
1195
1214
  try {
@@ -1225,6 +1244,23 @@ var ToolGateway = class {
1225
1244
  )
1226
1245
  };
1227
1246
  }
1247
+ /** Binds continuation to one executable operation, independent of unrelated catalog changes. */
1248
+ effectDigest(identity) {
1249
+ const definition = this.byIdentity.get(identityKey(identity));
1250
+ if (!definition) throw new ToolGatewayToolNotFoundError();
1251
+ const { entry } = definition;
1252
+ return digestCanonicalJson({
1253
+ version: 1,
1254
+ identity: entry.identity,
1255
+ source: entry.source,
1256
+ inputSchema: executableToolSchema(entry.inputSchema),
1257
+ outputSchema: executableToolSchema(entry.outputSchema ?? null),
1258
+ readOnly: entry.annotations?.readOnlyHint ?? null,
1259
+ destructive: entry.annotations?.destructiveHint ?? null,
1260
+ idempotent: entry.annotations?.idempotentHint ?? null,
1261
+ authority: definition.effectAuthorityDigest ?? definition.approvalAuthorityDigest ?? null
1262
+ });
1263
+ }
1228
1264
  async callModel(input) {
1229
1265
  const definition = this.byModelName.get(input.modelName);
1230
1266
  if (!definition) {
@@ -1258,6 +1294,7 @@ function prepareToolGatewayDefinitions(definitions) {
1258
1294
  const {
1259
1295
  execute,
1260
1296
  approvalAuthorityDigest,
1297
+ effectAuthorityDigest,
1261
1298
  requiresProviderPreflight: _requiresProviderPreflight,
1262
1299
  preflightCall,
1263
1300
  lifecycle,
@@ -1267,6 +1304,9 @@ function prepareToolGatewayDefinitions(definitions) {
1267
1304
  if (approvalAuthorityDigest !== void 0 && !/^[0-9a-f]{64}$/u.test(approvalAuthorityDigest)) {
1268
1305
  throw new Error("Tool gateway approval authority digest must be lowercase SHA-256 hex");
1269
1306
  }
1307
+ if (effectAuthorityDigest !== void 0 && !/^[0-9a-f]{64}$/u.test(effectAuthorityDigest)) {
1308
+ throw new Error("Tool gateway effect authority digest must be lowercase SHA-256 hex");
1309
+ }
1270
1310
  const entry = ToolGatewayCatalogEntry.parse({
1271
1311
  ...entryInput,
1272
1312
  codemodePath: paths[index]
@@ -1276,6 +1316,7 @@ function prepareToolGatewayDefinitions(definitions) {
1276
1316
  entry,
1277
1317
  execute,
1278
1318
  approvalAuthorityDigest,
1319
+ effectAuthorityDigest,
1279
1320
  preflightCall,
1280
1321
  lifecycle,
1281
1322
  validateInput: compileCatalogSchema(schemaValidators, entry.inputSchema),
@@ -1308,6 +1349,7 @@ function createWorkspaceToolGateway(input) {
1308
1349
  gateway: prepared.create({
1309
1350
  catalogDigest: catalog.digest,
1310
1351
  ...input.authorize ? { authorize: input.authorize } : {},
1352
+ ...input.resolveApproval ? { resolveApproval: input.resolveApproval } : {},
1311
1353
  ...input.requireApproval ? { requireApproval: input.requireApproval } : {}
1312
1354
  })
1313
1355
  };
@@ -1463,6 +1505,7 @@ export {
1463
1505
  TOOL_GATEWAY_INPUT_ISSUES_MAX,
1464
1506
  ToolGateway,
1465
1507
  ToolGatewayApprovalRequiredError,
1508
+ ToolGatewayBlockedError,
1466
1509
  ToolGatewayCatalogIntegrityError,
1467
1510
  ToolGatewayCatalogStaleError,
1468
1511
  ToolGatewayCatalogTooLargeError,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/catalog.ts","../src/input-issues.ts","../src/errors.ts","../src/declarations.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { bindMcpTelemetry, withMcpCallIdentity, measureMcpPhase } from \"@opengeni/observability\";\nimport Ajv, {\n _,\n str,\n type CodeKeywordDefinition,\n type KeywordCxt,\n type ValidateFunction,\n} from \"ajv\";\nimport Ajv2019 from \"ajv/dist/2019.js\";\nimport Ajv2020 from \"ajv/dist/2020.js\";\nimport {\n TOOL_GATEWAY_CATALOG_VERSION,\n ToolGatewayCallRequest,\n ToolGatewayCatalog,\n ToolGatewayCatalogEntry,\n ToolGatewayResult,\n isToolResultSpilledReceipt,\n type ToolGatewayCaller,\n type ToolGatewayCatalog as ToolGatewayCatalogValue,\n type ToolGatewayCatalogEntry as ToolGatewayCatalogEntryValue,\n type ToolGatewayIdentity,\n type ToolGatewayResult as ToolGatewayResultValue,\n} from \"@opengeni/contracts\";\nimport {\n assertToolGatewayCatalogSize,\n compareCanonicalStrings,\n digestCanonicalJson,\n digestToolGatewayCatalog,\n} from \"./catalog\";\nimport {\n ToolGatewayApprovalRequiredError,\n ToolGatewayCatalogStaleError,\n ToolGatewayInputValidationError,\n ToolGatewayOutputValidationError,\n ToolGatewayPathCollisionError,\n ToolGatewayToolNotFoundError,\n} from \"./errors\";\nimport { summarizeToolGatewayInputErrors } from \"./input-issues\";\n\nexport type ToolGatewayExecutionContext = {\n operationId: string;\n caller: ToolGatewayCaller;\n /** Trusted in-process SDK correlation; not operation identity or approval authority. */\n sourceCallId?: string;\n /** In-process transport metadata; never part of catalog identity or digest. */\n transportMeta?: Record<string, unknown> | null;\n signal?: AbortSignal;\n};\n\nexport type ToolGatewayCallContext = Pick<\n ToolGatewayExecutionContext,\n \"sourceCallId\" | \"transportMeta\" | \"signal\"\n>;\n\nexport type ToolGatewayDefinition = Omit<ToolGatewayCatalogEntryValue, \"codemodePath\"> & {\n /** Optional human-readable path. Unsafe/colliding segments are normalized. */\n codemodePath?: readonly string[];\n /** Internal authority revision bound into human approval capabilities. */\n approvalAuthorityDigest?: string;\n /** Connection-backed calls must have a side-effect-free provider preflight before approval. */\n requiresProviderPreflight?: boolean;\n /** In-process provider preflight; never enters the public catalog or its digest. */\n preflightCall?: (input: {\n call: ToolGatewayCall;\n entry: ToolGatewayCatalogEntryValue;\n context: ToolGatewayCallContext;\n }) => Promise<void> | void;\n /** In-process execution lifecycle; never enters the public catalog or its digest. */\n lifecycle?: ToolGatewayCallLifecycle;\n execute: (\n args: Record<string, unknown>,\n context: ToolGatewayExecutionContext,\n ) => Promise<ToolGatewayResultValue> | ToolGatewayResultValue;\n};\n\nexport type ToolGatewayAuthorization = (input: {\n call: ToolGatewayCall;\n entry: ToolGatewayCatalogEntryValue;\n}) => Promise<void> | void;\n\nexport type ToolGatewayCall = {\n operationId: string;\n catalogDigest: string;\n identity: ToolGatewayIdentity;\n arguments: Record<string, unknown>;\n caller: ToolGatewayCaller;\n};\n\nexport type ToolGatewayCallSettlement =\n | { outcome: \"completed\"; result: ToolGatewayResultValue }\n | { outcome: \"failed\"; error: unknown };\n\nexport type PreparedToolGatewayCallLifecycle = {\n /** Cross the side-effect boundary immediately before the executor closure. */\n begin?: () => Promise<void> | void;\n /** Settle the side-effect lifecycle after a returned result or thrown failure. */\n complete?: (settlement: ToolGatewayCallSettlement) => Promise<void> | void;\n};\n\nexport type ToolGatewayCallLifecycle = {\n /** Argument-sensitive preflight. Throwing here guarantees the executor never runs. */\n prepare: (input: {\n call: ToolGatewayCall;\n entry: ToolGatewayCatalogEntryValue;\n context: ToolGatewayCallContext;\n }) => Promise<PreparedToolGatewayCallLifecycle | void> | PreparedToolGatewayCallLifecycle | void;\n};\n\nexport type ModelToolGatewayCall = {\n operationId?: string;\n /** Exact SDK call id supplied by the host, never inferred from arguments or metadata. */\n sourceCallId?: string;\n modelName: string;\n arguments: Record<string, unknown>;\n subjectId: string;\n transportMeta?: Record<string, unknown> | null;\n signal?: AbortSignal;\n};\n\ntype CompiledDefinition = {\n entry: ToolGatewayCatalogEntryValue;\n execute: ToolGatewayDefinition[\"execute\"];\n approvalAuthorityDigest: string | undefined;\n preflightCall: ToolGatewayDefinition[\"preflightCall\"];\n lifecycle: ToolGatewayCallLifecycle | undefined;\n validateInput: ValidateFunction<unknown>;\n /** Lazily compiled all-errors validator, used only to describe a rejected call. */\n diagnoseInput: () => ValidateFunction<unknown>;\n validateOutput: ValidateFunction<unknown> | null;\n};\n\nexport type PreparedToolGatewayCall = {\n readonly call: ToolGatewayCall;\n readonly entry: ToolGatewayCatalogEntryValue;\n readonly approvalAuthorityDigest: string;\n execute: () => Promise<ToolGatewayResultValue>;\n};\n\nexport class PreparedToolGatewayDefinitions {\n readonly entries: readonly ToolGatewayCatalogEntryValue[];\n\n constructor(private readonly definitions: readonly CompiledDefinition[]) {\n this.entries = definitions.map(({ entry }) => entry);\n }\n\n create(input: {\n catalogDigest: string;\n authorize?: ToolGatewayAuthorization;\n requireApproval?: (\n entry: ToolGatewayCatalogEntryValue,\n caller: ToolGatewayCaller,\n context: { transportMeta?: Record<string, unknown> | null },\n ) => boolean;\n confirmModelApproval?: (input: {\n entry: ToolGatewayCatalogEntryValue;\n modelName: string;\n subjectId: string;\n }) => boolean;\n }): ToolGateway {\n return new ToolGateway(\n input.catalogDigest,\n this.definitions,\n input.authorize,\n input.requireApproval,\n input.confirmModelApproval,\n );\n }\n}\n\nexport class ToolGateway {\n private readonly byIdentity = new Map<string, CompiledDefinition>();\n private readonly byModelName = new Map<string, CompiledDefinition>();\n\n constructor(\n readonly catalogDigest: string,\n definitions: readonly CompiledDefinition[],\n private readonly authorize: ToolGatewayAuthorization | undefined,\n private readonly requireApproval:\n | ((\n entry: ToolGatewayCatalogEntryValue,\n caller: ToolGatewayCaller,\n context: { transportMeta?: Record<string, unknown> | null },\n ) => boolean)\n | undefined,\n private readonly confirmModelApproval:\n | ((input: {\n entry: ToolGatewayCatalogEntryValue;\n modelName: string;\n subjectId: string;\n }) => boolean)\n | undefined,\n ) {\n for (const definition of definitions) {\n this.byIdentity.set(identityKey(definition.entry.identity), definition);\n this.byModelName.set(definition.entry.modelName, definition);\n }\n }\n\n async call(\n input: ToolGatewayCall,\n context: ToolGatewayCallContext = {},\n ): Promise<ToolGatewayResultValue> {\n return await (await this.prepareCallWithModelApproval(input, context, false)).execute();\n }\n\n async prepareCall(\n input: ToolGatewayCall,\n context: ToolGatewayCallContext = {},\n ): Promise<PreparedToolGatewayCall> {\n return await this.prepareCallWithModelApproval(input, context, false);\n }\n\n private async prepareCallWithModelApproval(\n input: ToolGatewayCall,\n context: ToolGatewayCallContext,\n modelApprovalConfirmed: boolean,\n ): Promise<PreparedToolGatewayCall> {\n return withMcpCallIdentity(context.sourceCallId ?? input.operationId, async () => {\n const prepared = await measureMcpPhase(\"gateway_policy\", () =>\n this.prepareCallCore(input, context, modelApprovalConfirmed),\n );\n return { ...prepared, execute: bindMcpTelemetry(prepared.execute) };\n });\n }\n\n private async prepareCallCore(\n input: ToolGatewayCall,\n context: ToolGatewayCallContext,\n modelApprovalConfirmed: boolean,\n ): Promise<PreparedToolGatewayCall> {\n const request = ToolGatewayCallRequest.parse({\n operationId: input.operationId,\n catalogDigest: input.catalogDigest,\n identity: input.identity,\n arguments: input.arguments,\n });\n const operationId = request.operationId ?? input.operationId;\n const caller = input.caller;\n if (request.catalogDigest !== this.catalogDigest) {\n throw new ToolGatewayCatalogStaleError();\n }\n const definition = this.byIdentity.get(identityKey(request.identity));\n if (!definition) {\n throw new ToolGatewayToolNotFoundError();\n }\n if (this.requireApproval?.(definition.entry, caller, context)) {\n throw new ToolGatewayApprovalRequiredError();\n }\n if (!definition.validateInput(request.arguments)) {\n throw inputValidationError(definition, request.arguments);\n }\n if (\n caller.kind === \"model\" &&\n definition.entry.approval === \"human\" &&\n !modelApprovalConfirmed\n ) {\n throw new ToolGatewayApprovalRequiredError();\n }\n const call = {\n operationId,\n catalogDigest: request.catalogDigest,\n identity: request.identity,\n arguments: request.arguments,\n caller,\n } satisfies ToolGatewayCall;\n await measureMcpPhase(\"provider_authorization\", () =>\n this.authorize?.({ call, entry: definition.entry }),\n );\n if (definition.entry.approval === \"human\") {\n await measureMcpPhase(\"preflight\", () =>\n definition.preflightCall?.({\n call,\n entry: definition.entry,\n context,\n }),\n );\n }\n const lifecycle = await measureMcpPhase(\"lifecycle_prepare\", () =>\n definition.lifecycle?.prepare({\n call,\n entry: definition.entry,\n context,\n }),\n );\n return {\n call,\n entry: definition.entry,\n approvalAuthorityDigest:\n definition.approvalAuthorityDigest ??\n digestCanonicalJson({\n version: 1,\n catalogDigest: this.catalogDigest,\n identity: definition.entry.identity,\n }),\n execute: async () =>\n measureMcpPhase(\n \"execution\",\n async () => {\n await measureMcpPhase(\"lifecycle_begin\", () => lifecycle?.begin?.());\n let result: ToolGatewayResultValue;\n try {\n result = ToolGatewayResult.parse(\n await definition.execute(request.arguments, {\n operationId,\n caller,\n ...(context.sourceCallId === undefined\n ? {}\n : { sourceCallId: context.sourceCallId }),\n ...(context.transportMeta === undefined\n ? {}\n : { transportMeta: context.transportMeta }),\n ...(context.signal === undefined ? {} : { signal: context.signal }),\n }),\n );\n if (!result.isError && definition.validateOutput) {\n const outputMatchesSchema =\n result.structuredContent !== undefined &&\n definition.validateOutput(result.structuredContent);\n if (!outputMatchesSchema && !isToolResultSpilledReceipt(result.structuredContent)) {\n throw new ToolGatewayOutputValidationError();\n }\n }\n } catch (error) {\n await measureMcpPhase(\"lifecycle_complete\", () =>\n lifecycle?.complete?.({ outcome: \"failed\", error }),\n );\n throw error;\n }\n await measureMcpPhase(\"lifecycle_complete\", () =>\n lifecycle?.complete?.({ outcome: \"completed\", result }),\n );\n return result;\n },\n (result) => (result.isError ? \"rejected\" : \"completed\"),\n ),\n };\n }\n\n async callModel(input: ModelToolGatewayCall): Promise<ToolGatewayResultValue> {\n const definition = this.byModelName.get(input.modelName);\n if (!definition) {\n throw new ToolGatewayToolNotFoundError();\n }\n const call = {\n operationId: input.operationId ?? randomUUID(),\n catalogDigest: this.catalogDigest,\n identity: definition.entry.identity,\n arguments: input.arguments,\n caller: { kind: \"model\" as const, subjectId: input.subjectId },\n };\n const context = {\n ...(input.sourceCallId === undefined ? {} : { sourceCallId: input.sourceCallId }),\n ...(input.transportMeta === undefined ? {} : { transportMeta: input.transportMeta }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n };\n const modelApprovalConfirmed =\n definition.entry.approval === \"human\" &&\n this.confirmModelApproval?.({\n entry: definition.entry,\n modelName: input.modelName,\n subjectId: input.subjectId,\n }) === true;\n return await (\n await this.prepareCallWithModelApproval(call, context, modelApprovalConfirmed)\n ).execute();\n }\n}\n\nexport function prepareToolGatewayDefinitions(\n definitions: readonly ToolGatewayDefinition[],\n): PreparedToolGatewayDefinitions {\n const paths = allocateToolPaths(definitions);\n const schemaValidators = createSchemaValidators(\"first_error\");\n let diagnosticValidators: SchemaValidators | undefined;\n const compiled = definitions.map((definition, index): CompiledDefinition => {\n const {\n execute,\n approvalAuthorityDigest,\n requiresProviderPreflight: _requiresProviderPreflight,\n preflightCall,\n lifecycle,\n codemodePath: _path,\n ...entryInput\n } = definition;\n if (approvalAuthorityDigest !== undefined && !/^[0-9a-f]{64}$/u.test(approvalAuthorityDigest)) {\n throw new Error(\"Tool gateway approval authority digest must be lowercase SHA-256 hex\");\n }\n const entry = ToolGatewayCatalogEntry.parse({\n ...entryInput,\n codemodePath: paths[index],\n });\n let diagnoseInput: ValidateFunction<unknown> | undefined;\n return {\n entry,\n execute,\n approvalAuthorityDigest,\n preflightCall,\n lifecycle,\n validateInput: compileCatalogSchema(schemaValidators, entry.inputSchema),\n diagnoseInput: () =>\n (diagnoseInput ??= compileCatalogSchema(\n (diagnosticValidators ??= createSchemaValidators(\"all_errors\")),\n entry.inputSchema,\n )),\n validateOutput: entry.outputSchema\n ? compileCatalogSchema(schemaValidators, entry.outputSchema)\n : null,\n };\n });\n return new PreparedToolGatewayDefinitions(compiled);\n}\n\nexport function createWorkspaceToolGateway(input: {\n accountId: string;\n workspaceId: string;\n generation: number;\n definitions: readonly ToolGatewayDefinition[];\n createdAt?: Date;\n authorize?: ToolGatewayAuthorization;\n requireApproval?: (\n entry: ToolGatewayCatalogEntryValue,\n caller: ToolGatewayCaller,\n context: { transportMeta?: Record<string, unknown> | null },\n ) => boolean;\n}): { catalog: ToolGatewayCatalogValue; gateway: ToolGateway } {\n const prepared = prepareToolGatewayDefinitions(input.definitions);\n const unsigned = {\n version: TOOL_GATEWAY_CATALOG_VERSION,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n generation: input.generation,\n createdAt: (input.createdAt ?? new Date()).toISOString(),\n entries: [...prepared.entries],\n };\n const catalog = ToolGatewayCatalog.parse({\n ...unsigned,\n digest: digestToolGatewayCatalog(unsigned),\n });\n assertToolGatewayCatalogSize(catalog);\n return {\n catalog,\n gateway: prepared.create({\n catalogDigest: catalog.digest,\n ...(input.authorize ? { authorize: input.authorize } : {}),\n ...(input.requireApproval ? { requireApproval: input.requireApproval } : {}),\n }),\n };\n}\n\ntype SchemaCompiler = { compile(schema: object): ValidateFunction<unknown> };\n\ntype SchemaValidatorMode = \"first_error\" | \"all_errors\";\n\ntype SchemaValidators = {\n mode: SchemaValidatorMode;\n draft7: SchemaCompiler;\n draft2019: SchemaCompiler;\n draft2020: SchemaCompiler;\n};\n\nconst COMPILED_CATALOG_SCHEMA_CACHE_MAX_ENTRIES = 512;\nconst compiledCatalogSchemaCache = new Map<string, ValidateFunction<unknown>>();\n\n/**\n * Serialized-size ceiling for the all-errors diagnostic pass. The accept/reject\n * decision always uses the first-error validator, which stops at the first\n * failure so a schema's own bounds (for example `maxLength` ahead of `pattern`)\n * keep limiting validation cost. The diagnostic pass runs only after a\n * rejection and only on arguments this small; larger ones report the first\n * problem alone. Its `pattern` keeps the `maxLength` guard (see\n * `maxLengthGuardedPattern`).\n */\nexport const TOOL_GATEWAY_INPUT_DIAGNOSTIC_MAX_CHARS = 64 * 1024;\n\nfunction createSchemaValidators(mode: SchemaValidatorMode): SchemaValidators {\n const options = {\n allErrors: mode === \"all_errors\",\n coerceTypes: false,\n strict: false,\n useDefaults: false,\n validateFormats: false,\n } as const;\n const validators = {\n draft7: new Ajv(options),\n draft2019: new Ajv2019(options),\n draft2020: new Ajv2020(options),\n };\n if (mode === \"all_errors\") {\n for (const ajv of Object.values(validators)) {\n ajv.removeKeyword(\"pattern\").addKeyword(maxLengthGuardedPattern);\n }\n }\n return { mode, ...validators };\n}\n\nfunction codePointLength(value: string): number {\n let length = 0;\n for (const _codePoint of value) length += 1;\n return length;\n}\n\n/**\n * `pattern` for the all-errors diagnostic validators. The first-error validator\n * checks `maxLength` before `pattern` and stops there, so a schema's\n * `maxLength` bounds how long a string its (possibly backtracking-heavy)\n * pattern ever sees. With `allErrors` the built-in keyword would still run the\n * pattern on the over-long string. This version skips the pattern exactly when\n * the sibling `maxLength` already fails, so every subschema's validity is\n * unchanged and the diagnostic pass never runs a pattern on a string the\n * accept/reject validator would not have. Error shape matches the built-in.\n */\nconst maxLengthGuardedPattern: CodeKeywordDefinition = {\n keyword: \"pattern\",\n type: \"string\",\n schemaType: \"string\",\n error: {\n message: ({ schemaCode }) => str`must match pattern \"${schemaCode}\"`,\n params: ({ schemaCode }) => _`{pattern: ${schemaCode}}`,\n },\n code(cxt: KeywordCxt) {\n const { gen, data, schema, parentSchema, it } = cxt;\n const flags = it.opts.unicodeRegExp ? \"u\" : \"\";\n const regExp = gen.scopeValue(\"pattern\", {\n key: `${schema}/${flags}`,\n ref: it.opts.code.regExp(schema as string, flags),\n });\n const maxLength: unknown = parentSchema.maxLength;\n if (typeof maxLength !== \"number\") {\n cxt.fail(_`!${regExp}.test(${data})`);\n return;\n }\n const length =\n it.opts.unicode === false\n ? _`${data}.length`\n : _`${gen.scopeValue(\"func\", { ref: codePointLength })}(${data})`;\n cxt.fail(_`${length} <= ${maxLength} && !${regExp}.test(${data})`);\n },\n};\n\n/**\n * Describe why the first-error validator rejected `args`: every problem (capped)\n * when the arguments are small enough for the diagnostic pass, else the first.\n * Never includes argument values.\n */\nfunction inputValidationError(\n definition: CompiledDefinition,\n args: Record<string, unknown>,\n): ToolGatewayInputValidationError {\n let errors = definition.validateInput.errors;\n let diagnosticInput:\n | { schema: Record<string, unknown>; arguments: Record<string, unknown> }\n | undefined;\n try {\n const serialized = JSON.stringify(args);\n if (serialized !== undefined && serialized.length <= TOOL_GATEWAY_INPUT_DIAGNOSTIC_MAX_CHARS) {\n diagnosticInput = { schema: definition.entry.inputSchema, arguments: args };\n const diagnose = definition.diagnoseInput();\n if (!diagnose(args) && diagnose.errors?.length) errors = diagnose.errors;\n }\n } catch {\n // Diagnostics are best effort; the rejection itself is already decided.\n }\n const { issues, omittedIssueCount } = summarizeToolGatewayInputErrors(errors, diagnosticInput);\n return new ToolGatewayInputValidationError(issues, omittedIssueCount);\n}\n\nfunction compileCatalogSchema(\n validators: SchemaValidators,\n schema: ToolGatewayCatalogEntryValue[\"inputSchema\"],\n): ValidateFunction<unknown> {\n const dialect = typeof schema.$schema === \"string\" ? schema.$schema : \"\";\n const family = dialect.includes(\"2020-12\")\n ? \"2020-12\"\n : dialect.includes(\"2019-09\")\n ? \"2019-09\"\n : \"draft7\";\n const cacheKey = `${validators.mode}:${family}:${digestCanonicalJson(schema)}`;\n const cached = compiledCatalogSchemaCache.get(cacheKey);\n if (cached) {\n compiledCatalogSchemaCache.delete(cacheKey);\n compiledCatalogSchemaCache.set(cacheKey, cached);\n return cached;\n }\n const compiled =\n family === \"2020-12\"\n ? validators.draft2020.compile(schema)\n : family === \"2019-09\"\n ? validators.draft2019.compile(schema)\n : validators.draft7.compile(schema);\n while (compiledCatalogSchemaCache.size >= COMPILED_CATALOG_SCHEMA_CACHE_MAX_ENTRIES) {\n const oldest = compiledCatalogSchemaCache.keys().next().value;\n if (oldest === undefined) break;\n compiledCatalogSchemaCache.delete(oldest);\n }\n compiledCatalogSchemaCache.set(cacheKey, compiled);\n return compiled;\n}\n\nfunction allocateToolPaths(definitions: readonly ToolGatewayDefinition[]): string[][] {\n const requested = definitions.map((definition) =>\n definition.codemodePath?.length\n ? [...definition.codemodePath]\n : [definition.identity.serverId, definition.identity.toolName],\n );\n const bases = requested.map((path) => path.map(safeNamespaceSegment));\n const allocated = bases.map((base, index) => {\n const path = requested[index]!;\n if (path.every((segment, segmentIndex) => segment === base[segmentIndex])) return base;\n const suffix = `_${shortIdentityDigest(definitions[index]!.identity)}`;\n const last = base.at(-1)!;\n return [...base.slice(0, -1), `${last.slice(0, 128 - suffix.length)}${suffix}`];\n });\n assertNoToolPathCollisions(allocated);\n return allocated;\n}\n\ntype ToolPathNode = {\n children: Map<string, ToolPathNode>;\n leaf: boolean;\n};\n\nfunction assertNoToolPathCollisions(paths: readonly (readonly string[])[]): void {\n const root: ToolPathNode = { children: new Map(), leaf: false };\n const ordered = [...paths].sort(compareToolPaths);\n for (const path of ordered) {\n let node = root;\n for (const [index, segment] of path.entries()) {\n if (node.leaf) throw new ToolGatewayPathCollisionError(path, \"extends_leaf\");\n let child = node.children.get(segment);\n if (!child) {\n child = { children: new Map(), leaf: false };\n node.children.set(segment, child);\n }\n node = child;\n if (index === path.length - 1) {\n if (node.leaf || node.children.size > 0) {\n throw new ToolGatewayPathCollisionError(path, \"collision\");\n }\n node.leaf = true;\n }\n }\n }\n}\n\nfunction compareToolPaths(left: readonly string[], right: readonly string[]): number {\n const length = Math.min(left.length, right.length);\n for (let index = 0; index < length; index += 1) {\n const compared = compareCanonicalStrings(left[index]!, right[index]!);\n if (compared !== 0) return compared;\n }\n return left.length - right.length;\n}\n\nfunction safeNamespaceSegment(value: string): string {\n let normalized = value.replace(/[^A-Za-z0-9_$]/gu, \"_\");\n if (!/^[A-Za-z_$]/u.test(normalized)) normalized = `_${normalized}`;\n if ([\"__proto__\", \"prototype\", \"constructor\"].includes(normalized)) {\n normalized = `_${normalized}`;\n }\n return normalized.slice(0, 128) || \"_\";\n}\n\nfunction shortIdentityDigest(identity: ToolGatewayIdentity): string {\n return createHash(\"sha256\").update(identityKey(identity), \"utf8\").digest(\"hex\").slice(0, 10);\n}\n\nfunction identityKey(identity: ToolGatewayIdentity): string {\n return `${identity.serverId}\\u0000${identity.toolName}`;\n}\n\nexport * from \"./catalog\";\nexport * from \"./declarations\";\nexport * from \"./errors\";\nexport * from \"./input-issues\";\n","import { createHash } from \"node:crypto\";\nimport {\n ATTEMPT_TOOL_CATALOG_MAX_BYTES,\n ToolGatewayCatalog,\n type ToolGatewayCatalog as ToolGatewayCatalogValue,\n} from \"@opengeni/contracts\";\nimport { ToolGatewayCatalogIntegrityError, ToolGatewayCatalogTooLargeError } from \"./errors\";\n\nexport function digestToolGatewayCatalog(catalog: Omit<ToolGatewayCatalogValue, \"digest\">): string {\n const { createdAt: _createdAt, ...authoritative } = catalog;\n return digestCanonicalJson(authoritative);\n}\n\nexport function parseVerifiedToolGatewayCatalog(input: unknown): ToolGatewayCatalogValue {\n const catalog = ToolGatewayCatalog.parse(input);\n assertCatalogSize(catalog);\n const { digest, ...unsigned } = catalog;\n if (digestToolGatewayCatalog(unsigned) !== digest) {\n throw new ToolGatewayCatalogIntegrityError();\n }\n return catalog;\n}\n\nexport function digestCanonicalJson(value: unknown): string {\n return createHash(\"sha256\")\n .update(JSON.stringify(canonicalJsonValue(value)), \"utf8\")\n .digest(\"hex\");\n}\n\n/** Compare canonical JSON keys by JavaScript UTF-16 code units, independent of host locale. */\nexport function compareCanonicalStrings(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nexport function assertToolGatewayCatalogSize(catalog: ToolGatewayCatalogValue): void {\n assertCatalogSize(catalog);\n}\n\nfunction assertCatalogSize(catalog: ToolGatewayCatalogValue): void {\n if (\n new TextEncoder().encode(JSON.stringify(catalog)).byteLength > ATTEMPT_TOOL_CATALOG_MAX_BYTES\n ) {\n throw new ToolGatewayCatalogTooLargeError();\n }\n}\n\nfunction canonicalJsonValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonicalJsonValue);\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => compareCanonicalStrings(left, right))\n .map(([key, entry]) => [key, canonicalJsonValue(entry)]),\n );\n }\n return value;\n}\n","import type { ErrorObject } from \"ajv\";\n\n/**\n * One argument problem found by input-schema validation. Every field is derived\n * from the property path and the tool's schema, never from an argument value,\n * so the summary is safe to show to the model and to return over HTTP.\n */\nexport type ToolGatewayInputIssue = {\n /** Readable path of the offending property (`context`, `filters[0].field`); empty for the arguments object itself. */\n readonly path: string;\n /** JSON Schema keyword that failed, such as `required`, `type`, or `additionalProperties`. */\n readonly keyword: string;\n /** Short, value-free sentence fragment naming the property and what the schema expects. */\n readonly message: string;\n};\n\nexport type ToolGatewayInputIssueSummary = {\n readonly issues: readonly ToolGatewayInputIssue[];\n /** Distinct problems found beyond the reported cap. */\n readonly omittedIssueCount: number;\n};\n\n/** Maximum problems named in one validation error. */\nexport const TOOL_GATEWAY_INPUT_ISSUES_MAX = 8;\n\nconst PATH_MAX_CHARS = 120;\nconst MESSAGE_DETAIL_MAX_CHARS = 160;\nconst ALLOWED_VALUES_MAX = 10;\nconst ALLOWED_VALUE_MAX_CHARS = 60;\n\n/**\n * Convert validator errors into a capped, de-duplicated list of value-free issues.\n * Validator messages only quote schema facts (types, limits, patterns), and\n * values offered here come from `enum`/`const` in the schema, not the arguments.\n * Supplying the input schema and arguments also distinguishes union alternatives;\n * arguments are inspected only to select schema facts, never included in text.\n */\nexport function summarizeToolGatewayInputErrors(\n errors: readonly ErrorObject[] | null | undefined,\n input?: { schema: Record<string, unknown>; arguments: Record<string, unknown> },\n): ToolGatewayInputIssueSummary {\n const issues: ToolGatewayInputIssue[] = [];\n const seen = new Set<string>();\n let omittedIssueCount = 0;\n let candidates = unscopedInputIssues(errors ?? []);\n if (input) {\n try {\n candidates = unionAwareIssues(errors ?? [], input);\n } catch {\n // Diagnostics cannot replace the already-decided input rejection.\n }\n }\n for (const issue of candidates) {\n if (seen.has(issue.message)) continue;\n seen.add(issue.message);\n if (issues.length < TOOL_GATEWAY_INPUT_ISSUES_MAX) issues.push(issue);\n else omittedIssueCount += 1;\n }\n return { issues, omittedIssueCount };\n}\n\n/** Without bounded argument diagnostics, union errors are alternatives only. */\nfunction unscopedInputIssues(errors: readonly ErrorObject[]): ToolGatewayInputIssue[] {\n const union = errors.find((error) => error.keyword === \"anyOf\" || error.keyword === \"oneOf\");\n if (!union) return errors.map(issueFromError);\n const path = displayPath(pointerSegments(union.instancePath));\n return [\n {\n path,\n keyword: union.keyword,\n message: `${describe(path)} must match ${union.keyword === \"oneOf\" ? \"exactly one\" : \"one\"} declared alternative input format`,\n },\n ];\n}\n\ntype JsonSchema = Record<string, unknown>;\ntype LiteralConstraint = { path: readonly string[]; values: readonly unknown[]; required: boolean };\ntype UnionDiagnostic = {\n error: ErrorObject;\n branchPrefixes: readonly (readonly string[])[];\n selected: number | undefined;\n replacement: ToolGatewayInputIssue | undefined;\n unresolved?: boolean;\n};\n\n/**\n * An anyOf/oneOf failure contains errors from mutually exclusive alternatives.\n * A supplied const/enum tag can rule alternatives out, but a missing property or\n * a count of failures cannot choose one. Without a unique compatible branch,\n * describe the alternatives explicitly instead of combining their requirements.\n */\nfunction unionAwareIssues(\n errors: readonly ErrorObject[],\n input: { schema: JsonSchema; arguments: Record<string, unknown> },\n): ToolGatewayInputIssue[] {\n if (!errors.some((error) => error.keyword === \"anyOf\" || error.keyword === \"oneOf\"))\n return errors.map(issueFromError);\n const unions: UnionDiagnostic[] = [];\n const order = new Map(errors.map((error, index) => [error, index]));\n const independent = unconditionalErrorSites(input.schema, input.arguments, errors);\n const uncertainByPath = indexByPath(independent.uncertain, (entry) => entry.instancePath, false);\n const ownershipUncertain = (error: ErrorObject) =>\n !independent.sites.has(errorSite(error.schemaPath, error.instancePath)) &&\n pathAncestors(error.instancePath).some((path) =>\n (uncertainByPath.get(path) ?? []).some(\n (entry) =>\n error.schemaPath === entry.prefix || error.schemaPath.startsWith(`${entry.prefix}/`),\n ),\n );\n const belongs = (error: ErrorObject, union: ErrorObject, prefixes: readonly string[]) =>\n order.get(error)! < order.get(union)! &&\n !independent.sites.has(errorSite(error.schemaPath, error.instancePath)) &&\n !ownershipUncertain(error) &&\n belongsToBranch(error, union, prefixes);\n for (const error of errors) {\n if (error.keyword !== \"anyOf\" && error.keyword !== \"oneOf\") continue;\n const site = errorSite(error.schemaPath, error.instancePath);\n const alternatives = independent.ambiguous.has(site)\n ? undefined\n : independent.schemas.has(site)\n ? independent.schemas.get(site)\n : schemaAt(input.schema, error.schemaPath);\n if (\n !Array.isArray(alternatives) ||\n alternatives.some((branch) => !isSchema(branch) && typeof branch !== \"boolean\")\n ) {\n unions.push({\n error,\n branchPrefixes: [],\n selected: undefined,\n unresolved: true,\n replacement: {\n path: displayPath(pointerSegments(error.instancePath)),\n keyword: error.keyword,\n message: `${describe(displayPath(pointerSegments(error.instancePath)))} must match ${error.keyword === \"oneOf\" ? \"exactly one\" : \"one\"} declared alternative input format`,\n },\n });\n continue;\n }\n const branches = alternatives as (JsonSchema | boolean)[];\n const branchPrefixes = branches.map((branch, index) =>\n isSchema(branch)\n ? schemaPrefixes(branch, `${error.schemaPath}/${index}`, input.schema)\n : [`${error.schemaPath}/${index}`],\n );\n const constraints = branches.map((branch) =>\n isSchema(branch) ? literalConstraints(branch, input.schema) : [],\n );\n const at = argumentAt(input.arguments, pointerSegments(error.instancePath));\n const compatible = constraints.flatMap((branch, index) =>\n branches[index] === false ||\n branch.some((constraint) => {\n const supplied = argumentAt(at.value, constraint.path);\n return supplied.present && !constraint.values.some((value) => value === supplied.value);\n })\n ? []\n : [index],\n );\n const selected =\n compatible.length === 1 && compatible.length < branches.length ? compatible[0] : undefined;\n let replacement: ToolGatewayInputIssue | undefined;\n if (selected === undefined) {\n const common = constraints[0]?.find((constraint) =>\n constraints.every((branch) =>\n branch.some((other) => samePath(other.path, constraint.path)),\n ),\n );\n const supplied = common && argumentAt(at.value, common.path);\n const commonConstraints =\n common &&\n constraints.map(\n (branch) => branch.find((constraint) => samePath(constraint.path, common.path))!,\n );\n const allowed = commonConstraints?.flatMap((constraint) => constraint.values);\n const uniqueAllowed = allowed && [...new Set(allowed)];\n if (\n common &&\n supplied &&\n commonConstraints &&\n uniqueAllowed?.length &&\n ((supplied.present && !uniqueAllowed.some((value) => value === supplied.value)) ||\n (!supplied.present && commonConstraints.every((constraint) => constraint.required)))\n ) {\n const path = displayPath([...pointerSegments(error.instancePath), ...common.path]);\n const allowedText = allowedValuesText(uniqueAllowed);\n const missing =\n !supplied.present && commonConstraints.every((constraint) => constraint.required);\n replacement = {\n path,\n keyword: missing ? \"required\" : error.keyword,\n message: missing\n ? `missing required property \"${path}\" (selects one of ${allowedText})`\n : `${describe(path)} must be one of ${allowedText}`,\n };\n }\n }\n\n unions.push({ error, branchPrefixes, selected, replacement });\n }\n const replacements = new Map<UnionDiagnostic, ToolGatewayInputIssue>();\n const errorsWithin = indexByPath(errors, (error) => error.instancePath, true);\n const unionsWithin = indexByPath(unions, (union) => union.error.instancePath, true);\n const scopeIndexes = new WeakMap<readonly UnionDiagnostic[], Map<string, UnionDiagnostic[]>>();\n const project = (\n error: ErrorObject,\n scope: readonly UnionDiagnostic[],\n ): ToolGatewayInputIssue[] => {\n let scopeIndex = scopeIndexes.get(scope);\n if (!scopeIndex) {\n scopeIndex = indexByPath(scope, (union) => union.error.instancePath, false);\n scopeIndexes.set(scope, scopeIndex);\n }\n const applicable = pathAncestors(error.instancePath).flatMap(\n (path) => scopeIndex.get(path) ?? [],\n );\n for (const union of applicable) {\n if (error === union.error) continue;\n if (\n union.unresolved &&\n order.get(error)! < order.get(union.error)! &&\n !independent.sites.has(errorSite(error.schemaPath, error.instancePath)) &&\n !ownershipUncertain(error) &&\n (error.instancePath === union.error.instancePath ||\n error.instancePath.startsWith(`${union.error.instancePath}/`))\n )\n return [];\n const matchingBranches = union.branchPrefixes.flatMap((prefixes, index) =>\n belongs(error, union.error, prefixes) ? [index] : [],\n );\n if (\n matchingBranches.length &&\n (union.selected === undefined || !matchingBranches.includes(union.selected))\n )\n return [];\n }\n const union = applicable.find((candidate) => candidate.error === error);\n if (!union) {\n const issue = issueFromError(error);\n return [\n ownershipUncertain(error)\n ? {\n ...issue,\n message: `an independent constraint or alternative reports: ${issue.message}`,\n }\n : issue,\n ];\n }\n if (union.selected !== undefined) return [];\n if (union.replacement) return [union.replacement];\n const cached = replacements.get(union);\n if (cached) return [cached];\n const alternatives = union.branchPrefixes\n .slice(0, ALLOWED_VALUES_MAX)\n .map((prefixes, index) => {\n const nested = (unionsWithin.get(union.error.instancePath) ?? []).filter(\n (candidate) =>\n order.get(candidate.error)! < order.get(union.error)! &&\n belongs(candidate.error, union.error, prefixes),\n );\n const details = (errorsWithin.get(union.error.instancePath) ?? [])\n .filter(\n (candidate) => candidate !== union.error && belongs(candidate, union.error, prefixes),\n )\n .flatMap((candidate) => project(candidate, nested))\n .map((issue) => issue.message);\n const distinct = [...new Set(details)];\n const shown = distinct.slice(0, 2);\n if (distinct.length > shown.length) shown.push(\"other declared requirements\");\n return `alternative ${index + 1}${shown.length ? ` (${shown.join(\"; \")})` : \"\"}`;\n });\n if (union.branchPrefixes.length > ALLOWED_VALUES_MAX)\n alternatives.push(\"other declared alternatives\");\n const issue = {\n path: displayPath(pointerSegments(error.instancePath)),\n keyword: error.keyword,\n message: bounded(\n `${describe(displayPath(pointerSegments(error.instancePath)))} must match ${\n error.keyword === \"oneOf\" ? \"exactly one\" : \"one\"\n } declared input format: ${alternatives.join(\" or \")}`,\n 640,\n ),\n };\n replacements.set(union, issue);\n return [issue];\n };\n return errors.flatMap((error) => project(error, unions));\n}\n\n/** Index instances once so many array-item unions never scan one another's errors. */\nfunction indexByPath<T>(\n values: readonly T[],\n pathOf: (value: T) => string,\n includeDescendants: boolean,\n): Map<string, T[]> {\n const index = new Map<string, T[]>();\n for (const value of values) {\n const paths = includeDescendants ? pathAncestors(pathOf(value)) : [pathOf(value)];\n for (const path of paths) {\n const group = index.get(path);\n if (group) group.push(value);\n else index.set(path, [value]);\n }\n }\n return index;\n}\n\nfunction pathAncestors(path: string): string[] {\n const ancestors = [path];\n let parent = path;\n while (parent) {\n parent = parent.slice(0, parent.lastIndexOf(\"/\"));\n ancestors.push(parent);\n }\n return ancestors;\n}\n\nfunction belongsToBranch(\n error: ErrorObject,\n union: ErrorObject,\n prefixes: readonly string[],\n): boolean {\n return (\n (error.instancePath === union.instancePath ||\n error.instancePath.startsWith(`${union.instancePath}/`)) &&\n prefixes.some(\n (prefix) => error.schemaPath === prefix || error.schemaPath.startsWith(`${prefix}/`),\n )\n );\n}\n\nfunction isSchema(value: unknown): value is JsonSchema {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nconst schemaReferenceIndexes = new WeakMap<JsonSchema, Map<string, JsonSchema>>();\nconst schemaReferenceBases = new WeakMap<JsonSchema, WeakMap<JsonSchema, string>>();\nconst schemaReferenceLocals = new WeakMap<JsonSchema, WeakMap<JsonSchema, string>>();\n\n/** Resolve local pointers, anchors and identifiers declared inside this schema. */\nfunction schemaAt(root: JsonSchema, pointer: string, context?: JsonSchema): unknown {\n let index = schemaReferenceIndexes.get(root);\n if (!index) {\n index = new Map([[\"#\", root]]);\n const ambiguous = new Set<string>();\n const bases = new WeakMap<JsonSchema, string>();\n const locals = new WeakMap<JsonSchema, string>();\n const active = new Set<JsonSchema>();\n const register = (name: string, schema: JsonSchema) => {\n if (ambiguous.has(name)) return;\n const previous = index!.get(name);\n if (previous && previous !== schema) {\n index!.delete(name);\n ambiguous.add(name);\n } else index!.set(name, schema);\n };\n const visit = (schema: JsonSchema, path: string, inheritedId: string, localPath: string) => {\n if (active.has(schema)) return;\n active.add(schema);\n register(path, schema);\n let id = inheritedId;\n if (typeof schema.$id === \"string\") {\n id = schema.$id;\n try {\n if (inheritedId) id = new URL(id, inheritedId).href;\n } catch {\n /* Non-URL identifiers remain exact aliases. */\n }\n register(id, schema);\n register(`${id}#`, schema);\n localPath = \"#\";\n }\n bases.set(schema, id);\n locals.set(schema, localPath);\n if (typeof schema.$anchor === \"string\") {\n register(`#${schema.$anchor}`, schema);\n if (id) register(`${id}#${schema.$anchor}`, schema);\n }\n for (const [suffix, child] of schemaChildren(schema))\n visit(child, `${path}/${suffix}`, id, `${localPath}/${suffix}`);\n active.delete(schema);\n };\n visit(root, \"#\", \"\", \"#\");\n schemaReferenceIndexes.set(root, index);\n schemaReferenceBases.set(root, bases);\n schemaReferenceLocals.set(root, locals);\n }\n const base = context && schemaReferenceBases.get(root)?.get(context);\n if (base) {\n if (pointer.startsWith(\"#\")) pointer = `${base}${pointer}`;\n else\n try {\n pointer = new URL(pointer, base).href;\n } catch {\n /* Exact aliases remain available. */\n }\n }\n const exact = index.get(pointer);\n if (exact) return exact;\n // AJV appends keyword paths to the reference it followed, including anchors.\n let separator = pointer.lastIndexOf(\"/\");\n while (separator >= 0) {\n const target = index.get(pointer.slice(0, separator));\n if (target) {\n let value: unknown = target;\n for (const segment of pointerSegments(pointer.slice(separator))) {\n if (!value || typeof value !== \"object\") return undefined;\n value = (value as Record<string, unknown>)[segment];\n }\n return value;\n }\n separator = separator === 0 ? -1 : pointer.lastIndexOf(\"/\", separator - 1);\n }\n return undefined;\n}\n\nfunction schemaChildren(schema: JsonSchema): [string, JsonSchema][] {\n const children: [string, JsonSchema][] = [];\n for (const keyword of [\n \"$defs\",\n \"definitions\",\n \"properties\",\n \"patternProperties\",\n \"dependentSchemas\",\n \"dependencies\",\n ]) {\n const values = schema[keyword];\n if (isSchema(values))\n for (const [name, child] of Object.entries(values))\n if (isSchema(child)) children.push([`${keyword}/${pointerSegment(name)}`, child]);\n }\n for (const keyword of [\"anyOf\", \"oneOf\", \"allOf\", \"prefixItems\", \"items\"]) {\n const values = schema[keyword];\n if (Array.isArray(values))\n values.forEach((child, index) => {\n if (isSchema(child)) children.push([`${keyword}/${index}`, child]);\n });\n }\n for (const keyword of [\n \"items\",\n \"additionalItems\",\n \"additionalProperties\",\n \"unevaluatedProperties\",\n \"not\",\n \"if\",\n \"then\",\n \"else\",\n \"contains\",\n \"propertyNames\",\n ]) {\n const child = schema[keyword];\n if (isSchema(child)) children.push([keyword, child]);\n }\n return children;\n}\n\nfunction pointerSegment(value: string): string {\n return value.replace(/~/gu, \"~0\").replace(/\\//gu, \"~1\");\n}\n\nfunction errorSite(schemaPath: string, instancePath: string): string {\n return JSON.stringify([schemaPath, instancePath]);\n}\n\n/**\n * Shared references erase their source location in AJV errors. Preserve failures\n * reached independently of alternatives, even when the same referenced schema\n * also occurs in a later branch. Only conjunctions, supplied properties/items,\n * and uniquely selected literal tags mark sites as independent. Other branches\n * are indexed for resource-scoped lookup without marking them independent.\n */\nfunction unconditionalErrorSites(\n root: JsonSchema,\n args: Record<string, unknown>,\n errors: readonly ErrorObject[],\n): {\n sites: Set<string>;\n schemas: Map<string, unknown>;\n ambiguous: Set<string>;\n uncertain: { prefix: string; instancePath: string }[];\n} {\n const sites = new Set<string>();\n const schemaSites = new Map<string, unknown>();\n const uncertain: { prefix: string; instancePath: string }[] = [];\n const ambiguous = new Set<string>();\n const conditionalBranches = new Map(\n errors\n .filter((error) => error.keyword === \"if\")\n .map((error) => [\n errorSite(error.schemaPath, error.instancePath),\n error.params.failingKeyword,\n ]),\n );\n const active = new Set<string>();\n const schemas = new WeakMap<JsonSchema, number>();\n let schemaId = 0;\n const visit = (\n schema: JsonSchema,\n schemaPath: string,\n value: unknown,\n instancePath: string,\n independent: boolean,\n ) => {\n let id = schemas.get(schema);\n if (id === undefined) {\n id = schemaId++;\n schemas.set(schema, id);\n }\n const key = JSON.stringify([id, schemaPath, instancePath, independent]);\n if (active.has(key)) return;\n active.add(key);\n const base = schemaReferenceBases.get(root)?.get(schema);\n const local = base && schemaReferenceLocals.get(root)?.get(schema);\n const aliases = [...new Set([schemaPath, ...(local ? [local, `${base}${local}`] : [])])];\n for (const alias of aliases)\n for (const [keyword, child] of Object.entries(schema)) {\n const site = errorSite(`${alias}/${keyword}`, instancePath);\n if (independent) sites.add(site);\n if (ambiguous.has(site)) continue;\n if (schemaSites.has(site) && schemaSites.get(site) !== child) {\n schemaSites.delete(site);\n ambiguous.add(site);\n } else schemaSites.set(site, child);\n }\n if (typeof schema.$ref === \"string\") {\n const target = schemaAt(root, schema.$ref, schema);\n if (isSchema(target)) visit(target, schema.$ref, value, instancePath, independent);\n }\n if (Array.isArray(schema.allOf))\n schema.allOf.forEach((child, index) => {\n if (isSchema(child))\n visit(child, `${schemaPath}/allOf/${index}`, value, instancePath, independent);\n });\n for (const keyword of [\"anyOf\", \"oneOf\"]) {\n const alternatives = schema[keyword];\n if (!Array.isArray(alternatives)) continue;\n const compatible = alternatives.flatMap((branch, index) => {\n if (branch === false) return [];\n if (!isSchema(branch)) return [index];\n return literalConstraints(branch, root).some((constraint) => {\n const supplied = argumentAt(value, constraint.path);\n return supplied.present && !constraint.values.includes(supplied.value);\n })\n ? []\n : [index];\n });\n const selected =\n compatible.length === 1 && compatible.length < alternatives.length\n ? compatible[0]\n : undefined;\n alternatives.forEach((child, index) => {\n if (isSchema(child))\n visit(\n child,\n `${schemaPath}/${keyword}/${index}`,\n value,\n instancePath,\n independent && index === selected,\n );\n });\n }\n\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n if (isSchema(schema.properties))\n for (const [name, child] of Object.entries(schema.properties)) {\n if (isSchema(child) && Object.hasOwn(value, name))\n visit(\n child,\n `${schemaPath}/properties/${pointerSegment(name)}`,\n (value as Record<string, unknown>)[name],\n `${instancePath}/${pointerSegment(name)}`,\n independent,\n );\n }\n if (isSchema(schema.dependentSchemas))\n for (const [name, child] of Object.entries(schema.dependentSchemas)) {\n if (isSchema(child) && Object.hasOwn(value, name))\n visit(\n child,\n `${schemaPath}/dependentSchemas/${pointerSegment(name)}`,\n value,\n instancePath,\n independent,\n );\n }\n }\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n const declared = isSchema(schema.properties) ? schema.properties : {};\n const patterns = isSchema(schema.patternProperties)\n ? Object.entries(schema.patternProperties).map(\n ([pattern, child]) => [pattern, new RegExp(pattern, \"u\"), child] as const,\n )\n : [];\n for (const [name, childValue] of Object.entries(value)) {\n let matched = false;\n for (const [pattern, regexp, child] of patterns) {\n if (regexp.test(name)) {\n matched = true;\n if (isSchema(child))\n visit(\n child,\n `${schemaPath}/patternProperties/${pointerSegment(pattern)}`,\n childValue,\n `${instancePath}/${pointerSegment(name)}`,\n independent,\n );\n }\n }\n if (!Object.hasOwn(declared, name) && !matched && isSchema(schema.additionalProperties))\n visit(\n schema.additionalProperties,\n `${schemaPath}/additionalProperties`,\n childValue,\n `${instancePath}/${pointerSegment(name)}`,\n independent,\n );\n }\n if (isSchema(schema.dependencies))\n for (const [name, child] of Object.entries(schema.dependencies)) {\n if (isSchema(child) && Object.hasOwn(value, name))\n visit(\n child,\n `${schemaPath}/dependencies/${pointerSegment(name)}`,\n value,\n instancePath,\n independent,\n );\n }\n }\n if (Array.isArray(value)) {\n const tuple = Array.isArray(schema.prefixItems)\n ? schema.prefixItems\n : Array.isArray(schema.items)\n ? schema.items\n : [];\n const tupleKeyword = Array.isArray(schema.prefixItems) ? \"prefixItems\" : \"items\";\n value.forEach((item, index) => {\n const child =\n tuple[index] ?? (isSchema(schema.items) ? schema.items : schema.additionalItems);\n if (isSchema(child))\n visit(\n child,\n tuple[index]\n ? `${schemaPath}/${tupleKeyword}/${index}`\n : `${schemaPath}/${isSchema(schema.items) ? \"items\" : \"additionalItems\"}`,\n item,\n `${instancePath}/${index}`,\n independent,\n );\n });\n }\n // These applicators have existential or annotation semantics. A reused\n // reference cannot prove branch ownership here, so retain its failures as\n // explicitly ambiguous constraint evidence rather than suppressing them.\n for (const keyword of [\n \"contains\",\n \"propertyNames\",\n \"unevaluatedProperties\",\n \"unevaluatedItems\",\n ]) {\n const child = schema[keyword];\n if (isSchema(child))\n for (const prefix of schemaPrefixes(child, `${schemaPath}/${keyword}`, root).slice(1))\n uncertain.push({ prefix, instancePath });\n }\n // Failed conditionals name the branch AJV actually evaluated.\n const branch = conditionalBranches.get(errorSite(`${schemaPath}/if`, instancePath));\n if ((branch === \"then\" || branch === \"else\") && isSchema(schema[branch]))\n visit(schema[branch], `${schemaPath}/${branch}`, value, instancePath, independent);\n active.delete(key);\n };\n schemaAt(root, \"#\"); // Initialize resource scopes before recording any sites.\n visit(root, \"#\", args, \"\", true);\n return { sites, schemas: schemaSites, ambiguous, uncertain };\n}\n\nfunction schemaPrefixes(schema: JsonSchema, pointer: string, root: JsonSchema): string[] {\n const prefixes = [pointer];\n const seen = new Set<JsonSchema>();\n const visit = (value: JsonSchema) => {\n if (seen.has(value)) return;\n seen.add(value);\n if (typeof value.$ref === \"string\") {\n const target = schemaAt(root, value.$ref, value);\n if (isSchema(target)) {\n prefixes.push(value.$ref);\n visit(target);\n }\n }\n // References below a branch have schema paths outside its path prefix.\n for (const keyword of [\"properties\", \"patternProperties\", \"dependentSchemas\"]) {\n const children = value[keyword];\n if (isSchema(children))\n for (const child of Object.values(children)) if (isSchema(child)) visit(child);\n }\n for (const keyword of [\"anyOf\", \"oneOf\", \"allOf\", \"prefixItems\"]) {\n const children = value[keyword];\n if (Array.isArray(children)) for (const child of children) if (isSchema(child)) visit(child);\n }\n for (const keyword of [\n \"items\",\n \"additionalItems\",\n \"additionalProperties\",\n \"unevaluatedProperties\",\n \"not\",\n \"if\",\n \"then\",\n \"else\",\n \"contains\",\n \"propertyNames\",\n ]) {\n const child = value[keyword];\n if (isSchema(child)) visit(child);\n else if (keyword === \"items\" && Array.isArray(child))\n for (const entry of child) if (isSchema(entry)) visit(entry);\n }\n };\n visit(schema);\n return prefixes;\n}\n\nfunction literalConstraints(schema: JsonSchema, root: JsonSchema): LiteralConstraint[] {\n const constraints: LiteralConstraint[] = [];\n const active = new Set<JsonSchema>();\n const visit = (value: JsonSchema, path: readonly string[], required: boolean) => {\n if (active.has(value)) return;\n active.add(value);\n if (typeof value.$ref === \"string\") {\n const target = schemaAt(root, value.$ref, value);\n if (isSchema(target)) {\n visit(target, path, required);\n }\n }\n const literals = \"const\" in value ? [value.const] : Array.isArray(value.enum) ? value.enum : [];\n if (\n literals.length &&\n literals.every(\n (literal) => literal === null || [\"string\", \"number\", \"boolean\"].includes(typeof literal),\n )\n ) {\n constraints.push({ path, values: literals, required });\n }\n if (Array.isArray(value.allOf))\n for (const child of value.allOf) if (isSchema(child)) visit(child, path, required);\n if (isSchema(value.properties))\n for (const [key, child] of Object.entries(value.properties)) {\n if (isSchema(child))\n visit(\n child,\n [...path, key],\n required && Array.isArray(value.required) && value.required.includes(key),\n );\n }\n active.delete(value);\n };\n visit(schema, [], true);\n // Multiple conjunctions may constrain the same tag; all must hold.\n const combined: LiteralConstraint[] = [];\n for (const constraint of constraints) {\n const index = combined.findIndex((other) => samePath(other.path, constraint.path));\n if (index < 0) combined.push(constraint);\n else {\n const previous = combined[index]!;\n combined[index] = {\n path: constraint.path,\n values: previous.values.filter((value) => constraint.values.includes(value)),\n required: previous.required || constraint.required,\n };\n }\n }\n return combined;\n}\n\nfunction argumentAt(root: unknown, path: readonly string[]): { present: boolean; value: unknown } {\n let value = root;\n for (const segment of path) {\n if (value === null || typeof value !== \"object\" || !Object.hasOwn(value, segment))\n return { present: false, value: undefined };\n value = (value as Record<string, unknown>)[segment];\n }\n return { present: true, value };\n}\n\nfunction samePath(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((segment, index) => segment === right[index]);\n}\n\n/** One-line summary of issues, for example `missing required property \"context\"`. */\nexport function formatToolGatewayInputIssues(\n issues: readonly ToolGatewayInputIssue[],\n omittedIssueCount = 0,\n): string {\n const parts = issues.map((issue) => issue.message);\n if (omittedIssueCount > 0) {\n parts.push(`and ${omittedIssueCount} more ${omittedIssueCount === 1 ? \"problem\" : \"problems\"}`);\n }\n return parts.join(\"; \");\n}\n\nfunction issueFromError(error: ErrorObject): ToolGatewayInputIssue {\n const params = (error.params ?? {}) as Record<string, unknown>;\n const at = pointerSegments(error.instancePath);\n const subject = describe(displayPath(at));\n // A `propertyNames` subschema failure describes a key of the object at\n // `instancePath`, not the object itself; name the object, never the key.\n const keyword =\n (error as { propertyName?: unknown }).propertyName !== undefined\n ? \"propertyNames\"\n : error.keyword;\n switch (keyword) {\n case \"required\": {\n const path = displayPath([...at, String(params.missingProperty)]);\n return { path, keyword: error.keyword, message: `missing required property \"${path}\"` };\n }\n case \"dependentRequired\":\n case \"dependencies\": {\n const path = displayPath([...at, String(params.missingProperty)]);\n const trigger = displayPath([...at, String(params.property)]);\n return {\n path,\n keyword: error.keyword,\n message: `missing required property \"${path}\" (required when \"${trigger}\" is present)`,\n };\n }\n case \"additionalProperties\":\n case \"unevaluatedProperties\": {\n const name = params.additionalProperty ?? params.unevaluatedProperty;\n const path = displayPath([...at, String(name)]);\n return { path, keyword: error.keyword, message: `property \"${path}\" is not allowed` };\n }\n case \"type\": {\n const expected = Array.isArray(params.type) ? params.type.join(\" or \") : String(params.type);\n return {\n path: displayPath(at),\n keyword: error.keyword,\n message: `${subject} must be ${bounded(expected, MESSAGE_DETAIL_MAX_CHARS)}`,\n };\n }\n case \"enum\": {\n const allowed = Array.isArray(params.allowedValues)\n ? allowedValuesText(params.allowedValues)\n : null;\n return {\n path: displayPath(at),\n keyword: error.keyword,\n message: allowed\n ? `${subject} must be one of ${allowed}`\n : `${subject} must be one of the allowed values`,\n };\n }\n case \"const\":\n return {\n path: displayPath(at),\n keyword: error.keyword,\n message: `${subject} must equal ${schemaValueText(params.allowedValue)}`,\n };\n case \"propertyNames\":\n return {\n path: displayPath(at),\n keyword,\n message: `${subject} has a property name the schema does not allow`,\n };\n default:\n return {\n path: displayPath(at),\n keyword: bounded(error.keyword, 64),\n message: `${subject} ${bounded(cleanText(error.message ?? \"is invalid\"), MESSAGE_DETAIL_MAX_CHARS)}`,\n };\n }\n}\n\nfunction describe(path: string): string {\n return path ? `\"${path}\"` : \"arguments\";\n}\n\nfunction pointerSegments(pointer: string): string[] {\n if (!pointer) return [];\n return pointer\n .slice(1)\n .split(\"/\")\n .map((segment) => segment.replace(/~1/gu, \"/\").replace(/~0/gu, \"~\"));\n}\n\n/**\n * Render JSON Pointer segments as `a.b[0].c`. A top-level name is shown as is;\n * an unusual nested name is bracket-quoted so the path stays unambiguous.\n */\nfunction displayPath(segments: readonly string[]): string {\n let path = \"\";\n for (const segment of segments) {\n if (/^(?:0|[1-9][0-9]*)$/u.test(segment)) path += `[${segment}]`;\n else if (!path) path = cleanText(segment);\n else if (/^[A-Za-z_$][A-Za-z0-9_$-]*$/u.test(segment)) path += `.${segment}`;\n else path += `[${JSON.stringify(segment)}]`;\n if (path.length > PATH_MAX_CHARS) break;\n }\n return bounded(path, PATH_MAX_CHARS);\n}\n\nfunction allowedValuesText(values: readonly unknown[]): string | null {\n if (values.length === 0) return null;\n const shown = values.slice(0, ALLOWED_VALUES_MAX).map(schemaValueText);\n if (values.length > ALLOWED_VALUES_MAX) shown.push(\"...\");\n return shown.join(\", \");\n}\n\nfunction schemaValueText(value: unknown): string {\n let text: string;\n try {\n text = JSON.stringify(value) ?? String(value);\n } catch {\n text = \"the schema constant\";\n }\n return bounded(cleanText(text), ALLOWED_VALUE_MAX_CHARS);\n}\n\nfunction cleanText(value: string): string {\n return value.replace(/[\\u0000-\\u001f\\u007f]+/gu, \" \").trim();\n}\n\nfunction bounded(value: string, max: number): string {\n return value.length <= max ? value : `${value.slice(0, max - 3)}...`;\n}\n","import { formatToolGatewayInputIssues, type ToolGatewayInputIssue } from \"./input-issues\";\n\nexport class ToolGatewayCatalogStaleError extends Error {\n readonly code = \"catalog_stale\";\n\n constructor() {\n super(\"Tool catalog is stale for the active gateway\");\n this.name = \"ToolGatewayCatalogStaleError\";\n }\n}\n\nexport class ToolGatewayToolNotFoundError extends Error {\n readonly code = \"tool_not_found\";\n\n constructor() {\n super(\"Tool is not present in the active gateway catalog\");\n this.name = \"ToolGatewayToolNotFoundError\";\n }\n}\n\nexport class ToolGatewayApprovalRequiredError extends Error {\n readonly code = \"approval_required\";\n\n constructor() {\n super(\"Tool requires human approval\");\n this.name = \"ToolGatewayApprovalRequiredError\";\n }\n}\n\nexport class ToolGatewayCatalogIntegrityError extends Error {\n readonly code = \"catalog_integrity_failed\";\n\n constructor() {\n super(\"Tool catalog digest does not match its authoritative content\");\n this.name = \"ToolGatewayCatalogIntegrityError\";\n }\n}\n\nexport class ToolGatewayCatalogTooLargeError extends Error {\n readonly code = \"catalog_too_large\";\n\n constructor() {\n super(\"Tool catalog exceeds the maximum serialized size\");\n this.name = \"ToolGatewayCatalogTooLargeError\";\n }\n}\n\nexport class ToolGatewayPathCollisionError extends Error {\n readonly code = \"tool_path_collision\";\n\n constructor(path: readonly string[], kind: \"collision\" | \"extends_leaf\") {\n super(\n kind === \"extends_leaf\"\n ? `Tool path ${path.join(\".\")} extends a tool leaf`\n : `Tool path ${path.join(\".\")} collides`,\n );\n this.name = \"ToolGatewayPathCollisionError\";\n }\n}\n\nexport class ToolGatewayInputValidationError extends Error {\n readonly code = \"invalid_tool_arguments\";\n /** Value-free problems, capped at `TOOL_GATEWAY_INPUT_ISSUES_MAX`. */\n readonly issues: readonly ToolGatewayInputIssue[];\n /** Distinct problems found beyond the reported cap. */\n readonly omittedIssueCount: number;\n /** One-line summary of `issues`, or an empty string when none were captured. */\n readonly summary: string;\n\n constructor(issues: readonly ToolGatewayInputIssue[] = [], omittedIssueCount = 0) {\n const summary = formatToolGatewayInputIssues(issues, omittedIssueCount);\n super(\n summary\n ? `Tool arguments do not match the tool's input schema: ${summary}`\n : \"Tool arguments do not match the tool's input schema\",\n );\n this.name = \"ToolGatewayInputValidationError\";\n this.issues = issues;\n this.omittedIssueCount = omittedIssueCount;\n this.summary = summary;\n }\n}\n\nexport class ToolGatewayOutputValidationError extends Error {\n readonly code = \"invalid_tool_result\";\n\n constructor() {\n super(\"Tool result does not match the gateway catalog output schema\");\n this.name = \"ToolGatewayOutputValidationError\";\n }\n}\n","import type { ToolGatewayCatalogEntry } from \"@opengeni/contracts\";\nimport { compareCanonicalStrings, parseVerifiedToolGatewayCatalog } from \"./catalog\";\nimport { ToolGatewayPathCollisionError } from \"./errors\";\n\nexport type GenerateToolGatewayDeclarationsOptions = {\n moduleSpecifier?: string;\n interfaceName?: string;\n};\n\ntype NamespaceNode = {\n children: Map<string, NamespaceNode>;\n entry: ToolGatewayCatalogEntry | null;\n};\n\n/** Generate declaration merging for one exact digest-pinned workspace catalog. */\nexport function generateToolGatewayDeclarations(\n catalog: Parameters<typeof parseVerifiedToolGatewayCatalog>[0],\n options: GenerateToolGatewayDeclarationsOptions = {},\n): string {\n const verified = parseVerifiedToolGatewayCatalog(catalog);\n return generateToolDeclarations(\n { digest: verified.digest, entries: verified.entries },\n {\n moduleSpecifier: options.moduleSpecifier ?? \"@opengeni/sdk\",\n interfaceName: options.interfaceName ?? \"OpenGeniGeneratedTools\",\n callOptionsType: \"OpenGeniToolCallOptions\",\n fallbackResultType: \"ToolGatewayResult\",\n generatedBy: \"@opengeni/tool-gateway\",\n catalogDigestLabel: \"Tool catalog digest\",\n },\n );\n}\n\nexport function generateToolDeclarations(\n catalog: { digest: string; entries: readonly ToolGatewayCatalogEntry[] },\n options: {\n moduleSpecifier: string;\n interfaceName: string;\n callOptionsType: string;\n fallbackResultType: string;\n /** Optional runtime wrapper for typed results carrying out-of-band image blocks. */\n typedResultWrapperType?: string;\n generatedBy: string;\n catalogDigestLabel?: string;\n },\n): string {\n const root = namespaceNode();\n for (const entry of catalog.entries) insertEntry(root, entry);\n return [\n `// Generated by ${options.generatedBy}. Do not edit.`,\n `// ${options.catalogDigestLabel ?? \"Tool catalog digest\"}: ${catalog.digest}`,\n ...(options.typedResultWrapperType\n ? [\n \"// Typed calls normally return their structured output. If image blocks are present,\",\n \"// they return CodemodeMultimodalValue<T> with local image paths and original content.\",\n ]\n : []),\n `import type { ${[\n options.callOptionsType,\n options.fallbackResultType,\n ...(options.typedResultWrapperType ? [options.typedResultWrapperType] : []),\n ].join(\", \")} } from ${JSON.stringify(options.moduleSpecifier)};`,\n \"\",\n `declare module ${JSON.stringify(options.moduleSpecifier)} {`,\n ` interface ${options.interfaceName} {`,\n ...renderChildren(root, 4, options),\n \" }\",\n \"}\",\n \"\",\n \"export {};\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Honest bounded JSON-Schema-to-TypeScript projection for generated declarations. */\nexport function jsonSchemaToTypeScript(schema: unknown): string {\n return schemaType(schema, schema, new Set(), 0);\n}\n\nfunction namespaceNode(): NamespaceNode {\n return { children: new Map(), entry: null };\n}\n\nfunction insertEntry(root: NamespaceNode, entry: ToolGatewayCatalogEntry): void {\n let node = root;\n for (const [index, segment] of entry.codemodePath.entries()) {\n if (node.entry) {\n throw new ToolGatewayPathCollisionError(entry.codemodePath, \"extends_leaf\");\n }\n let child = node.children.get(segment);\n if (!child) {\n child = namespaceNode();\n node.children.set(segment, child);\n }\n node = child;\n if (index === entry.codemodePath.length - 1) {\n if (node.entry || node.children.size > 0) {\n throw new ToolGatewayPathCollisionError(entry.codemodePath, \"collision\");\n }\n node.entry = entry;\n }\n }\n}\n\nfunction renderChildren(\n node: NamespaceNode,\n indent: number,\n options: Parameters<typeof generateToolDeclarations>[1],\n): string[] {\n const lines: string[] = [];\n for (const [name, child] of [...node.children].sort(([left], [right]) =>\n compareCanonicalStrings(left, right),\n )) {\n if (child.entry) {\n const entry = child.entry;\n const input = jsonSchemaToTypeScript(entry.inputSchema);\n const structuredOutput = entry.outputSchema\n ? jsonSchemaToTypeScript(entry.outputSchema)\n : null;\n const output = structuredOutput\n ? options.typedResultWrapperType\n ? `${structuredOutput} | ${options.typedResultWrapperType}<${structuredOutput}>`\n : structuredOutput\n : options.fallbackResultType;\n const description = boundedDoc(entry.description ?? entry.title);\n if (description) lines.push(...renderDoc(description, indent));\n lines.push(`${spaces(indent)}readonly ${name}: (`);\n lines.push(\n `${spaces(indent + 2)}argumentsValue${rootObjectArgumentsAreOptional(entry.inputSchema) ? \"?\" : \"\"}: ${input},`,\n );\n lines.push(`${spaces(indent + 2)}options?: ${options.callOptionsType},`);\n lines.push(`${spaces(indent)}) => Promise<${output}>;`);\n continue;\n }\n lines.push(`${spaces(indent)}readonly ${name}: {`);\n lines.push(...renderChildren(child, indent + 2, options));\n lines.push(`${spaces(indent)}};`);\n }\n return lines;\n}\n\nfunction rootObjectArgumentsAreOptional(schema: unknown): boolean {\n if (!isObject(schema)) return false;\n const required = Array.isArray(schema.required)\n ? schema.required.filter((value): value is string => typeof value === \"string\")\n : [];\n return required.length === 0 && (schema.type === \"object\" || isObject(schema.properties));\n}\n\nfunction schemaType(schema: unknown, root: unknown, resolving: Set<string>, depth: number): string {\n if (depth > 48 || schema === true) return \"unknown\";\n if (schema === false) return \"never\";\n if (!isObject(schema)) return \"unknown\";\n if (typeof schema.$ref === \"string\") {\n if (!schema.$ref.startsWith(\"#/\") || resolving.has(schema.$ref)) return \"unknown\";\n const resolved = resolveLocalReference(root, schema.$ref);\n if (resolved === undefined) return \"unknown\";\n const next = new Set(resolving);\n next.add(schema.$ref);\n return schemaType(resolved, root, next, depth + 1);\n }\n if (Object.hasOwn(schema, \"const\")) return literalType(schema.const);\n if (Array.isArray(schema.enum)) return union(schema.enum.map(literalType));\n const composites: string[] = [];\n if (Array.isArray(schema.oneOf)) {\n composites.push(\n union(schema.oneOf.map((part) => schemaType(part, root, resolving, depth + 1))),\n );\n }\n if (Array.isArray(schema.anyOf)) {\n composites.push(\n union(schema.anyOf.map((part) => schemaType(part, root, resolving, depth + 1))),\n );\n }\n if (Array.isArray(schema.allOf)) {\n composites.push(\n intersection(schema.allOf.map((part) => schemaType(part, root, resolving, depth + 1))),\n );\n }\n if (composites.length > 0) {\n const composed = intersection(composites);\n return schema.nullable === true ? union([composed, \"null\"]) : composed;\n }\n const types = Array.isArray(schema.type)\n ? schema.type.filter((value): value is string => typeof value === \"string\")\n : typeof schema.type === \"string\"\n ? [schema.type]\n : inferredTypes(schema);\n const rendered = types.map((type) => typeType(type, schema, root, resolving, depth + 1));\n if (schema.nullable === true) rendered.push(\"null\");\n return union(rendered.length > 0 ? rendered : [\"unknown\"]);\n}\n\nfunction typeType(\n type: string,\n schema: Record<string, unknown>,\n root: unknown,\n resolving: Set<string>,\n depth: number,\n): string {\n if (type === \"null\" || type === \"boolean\" || type === \"string\") return type;\n if (type === \"integer\" || type === \"number\") return \"number\";\n if (type === \"array\") return arrayType(schema, root, resolving, depth);\n if (type !== \"object\") return \"unknown\";\n return objectType(schema, root, resolving, depth);\n}\n\nfunction arrayType(\n schema: Record<string, unknown>,\n root: unknown,\n resolving: Set<string>,\n depth: number,\n): string {\n if (Array.isArray(schema.prefixItems)) {\n const tuple = schema.prefixItems.map((item) => schemaType(item, root, resolving, depth + 1));\n if (schema.items === false) return `readonly [${tuple.join(\", \")}]`;\n const rest =\n schema.items === undefined || schema.items === true\n ? \"unknown\"\n : schemaType(schema.items, root, resolving, depth + 1);\n return `readonly [${tuple.join(\", \")}${tuple.length > 0 ? \", \" : \"\"}...${rest}[]]`;\n }\n const item =\n schema.items === undefined || schema.items === true\n ? \"unknown\"\n : schemaType(schema.items, root, resolving, depth + 1);\n return `readonly (${item})[]`;\n}\n\nfunction objectType(\n schema: Record<string, unknown>,\n root: unknown,\n resolving: Set<string>,\n depth: number,\n): string {\n const properties = isObject(schema.properties) ? schema.properties : {};\n const required = new Set(\n Array.isArray(schema.required)\n ? schema.required.filter((value): value is string => typeof value === \"string\")\n : [],\n );\n const entries = Object.entries(properties).sort(([left], [right]) =>\n compareCanonicalStrings(left, right),\n );\n const fields = entries.map(\n ([name, value]) =>\n `readonly ${identifierOrQuoted(name)}${required.has(name) ? \"\" : \"?\"}: ${schemaType(value, root, resolving, depth + 1)}`,\n );\n for (const missing of [...required]\n .filter((name) => !Object.hasOwn(properties, name))\n .sort(compareCanonicalStrings)) {\n fields.push(`readonly ${identifierOrQuoted(missing)}: unknown`);\n }\n if (schema.additionalProperties !== false) {\n if (\n entries.length === 0 &&\n schema.additionalProperties !== undefined &&\n schema.additionalProperties !== true\n ) {\n return `Readonly<Record<string, ${schemaType(\n schema.additionalProperties,\n root,\n resolving,\n depth + 1,\n )}>>`;\n }\n fields.push(\"readonly [key: string]: unknown\");\n }\n return fields.length === 0 ? \"Record<string, never>\" : `{ ${fields.join(\"; \")} }`;\n}\n\nfunction inferredTypes(schema: Record<string, unknown>): string[] {\n if (isObject(schema.properties) || Object.hasOwn(schema, \"additionalProperties\")) {\n return [\"object\"];\n }\n if (Object.hasOwn(schema, \"items\") || Array.isArray(schema.prefixItems)) return [\"array\"];\n return [];\n}\n\nfunction resolveLocalReference(root: unknown, reference: string): unknown {\n let current = root;\n for (const encoded of reference.slice(2).split(\"/\")) {\n if (!isObject(current)) return undefined;\n const segment = encoded.replace(/~1/gu, \"/\").replace(/~0/gu, \"~\");\n if (!Object.hasOwn(current, segment)) return undefined;\n current = current[segment];\n }\n return current;\n}\n\nfunction literalType(value: unknown): string {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) return `readonly [${value.map(literalType).join(\", \")}]`;\n if (isObject(value)) {\n return `{ ${Object.entries(value)\n .sort(([left], [right]) => compareCanonicalStrings(left, right))\n .map(([key, child]) => `readonly ${identifierOrQuoted(key)}: ${literalType(child)}`)\n .join(\"; \")} }`;\n }\n return \"unknown\";\n}\n\nfunction union(values: string[]): string {\n const unique = [...new Set(values)];\n if (unique.includes(\"unknown\")) return \"unknown\";\n if (unique.length === 0) return \"never\";\n return unique.length === 1 ? unique[0]! : unique.map(parenthesizeComposite).join(\" | \");\n}\n\nfunction intersection(values: string[]): string {\n const unique = [...new Set(values.filter((value) => value !== \"unknown\"))];\n return unique.length === 0\n ? \"unknown\"\n : unique.length === 1\n ? unique[0]!\n : unique.map(parenthesizeComposite).join(\" & \");\n}\n\nfunction parenthesizeComposite(value: string): string {\n return /[|&]/u.test(value) ? `(${value})` : value;\n}\n\nfunction identifierOrQuoted(value: string): string {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(value) ? value : JSON.stringify(value);\n}\n\nfunction boundedDoc(value: string | undefined): string | null {\n if (!value) return null;\n const normalized = value.replace(/\\s+/gu, \" \").trim().replace(/\\*\\//gu, \"*\\\\/\");\n if (!normalized) return null;\n return normalized.length <= 512 ? normalized : `${normalized.slice(0, 509)}...`;\n}\n\nfunction renderDoc(value: string, indent: number): string[] {\n return [`${spaces(indent)}/** ${value} */`];\n}\n\nfunction spaces(count: number): string {\n return \" \".repeat(count);\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n"],"mappings":";AAAA,SAAS,cAAAA,aAAY,kBAAkB;AACvC,SAAS,kBAAkB,qBAAqB,uBAAuB;AACvE,OAAO;AAAA,EACL;AAAA,EACA;AAAA,OAIK;AACP,OAAO,aAAa;AACpB,OAAO,aAAa;AACpB;AAAA,EACE;AAAA,EACA;AAAA,EACA,sBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;;;ACvBP,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,OAEK;;;ACkBA,IAAM,gCAAgC;AAE7C,IAAM,iBAAiB;AACvB,IAAM,2BAA2B;AACjC,IAAM,qBAAqB;AAC3B,IAAM,0BAA0B;AASzB,SAAS,gCACd,QACA,OAC8B;AAC9B,QAAM,SAAkC,CAAC;AACzC,QAAM,OAAO,oBAAI,IAAY;AAC7B,MAAI,oBAAoB;AACxB,MAA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aAAa,aAAa,EAAE,SAAS,UAAU,GAAG;AAClE,iBAAa,IAAI,UAAU;AAAA,EAC7B;AACA,SAAO,WAAW,MAAM,GAAG,GAAG,KAAK;AACrC;AAEA,SAAS,oBAAoB,UAAuC;AAClE,SAAOC,YAAW,QAAQ,EAAE,OAAO,YAAY,QAAQ,GAAG,MAAM,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,EAAE;AAC7F;AAEA,SAAS,YAAY,UAAuC;AAC1D,SAAO,GAAG,SAAS,QAAQ,KAAS,SAAS,QAAQ;AACvD;","names":["createHash","ToolGatewayCatalog","union","issue","branch","item","ToolGatewayCatalog","createHash"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/catalog.ts","../src/input-issues.ts","../src/errors.ts","../src/declarations.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { bindMcpTelemetry, withMcpCallIdentity, measureMcpPhase } from \"@opengeni/observability\";\nimport Ajv, {\n _,\n str,\n type CodeKeywordDefinition,\n type KeywordCxt,\n type ValidateFunction,\n} from \"ajv\";\nimport Ajv2019 from \"ajv/dist/2019.js\";\nimport Ajv2020 from \"ajv/dist/2020.js\";\nimport {\n TOOL_GATEWAY_CATALOG_VERSION,\n ToolGatewayCallRequest,\n ToolGatewayCatalog,\n ToolGatewayCatalogEntry,\n ToolGatewayResult,\n isToolResultSpilledReceipt,\n executableToolSchema,\n type ToolGatewayCaller,\n type ToolGatewayCatalog as ToolGatewayCatalogValue,\n type ToolGatewayCatalogEntry as ToolGatewayCatalogEntryValue,\n type ToolGatewayIdentity,\n type ToolGatewayResult as ToolGatewayResultValue,\n} from \"@opengeni/contracts\";\nimport {\n assertToolGatewayCatalogSize,\n compareCanonicalStrings,\n digestCanonicalJson,\n digestToolGatewayCatalog,\n} from \"./catalog\";\nimport {\n ToolGatewayApprovalRequiredError,\n ToolGatewayBlockedError,\n ToolGatewayCatalogStaleError,\n ToolGatewayInputValidationError,\n ToolGatewayOutputValidationError,\n ToolGatewayPathCollisionError,\n ToolGatewayToolNotFoundError,\n} from \"./errors\";\nimport { summarizeToolGatewayInputErrors } from \"./input-issues\";\n\nexport type ToolGatewayExecutionContext = {\n operationId: string;\n caller: ToolGatewayCaller;\n /** Trusted in-process SDK correlation; not operation identity or approval authority. */\n sourceCallId?: string;\n /** In-process transport metadata; never part of catalog identity or digest. */\n transportMeta?: Record<string, unknown> | null;\n signal?: AbortSignal;\n};\n\nexport type ToolGatewayCallContext = Pick<\n ToolGatewayExecutionContext,\n \"sourceCallId\" | \"transportMeta\" | \"signal\"\n>;\n\nexport type ToolGatewayDefinition = Omit<ToolGatewayCatalogEntryValue, \"codemodePath\"> & {\n /** Optional human-readable path. Unsafe/colliding segments are normalized. */\n codemodePath?: readonly string[];\n /** Internal authority revision bound into human approval capabilities. */\n approvalAuthorityDigest?: string;\n /** Executable effect/account identity; excludes unrelated revision changes. */\n effectAuthorityDigest?: string;\n /** Connection-backed calls must have a side-effect-free provider preflight before approval. */\n requiresProviderPreflight?: boolean;\n /** In-process provider preflight; never enters the public catalog or its digest. */\n preflightCall?: (input: {\n call: ToolGatewayCall;\n entry: ToolGatewayCatalogEntryValue;\n context: ToolGatewayCallContext;\n }) => Promise<void> | void;\n /** In-process execution lifecycle; never enters the public catalog or its digest. */\n lifecycle?: ToolGatewayCallLifecycle;\n execute: (\n args: Record<string, unknown>,\n context: ToolGatewayExecutionContext,\n ) => Promise<ToolGatewayResultValue> | ToolGatewayResultValue;\n};\n\nexport type ToolGatewayAuthorization = (input: {\n call: ToolGatewayCall;\n entry: ToolGatewayCatalogEntryValue;\n}) => Promise<void> | void;\n\n/** A trusted adapter resolves user preferences after schema and access validation. */\nexport type ToolGatewayApprovalResolver = (input: {\n call: ToolGatewayCall;\n entry: ToolGatewayCatalogEntryValue;\n}) => Promise<\"allow\" | \"ask\" | \"block\"> | \"allow\" | \"ask\" | \"block\";\n\nexport type ToolGatewayCall = {\n operationId: string;\n catalogDigest: string;\n identity: ToolGatewayIdentity;\n arguments: Record<string, unknown>;\n caller: ToolGatewayCaller;\n};\n\nexport type ToolGatewayCallSettlement =\n | { outcome: \"completed\"; result: ToolGatewayResultValue }\n | { outcome: \"failed\"; error: unknown };\n\nexport type PreparedToolGatewayCallLifecycle = {\n /** Exact durable review created by a trusted policy adapter. */\n waitingForApproval?: { requestId: string; actionFingerprint: string };\n /** Cross the side-effect boundary immediately before the executor closure. */\n begin?: () => Promise<void> | void;\n /** Settle the side-effect lifecycle after a returned result or thrown failure. */\n complete?: (settlement: ToolGatewayCallSettlement) => Promise<void> | void;\n};\n\nexport type ToolGatewayCallLifecycle = {\n /** Argument-sensitive preflight. Throwing here guarantees the executor never runs. */\n prepare: (input: {\n call: ToolGatewayCall;\n entry: ToolGatewayCatalogEntryValue;\n context: ToolGatewayCallContext;\n }) => Promise<PreparedToolGatewayCallLifecycle | void> | PreparedToolGatewayCallLifecycle | void;\n};\n\nexport type ModelToolGatewayCall = {\n operationId?: string;\n /** Exact SDK call id supplied by the host, never inferred from arguments or metadata. */\n sourceCallId?: string;\n modelName: string;\n arguments: Record<string, unknown>;\n subjectId: string;\n transportMeta?: Record<string, unknown> | null;\n signal?: AbortSignal;\n};\n\ntype CompiledDefinition = {\n entry: ToolGatewayCatalogEntryValue;\n execute: ToolGatewayDefinition[\"execute\"];\n approvalAuthorityDigest: string | undefined;\n effectAuthorityDigest: string | undefined;\n preflightCall: ToolGatewayDefinition[\"preflightCall\"];\n lifecycle: ToolGatewayCallLifecycle | undefined;\n validateInput: ValidateFunction<unknown>;\n /** Lazily compiled all-errors validator, used only to describe a rejected call. */\n diagnoseInput: () => ValidateFunction<unknown>;\n validateOutput: ValidateFunction<unknown> | null;\n};\n\nexport type PreparedToolGatewayCall = {\n readonly call: ToolGatewayCall;\n readonly entry: ToolGatewayCatalogEntryValue;\n readonly approvalAuthorityDigest: string;\n /** Effective choice; optional for older adapters constructing this interface. */\n readonly approvalDecision?: \"allow\" | \"ask\";\n readonly waitingForApproval?: { requestId: string; actionFingerprint: string };\n readonly effectDigest?: string;\n execute: () => Promise<ToolGatewayResultValue>;\n};\n\nexport class PreparedToolGatewayDefinitions {\n readonly entries: readonly ToolGatewayCatalogEntryValue[];\n\n constructor(private readonly definitions: readonly CompiledDefinition[]) {\n this.entries = definitions.map(({ entry }) => entry);\n }\n\n create(input: {\n catalogDigest: string;\n authorize?: ToolGatewayAuthorization;\n resolveApproval?: ToolGatewayApprovalResolver;\n requireApproval?: (\n entry: ToolGatewayCatalogEntryValue,\n caller: ToolGatewayCaller,\n context: { transportMeta?: Record<string, unknown> | null },\n ) => boolean;\n confirmModelApproval?: (input: {\n entry: ToolGatewayCatalogEntryValue;\n modelName: string;\n subjectId: string;\n }) => boolean;\n }): ToolGateway {\n return new ToolGateway(\n input.catalogDigest,\n this.definitions,\n input.authorize,\n input.requireApproval,\n input.confirmModelApproval,\n input.resolveApproval,\n );\n }\n}\n\nexport class ToolGateway {\n private readonly byIdentity = new Map<string, CompiledDefinition>();\n private readonly byModelName = new Map<string, CompiledDefinition>();\n\n constructor(\n readonly catalogDigest: string,\n definitions: readonly CompiledDefinition[],\n private readonly authorize: ToolGatewayAuthorization | undefined,\n private readonly requireApproval:\n | ((\n entry: ToolGatewayCatalogEntryValue,\n caller: ToolGatewayCaller,\n context: { transportMeta?: Record<string, unknown> | null },\n ) => boolean)\n | undefined,\n private readonly confirmModelApproval:\n | ((input: {\n entry: ToolGatewayCatalogEntryValue;\n modelName: string;\n subjectId: string;\n }) => boolean)\n | undefined,\n private readonly resolveApproval?: ToolGatewayApprovalResolver,\n ) {\n for (const definition of definitions) {\n this.byIdentity.set(identityKey(definition.entry.identity), definition);\n this.byModelName.set(definition.entry.modelName, definition);\n }\n }\n\n async call(\n input: ToolGatewayCall,\n context: ToolGatewayCallContext = {},\n ): Promise<ToolGatewayResultValue> {\n return await (await this.prepareCallWithModelApproval(input, context, false)).execute();\n }\n\n async prepareCall(\n input: ToolGatewayCall,\n context: ToolGatewayCallContext = {},\n ): Promise<PreparedToolGatewayCall> {\n return await this.prepareCallWithModelApproval(input, context, false);\n }\n\n private async prepareCallWithModelApproval(\n input: ToolGatewayCall,\n context: ToolGatewayCallContext,\n modelApprovalConfirmed: boolean,\n ): Promise<PreparedToolGatewayCall> {\n return withMcpCallIdentity(context.sourceCallId ?? input.operationId, async () => {\n const prepared = await measureMcpPhase(\"gateway_policy\", () =>\n this.prepareCallCore(input, context, modelApprovalConfirmed),\n );\n return { ...prepared, execute: bindMcpTelemetry(prepared.execute) };\n });\n }\n\n private async prepareCallCore(\n input: ToolGatewayCall,\n context: ToolGatewayCallContext,\n modelApprovalConfirmed: boolean,\n ): Promise<PreparedToolGatewayCall> {\n const request = ToolGatewayCallRequest.parse({\n operationId: input.operationId,\n catalogDigest: input.catalogDigest,\n identity: input.identity,\n arguments: input.arguments,\n });\n const operationId = request.operationId ?? input.operationId;\n const caller = input.caller;\n if (request.catalogDigest !== this.catalogDigest) {\n throw new ToolGatewayCatalogStaleError();\n }\n const definition = this.byIdentity.get(identityKey(request.identity));\n if (!definition) {\n throw new ToolGatewayToolNotFoundError();\n }\n if (!this.resolveApproval && this.requireApproval?.(definition.entry, caller, context)) {\n throw new ToolGatewayApprovalRequiredError();\n }\n if (!definition.validateInput(request.arguments)) {\n throw inputValidationError(definition, request.arguments);\n }\n if (\n caller.kind === \"model\" &&\n !this.resolveApproval &&\n definition.entry.approval === \"human\" &&\n !modelApprovalConfirmed\n ) {\n throw new ToolGatewayApprovalRequiredError();\n }\n const call = {\n operationId,\n catalogDigest: request.catalogDigest,\n identity: request.identity,\n arguments: request.arguments,\n caller,\n } satisfies ToolGatewayCall;\n await measureMcpPhase(\"provider_authorization\", () =>\n this.authorize?.({ call, entry: definition.entry }),\n );\n const approvalDecision = this.resolveApproval\n ? await this.resolveApproval({ call, entry: definition.entry })\n : definition.entry.approval === \"human\"\n ? \"ask\"\n : \"allow\";\n if (approvalDecision === \"block\") throw new ToolGatewayBlockedError();\n if (\n this.resolveApproval &&\n approvalDecision === \"ask\" &&\n (caller.kind === \"model\"\n ? !modelApprovalConfirmed\n : context.transportMeta?.approvalConfirmed !== true)\n ) {\n throw new ToolGatewayApprovalRequiredError();\n }\n if (approvalDecision === \"ask\") {\n await measureMcpPhase(\"preflight\", () =>\n definition.preflightCall?.({\n call,\n entry: definition.entry,\n context,\n }),\n );\n }\n const lifecycle = await measureMcpPhase(\"lifecycle_prepare\", () =>\n definition.lifecycle?.prepare({\n call,\n entry: definition.entry,\n context,\n }),\n );\n return {\n call,\n entry: definition.entry,\n approvalDecision,\n ...(lifecycle?.waitingForApproval\n ? { waitingForApproval: lifecycle.waitingForApproval }\n : {}),\n effectDigest: this.effectDigest(request.identity),\n approvalAuthorityDigest:\n definition.approvalAuthorityDigest ??\n digestCanonicalJson({\n version: 1,\n catalogDigest: this.catalogDigest,\n identity: definition.entry.identity,\n }),\n execute: async () =>\n measureMcpPhase(\n \"execution\",\n async () => {\n if (lifecycle?.waitingForApproval) throw new ToolGatewayApprovalRequiredError();\n await measureMcpPhase(\"lifecycle_begin\", () => lifecycle?.begin?.());\n let result: ToolGatewayResultValue;\n try {\n result = ToolGatewayResult.parse(\n await definition.execute(request.arguments, {\n operationId,\n caller,\n ...(context.sourceCallId === undefined\n ? {}\n : { sourceCallId: context.sourceCallId }),\n ...(context.transportMeta === undefined\n ? {}\n : { transportMeta: context.transportMeta }),\n ...(context.signal === undefined ? {} : { signal: context.signal }),\n }),\n );\n if (!result.isError && definition.validateOutput) {\n const outputMatchesSchema =\n result.structuredContent !== undefined &&\n definition.validateOutput(result.structuredContent);\n if (!outputMatchesSchema && !isToolResultSpilledReceipt(result.structuredContent)) {\n throw new ToolGatewayOutputValidationError();\n }\n }\n } catch (error) {\n await measureMcpPhase(\"lifecycle_complete\", () =>\n lifecycle?.complete?.({ outcome: \"failed\", error }),\n );\n throw error;\n }\n await measureMcpPhase(\"lifecycle_complete\", () =>\n lifecycle?.complete?.({ outcome: \"completed\", result }),\n );\n return result;\n },\n (result) => (result.isError ? \"rejected\" : \"completed\"),\n ),\n };\n }\n\n /** Binds continuation to one executable operation, independent of unrelated catalog changes. */\n effectDigest(identity: ToolGatewayIdentity): string {\n const definition = this.byIdentity.get(identityKey(identity));\n if (!definition) throw new ToolGatewayToolNotFoundError();\n const { entry } = definition;\n return digestCanonicalJson({\n version: 1,\n identity: entry.identity,\n source: entry.source,\n inputSchema: executableToolSchema(entry.inputSchema),\n outputSchema: executableToolSchema(entry.outputSchema ?? null),\n readOnly: entry.annotations?.readOnlyHint ?? null,\n destructive: entry.annotations?.destructiveHint ?? null,\n idempotent: entry.annotations?.idempotentHint ?? null,\n authority: definition.effectAuthorityDigest ?? definition.approvalAuthorityDigest ?? null,\n });\n }\n\n async callModel(input: ModelToolGatewayCall): Promise<ToolGatewayResultValue> {\n const definition = this.byModelName.get(input.modelName);\n if (!definition) {\n throw new ToolGatewayToolNotFoundError();\n }\n const call = {\n operationId: input.operationId ?? randomUUID(),\n catalogDigest: this.catalogDigest,\n identity: definition.entry.identity,\n arguments: input.arguments,\n caller: { kind: \"model\" as const, subjectId: input.subjectId },\n };\n const context = {\n ...(input.sourceCallId === undefined ? {} : { sourceCallId: input.sourceCallId }),\n ...(input.transportMeta === undefined ? {} : { transportMeta: input.transportMeta }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n };\n const modelApprovalConfirmed =\n definition.entry.approval === \"human\" &&\n this.confirmModelApproval?.({\n entry: definition.entry,\n modelName: input.modelName,\n subjectId: input.subjectId,\n }) === true;\n return await (\n await this.prepareCallWithModelApproval(call, context, modelApprovalConfirmed)\n ).execute();\n }\n}\n\nexport function prepareToolGatewayDefinitions(\n definitions: readonly ToolGatewayDefinition[],\n): PreparedToolGatewayDefinitions {\n const paths = allocateToolPaths(definitions);\n const schemaValidators = createSchemaValidators(\"first_error\");\n let diagnosticValidators: SchemaValidators | undefined;\n const compiled = definitions.map((definition, index): CompiledDefinition => {\n const {\n execute,\n approvalAuthorityDigest,\n effectAuthorityDigest,\n requiresProviderPreflight: _requiresProviderPreflight,\n preflightCall,\n lifecycle,\n codemodePath: _path,\n ...entryInput\n } = definition;\n if (approvalAuthorityDigest !== undefined && !/^[0-9a-f]{64}$/u.test(approvalAuthorityDigest)) {\n throw new Error(\"Tool gateway approval authority digest must be lowercase SHA-256 hex\");\n }\n if (effectAuthorityDigest !== undefined && !/^[0-9a-f]{64}$/u.test(effectAuthorityDigest)) {\n throw new Error(\"Tool gateway effect authority digest must be lowercase SHA-256 hex\");\n }\n const entry = ToolGatewayCatalogEntry.parse({\n ...entryInput,\n codemodePath: paths[index],\n });\n let diagnoseInput: ValidateFunction<unknown> | undefined;\n return {\n entry,\n execute,\n approvalAuthorityDigest,\n effectAuthorityDigest,\n preflightCall,\n lifecycle,\n validateInput: compileCatalogSchema(schemaValidators, entry.inputSchema),\n diagnoseInput: () =>\n (diagnoseInput ??= compileCatalogSchema(\n (diagnosticValidators ??= createSchemaValidators(\"all_errors\")),\n entry.inputSchema,\n )),\n validateOutput: entry.outputSchema\n ? compileCatalogSchema(schemaValidators, entry.outputSchema)\n : null,\n };\n });\n return new PreparedToolGatewayDefinitions(compiled);\n}\n\nexport function createWorkspaceToolGateway(input: {\n accountId: string;\n workspaceId: string;\n generation: number;\n definitions: readonly ToolGatewayDefinition[];\n createdAt?: Date;\n authorize?: ToolGatewayAuthorization;\n resolveApproval?: ToolGatewayApprovalResolver;\n requireApproval?: (\n entry: ToolGatewayCatalogEntryValue,\n caller: ToolGatewayCaller,\n context: { transportMeta?: Record<string, unknown> | null },\n ) => boolean;\n}): { catalog: ToolGatewayCatalogValue; gateway: ToolGateway } {\n const prepared = prepareToolGatewayDefinitions(input.definitions);\n const unsigned = {\n version: TOOL_GATEWAY_CATALOG_VERSION,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n generation: input.generation,\n createdAt: (input.createdAt ?? new Date()).toISOString(),\n entries: [...prepared.entries],\n };\n const catalog = ToolGatewayCatalog.parse({\n ...unsigned,\n digest: digestToolGatewayCatalog(unsigned),\n });\n assertToolGatewayCatalogSize(catalog);\n return {\n catalog,\n gateway: prepared.create({\n catalogDigest: catalog.digest,\n ...(input.authorize ? { authorize: input.authorize } : {}),\n ...(input.resolveApproval ? { resolveApproval: input.resolveApproval } : {}),\n ...(input.requireApproval ? { requireApproval: input.requireApproval } : {}),\n }),\n };\n}\n\ntype SchemaCompiler = { compile(schema: object): ValidateFunction<unknown> };\n\ntype SchemaValidatorMode = \"first_error\" | \"all_errors\";\n\ntype SchemaValidators = {\n mode: SchemaValidatorMode;\n draft7: SchemaCompiler;\n draft2019: SchemaCompiler;\n draft2020: SchemaCompiler;\n};\n\nconst COMPILED_CATALOG_SCHEMA_CACHE_MAX_ENTRIES = 512;\nconst compiledCatalogSchemaCache = new Map<string, ValidateFunction<unknown>>();\n\n/**\n * Serialized-size ceiling for the all-errors diagnostic pass. The accept/reject\n * decision always uses the first-error validator, which stops at the first\n * failure so a schema's own bounds (for example `maxLength` ahead of `pattern`)\n * keep limiting validation cost. The diagnostic pass runs only after a\n * rejection and only on arguments this small; larger ones report the first\n * problem alone. Its `pattern` keeps the `maxLength` guard (see\n * `maxLengthGuardedPattern`).\n */\nexport const TOOL_GATEWAY_INPUT_DIAGNOSTIC_MAX_CHARS = 64 * 1024;\n\nfunction createSchemaValidators(mode: SchemaValidatorMode): SchemaValidators {\n const options = {\n allErrors: mode === \"all_errors\",\n coerceTypes: false,\n strict: false,\n useDefaults: false,\n validateFormats: false,\n } as const;\n const validators = {\n draft7: new Ajv(options),\n draft2019: new Ajv2019(options),\n draft2020: new Ajv2020(options),\n };\n if (mode === \"all_errors\") {\n for (const ajv of Object.values(validators)) {\n ajv.removeKeyword(\"pattern\").addKeyword(maxLengthGuardedPattern);\n }\n }\n return { mode, ...validators };\n}\n\nfunction codePointLength(value: string): number {\n let length = 0;\n for (const _codePoint of value) length += 1;\n return length;\n}\n\n/**\n * `pattern` for the all-errors diagnostic validators. The first-error validator\n * checks `maxLength` before `pattern` and stops there, so a schema's\n * `maxLength` bounds how long a string its (possibly backtracking-heavy)\n * pattern ever sees. With `allErrors` the built-in keyword would still run the\n * pattern on the over-long string. This version skips the pattern exactly when\n * the sibling `maxLength` already fails, so every subschema's validity is\n * unchanged and the diagnostic pass never runs a pattern on a string the\n * accept/reject validator would not have. Error shape matches the built-in.\n */\nconst maxLengthGuardedPattern: CodeKeywordDefinition = {\n keyword: \"pattern\",\n type: \"string\",\n schemaType: \"string\",\n error: {\n message: ({ schemaCode }) => str`must match pattern \"${schemaCode}\"`,\n params: ({ schemaCode }) => _`{pattern: ${schemaCode}}`,\n },\n code(cxt: KeywordCxt) {\n const { gen, data, schema, parentSchema, it } = cxt;\n const flags = it.opts.unicodeRegExp ? \"u\" : \"\";\n const regExp = gen.scopeValue(\"pattern\", {\n key: `${schema}/${flags}`,\n ref: it.opts.code.regExp(schema as string, flags),\n });\n const maxLength: unknown = parentSchema.maxLength;\n if (typeof maxLength !== \"number\") {\n cxt.fail(_`!${regExp}.test(${data})`);\n return;\n }\n const length =\n it.opts.unicode === false\n ? _`${data}.length`\n : _`${gen.scopeValue(\"func\", { ref: codePointLength })}(${data})`;\n cxt.fail(_`${length} <= ${maxLength} && !${regExp}.test(${data})`);\n },\n};\n\n/**\n * Describe why the first-error validator rejected `args`: every problem (capped)\n * when the arguments are small enough for the diagnostic pass, else the first.\n * Never includes argument values.\n */\nfunction inputValidationError(\n definition: CompiledDefinition,\n args: Record<string, unknown>,\n): ToolGatewayInputValidationError {\n let errors = definition.validateInput.errors;\n let diagnosticInput:\n | { schema: Record<string, unknown>; arguments: Record<string, unknown> }\n | undefined;\n try {\n const serialized = JSON.stringify(args);\n if (serialized !== undefined && serialized.length <= TOOL_GATEWAY_INPUT_DIAGNOSTIC_MAX_CHARS) {\n diagnosticInput = { schema: definition.entry.inputSchema, arguments: args };\n const diagnose = definition.diagnoseInput();\n if (!diagnose(args) && diagnose.errors?.length) errors = diagnose.errors;\n }\n } catch {\n // Diagnostics are best effort; the rejection itself is already decided.\n }\n const { issues, omittedIssueCount } = summarizeToolGatewayInputErrors(errors, diagnosticInput);\n return new ToolGatewayInputValidationError(issues, omittedIssueCount);\n}\n\nfunction compileCatalogSchema(\n validators: SchemaValidators,\n schema: ToolGatewayCatalogEntryValue[\"inputSchema\"],\n): ValidateFunction<unknown> {\n const dialect = typeof schema.$schema === \"string\" ? schema.$schema : \"\";\n const family = dialect.includes(\"2020-12\")\n ? \"2020-12\"\n : dialect.includes(\"2019-09\")\n ? \"2019-09\"\n : \"draft7\";\n const cacheKey = `${validators.mode}:${family}:${digestCanonicalJson(schema)}`;\n const cached = compiledCatalogSchemaCache.get(cacheKey);\n if (cached) {\n compiledCatalogSchemaCache.delete(cacheKey);\n compiledCatalogSchemaCache.set(cacheKey, cached);\n return cached;\n }\n const compiled =\n family === \"2020-12\"\n ? validators.draft2020.compile(schema)\n : family === \"2019-09\"\n ? validators.draft2019.compile(schema)\n : validators.draft7.compile(schema);\n while (compiledCatalogSchemaCache.size >= COMPILED_CATALOG_SCHEMA_CACHE_MAX_ENTRIES) {\n const oldest = compiledCatalogSchemaCache.keys().next().value;\n if (oldest === undefined) break;\n compiledCatalogSchemaCache.delete(oldest);\n }\n compiledCatalogSchemaCache.set(cacheKey, compiled);\n return compiled;\n}\n\nfunction allocateToolPaths(definitions: readonly ToolGatewayDefinition[]): string[][] {\n const requested = definitions.map((definition) =>\n definition.codemodePath?.length\n ? [...definition.codemodePath]\n : [definition.identity.serverId, definition.identity.toolName],\n );\n const bases = requested.map((path) => path.map(safeNamespaceSegment));\n const allocated = bases.map((base, index) => {\n const path = requested[index]!;\n if (path.every((segment, segmentIndex) => segment === base[segmentIndex])) return base;\n const suffix = `_${shortIdentityDigest(definitions[index]!.identity)}`;\n const last = base.at(-1)!;\n return [...base.slice(0, -1), `${last.slice(0, 128 - suffix.length)}${suffix}`];\n });\n assertNoToolPathCollisions(allocated);\n return allocated;\n}\n\ntype ToolPathNode = {\n children: Map<string, ToolPathNode>;\n leaf: boolean;\n};\n\nfunction assertNoToolPathCollisions(paths: readonly (readonly string[])[]): void {\n const root: ToolPathNode = { children: new Map(), leaf: false };\n const ordered = [...paths].sort(compareToolPaths);\n for (const path of ordered) {\n let node = root;\n for (const [index, segment] of path.entries()) {\n if (node.leaf) throw new ToolGatewayPathCollisionError(path, \"extends_leaf\");\n let child = node.children.get(segment);\n if (!child) {\n child = { children: new Map(), leaf: false };\n node.children.set(segment, child);\n }\n node = child;\n if (index === path.length - 1) {\n if (node.leaf || node.children.size > 0) {\n throw new ToolGatewayPathCollisionError(path, \"collision\");\n }\n node.leaf = true;\n }\n }\n }\n}\n\nfunction compareToolPaths(left: readonly string[], right: readonly string[]): number {\n const length = Math.min(left.length, right.length);\n for (let index = 0; index < length; index += 1) {\n const compared = compareCanonicalStrings(left[index]!, right[index]!);\n if (compared !== 0) return compared;\n }\n return left.length - right.length;\n}\n\nfunction safeNamespaceSegment(value: string): string {\n let normalized = value.replace(/[^A-Za-z0-9_$]/gu, \"_\");\n if (!/^[A-Za-z_$]/u.test(normalized)) normalized = `_${normalized}`;\n if ([\"__proto__\", \"prototype\", \"constructor\"].includes(normalized)) {\n normalized = `_${normalized}`;\n }\n return normalized.slice(0, 128) || \"_\";\n}\n\nfunction shortIdentityDigest(identity: ToolGatewayIdentity): string {\n return createHash(\"sha256\").update(identityKey(identity), \"utf8\").digest(\"hex\").slice(0, 10);\n}\n\nfunction identityKey(identity: ToolGatewayIdentity): string {\n return `${identity.serverId}\\u0000${identity.toolName}`;\n}\n\nexport * from \"./catalog\";\nexport * from \"./declarations\";\nexport * from \"./errors\";\nexport * from \"./input-issues\";\n","import { createHash } from \"node:crypto\";\nimport {\n ATTEMPT_TOOL_CATALOG_MAX_BYTES,\n ToolGatewayCatalog,\n type ToolGatewayCatalog as ToolGatewayCatalogValue,\n} from \"@opengeni/contracts\";\nimport { ToolGatewayCatalogIntegrityError, ToolGatewayCatalogTooLargeError } from \"./errors\";\n\nexport function digestToolGatewayCatalog(catalog: Omit<ToolGatewayCatalogValue, \"digest\">): string {\n const { createdAt: _createdAt, ...authoritative } = catalog;\n return digestCanonicalJson(authoritative);\n}\n\nexport function parseVerifiedToolGatewayCatalog(input: unknown): ToolGatewayCatalogValue {\n const catalog = ToolGatewayCatalog.parse(input);\n assertCatalogSize(catalog);\n const { digest, ...unsigned } = catalog;\n if (digestToolGatewayCatalog(unsigned) !== digest) {\n throw new ToolGatewayCatalogIntegrityError();\n }\n return catalog;\n}\n\nexport function digestCanonicalJson(value: unknown): string {\n return createHash(\"sha256\")\n .update(JSON.stringify(canonicalJsonValue(value)), \"utf8\")\n .digest(\"hex\");\n}\n\n/** Compare canonical JSON keys by JavaScript UTF-16 code units, independent of host locale. */\nexport function compareCanonicalStrings(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nexport function assertToolGatewayCatalogSize(catalog: ToolGatewayCatalogValue): void {\n assertCatalogSize(catalog);\n}\n\nfunction assertCatalogSize(catalog: ToolGatewayCatalogValue): void {\n if (\n new TextEncoder().encode(JSON.stringify(catalog)).byteLength > ATTEMPT_TOOL_CATALOG_MAX_BYTES\n ) {\n throw new ToolGatewayCatalogTooLargeError();\n }\n}\n\nfunction canonicalJsonValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonicalJsonValue);\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => compareCanonicalStrings(left, right))\n .map(([key, entry]) => [key, canonicalJsonValue(entry)]),\n );\n }\n return value;\n}\n","import type { ErrorObject } from \"ajv\";\n\n/**\n * One argument problem found by input-schema validation. Every field is derived\n * from the property path and the tool's schema, never from an argument value,\n * so the summary is safe to show to the model and to return over HTTP.\n */\nexport type ToolGatewayInputIssue = {\n /** Readable path of the offending property (`context`, `filters[0].field`); empty for the arguments object itself. */\n readonly path: string;\n /** JSON Schema keyword that failed, such as `required`, `type`, or `additionalProperties`. */\n readonly keyword: string;\n /** Short, value-free sentence fragment naming the property and what the schema expects. */\n readonly message: string;\n};\n\nexport type ToolGatewayInputIssueSummary = {\n readonly issues: readonly ToolGatewayInputIssue[];\n /** Distinct problems found beyond the reported cap. */\n readonly omittedIssueCount: number;\n};\n\n/** Maximum problems named in one validation error. */\nexport const TOOL_GATEWAY_INPUT_ISSUES_MAX = 8;\n\nconst PATH_MAX_CHARS = 120;\nconst MESSAGE_DETAIL_MAX_CHARS = 160;\nconst ALLOWED_VALUES_MAX = 10;\nconst ALLOWED_VALUE_MAX_CHARS = 60;\n\n/**\n * Convert validator errors into a capped, de-duplicated list of value-free issues.\n * Validator messages only quote schema facts (types, limits, patterns), and\n * values offered here come from `enum`/`const` in the schema, not the arguments.\n * Supplying the input schema and arguments also distinguishes union alternatives;\n * arguments are inspected only to select schema facts, never included in text.\n */\nexport function summarizeToolGatewayInputErrors(\n errors: readonly ErrorObject[] | null | undefined,\n input?: { schema: Record<string, unknown>; arguments: Record<string, unknown> },\n): ToolGatewayInputIssueSummary {\n const issues: ToolGatewayInputIssue[] = [];\n const seen = new Set<string>();\n let omittedIssueCount = 0;\n let candidates = unscopedInputIssues(errors ?? []);\n if (input) {\n try {\n candidates = unionAwareIssues(errors ?? [], input);\n } catch {\n // Diagnostics cannot replace the already-decided input rejection.\n }\n }\n for (const issue of candidates) {\n if (seen.has(issue.message)) continue;\n seen.add(issue.message);\n if (issues.length < TOOL_GATEWAY_INPUT_ISSUES_MAX) issues.push(issue);\n else omittedIssueCount += 1;\n }\n return { issues, omittedIssueCount };\n}\n\n/** Without bounded argument diagnostics, union errors are alternatives only. */\nfunction unscopedInputIssues(errors: readonly ErrorObject[]): ToolGatewayInputIssue[] {\n const union = errors.find((error) => error.keyword === \"anyOf\" || error.keyword === \"oneOf\");\n if (!union) return errors.map(issueFromError);\n const path = displayPath(pointerSegments(union.instancePath));\n return [\n {\n path,\n keyword: union.keyword,\n message: `${describe(path)} must match ${union.keyword === \"oneOf\" ? \"exactly one\" : \"one\"} declared alternative input format`,\n },\n ];\n}\n\ntype JsonSchema = Record<string, unknown>;\ntype LiteralConstraint = { path: readonly string[]; values: readonly unknown[]; required: boolean };\ntype UnionDiagnostic = {\n error: ErrorObject;\n branchPrefixes: readonly (readonly string[])[];\n selected: number | undefined;\n replacement: ToolGatewayInputIssue | undefined;\n unresolved?: boolean;\n};\n\n/**\n * An anyOf/oneOf failure contains errors from mutually exclusive alternatives.\n * A supplied const/enum tag can rule alternatives out, but a missing property or\n * a count of failures cannot choose one. Without a unique compatible branch,\n * describe the alternatives explicitly instead of combining their requirements.\n */\nfunction unionAwareIssues(\n errors: readonly ErrorObject[],\n input: { schema: JsonSchema; arguments: Record<string, unknown> },\n): ToolGatewayInputIssue[] {\n if (!errors.some((error) => error.keyword === \"anyOf\" || error.keyword === \"oneOf\"))\n return errors.map(issueFromError);\n const unions: UnionDiagnostic[] = [];\n const order = new Map(errors.map((error, index) => [error, index]));\n const independent = unconditionalErrorSites(input.schema, input.arguments, errors);\n const uncertainByPath = indexByPath(independent.uncertain, (entry) => entry.instancePath, false);\n const ownershipUncertain = (error: ErrorObject) =>\n !independent.sites.has(errorSite(error.schemaPath, error.instancePath)) &&\n pathAncestors(error.instancePath).some((path) =>\n (uncertainByPath.get(path) ?? []).some(\n (entry) =>\n error.schemaPath === entry.prefix || error.schemaPath.startsWith(`${entry.prefix}/`),\n ),\n );\n const belongs = (error: ErrorObject, union: ErrorObject, prefixes: readonly string[]) =>\n order.get(error)! < order.get(union)! &&\n !independent.sites.has(errorSite(error.schemaPath, error.instancePath)) &&\n !ownershipUncertain(error) &&\n belongsToBranch(error, union, prefixes);\n for (const error of errors) {\n if (error.keyword !== \"anyOf\" && error.keyword !== \"oneOf\") continue;\n const site = errorSite(error.schemaPath, error.instancePath);\n const alternatives = independent.ambiguous.has(site)\n ? undefined\n : independent.schemas.has(site)\n ? independent.schemas.get(site)\n : schemaAt(input.schema, error.schemaPath);\n if (\n !Array.isArray(alternatives) ||\n alternatives.some((branch) => !isSchema(branch) && typeof branch !== \"boolean\")\n ) {\n unions.push({\n error,\n branchPrefixes: [],\n selected: undefined,\n unresolved: true,\n replacement: {\n path: displayPath(pointerSegments(error.instancePath)),\n keyword: error.keyword,\n message: `${describe(displayPath(pointerSegments(error.instancePath)))} must match ${error.keyword === \"oneOf\" ? \"exactly one\" : \"one\"} declared alternative input format`,\n },\n });\n continue;\n }\n const branches = alternatives as (JsonSchema | boolean)[];\n const branchPrefixes = branches.map((branch, index) =>\n isSchema(branch)\n ? schemaPrefixes(branch, `${error.schemaPath}/${index}`, input.schema)\n : [`${error.schemaPath}/${index}`],\n );\n const constraints = branches.map((branch) =>\n isSchema(branch) ? literalConstraints(branch, input.schema) : [],\n );\n const at = argumentAt(input.arguments, pointerSegments(error.instancePath));\n const compatible = constraints.flatMap((branch, index) =>\n branches[index] === false ||\n branch.some((constraint) => {\n const supplied = argumentAt(at.value, constraint.path);\n return supplied.present && !constraint.values.some((value) => value === supplied.value);\n })\n ? []\n : [index],\n );\n const selected =\n compatible.length === 1 && compatible.length < branches.length ? compatible[0] : undefined;\n let replacement: ToolGatewayInputIssue | undefined;\n if (selected === undefined) {\n const common = constraints[0]?.find((constraint) =>\n constraints.every((branch) =>\n branch.some((other) => samePath(other.path, constraint.path)),\n ),\n );\n const supplied = common && argumentAt(at.value, common.path);\n const commonConstraints =\n common &&\n constraints.map(\n (branch) => branch.find((constraint) => samePath(constraint.path, common.path))!,\n );\n const allowed = commonConstraints?.flatMap((constraint) => constraint.values);\n const uniqueAllowed = allowed && [...new Set(allowed)];\n if (\n common &&\n supplied &&\n commonConstraints &&\n uniqueAllowed?.length &&\n ((supplied.present && !uniqueAllowed.some((value) => value === supplied.value)) ||\n (!supplied.present && commonConstraints.every((constraint) => constraint.required)))\n ) {\n const path = displayPath([...pointerSegments(error.instancePath), ...common.path]);\n const allowedText = allowedValuesText(uniqueAllowed);\n const missing =\n !supplied.present && commonConstraints.every((constraint) => constraint.required);\n replacement = {\n path,\n keyword: missing ? \"required\" : error.keyword,\n message: missing\n ? `missing required property \"${path}\" (selects one of ${allowedText})`\n : `${describe(path)} must be one of ${allowedText}`,\n };\n }\n }\n\n unions.push({ error, branchPrefixes, selected, replacement });\n }\n const replacements = new Map<UnionDiagnostic, ToolGatewayInputIssue>();\n const errorsWithin = indexByPath(errors, (error) => error.instancePath, true);\n const unionsWithin = indexByPath(unions, (union) => union.error.instancePath, true);\n const scopeIndexes = new WeakMap<readonly UnionDiagnostic[], Map<string, UnionDiagnostic[]>>();\n const project = (\n error: ErrorObject,\n scope: readonly UnionDiagnostic[],\n ): ToolGatewayInputIssue[] => {\n let scopeIndex = scopeIndexes.get(scope);\n if (!scopeIndex) {\n scopeIndex = indexByPath(scope, (union) => union.error.instancePath, false);\n scopeIndexes.set(scope, scopeIndex);\n }\n const applicable = pathAncestors(error.instancePath).flatMap(\n (path) => scopeIndex.get(path) ?? [],\n );\n for (const union of applicable) {\n if (error === union.error) continue;\n if (\n union.unresolved &&\n order.get(error)! < order.get(union.error)! &&\n !independent.sites.has(errorSite(error.schemaPath, error.instancePath)) &&\n !ownershipUncertain(error) &&\n (error.instancePath === union.error.instancePath ||\n error.instancePath.startsWith(`${union.error.instancePath}/`))\n )\n return [];\n const matchingBranches = union.branchPrefixes.flatMap((prefixes, index) =>\n belongs(error, union.error, prefixes) ? [index] : [],\n );\n if (\n matchingBranches.length &&\n (union.selected === undefined || !matchingBranches.includes(union.selected))\n )\n return [];\n }\n const union = applicable.find((candidate) => candidate.error === error);\n if (!union) {\n const issue = issueFromError(error);\n return [\n ownershipUncertain(error)\n ? {\n ...issue,\n message: `an independent constraint or alternative reports: ${issue.message}`,\n }\n : issue,\n ];\n }\n if (union.selected !== undefined) return [];\n if (union.replacement) return [union.replacement];\n const cached = replacements.get(union);\n if (cached) return [cached];\n const alternatives = union.branchPrefixes\n .slice(0, ALLOWED_VALUES_MAX)\n .map((prefixes, index) => {\n const nested = (unionsWithin.get(union.error.instancePath) ?? []).filter(\n (candidate) =>\n order.get(candidate.error)! < order.get(union.error)! &&\n belongs(candidate.error, union.error, prefixes),\n );\n const details = (errorsWithin.get(union.error.instancePath) ?? [])\n .filter(\n (candidate) => candidate !== union.error && belongs(candidate, union.error, prefixes),\n )\n .flatMap((candidate) => project(candidate, nested))\n .map((issue) => issue.message);\n const distinct = [...new Set(details)];\n const shown = distinct.slice(0, 2);\n if (distinct.length > shown.length) shown.push(\"other declared requirements\");\n return `alternative ${index + 1}${shown.length ? ` (${shown.join(\"; \")})` : \"\"}`;\n });\n if (union.branchPrefixes.length > ALLOWED_VALUES_MAX)\n alternatives.push(\"other declared alternatives\");\n const issue = {\n path: displayPath(pointerSegments(error.instancePath)),\n keyword: error.keyword,\n message: bounded(\n `${describe(displayPath(pointerSegments(error.instancePath)))} must match ${\n error.keyword === \"oneOf\" ? \"exactly one\" : \"one\"\n } declared input format: ${alternatives.join(\" or \")}`,\n 640,\n ),\n };\n replacements.set(union, issue);\n return [issue];\n };\n return errors.flatMap((error) => project(error, unions));\n}\n\n/** Index instances once so many array-item unions never scan one another's errors. */\nfunction indexByPath<T>(\n values: readonly T[],\n pathOf: (value: T) => string,\n includeDescendants: boolean,\n): Map<string, T[]> {\n const index = new Map<string, T[]>();\n for (const value of values) {\n const paths = includeDescendants ? pathAncestors(pathOf(value)) : [pathOf(value)];\n for (const path of paths) {\n const group = index.get(path);\n if (group) group.push(value);\n else index.set(path, [value]);\n }\n }\n return index;\n}\n\nfunction pathAncestors(path: string): string[] {\n const ancestors = [path];\n let parent = path;\n while (parent) {\n parent = parent.slice(0, parent.lastIndexOf(\"/\"));\n ancestors.push(parent);\n }\n return ancestors;\n}\n\nfunction belongsToBranch(\n error: ErrorObject,\n union: ErrorObject,\n prefixes: readonly string[],\n): boolean {\n return (\n (error.instancePath === union.instancePath ||\n error.instancePath.startsWith(`${union.instancePath}/`)) &&\n prefixes.some(\n (prefix) => error.schemaPath === prefix || error.schemaPath.startsWith(`${prefix}/`),\n )\n );\n}\n\nfunction isSchema(value: unknown): value is JsonSchema {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nconst schemaReferenceIndexes = new WeakMap<JsonSchema, Map<string, JsonSchema>>();\nconst schemaReferenceBases = new WeakMap<JsonSchema, WeakMap<JsonSchema, string>>();\nconst schemaReferenceLocals = new WeakMap<JsonSchema, WeakMap<JsonSchema, string>>();\n\n/** Resolve local pointers, anchors and identifiers declared inside this schema. */\nfunction schemaAt(root: JsonSchema, pointer: string, context?: JsonSchema): unknown {\n let index = schemaReferenceIndexes.get(root);\n if (!index) {\n index = new Map([[\"#\", root]]);\n const ambiguous = new Set<string>();\n const bases = new WeakMap<JsonSchema, string>();\n const locals = new WeakMap<JsonSchema, string>();\n const active = new Set<JsonSchema>();\n const register = (name: string, schema: JsonSchema) => {\n if (ambiguous.has(name)) return;\n const previous = index!.get(name);\n if (previous && previous !== schema) {\n index!.delete(name);\n ambiguous.add(name);\n } else index!.set(name, schema);\n };\n const visit = (schema: JsonSchema, path: string, inheritedId: string, localPath: string) => {\n if (active.has(schema)) return;\n active.add(schema);\n register(path, schema);\n let id = inheritedId;\n if (typeof schema.$id === \"string\") {\n id = schema.$id;\n try {\n if (inheritedId) id = new URL(id, inheritedId).href;\n } catch {\n /* Non-URL identifiers remain exact aliases. */\n }\n register(id, schema);\n register(`${id}#`, schema);\n localPath = \"#\";\n }\n bases.set(schema, id);\n locals.set(schema, localPath);\n if (typeof schema.$anchor === \"string\") {\n register(`#${schema.$anchor}`, schema);\n if (id) register(`${id}#${schema.$anchor}`, schema);\n }\n for (const [suffix, child] of schemaChildren(schema))\n visit(child, `${path}/${suffix}`, id, `${localPath}/${suffix}`);\n active.delete(schema);\n };\n visit(root, \"#\", \"\", \"#\");\n schemaReferenceIndexes.set(root, index);\n schemaReferenceBases.set(root, bases);\n schemaReferenceLocals.set(root, locals);\n }\n const base = context && schemaReferenceBases.get(root)?.get(context);\n if (base) {\n if (pointer.startsWith(\"#\")) pointer = `${base}${pointer}`;\n else\n try {\n pointer = new URL(pointer, base).href;\n } catch {\n /* Exact aliases remain available. */\n }\n }\n const exact = index.get(pointer);\n if (exact) return exact;\n // AJV appends keyword paths to the reference it followed, including anchors.\n let separator = pointer.lastIndexOf(\"/\");\n while (separator >= 0) {\n const target = index.get(pointer.slice(0, separator));\n if (target) {\n let value: unknown = target;\n for (const segment of pointerSegments(pointer.slice(separator))) {\n if (!value || typeof value !== \"object\") return undefined;\n value = (value as Record<string, unknown>)[segment];\n }\n return value;\n }\n separator = separator === 0 ? -1 : pointer.lastIndexOf(\"/\", separator - 1);\n }\n return undefined;\n}\n\nfunction schemaChildren(schema: JsonSchema): [string, JsonSchema][] {\n const children: [string, JsonSchema][] = [];\n for (const keyword of [\n \"$defs\",\n \"definitions\",\n \"properties\",\n \"patternProperties\",\n \"dependentSchemas\",\n \"dependencies\",\n ]) {\n const values = schema[keyword];\n if (isSchema(values))\n for (const [name, child] of Object.entries(values))\n if (isSchema(child)) children.push([`${keyword}/${pointerSegment(name)}`, child]);\n }\n for (const keyword of [\"anyOf\", \"oneOf\", \"allOf\", \"prefixItems\", \"items\"]) {\n const values = schema[keyword];\n if (Array.isArray(values))\n values.forEach((child, index) => {\n if (isSchema(child)) children.push([`${keyword}/${index}`, child]);\n });\n }\n for (const keyword of [\n \"items\",\n \"additionalItems\",\n \"additionalProperties\",\n \"unevaluatedProperties\",\n \"not\",\n \"if\",\n \"then\",\n \"else\",\n \"contains\",\n \"propertyNames\",\n ]) {\n const child = schema[keyword];\n if (isSchema(child)) children.push([keyword, child]);\n }\n return children;\n}\n\nfunction pointerSegment(value: string): string {\n return value.replace(/~/gu, \"~0\").replace(/\\//gu, \"~1\");\n}\n\nfunction errorSite(schemaPath: string, instancePath: string): string {\n return JSON.stringify([schemaPath, instancePath]);\n}\n\n/**\n * Shared references erase their source location in AJV errors. Preserve failures\n * reached independently of alternatives, even when the same referenced schema\n * also occurs in a later branch. Only conjunctions, supplied properties/items,\n * and uniquely selected literal tags mark sites as independent. Other branches\n * are indexed for resource-scoped lookup without marking them independent.\n */\nfunction unconditionalErrorSites(\n root: JsonSchema,\n args: Record<string, unknown>,\n errors: readonly ErrorObject[],\n): {\n sites: Set<string>;\n schemas: Map<string, unknown>;\n ambiguous: Set<string>;\n uncertain: { prefix: string; instancePath: string }[];\n} {\n const sites = new Set<string>();\n const schemaSites = new Map<string, unknown>();\n const uncertain: { prefix: string; instancePath: string }[] = [];\n const ambiguous = new Set<string>();\n const conditionalBranches = new Map(\n errors\n .filter((error) => error.keyword === \"if\")\n .map((error) => [\n errorSite(error.schemaPath, error.instancePath),\n error.params.failingKeyword,\n ]),\n );\n const active = new Set<string>();\n const schemas = new WeakMap<JsonSchema, number>();\n let schemaId = 0;\n const visit = (\n schema: JsonSchema,\n schemaPath: string,\n value: unknown,\n instancePath: string,\n independent: boolean,\n ) => {\n let id = schemas.get(schema);\n if (id === undefined) {\n id = schemaId++;\n schemas.set(schema, id);\n }\n const key = JSON.stringify([id, schemaPath, instancePath, independent]);\n if (active.has(key)) return;\n active.add(key);\n const base = schemaReferenceBases.get(root)?.get(schema);\n const local = base && schemaReferenceLocals.get(root)?.get(schema);\n const aliases = [...new Set([schemaPath, ...(local ? [local, `${base}${local}`] : [])])];\n for (const alias of aliases)\n for (const [keyword, child] of Object.entries(schema)) {\n const site = errorSite(`${alias}/${keyword}`, instancePath);\n if (independent) sites.add(site);\n if (ambiguous.has(site)) continue;\n if (schemaSites.has(site) && schemaSites.get(site) !== child) {\n schemaSites.delete(site);\n ambiguous.add(site);\n } else schemaSites.set(site, child);\n }\n if (typeof schema.$ref === \"string\") {\n const target = schemaAt(root, schema.$ref, schema);\n if (isSchema(target)) visit(target, schema.$ref, value, instancePath, independent);\n }\n if (Array.isArray(schema.allOf))\n schema.allOf.forEach((child, index) => {\n if (isSchema(child))\n visit(child, `${schemaPath}/allOf/${index}`, value, instancePath, independent);\n });\n for (const keyword of [\"anyOf\", \"oneOf\"]) {\n const alternatives = schema[keyword];\n if (!Array.isArray(alternatives)) continue;\n const compatible = alternatives.flatMap((branch, index) => {\n if (branch === false) return [];\n if (!isSchema(branch)) return [index];\n return literalConstraints(branch, root).some((constraint) => {\n const supplied = argumentAt(value, constraint.path);\n return supplied.present && !constraint.values.includes(supplied.value);\n })\n ? []\n : [index];\n });\n const selected =\n compatible.length === 1 && compatible.length < alternatives.length\n ? compatible[0]\n : undefined;\n alternatives.forEach((child, index) => {\n if (isSchema(child))\n visit(\n child,\n `${schemaPath}/${keyword}/${index}`,\n value,\n instancePath,\n independent && index === selected,\n );\n });\n }\n\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n if (isSchema(schema.properties))\n for (const [name, child] of Object.entries(schema.properties)) {\n if (isSchema(child) && Object.hasOwn(value, name))\n visit(\n child,\n `${schemaPath}/properties/${pointerSegment(name)}`,\n (value as Record<string, unknown>)[name],\n `${instancePath}/${pointerSegment(name)}`,\n independent,\n );\n }\n if (isSchema(schema.dependentSchemas))\n for (const [name, child] of Object.entries(schema.dependentSchemas)) {\n if (isSchema(child) && Object.hasOwn(value, name))\n visit(\n child,\n `${schemaPath}/dependentSchemas/${pointerSegment(name)}`,\n value,\n instancePath,\n independent,\n );\n }\n }\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n const declared = isSchema(schema.properties) ? schema.properties : {};\n const patterns = isSchema(schema.patternProperties)\n ? Object.entries(schema.patternProperties).map(\n ([pattern, child]) => [pattern, new RegExp(pattern, \"u\"), child] as const,\n )\n : [];\n for (const [name, childValue] of Object.entries(value)) {\n let matched = false;\n for (const [pattern, regexp, child] of patterns) {\n if (regexp.test(name)) {\n matched = true;\n if (isSchema(child))\n visit(\n child,\n `${schemaPath}/patternProperties/${pointerSegment(pattern)}`,\n childValue,\n `${instancePath}/${pointerSegment(name)}`,\n independent,\n );\n }\n }\n if (!Object.hasOwn(declared, name) && !matched && isSchema(schema.additionalProperties))\n visit(\n schema.additionalProperties,\n `${schemaPath}/additionalProperties`,\n childValue,\n `${instancePath}/${pointerSegment(name)}`,\n independent,\n );\n }\n if (isSchema(schema.dependencies))\n for (const [name, child] of Object.entries(schema.dependencies)) {\n if (isSchema(child) && Object.hasOwn(value, name))\n visit(\n child,\n `${schemaPath}/dependencies/${pointerSegment(name)}`,\n value,\n instancePath,\n independent,\n );\n }\n }\n if (Array.isArray(value)) {\n const tuple = Array.isArray(schema.prefixItems)\n ? schema.prefixItems\n : Array.isArray(schema.items)\n ? schema.items\n : [];\n const tupleKeyword = Array.isArray(schema.prefixItems) ? \"prefixItems\" : \"items\";\n value.forEach((item, index) => {\n const child =\n tuple[index] ?? (isSchema(schema.items) ? schema.items : schema.additionalItems);\n if (isSchema(child))\n visit(\n child,\n tuple[index]\n ? `${schemaPath}/${tupleKeyword}/${index}`\n : `${schemaPath}/${isSchema(schema.items) ? \"items\" : \"additionalItems\"}`,\n item,\n `${instancePath}/${index}`,\n independent,\n );\n });\n }\n // These applicators have existential or annotation semantics. A reused\n // reference cannot prove branch ownership here, so retain its failures as\n // explicitly ambiguous constraint evidence rather than suppressing them.\n for (const keyword of [\n \"contains\",\n \"propertyNames\",\n \"unevaluatedProperties\",\n \"unevaluatedItems\",\n ]) {\n const child = schema[keyword];\n if (isSchema(child))\n for (const prefix of schemaPrefixes(child, `${schemaPath}/${keyword}`, root).slice(1))\n uncertain.push({ prefix, instancePath });\n }\n // Failed conditionals name the branch AJV actually evaluated.\n const branch = conditionalBranches.get(errorSite(`${schemaPath}/if`, instancePath));\n if ((branch === \"then\" || branch === \"else\") && isSchema(schema[branch]))\n visit(schema[branch], `${schemaPath}/${branch}`, value, instancePath, independent);\n active.delete(key);\n };\n schemaAt(root, \"#\"); // Initialize resource scopes before recording any sites.\n visit(root, \"#\", args, \"\", true);\n return { sites, schemas: schemaSites, ambiguous, uncertain };\n}\n\nfunction schemaPrefixes(schema: JsonSchema, pointer: string, root: JsonSchema): string[] {\n const prefixes = [pointer];\n const seen = new Set<JsonSchema>();\n const visit = (value: JsonSchema) => {\n if (seen.has(value)) return;\n seen.add(value);\n if (typeof value.$ref === \"string\") {\n const target = schemaAt(root, value.$ref, value);\n if (isSchema(target)) {\n prefixes.push(value.$ref);\n visit(target);\n }\n }\n // References below a branch have schema paths outside its path prefix.\n for (const keyword of [\"properties\", \"patternProperties\", \"dependentSchemas\"]) {\n const children = value[keyword];\n if (isSchema(children))\n for (const child of Object.values(children)) if (isSchema(child)) visit(child);\n }\n for (const keyword of [\"anyOf\", \"oneOf\", \"allOf\", \"prefixItems\"]) {\n const children = value[keyword];\n if (Array.isArray(children)) for (const child of children) if (isSchema(child)) visit(child);\n }\n for (const keyword of [\n \"items\",\n \"additionalItems\",\n \"additionalProperties\",\n \"unevaluatedProperties\",\n \"not\",\n \"if\",\n \"then\",\n \"else\",\n \"contains\",\n \"propertyNames\",\n ]) {\n const child = value[keyword];\n if (isSchema(child)) visit(child);\n else if (keyword === \"items\" && Array.isArray(child))\n for (const entry of child) if (isSchema(entry)) visit(entry);\n }\n };\n visit(schema);\n return prefixes;\n}\n\nfunction literalConstraints(schema: JsonSchema, root: JsonSchema): LiteralConstraint[] {\n const constraints: LiteralConstraint[] = [];\n const active = new Set<JsonSchema>();\n const visit = (value: JsonSchema, path: readonly string[], required: boolean) => {\n if (active.has(value)) return;\n active.add(value);\n if (typeof value.$ref === \"string\") {\n const target = schemaAt(root, value.$ref, value);\n if (isSchema(target)) {\n visit(target, path, required);\n }\n }\n const literals = \"const\" in value ? [value.const] : Array.isArray(value.enum) ? value.enum : [];\n if (\n literals.length &&\n literals.every(\n (literal) => literal === null || [\"string\", \"number\", \"boolean\"].includes(typeof literal),\n )\n ) {\n constraints.push({ path, values: literals, required });\n }\n if (Array.isArray(value.allOf))\n for (const child of value.allOf) if (isSchema(child)) visit(child, path, required);\n if (isSchema(value.properties))\n for (const [key, child] of Object.entries(value.properties)) {\n if (isSchema(child))\n visit(\n child,\n [...path, key],\n required && Array.isArray(value.required) && value.required.includes(key),\n );\n }\n active.delete(value);\n };\n visit(schema, [], true);\n // Multiple conjunctions may constrain the same tag; all must hold.\n const combined: LiteralConstraint[] = [];\n for (const constraint of constraints) {\n const index = combined.findIndex((other) => samePath(other.path, constraint.path));\n if (index < 0) combined.push(constraint);\n else {\n const previous = combined[index]!;\n combined[index] = {\n path: constraint.path,\n values: previous.values.filter((value) => constraint.values.includes(value)),\n required: previous.required || constraint.required,\n };\n }\n }\n return combined;\n}\n\nfunction argumentAt(root: unknown, path: readonly string[]): { present: boolean; value: unknown } {\n let value = root;\n for (const segment of path) {\n if (value === null || typeof value !== \"object\" || !Object.hasOwn(value, segment))\n return { present: false, value: undefined };\n value = (value as Record<string, unknown>)[segment];\n }\n return { present: true, value };\n}\n\nfunction samePath(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((segment, index) => segment === right[index]);\n}\n\n/** One-line summary of issues, for example `missing required property \"context\"`. */\nexport function formatToolGatewayInputIssues(\n issues: readonly ToolGatewayInputIssue[],\n omittedIssueCount = 0,\n): string {\n const parts = issues.map((issue) => issue.message);\n if (omittedIssueCount > 0) {\n parts.push(`and ${omittedIssueCount} more ${omittedIssueCount === 1 ? \"problem\" : \"problems\"}`);\n }\n return parts.join(\"; \");\n}\n\nfunction issueFromError(error: ErrorObject): ToolGatewayInputIssue {\n const params = (error.params ?? {}) as Record<string, unknown>;\n const at = pointerSegments(error.instancePath);\n const subject = describe(displayPath(at));\n // A `propertyNames` subschema failure describes a key of the object at\n // `instancePath`, not the object itself; name the object, never the key.\n const keyword =\n (error as { propertyName?: unknown }).propertyName !== undefined\n ? \"propertyNames\"\n : error.keyword;\n switch (keyword) {\n case \"required\": {\n const path = displayPath([...at, String(params.missingProperty)]);\n return { path, keyword: error.keyword, message: `missing required property \"${path}\"` };\n }\n case \"dependentRequired\":\n case \"dependencies\": {\n const path = displayPath([...at, String(params.missingProperty)]);\n const trigger = displayPath([...at, String(params.property)]);\n return {\n path,\n keyword: error.keyword,\n message: `missing required property \"${path}\" (required when \"${trigger}\" is present)`,\n };\n }\n case \"additionalProperties\":\n case \"unevaluatedProperties\": {\n const name = params.additionalProperty ?? params.unevaluatedProperty;\n const path = displayPath([...at, String(name)]);\n return { path, keyword: error.keyword, message: `property \"${path}\" is not allowed` };\n }\n case \"type\": {\n const expected = Array.isArray(params.type) ? params.type.join(\" or \") : String(params.type);\n return {\n path: displayPath(at),\n keyword: error.keyword,\n message: `${subject} must be ${bounded(expected, MESSAGE_DETAIL_MAX_CHARS)}`,\n };\n }\n case \"enum\": {\n const allowed = Array.isArray(params.allowedValues)\n ? allowedValuesText(params.allowedValues)\n : null;\n return {\n path: displayPath(at),\n keyword: error.keyword,\n message: allowed\n ? `${subject} must be one of ${allowed}`\n : `${subject} must be one of the allowed values`,\n };\n }\n case \"const\":\n return {\n path: displayPath(at),\n keyword: error.keyword,\n message: `${subject} must equal ${schemaValueText(params.allowedValue)}`,\n };\n case \"propertyNames\":\n return {\n path: displayPath(at),\n keyword,\n message: `${subject} has a property name the schema does not allow`,\n };\n default:\n return {\n path: displayPath(at),\n keyword: bounded(error.keyword, 64),\n message: `${subject} ${bounded(cleanText(error.message ?? \"is invalid\"), MESSAGE_DETAIL_MAX_CHARS)}`,\n };\n }\n}\n\nfunction describe(path: string): string {\n return path ? `\"${path}\"` : \"arguments\";\n}\n\nfunction pointerSegments(pointer: string): string[] {\n if (!pointer) return [];\n return pointer\n .slice(1)\n .split(\"/\")\n .map((segment) => segment.replace(/~1/gu, \"/\").replace(/~0/gu, \"~\"));\n}\n\n/**\n * Render JSON Pointer segments as `a.b[0].c`. A top-level name is shown as is;\n * an unusual nested name is bracket-quoted so the path stays unambiguous.\n */\nfunction displayPath(segments: readonly string[]): string {\n let path = \"\";\n for (const segment of segments) {\n if (/^(?:0|[1-9][0-9]*)$/u.test(segment)) path += `[${segment}]`;\n else if (!path) path = cleanText(segment);\n else if (/^[A-Za-z_$][A-Za-z0-9_$-]*$/u.test(segment)) path += `.${segment}`;\n else path += `[${JSON.stringify(segment)}]`;\n if (path.length > PATH_MAX_CHARS) break;\n }\n return bounded(path, PATH_MAX_CHARS);\n}\n\nfunction allowedValuesText(values: readonly unknown[]): string | null {\n if (values.length === 0) return null;\n const shown = values.slice(0, ALLOWED_VALUES_MAX).map(schemaValueText);\n if (values.length > ALLOWED_VALUES_MAX) shown.push(\"...\");\n return shown.join(\", \");\n}\n\nfunction schemaValueText(value: unknown): string {\n let text: string;\n try {\n text = JSON.stringify(value) ?? String(value);\n } catch {\n text = \"the schema constant\";\n }\n return bounded(cleanText(text), ALLOWED_VALUE_MAX_CHARS);\n}\n\nfunction cleanText(value: string): string {\n return value.replace(/[\\u0000-\\u001f\\u007f]+/gu, \" \").trim();\n}\n\nfunction bounded(value: string, max: number): string {\n return value.length <= max ? value : `${value.slice(0, max - 3)}...`;\n}\n","import { formatToolGatewayInputIssues, type ToolGatewayInputIssue } from \"./input-issues\";\n\nexport class ToolGatewayCatalogStaleError extends Error {\n readonly code = \"catalog_stale\";\n\n constructor() {\n super(\"Tool catalog is stale for the active gateway\");\n this.name = \"ToolGatewayCatalogStaleError\";\n }\n}\n\nexport class ToolGatewayToolNotFoundError extends Error {\n readonly code = \"tool_not_found\";\n\n constructor() {\n super(\"Tool is not present in the active gateway catalog\");\n this.name = \"ToolGatewayToolNotFoundError\";\n }\n}\n\nexport class ToolGatewayApprovalRequiredError extends Error {\n readonly code = \"approval_required\";\n\n constructor() {\n super(\"Tool requires human approval\");\n this.name = \"ToolGatewayApprovalRequiredError\";\n }\n}\n\nexport class ToolGatewayBlockedError extends Error {\n readonly code = \"tool_blocked\";\n constructor() {\n super(\"This action is blocked by your tool permissions\");\n this.name = \"ToolGatewayBlockedError\";\n }\n}\n\nexport class ToolGatewayCatalogIntegrityError extends Error {\n readonly code = \"catalog_integrity_failed\";\n\n constructor() {\n super(\"Tool catalog digest does not match its authoritative content\");\n this.name = \"ToolGatewayCatalogIntegrityError\";\n }\n}\n\nexport class ToolGatewayCatalogTooLargeError extends Error {\n readonly code = \"catalog_too_large\";\n\n constructor() {\n super(\"Tool catalog exceeds the maximum serialized size\");\n this.name = \"ToolGatewayCatalogTooLargeError\";\n }\n}\n\nexport class ToolGatewayPathCollisionError extends Error {\n readonly code = \"tool_path_collision\";\n\n constructor(path: readonly string[], kind: \"collision\" | \"extends_leaf\") {\n super(\n kind === \"extends_leaf\"\n ? `Tool path ${path.join(\".\")} extends a tool leaf`\n : `Tool path ${path.join(\".\")} collides`,\n );\n this.name = \"ToolGatewayPathCollisionError\";\n }\n}\n\nexport class ToolGatewayInputValidationError extends Error {\n readonly code = \"invalid_tool_arguments\";\n /** Value-free problems, capped at `TOOL_GATEWAY_INPUT_ISSUES_MAX`. */\n readonly issues: readonly ToolGatewayInputIssue[];\n /** Distinct problems found beyond the reported cap. */\n readonly omittedIssueCount: number;\n /** One-line summary of `issues`, or an empty string when none were captured. */\n readonly summary: string;\n\n constructor(issues: readonly ToolGatewayInputIssue[] = [], omittedIssueCount = 0) {\n const summary = formatToolGatewayInputIssues(issues, omittedIssueCount);\n super(\n summary\n ? `Tool arguments do not match the tool's input schema: ${summary}`\n : \"Tool arguments do not match the tool's input schema\",\n );\n this.name = \"ToolGatewayInputValidationError\";\n this.issues = issues;\n this.omittedIssueCount = omittedIssueCount;\n this.summary = summary;\n }\n}\n\nexport class ToolGatewayOutputValidationError extends Error {\n readonly code = \"invalid_tool_result\";\n\n constructor() {\n super(\"Tool result does not match the gateway catalog output schema\");\n this.name = \"ToolGatewayOutputValidationError\";\n }\n}\n","import type { ToolGatewayCatalogEntry } from \"@opengeni/contracts\";\nimport { compareCanonicalStrings, parseVerifiedToolGatewayCatalog } from \"./catalog\";\nimport { ToolGatewayPathCollisionError } from \"./errors\";\n\nexport type GenerateToolGatewayDeclarationsOptions = {\n moduleSpecifier?: string;\n interfaceName?: string;\n};\n\ntype NamespaceNode = {\n children: Map<string, NamespaceNode>;\n entry: ToolGatewayCatalogEntry | null;\n};\n\n/** Generate declaration merging for one exact digest-pinned workspace catalog. */\nexport function generateToolGatewayDeclarations(\n catalog: Parameters<typeof parseVerifiedToolGatewayCatalog>[0],\n options: GenerateToolGatewayDeclarationsOptions = {},\n): string {\n const verified = parseVerifiedToolGatewayCatalog(catalog);\n return generateToolDeclarations(\n { digest: verified.digest, entries: verified.entries },\n {\n moduleSpecifier: options.moduleSpecifier ?? \"@opengeni/sdk\",\n interfaceName: options.interfaceName ?? \"OpenGeniGeneratedTools\",\n callOptionsType: \"OpenGeniToolCallOptions\",\n fallbackResultType: \"ToolGatewayResult\",\n generatedBy: \"@opengeni/tool-gateway\",\n catalogDigestLabel: \"Tool catalog digest\",\n },\n );\n}\n\nexport function generateToolDeclarations(\n catalog: { digest: string; entries: readonly ToolGatewayCatalogEntry[] },\n options: {\n moduleSpecifier: string;\n interfaceName: string;\n callOptionsType: string;\n fallbackResultType: string;\n /** Optional runtime wrapper for typed results carrying out-of-band image blocks. */\n typedResultWrapperType?: string;\n generatedBy: string;\n catalogDigestLabel?: string;\n },\n): string {\n const root = namespaceNode();\n for (const entry of catalog.entries) insertEntry(root, entry);\n return [\n `// Generated by ${options.generatedBy}. Do not edit.`,\n `// ${options.catalogDigestLabel ?? \"Tool catalog digest\"}: ${catalog.digest}`,\n ...(options.typedResultWrapperType\n ? [\n \"// Typed calls normally return their structured output. If image blocks are present,\",\n \"// they return CodemodeMultimodalValue<T> with local image paths and original content.\",\n ]\n : []),\n `import type { ${[\n options.callOptionsType,\n options.fallbackResultType,\n ...(options.typedResultWrapperType ? [options.typedResultWrapperType] : []),\n ].join(\", \")} } from ${JSON.stringify(options.moduleSpecifier)};`,\n \"\",\n `declare module ${JSON.stringify(options.moduleSpecifier)} {`,\n ` interface ${options.interfaceName} {`,\n ...renderChildren(root, 4, options),\n \" }\",\n \"}\",\n \"\",\n \"export {};\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Honest bounded JSON-Schema-to-TypeScript projection for generated declarations. */\nexport function jsonSchemaToTypeScript(schema: unknown): string {\n return schemaType(schema, schema, new Set(), 0);\n}\n\nfunction namespaceNode(): NamespaceNode {\n return { children: new Map(), entry: null };\n}\n\nfunction insertEntry(root: NamespaceNode, entry: ToolGatewayCatalogEntry): void {\n let node = root;\n for (const [index, segment] of entry.codemodePath.entries()) {\n if (node.entry) {\n throw new ToolGatewayPathCollisionError(entry.codemodePath, \"extends_leaf\");\n }\n let child = node.children.get(segment);\n if (!child) {\n child = namespaceNode();\n node.children.set(segment, child);\n }\n node = child;\n if (index === entry.codemodePath.length - 1) {\n if (node.entry || node.children.size > 0) {\n throw new ToolGatewayPathCollisionError(entry.codemodePath, \"collision\");\n }\n node.entry = entry;\n }\n }\n}\n\nfunction renderChildren(\n node: NamespaceNode,\n indent: number,\n options: Parameters<typeof generateToolDeclarations>[1],\n): string[] {\n const lines: string[] = [];\n for (const [name, child] of [...node.children].sort(([left], [right]) =>\n compareCanonicalStrings(left, right),\n )) {\n if (child.entry) {\n const entry = child.entry;\n const input = jsonSchemaToTypeScript(entry.inputSchema);\n const structuredOutput = entry.outputSchema\n ? jsonSchemaToTypeScript(entry.outputSchema)\n : null;\n const output = structuredOutput\n ? options.typedResultWrapperType\n ? `${structuredOutput} | ${options.typedResultWrapperType}<${structuredOutput}>`\n : structuredOutput\n : options.fallbackResultType;\n const description = boundedDoc(entry.description ?? entry.title);\n if (description) lines.push(...renderDoc(description, indent));\n lines.push(`${spaces(indent)}readonly ${name}: (`);\n lines.push(\n `${spaces(indent + 2)}argumentsValue${rootObjectArgumentsAreOptional(entry.inputSchema) ? \"?\" : \"\"}: ${input},`,\n );\n lines.push(`${spaces(indent + 2)}options?: ${options.callOptionsType},`);\n lines.push(`${spaces(indent)}) => Promise<${output}>;`);\n continue;\n }\n lines.push(`${spaces(indent)}readonly ${name}: {`);\n lines.push(...renderChildren(child, indent + 2, options));\n lines.push(`${spaces(indent)}};`);\n }\n return lines;\n}\n\nfunction rootObjectArgumentsAreOptional(schema: unknown): boolean {\n if (!isObject(schema)) return false;\n const required = Array.isArray(schema.required)\n ? schema.required.filter((value): value is string => typeof value === \"string\")\n : [];\n return required.length === 0 && (schema.type === \"object\" || isObject(schema.properties));\n}\n\nfunction schemaType(schema: unknown, root: unknown, resolving: Set<string>, depth: number): string {\n if (depth > 48 || schema === true) return \"unknown\";\n if (schema === false) return \"never\";\n if (!isObject(schema)) return \"unknown\";\n if (typeof schema.$ref === \"string\") {\n if (!schema.$ref.startsWith(\"#/\") || resolving.has(schema.$ref)) return \"unknown\";\n const resolved = resolveLocalReference(root, schema.$ref);\n if (resolved === undefined) return \"unknown\";\n const next = new Set(resolving);\n next.add(schema.$ref);\n return schemaType(resolved, root, next, depth + 1);\n }\n if (Object.hasOwn(schema, \"const\")) return literalType(schema.const);\n if (Array.isArray(schema.enum)) return union(schema.enum.map(literalType));\n const composites: string[] = [];\n if (Array.isArray(schema.oneOf)) {\n composites.push(\n union(schema.oneOf.map((part) => schemaType(part, root, resolving, depth + 1))),\n );\n }\n if (Array.isArray(schema.anyOf)) {\n composites.push(\n union(schema.anyOf.map((part) => schemaType(part, root, resolving, depth + 1))),\n );\n }\n if (Array.isArray(schema.allOf)) {\n composites.push(\n intersection(schema.allOf.map((part) => schemaType(part, root, resolving, depth + 1))),\n );\n }\n if (composites.length > 0) {\n const composed = intersection(composites);\n return schema.nullable === true ? union([composed, \"null\"]) : composed;\n }\n const types = Array.isArray(schema.type)\n ? schema.type.filter((value): value is string => typeof value === \"string\")\n : typeof schema.type === \"string\"\n ? [schema.type]\n : inferredTypes(schema);\n const rendered = types.map((type) => typeType(type, schema, root, resolving, depth + 1));\n if (schema.nullable === true) rendered.push(\"null\");\n return union(rendered.length > 0 ? rendered : [\"unknown\"]);\n}\n\nfunction typeType(\n type: string,\n schema: Record<string, unknown>,\n root: unknown,\n resolving: Set<string>,\n depth: number,\n): string {\n if (type === \"null\" || type === \"boolean\" || type === \"string\") return type;\n if (type === \"integer\" || type === \"number\") return \"number\";\n if (type === \"array\") return arrayType(schema, root, resolving, depth);\n if (type !== \"object\") return \"unknown\";\n return objectType(schema, root, resolving, depth);\n}\n\nfunction arrayType(\n schema: Record<string, unknown>,\n root: unknown,\n resolving: Set<string>,\n depth: number,\n): string {\n if (Array.isArray(schema.prefixItems)) {\n const tuple = schema.prefixItems.map((item) => schemaType(item, root, resolving, depth + 1));\n if (schema.items === false) return `readonly [${tuple.join(\", \")}]`;\n const rest =\n schema.items === undefined || schema.items === true\n ? \"unknown\"\n : schemaType(schema.items, root, resolving, depth + 1);\n return `readonly [${tuple.join(\", \")}${tuple.length > 0 ? \", \" : \"\"}...${rest}[]]`;\n }\n const item =\n schema.items === undefined || schema.items === true\n ? \"unknown\"\n : schemaType(schema.items, root, resolving, depth + 1);\n return `readonly (${item})[]`;\n}\n\nfunction objectType(\n schema: Record<string, unknown>,\n root: unknown,\n resolving: Set<string>,\n depth: number,\n): string {\n const properties = isObject(schema.properties) ? schema.properties : {};\n const required = new Set(\n Array.isArray(schema.required)\n ? schema.required.filter((value): value is string => typeof value === \"string\")\n : [],\n );\n const entries = Object.entries(properties).sort(([left], [right]) =>\n compareCanonicalStrings(left, right),\n );\n const fields = entries.map(\n ([name, value]) =>\n `readonly ${identifierOrQuoted(name)}${required.has(name) ? \"\" : \"?\"}: ${schemaType(value, root, resolving, depth + 1)}`,\n );\n for (const missing of [...required]\n .filter((name) => !Object.hasOwn(properties, name))\n .sort(compareCanonicalStrings)) {\n fields.push(`readonly ${identifierOrQuoted(missing)}: unknown`);\n }\n if (schema.additionalProperties !== false) {\n if (\n entries.length === 0 &&\n schema.additionalProperties !== undefined &&\n schema.additionalProperties !== true\n ) {\n return `Readonly<Record<string, ${schemaType(\n schema.additionalProperties,\n root,\n resolving,\n depth + 1,\n )}>>`;\n }\n fields.push(\"readonly [key: string]: unknown\");\n }\n return fields.length === 0 ? \"Record<string, never>\" : `{ ${fields.join(\"; \")} }`;\n}\n\nfunction inferredTypes(schema: Record<string, unknown>): string[] {\n if (isObject(schema.properties) || Object.hasOwn(schema, \"additionalProperties\")) {\n return [\"object\"];\n }\n if (Object.hasOwn(schema, \"items\") || Array.isArray(schema.prefixItems)) return [\"array\"];\n return [];\n}\n\nfunction resolveLocalReference(root: unknown, reference: string): unknown {\n let current = root;\n for (const encoded of reference.slice(2).split(\"/\")) {\n if (!isObject(current)) return undefined;\n const segment = encoded.replace(/~1/gu, \"/\").replace(/~0/gu, \"~\");\n if (!Object.hasOwn(current, segment)) return undefined;\n current = current[segment];\n }\n return current;\n}\n\nfunction literalType(value: unknown): string {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) return `readonly [${value.map(literalType).join(\", \")}]`;\n if (isObject(value)) {\n return `{ ${Object.entries(value)\n .sort(([left], [right]) => compareCanonicalStrings(left, right))\n .map(([key, child]) => `readonly ${identifierOrQuoted(key)}: ${literalType(child)}`)\n .join(\"; \")} }`;\n }\n return \"unknown\";\n}\n\nfunction union(values: string[]): string {\n const unique = [...new Set(values)];\n if (unique.includes(\"unknown\")) return \"unknown\";\n if (unique.length === 0) return \"never\";\n return unique.length === 1 ? unique[0]! : unique.map(parenthesizeComposite).join(\" | \");\n}\n\nfunction intersection(values: string[]): string {\n const unique = [...new Set(values.filter((value) => value !== \"unknown\"))];\n return unique.length === 0\n ? \"unknown\"\n : unique.length === 1\n ? unique[0]!\n : unique.map(parenthesizeComposite).join(\" & \");\n}\n\nfunction parenthesizeComposite(value: string): string {\n return /[|&]/u.test(value) ? `(${value})` : value;\n}\n\nfunction identifierOrQuoted(value: string): string {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(value) ? value : JSON.stringify(value);\n}\n\nfunction boundedDoc(value: string | undefined): string | null {\n if (!value) return null;\n const normalized = value.replace(/\\s+/gu, \" \").trim().replace(/\\*\\//gu, \"*\\\\/\");\n if (!normalized) return null;\n return normalized.length <= 512 ? normalized : `${normalized.slice(0, 509)}...`;\n}\n\nfunction renderDoc(value: string, indent: number): string[] {\n return [`${spaces(indent)}/** ${value} */`];\n}\n\nfunction spaces(count: number): string {\n return \" \".repeat(count);\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\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ACV,gBAAQ,EAAE,UAAU,oBAAI,IAAI,GAAG,MAAM,MAAM;AAC3C,aAAK,SAAS,IAAI,SAAS,KAAK;AAAA,MAClC;AACA,aAAO;AACP,UAAI,UAAU,KAAK,SAAS,GAAG;AAC7B,YAAI,KAAK,QAAQ,KAAK,SAAS,OAAO,GAAG;AACvC,gBAAM,IAAI,8BAA8B,MAAM,WAAW;AAAA,QAC3D;AACA,aAAK,OAAO;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,iBAAiB,MAAyB,OAAkC;AACnF,QAAM,SAAS,KAAK,IAAI,KAAK,QAAQ,MAAM,MAAM;AACjD,WAAS,QAAQ,GAAG,QAAQ,QAAQ,SAAS,GAAG;AAC9C,UAAM,WAAW,wBAAwB,KAAK,KAAK,GAAI,MAAM,KAAK,CAAE;AACpE,QAAI,aAAa,EAAG,QAAO;AAAA,EAC7B;AACA,SAAO,KAAK,SAAS,MAAM;AAC7B;AAEA,SAAS,qBAAqB,OAAuB;AACnD,MAAI,aAAa,MAAM,QAAQ,oBAAoB,GAAG;AACtD,MAAI,CAAC,eAAe,KAAK,UAAU,EAAG,cAAa,IAAI,UAAU;AACjE,MAAI,CAAC,aAAa,aAAa,aAAa,EAAE,SAAS,UAAU,GAAG;AAClE,iBAAa,IAAI,UAAU;AAAA,EAC7B;AACA,SAAO,WAAW,MAAM,GAAG,GAAG,KAAK;AACrC;AAEA,SAAS,oBAAoB,UAAuC;AAClE,SAAOC,YAAW,QAAQ,EAAE,OAAO,YAAY,QAAQ,GAAG,MAAM,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,EAAE;AAC7F;AAEA,SAAS,YAAY,UAAuC;AAC1D,SAAO,GAAG,SAAS,QAAQ,KAAS,SAAS,QAAQ;AACvD;","names":["createHash","ToolGatewayCatalog","union","issue","branch","item","ToolGatewayCatalog","createHash"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengeni/tool-gateway",
3
- "version": "1.2.1-canary.37222965366001",
3
+ "version": "1.3.0",
4
4
  "description": "Protocol-neutral catalog validation, authorization, and execution core for OpenGeni tools.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -34,8 +34,8 @@
34
34
  "prepublishOnly": "bash ../../scripts/prepublish-guard"
35
35
  },
36
36
  "dependencies": {
37
- "@opengeni/contracts": "1.2.1-canary.37222965366001",
38
- "@opengeni/observability": "1.2.1-canary.37222965366001",
37
+ "@opengeni/contracts": "1.3.0",
38
+ "@opengeni/observability": "1.3.0",
39
39
  "ajv": "^8.20.0"
40
40
  },
41
41
  "engines": {
package/src/errors.ts CHANGED
@@ -27,6 +27,14 @@ export class ToolGatewayApprovalRequiredError extends Error {
27
27
  }
28
28
  }
29
29
 
30
+ export class ToolGatewayBlockedError extends Error {
31
+ readonly code = "tool_blocked";
32
+ constructor() {
33
+ super("This action is blocked by your tool permissions");
34
+ this.name = "ToolGatewayBlockedError";
35
+ }
36
+ }
37
+
30
38
  export class ToolGatewayCatalogIntegrityError extends Error {
31
39
  readonly code = "catalog_integrity_failed";
32
40
 
package/src/index.ts CHANGED
@@ -16,6 +16,7 @@ import {
16
16
  ToolGatewayCatalogEntry,
17
17
  ToolGatewayResult,
18
18
  isToolResultSpilledReceipt,
19
+ executableToolSchema,
19
20
  type ToolGatewayCaller,
20
21
  type ToolGatewayCatalog as ToolGatewayCatalogValue,
21
22
  type ToolGatewayCatalogEntry as ToolGatewayCatalogEntryValue,
@@ -30,6 +31,7 @@ import {
30
31
  } from "./catalog";
31
32
  import {
32
33
  ToolGatewayApprovalRequiredError,
34
+ ToolGatewayBlockedError,
33
35
  ToolGatewayCatalogStaleError,
34
36
  ToolGatewayInputValidationError,
35
37
  ToolGatewayOutputValidationError,
@@ -58,6 +60,8 @@ export type ToolGatewayDefinition = Omit<ToolGatewayCatalogEntryValue, "codemode
58
60
  codemodePath?: readonly string[];
59
61
  /** Internal authority revision bound into human approval capabilities. */
60
62
  approvalAuthorityDigest?: string;
63
+ /** Executable effect/account identity; excludes unrelated revision changes. */
64
+ effectAuthorityDigest?: string;
61
65
  /** Connection-backed calls must have a side-effect-free provider preflight before approval. */
62
66
  requiresProviderPreflight?: boolean;
63
67
  /** In-process provider preflight; never enters the public catalog or its digest. */
@@ -79,6 +83,12 @@ export type ToolGatewayAuthorization = (input: {
79
83
  entry: ToolGatewayCatalogEntryValue;
80
84
  }) => Promise<void> | void;
81
85
 
86
+ /** A trusted adapter resolves user preferences after schema and access validation. */
87
+ export type ToolGatewayApprovalResolver = (input: {
88
+ call: ToolGatewayCall;
89
+ entry: ToolGatewayCatalogEntryValue;
90
+ }) => Promise<"allow" | "ask" | "block"> | "allow" | "ask" | "block";
91
+
82
92
  export type ToolGatewayCall = {
83
93
  operationId: string;
84
94
  catalogDigest: string;
@@ -92,6 +102,8 @@ export type ToolGatewayCallSettlement =
92
102
  | { outcome: "failed"; error: unknown };
93
103
 
94
104
  export type PreparedToolGatewayCallLifecycle = {
105
+ /** Exact durable review created by a trusted policy adapter. */
106
+ waitingForApproval?: { requestId: string; actionFingerprint: string };
95
107
  /** Cross the side-effect boundary immediately before the executor closure. */
96
108
  begin?: () => Promise<void> | void;
97
109
  /** Settle the side-effect lifecycle after a returned result or thrown failure. */
@@ -122,6 +134,7 @@ type CompiledDefinition = {
122
134
  entry: ToolGatewayCatalogEntryValue;
123
135
  execute: ToolGatewayDefinition["execute"];
124
136
  approvalAuthorityDigest: string | undefined;
137
+ effectAuthorityDigest: string | undefined;
125
138
  preflightCall: ToolGatewayDefinition["preflightCall"];
126
139
  lifecycle: ToolGatewayCallLifecycle | undefined;
127
140
  validateInput: ValidateFunction<unknown>;
@@ -134,6 +147,10 @@ export type PreparedToolGatewayCall = {
134
147
  readonly call: ToolGatewayCall;
135
148
  readonly entry: ToolGatewayCatalogEntryValue;
136
149
  readonly approvalAuthorityDigest: string;
150
+ /** Effective choice; optional for older adapters constructing this interface. */
151
+ readonly approvalDecision?: "allow" | "ask";
152
+ readonly waitingForApproval?: { requestId: string; actionFingerprint: string };
153
+ readonly effectDigest?: string;
137
154
  execute: () => Promise<ToolGatewayResultValue>;
138
155
  };
139
156
 
@@ -147,6 +164,7 @@ export class PreparedToolGatewayDefinitions {
147
164
  create(input: {
148
165
  catalogDigest: string;
149
166
  authorize?: ToolGatewayAuthorization;
167
+ resolveApproval?: ToolGatewayApprovalResolver;
150
168
  requireApproval?: (
151
169
  entry: ToolGatewayCatalogEntryValue,
152
170
  caller: ToolGatewayCaller,
@@ -164,6 +182,7 @@ export class PreparedToolGatewayDefinitions {
164
182
  input.authorize,
165
183
  input.requireApproval,
166
184
  input.confirmModelApproval,
185
+ input.resolveApproval,
167
186
  );
168
187
  }
169
188
  }
@@ -190,6 +209,7 @@ export class ToolGateway {
190
209
  subjectId: string;
191
210
  }) => boolean)
192
211
  | undefined,
212
+ private readonly resolveApproval?: ToolGatewayApprovalResolver,
193
213
  ) {
194
214
  for (const definition of definitions) {
195
215
  this.byIdentity.set(identityKey(definition.entry.identity), definition);
@@ -244,7 +264,7 @@ export class ToolGateway {
244
264
  if (!definition) {
245
265
  throw new ToolGatewayToolNotFoundError();
246
266
  }
247
- if (this.requireApproval?.(definition.entry, caller, context)) {
267
+ if (!this.resolveApproval && this.requireApproval?.(definition.entry, caller, context)) {
248
268
  throw new ToolGatewayApprovalRequiredError();
249
269
  }
250
270
  if (!definition.validateInput(request.arguments)) {
@@ -252,6 +272,7 @@ export class ToolGateway {
252
272
  }
253
273
  if (
254
274
  caller.kind === "model" &&
275
+ !this.resolveApproval &&
255
276
  definition.entry.approval === "human" &&
256
277
  !modelApprovalConfirmed
257
278
  ) {
@@ -267,7 +288,22 @@ export class ToolGateway {
267
288
  await measureMcpPhase("provider_authorization", () =>
268
289
  this.authorize?.({ call, entry: definition.entry }),
269
290
  );
270
- if (definition.entry.approval === "human") {
291
+ const approvalDecision = this.resolveApproval
292
+ ? await this.resolveApproval({ call, entry: definition.entry })
293
+ : definition.entry.approval === "human"
294
+ ? "ask"
295
+ : "allow";
296
+ if (approvalDecision === "block") throw new ToolGatewayBlockedError();
297
+ if (
298
+ this.resolveApproval &&
299
+ approvalDecision === "ask" &&
300
+ (caller.kind === "model"
301
+ ? !modelApprovalConfirmed
302
+ : context.transportMeta?.approvalConfirmed !== true)
303
+ ) {
304
+ throw new ToolGatewayApprovalRequiredError();
305
+ }
306
+ if (approvalDecision === "ask") {
271
307
  await measureMcpPhase("preflight", () =>
272
308
  definition.preflightCall?.({
273
309
  call,
@@ -286,6 +322,11 @@ export class ToolGateway {
286
322
  return {
287
323
  call,
288
324
  entry: definition.entry,
325
+ approvalDecision,
326
+ ...(lifecycle?.waitingForApproval
327
+ ? { waitingForApproval: lifecycle.waitingForApproval }
328
+ : {}),
329
+ effectDigest: this.effectDigest(request.identity),
289
330
  approvalAuthorityDigest:
290
331
  definition.approvalAuthorityDigest ??
291
332
  digestCanonicalJson({
@@ -297,6 +338,7 @@ export class ToolGateway {
297
338
  measureMcpPhase(
298
339
  "execution",
299
340
  async () => {
341
+ if (lifecycle?.waitingForApproval) throw new ToolGatewayApprovalRequiredError();
300
342
  await measureMcpPhase("lifecycle_begin", () => lifecycle?.begin?.());
301
343
  let result: ToolGatewayResultValue;
302
344
  try {
@@ -337,6 +379,24 @@ export class ToolGateway {
337
379
  };
338
380
  }
339
381
 
382
+ /** Binds continuation to one executable operation, independent of unrelated catalog changes. */
383
+ effectDigest(identity: ToolGatewayIdentity): string {
384
+ const definition = this.byIdentity.get(identityKey(identity));
385
+ if (!definition) throw new ToolGatewayToolNotFoundError();
386
+ const { entry } = definition;
387
+ return digestCanonicalJson({
388
+ version: 1,
389
+ identity: entry.identity,
390
+ source: entry.source,
391
+ inputSchema: executableToolSchema(entry.inputSchema),
392
+ outputSchema: executableToolSchema(entry.outputSchema ?? null),
393
+ readOnly: entry.annotations?.readOnlyHint ?? null,
394
+ destructive: entry.annotations?.destructiveHint ?? null,
395
+ idempotent: entry.annotations?.idempotentHint ?? null,
396
+ authority: definition.effectAuthorityDigest ?? definition.approvalAuthorityDigest ?? null,
397
+ });
398
+ }
399
+
340
400
  async callModel(input: ModelToolGatewayCall): Promise<ToolGatewayResultValue> {
341
401
  const definition = this.byModelName.get(input.modelName);
342
402
  if (!definition) {
@@ -377,6 +437,7 @@ export function prepareToolGatewayDefinitions(
377
437
  const {
378
438
  execute,
379
439
  approvalAuthorityDigest,
440
+ effectAuthorityDigest,
380
441
  requiresProviderPreflight: _requiresProviderPreflight,
381
442
  preflightCall,
382
443
  lifecycle,
@@ -386,6 +447,9 @@ export function prepareToolGatewayDefinitions(
386
447
  if (approvalAuthorityDigest !== undefined && !/^[0-9a-f]{64}$/u.test(approvalAuthorityDigest)) {
387
448
  throw new Error("Tool gateway approval authority digest must be lowercase SHA-256 hex");
388
449
  }
450
+ if (effectAuthorityDigest !== undefined && !/^[0-9a-f]{64}$/u.test(effectAuthorityDigest)) {
451
+ throw new Error("Tool gateway effect authority digest must be lowercase SHA-256 hex");
452
+ }
389
453
  const entry = ToolGatewayCatalogEntry.parse({
390
454
  ...entryInput,
391
455
  codemodePath: paths[index],
@@ -395,6 +459,7 @@ export function prepareToolGatewayDefinitions(
395
459
  entry,
396
460
  execute,
397
461
  approvalAuthorityDigest,
462
+ effectAuthorityDigest,
398
463
  preflightCall,
399
464
  lifecycle,
400
465
  validateInput: compileCatalogSchema(schemaValidators, entry.inputSchema),
@@ -418,6 +483,7 @@ export function createWorkspaceToolGateway(input: {
418
483
  definitions: readonly ToolGatewayDefinition[];
419
484
  createdAt?: Date;
420
485
  authorize?: ToolGatewayAuthorization;
486
+ resolveApproval?: ToolGatewayApprovalResolver;
421
487
  requireApproval?: (
422
488
  entry: ToolGatewayCatalogEntryValue,
423
489
  caller: ToolGatewayCaller,
@@ -443,6 +509,7 @@ export function createWorkspaceToolGateway(input: {
443
509
  gateway: prepared.create({
444
510
  catalogDigest: catalog.digest,
445
511
  ...(input.authorize ? { authorize: input.authorize } : {}),
512
+ ...(input.resolveApproval ? { resolveApproval: input.resolveApproval } : {}),
446
513
  ...(input.requireApproval ? { requireApproval: input.requireApproval } : {}),
447
514
  }),
448
515
  };