@opengeni/tool-gateway 0.1.6 → 0.1.7-canary.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -3,11 +3,13 @@ import { type ToolGatewayCaller, type ToolGatewayCatalog as ToolGatewayCatalogVa
3
3
  export type ToolGatewayExecutionContext = {
4
4
  operationId: string;
5
5
  caller: ToolGatewayCaller;
6
+ /** Trusted in-process SDK correlation; not operation identity or approval authority. */
7
+ sourceCallId?: string;
6
8
  /** In-process transport metadata; never part of catalog identity or digest. */
7
9
  transportMeta?: Record<string, unknown> | null;
8
10
  signal?: AbortSignal;
9
11
  };
10
- export type ToolGatewayCallContext = Pick<ToolGatewayExecutionContext, "transportMeta" | "signal">;
12
+ export type ToolGatewayCallContext = Pick<ToolGatewayExecutionContext, "sourceCallId" | "transportMeta" | "signal">;
11
13
  export type ToolGatewayDefinition = Omit<ToolGatewayCatalogEntryValue, "codemodePath"> & {
12
14
  /** Optional human-readable path. Unsafe/colliding segments are normalized. */
13
15
  codemodePath?: readonly string[];
@@ -59,6 +61,8 @@ export type ToolGatewayCallLifecycle = {
59
61
  };
60
62
  export type ModelToolGatewayCall = {
61
63
  operationId?: string;
64
+ /** Exact SDK call id supplied by the host, never inferred from arguments or metadata. */
65
+ sourceCallId?: string;
62
66
  modelName: string;
63
67
  arguments: Record<string, unknown>;
64
68
  subjectId: string;
package/dist/index.js CHANGED
@@ -445,6 +445,7 @@ var ToolGateway = class {
445
445
  await definition.execute(request.arguments, {
446
446
  operationId,
447
447
  caller,
448
+ ...context.sourceCallId === void 0 ? {} : { sourceCallId: context.sourceCallId },
448
449
  ...context.transportMeta === void 0 ? {} : { transportMeta: context.transportMeta },
449
450
  ...context.signal === void 0 ? {} : { signal: context.signal }
450
451
  })
@@ -477,6 +478,7 @@ var ToolGateway = class {
477
478
  caller: { kind: "model", subjectId: input.subjectId }
478
479
  };
479
480
  const context = {
481
+ ...input.sourceCallId === void 0 ? {} : { sourceCallId: input.sourceCallId },
480
482
  ...input.transportMeta === void 0 ? {} : { transportMeta: input.transportMeta },
481
483
  ...input.signal === void 0 ? {} : { signal: input.signal }
482
484
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/catalog.ts","../src/errors.ts","../src/declarations.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport Ajv, { type ValidateFunction } 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\";\n\nexport type ToolGatewayExecutionContext = {\n operationId: string;\n caller: ToolGatewayCaller;\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<ToolGatewayExecutionContext, \"transportMeta\" | \"signal\">;\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 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 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 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 new ToolGatewayInputValidationError();\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 this.authorize?.({ call, entry: definition.entry });\n if (definition.entry.approval === \"human\") {\n await definition.preflightCall?.({\n call,\n entry: definition.entry,\n context,\n });\n }\n const lifecycle = await definition.lifecycle?.prepare({\n call,\n entry: definition.entry,\n context,\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 await lifecycle?.begin?.();\n let result: ToolGatewayResultValue;\n try {\n result = ToolGatewayResult.parse(\n await definition.execute(request.arguments, {\n operationId,\n caller,\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 lifecycle?.complete?.({ outcome: \"failed\", error });\n throw error;\n }\n await lifecycle?.complete?.({ outcome: \"completed\", result });\n return result;\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.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();\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 return {\n entry,\n execute,\n approvalAuthorityDigest,\n preflightCall,\n lifecycle,\n validateInput: compileCatalogSchema(schemaValidators, entry.inputSchema),\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\nconst COMPILED_CATALOG_SCHEMA_CACHE_MAX_ENTRIES = 512;\nconst compiledCatalogSchemaCache = new Map<string, ValidateFunction<unknown>>();\n\nfunction createSchemaValidators(): {\n draft7: SchemaCompiler;\n draft2019: SchemaCompiler;\n draft2020: SchemaCompiler;\n} {\n const options = {\n allErrors: false,\n coerceTypes: false,\n strict: false,\n useDefaults: false,\n validateFormats: false,\n } as const;\n return {\n draft7: new Ajv(options),\n draft2019: new Ajv2019(options),\n draft2020: new Ajv2020(options),\n };\n}\n\nfunction compileCatalogSchema(\n validators: ReturnType<typeof createSchemaValidators>,\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 = `${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\";\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","export 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\n constructor() {\n super(\"Tool arguments do not match the gateway catalog input schema\");\n this.name = \"ToolGatewayInputValidationError\";\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 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 `import type { ${options.callOptionsType}, ${options.fallbackResultType} } 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 output = entry.outputSchema\n ? jsonSchemaToTypeScript(entry.outputSchema)\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,OAAO,SAAoC;AAC3C,OAAO,aAAa;AACpB,OAAO,aAAa;AACpB;AAAA,EACE;AAAA,EACA;AAAA,EACA,sBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;;;AChBP,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,OAEK;;;ACLA,IAAM,+BAAN,cAA2C,MAAM;AAAA,EAC7C,OAAO;AAAA,EAEhB,cAAc;AAC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iB,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","item","ToolGatewayCatalog","createHash"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/catalog.ts","../src/errors.ts","../src/declarations.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport Ajv, { type ValidateFunction } 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\";\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 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 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 new ToolGatewayInputValidationError();\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 this.authorize?.({ call, entry: definition.entry });\n if (definition.entry.approval === \"human\") {\n await definition.preflightCall?.({\n call,\n entry: definition.entry,\n context,\n });\n }\n const lifecycle = await definition.lifecycle?.prepare({\n call,\n entry: definition.entry,\n context,\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 await 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 ? {} : { 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 lifecycle?.complete?.({ outcome: \"failed\", error });\n throw error;\n }\n await lifecycle?.complete?.({ outcome: \"completed\", result });\n return result;\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();\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 return {\n entry,\n execute,\n approvalAuthorityDigest,\n preflightCall,\n lifecycle,\n validateInput: compileCatalogSchema(schemaValidators, entry.inputSchema),\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\nconst COMPILED_CATALOG_SCHEMA_CACHE_MAX_ENTRIES = 512;\nconst compiledCatalogSchemaCache = new Map<string, ValidateFunction<unknown>>();\n\nfunction createSchemaValidators(): {\n draft7: SchemaCompiler;\n draft2019: SchemaCompiler;\n draft2020: SchemaCompiler;\n} {\n const options = {\n allErrors: false,\n coerceTypes: false,\n strict: false,\n useDefaults: false,\n validateFormats: false,\n } as const;\n return {\n draft7: new Ajv(options),\n draft2019: new Ajv2019(options),\n draft2020: new Ajv2020(options),\n };\n}\n\nfunction compileCatalogSchema(\n validators: ReturnType<typeof createSchemaValidators>,\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 = `${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\";\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","export 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\n constructor() {\n super(\"Tool arguments do not match the gateway catalog input schema\");\n this.name = \"ToolGatewayInputValidationError\";\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 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 `import type { ${options.callOptionsType}, ${options.fallbackResultType} } 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 output = entry.outputSchema\n ? jsonSchemaToTypeScript(entry.outputSchema)\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,OAAO,SAAoC;AAC3C,OAAO,aAAa;AACpB,OAAO,aAAa;AACpB;AAAA,EACE;AAAA,EACA;AAAA,EACA,sBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;;;AChBP,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,OAEK;;;ACLA,IAAM,+BAAN,cAA2C,MAAM;AAAA,EAC7C,OAAO;AAAA,EAEhB,cAAc;AACZ,UAAM,8CAA8C;AACpD,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,+BAAN,cAA2C,MAAM;AAAA,EAC7C,OAAO;AAAA,EAEhB,cAAc;AACZ,UAAM,mDAAmD;AACzD,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,mCAAN,cAA+C,MAAM;AAAA,EACjD,OAAO;AAAA,EAEhB,cAAc;AACZ,UAAM,8BAA8B;AACpC,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,mCAAN,cAA+C,MAAM;AAAA,EACjD,OAAO;A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,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","item","ToolGatewayCatalog","createHash"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengeni/tool-gateway",
3
- "version": "0.1.6",
3
+ "version": "0.1.7-canary.1",
4
4
  "description": "Protocol-neutral catalog validation, authorization, and execution core for OpenGeni tools.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -34,7 +34,7 @@
34
34
  "prepublishOnly": "bash ../../scripts/prepublish-guard"
35
35
  },
36
36
  "dependencies": {
37
- "@opengeni/contracts": "^3.0.1",
37
+ "@opengeni/contracts": "^3.0.2-canary.1",
38
38
  "ajv": "^8.20.0"
39
39
  },
40
40
  "engines": {
package/src/index.ts CHANGED
@@ -33,12 +33,17 @@ import {
33
33
  export type ToolGatewayExecutionContext = {
34
34
  operationId: string;
35
35
  caller: ToolGatewayCaller;
36
+ /** Trusted in-process SDK correlation; not operation identity or approval authority. */
37
+ sourceCallId?: string;
36
38
  /** In-process transport metadata; never part of catalog identity or digest. */
37
39
  transportMeta?: Record<string, unknown> | null;
38
40
  signal?: AbortSignal;
39
41
  };
40
42
 
41
- export type ToolGatewayCallContext = Pick<ToolGatewayExecutionContext, "transportMeta" | "signal">;
43
+ export type ToolGatewayCallContext = Pick<
44
+ ToolGatewayExecutionContext,
45
+ "sourceCallId" | "transportMeta" | "signal"
46
+ >;
42
47
 
43
48
  export type ToolGatewayDefinition = Omit<ToolGatewayCatalogEntryValue, "codemodePath"> & {
44
49
  /** Optional human-readable path. Unsafe/colliding segments are normalized. */
@@ -96,6 +101,8 @@ export type ToolGatewayCallLifecycle = {
96
101
 
97
102
  export type ModelToolGatewayCall = {
98
103
  operationId?: string;
104
+ /** Exact SDK call id supplied by the host, never inferred from arguments or metadata. */
105
+ sourceCallId?: string;
99
106
  modelName: string;
100
107
  arguments: Record<string, unknown>;
101
108
  subjectId: string;
@@ -265,6 +272,7 @@ export class ToolGateway {
265
272
  await definition.execute(request.arguments, {
266
273
  operationId,
267
274
  caller,
275
+ ...(context.sourceCallId === undefined ? {} : { sourceCallId: context.sourceCallId }),
268
276
  ...(context.transportMeta === undefined
269
277
  ? {}
270
278
  : { transportMeta: context.transportMeta }),
@@ -302,6 +310,7 @@ export class ToolGateway {
302
310
  caller: { kind: "model" as const, subjectId: input.subjectId },
303
311
  };
304
312
  const context = {
313
+ ...(input.sourceCallId === undefined ? {} : { sourceCallId: input.sourceCallId }),
305
314
  ...(input.transportMeta === undefined ? {} : { transportMeta: input.transportMeta }),
306
315
  ...(input.signal === undefined ? {} : { signal: input.signal }),
307
316
  };