@anvia/core 1.0.0-rc.2 → 1.0.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +69 -9
  2. package/dist/agent/index.d.ts +20 -13
  3. package/dist/agent/index.js +36 -15
  4. package/dist/{agent-yBG8e9Jj.d.ts → agent-CXScUOpX.d.ts} +12 -15
  5. package/dist/{chunk-77AIYARB.js → chunk-3CMWKK32.js} +28 -19
  6. package/dist/chunk-3CMWKK32.js.map +1 -0
  7. package/dist/chunk-3RM57ZT2.js +31 -0
  8. package/dist/chunk-3RM57ZT2.js.map +1 -0
  9. package/dist/{chunk-EINTGEGY.js → chunk-5MK3BISB.js} +101 -26
  10. package/dist/chunk-5MK3BISB.js.map +1 -0
  11. package/dist/{chunk-KIDGIJM7.js → chunk-AZB6N7P4.js} +94 -86
  12. package/dist/chunk-AZB6N7P4.js.map +1 -0
  13. package/dist/{chunk-DBSCKTUL.js → chunk-BY4OMNIU.js} +1746 -840
  14. package/dist/chunk-BY4OMNIU.js.map +1 -0
  15. package/dist/{chunk-KR3RCCHJ.js → chunk-D2ECOWN5.js} +26 -11
  16. package/dist/chunk-D2ECOWN5.js.map +1 -0
  17. package/dist/{chunk-FMHLROPQ.js → chunk-GQL5KRAH.js} +13 -33
  18. package/dist/chunk-GQL5KRAH.js.map +1 -0
  19. package/dist/{chunk-OJH6HWHX.js → chunk-KFR4CDGK.js} +8 -2
  20. package/dist/chunk-KFR4CDGK.js.map +1 -0
  21. package/dist/{chunk-D37WMSP6.js → chunk-KV6QCRQ4.js} +50 -10
  22. package/dist/chunk-KV6QCRQ4.js.map +1 -0
  23. package/dist/{chunk-XKYYBABH.js → chunk-LXMAFD23.js} +2 -2
  24. package/dist/{chunk-TIZYTPJO.js → chunk-PK5LKOFL.js} +33 -2
  25. package/dist/chunk-PK5LKOFL.js.map +1 -0
  26. package/dist/chunk-TRQ3XRFD.js +54 -0
  27. package/dist/chunk-TRQ3XRFD.js.map +1 -0
  28. package/dist/{chunk-CWM7B2OO.js → chunk-VKYZZXP5.js} +10 -2
  29. package/dist/chunk-VKYZZXP5.js.map +1 -0
  30. package/dist/{chunk-4WI3VGZK.js → chunk-ZCPOIDAQ.js} +3 -3
  31. package/dist/{client-B8DT1vUG.d.ts → client-DvUatElp.d.ts} +4 -3
  32. package/dist/completion/index.d.ts +3 -3
  33. package/dist/completion/index.js +2 -2
  34. package/dist/documents/index.d.ts +34 -0
  35. package/dist/documents/index.js +315 -0
  36. package/dist/documents/index.js.map +1 -0
  37. package/dist/{dynamic-tools-KwEGRbHp.d.ts → dynamic-tools-AEBOTgu1.d.ts} +3 -3
  38. package/dist/embeddings/index.js +2 -1
  39. package/dist/evals/index.d.ts +19 -11
  40. package/dist/evals/index.js +88 -55
  41. package/dist/evals/index.js.map +1 -1
  42. package/dist/extractor/index.d.ts +1 -1
  43. package/dist/extractor/index.js +3 -3
  44. package/dist/guardrails/index.d.ts +6 -129
  45. package/dist/guardrails/index.js +1 -1
  46. package/dist/image-generation/index.d.ts +1 -1
  47. package/dist/index.d.ts +15 -14
  48. package/dist/index.js +40 -19
  49. package/dist/interactions-csssHYcN.d.ts +174 -0
  50. package/dist/internal/agent.d.ts +18 -22
  51. package/dist/internal/agent.js +45 -14
  52. package/dist/internal/agent.js.map +1 -1
  53. package/dist/mcp/index.d.ts +4 -4
  54. package/dist/mcp/index.js +6 -5
  55. package/dist/memory/index.d.ts +3 -3
  56. package/dist/memory/index.js +3 -3
  57. package/dist/{message-schema-Cn7ezRfJ.d.ts → message-schema-B2M7AYzR.d.ts} +1 -1
  58. package/dist/observability/index.d.ts +8 -7
  59. package/dist/observability/index.js +3 -3
  60. package/dist/pipeline/index.d.ts +18 -18
  61. package/dist/pipeline/index.js +20 -29
  62. package/dist/pipeline/index.js.map +1 -1
  63. package/dist/skills/index.d.ts +4 -4
  64. package/dist/skills/index.js +6 -5
  65. package/dist/speech-generation/index.d.ts +1 -1
  66. package/dist/text-C_6eKrbC.d.ts +32 -0
  67. package/dist/{think-tool-6H2QNQzQ.d.ts → think-tool-D8frXxwV.d.ts} +16 -2
  68. package/dist/tool/index.d.ts +6 -6
  69. package/dist/tool/index.js +9 -4
  70. package/dist/{tool--Mz4v1eL.d.ts → tool-r62gf3QY.d.ts} +3 -2
  71. package/dist/transcription/index.d.ts +1 -1
  72. package/dist/{types-Dld1TpWj.d.ts → types-C3gv9EX6.d.ts} +1 -1
  73. package/dist/{types-3x3mOLHU.d.ts → types-CElwurHZ.d.ts} +56 -35
  74. package/dist/types-CIPaIbZo.d.ts +105 -0
  75. package/dist/{types-CQ_ioXWK.d.ts → types-D9rKQ_as.d.ts} +24 -2
  76. package/dist/{types-BVzM4RsC.d.ts → types-DbolvLtZ.d.ts} +1 -1
  77. package/dist/{types-DiJqJejp.d.ts → types-RT3cuyRk.d.ts} +1 -1
  78. package/dist/vector-store/index.d.ts +4 -4
  79. package/dist/vector-store/index.js +4 -3
  80. package/package.json +6 -6
  81. package/dist/chunk-77AIYARB.js.map +0 -1
  82. package/dist/chunk-CWM7B2OO.js.map +0 -1
  83. package/dist/chunk-D37WMSP6.js.map +0 -1
  84. package/dist/chunk-DBSCKTUL.js.map +0 -1
  85. package/dist/chunk-EINTGEGY.js.map +0 -1
  86. package/dist/chunk-FMHLROPQ.js.map +0 -1
  87. package/dist/chunk-KIDGIJM7.js.map +0 -1
  88. package/dist/chunk-KR3RCCHJ.js.map +0 -1
  89. package/dist/chunk-OJH6HWHX.js.map +0 -1
  90. package/dist/chunk-TIZYTPJO.js.map +0 -1
  91. package/dist/loaders/index.d.ts +0 -87
  92. package/dist/loaders/index.js +0 -299
  93. package/dist/loaders/index.js.map +0 -1
  94. package/dist/middleware-C7PdmKF7.d.ts +0 -56
  95. /package/dist/{chunk-XKYYBABH.js.map → chunk-LXMAFD23.js.map} +0 -0
  96. /package/dist/{chunk-4WI3VGZK.js.map → chunk-ZCPOIDAQ.js.map} +0 -0
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-CQNNSZPG.js";
4
4
  import {
5
5
  ToolOutput
6
- } from "./chunk-77AIYARB.js";
6
+ } from "./chunk-3CMWKK32.js";
7
7
  import {
8
8
  abortError,
9
9
  throwIfAborted
@@ -191,6 +191,11 @@ for (const [network, prefix] of [
191
191
  }
192
192
  var defaultAddressResolver = (hostname) => lookup(hostname, { all: true, verbatim: true });
193
193
  function parseAndValidateMcpUrl(url) {
194
+ const parsed = parseMcpHttpUrl(url);
195
+ validateMcpHostname(parsed.hostname);
196
+ return parsed;
197
+ }
198
+ function parseMcpHttpUrl(url) {
194
199
  let parsed;
195
200
  try {
196
201
  parsed = new URL(url);
@@ -200,7 +205,6 @@ function parseAndValidateMcpUrl(url) {
200
205
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
201
206
  throw new Error(`MCP URL blocked: only HTTP(S) URLs are allowed (${parsed.protocol})`);
202
207
  }
203
- validateMcpHostname(parsed.hostname);
204
208
  return parsed;
205
209
  }
206
210
  async function resolveAndValidateMcpHostname(hostname, resolveAddresses = defaultAddressResolver) {
@@ -311,6 +315,13 @@ var safeMcpDispatcher = new Agent({
311
315
 
312
316
  // src/mcp/client.ts
313
317
  var coreClientVersion;
318
+ var transportOwnedHttpHeaders = /* @__PURE__ */ new Set([
319
+ "accept",
320
+ "content-type",
321
+ "last-event-id",
322
+ "mcp-protocol-version",
323
+ "mcp-session-id"
324
+ ]);
314
325
  var McpClient = class {
315
326
  name;
316
327
  #options;
@@ -393,13 +404,14 @@ var McpClient = class {
393
404
  const serverInfo = copyServerInfo(client.getServerVersion());
394
405
  const capabilities = copyJsonObject(client.getServerCapabilities());
395
406
  const instructions = client.getInstructions();
396
- const server = freezeServer({
407
+ let registration = {
397
408
  name: this.name,
398
- tools,
399
- ...serverInfo === void 0 ? {} : { serverInfo },
400
- ...capabilities === void 0 ? {} : { capabilities },
401
- ...instructions === void 0 ? {} : { instructions }
402
- });
409
+ tools
410
+ };
411
+ if (serverInfo !== void 0) registration = { ...registration, serverInfo };
412
+ if (capabilities !== void 0) registration = { ...registration, capabilities };
413
+ if (instructions !== void 0) registration = { ...registration, instructions };
414
+ const server = freezeServer(registration);
403
415
  this.#server = server;
404
416
  return server;
405
417
  } catch (error) {
@@ -421,25 +433,88 @@ async function createTransport(options, connectOptions) {
421
433
  return transport.create({ abortSignal: connectOptions.abortSignal });
422
434
  }
423
435
  if (transport.type === "stdio") {
424
- return new StdioClientTransport({
425
- command: transport.command,
426
- ...transport.args === void 0 ? {} : { args: transport.args },
427
- ...transport.env === void 0 ? {} : { env: transport.env },
428
- ...transport.cwd === void 0 ? {} : { cwd: transport.cwd },
429
- ...transport.stderr === void 0 ? {} : { stderr: transport.stderr },
430
- ...transport.maxBufferSize === void 0 ? {} : { maxBufferSize: transport.maxBufferSize }
431
- });
436
+ let parameters2 = {
437
+ command: transport.command
438
+ };
439
+ if (transport.args !== void 0) parameters2 = { ...parameters2, args: transport.args };
440
+ if (transport.env !== void 0) parameters2 = { ...parameters2, env: transport.env };
441
+ if (transport.cwd !== void 0) parameters2 = { ...parameters2, cwd: transport.cwd };
442
+ if (transport.stderr !== void 0) parameters2 = { ...parameters2, stderr: transport.stderr };
443
+ if (transport.maxBufferSize !== void 0) {
444
+ parameters2 = { ...parameters2, maxBufferSize: transport.maxBufferSize };
445
+ }
446
+ return new StdioClientTransport(parameters2);
447
+ }
448
+ const ssrfProtection = transport.ssrfProtection ?? "strict";
449
+ if (ssrfProtection !== "strict" && ssrfProtection !== "disabled") {
450
+ throw new TypeError("MCP Streamable HTTP ssrfProtection must be strict or disabled");
451
+ }
452
+ let parameters = {};
453
+ let url;
454
+ let transportFetch;
455
+ if (ssrfProtection === "strict") {
456
+ transportFetch = createSafeMcpFetch();
457
+ url = parseAndValidateMcpUrl(transport.url);
458
+ } else {
459
+ url = parseMcpHttpUrl(transport.url);
460
+ }
461
+ if (transport.headers !== void 0) {
462
+ const headers = copyMcpHeaders(transport.headers, transport.authProvider !== void 0);
463
+ const fetchRequest = transportFetch ?? defaultMcpFetch;
464
+ transportFetch = createMcpEndpointFetch(url, headers, fetchRequest);
465
+ }
466
+ if (transportFetch !== void 0) parameters = { ...parameters, fetch: transportFetch };
467
+ if (transport.authProvider !== void 0) {
468
+ parameters = { ...parameters, authProvider: transport.authProvider };
469
+ }
470
+ if (transport.reconnectionOptions !== void 0) {
471
+ parameters = { ...parameters, reconnectionOptions: transport.reconnectionOptions };
472
+ }
473
+ if (transport.sessionId !== void 0) {
474
+ parameters = { ...parameters, sessionId: transport.sessionId };
475
+ }
476
+ return asSdkTransport(new StreamableHTTPClientTransport(url, parameters));
477
+ }
478
+ function copyMcpHeaders(value, hasAuthProvider) {
479
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
480
+ throw new TypeError("MCP Streamable HTTP headers must be a plain object");
481
+ }
482
+ const prototype = Object.getPrototypeOf(value);
483
+ if (prototype !== Object.prototype && prototype !== null) {
484
+ throw new TypeError("MCP Streamable HTTP headers must be a plain object");
485
+ }
486
+ const headers = new Headers();
487
+ for (const [name, headerValue] of Object.entries(value)) {
488
+ if (typeof headerValue !== "string") {
489
+ throw new TypeError(`MCP Streamable HTTP header ${name} must be a string`);
490
+ }
491
+ const normalizedName = name.toLowerCase();
492
+ if (transportOwnedHttpHeaders.has(normalizedName)) {
493
+ throw new TypeError(`MCP Streamable HTTP header ${name} is owned by the transport`);
494
+ }
495
+ if (hasAuthProvider && normalizedName === "authorization") {
496
+ throw new TypeError(
497
+ "MCP Streamable HTTP authorization header cannot be combined with authProvider"
498
+ );
499
+ }
500
+ headers.set(name, headerValue);
432
501
  }
433
- return asSdkTransport(
434
- new StreamableHTTPClientTransport(parseAndValidateMcpUrl(transport.url), {
435
- ...transport.requestInit === void 0 ? {} : { requestInit: transport.requestInit },
436
- ...transport.authProvider === void 0 ? {} : { authProvider: transport.authProvider },
437
- ...transport.reconnectionOptions === void 0 ? {} : { reconnectionOptions: transport.reconnectionOptions },
438
- ...transport.sessionId === void 0 ? {} : { sessionId: transport.sessionId },
439
- fetch: createSafeMcpFetch()
440
- })
441
- );
502
+ return headers;
503
+ }
504
+ function createMcpEndpointFetch(endpoint, configuredHeaders, fetchRequest) {
505
+ return (input, init) => {
506
+ const requestUrl = input instanceof Request ? new URL(input.url) : new URL(input);
507
+ if (requestUrl.href !== endpoint.href) return fetchRequest(input, init);
508
+ const requestHeaders = new Headers(
509
+ init?.headers ?? (input instanceof Request ? input.headers : void 0)
510
+ );
511
+ configuredHeaders.forEach((value, name) => {
512
+ requestHeaders.set(name, value);
513
+ });
514
+ return fetchRequest(input, { ...init, headers: requestHeaders, redirect: "error" });
515
+ };
442
516
  }
517
+ var defaultMcpFetch = (input, init) => globalThis.fetch(input, init);
443
518
  async function listAllTools(client, abortSignal) {
444
519
  const tools = [];
445
520
  const seenCursors = /* @__PURE__ */ new Set();
@@ -626,4 +701,4 @@ export {
626
701
  McpClient,
627
702
  McpClientGroup
628
703
  };
629
- //# sourceMappingURL=chunk-EINTGEGY.js.map
704
+ //# sourceMappingURL=chunk-5MK3BISB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mcp/client.ts","../src/mcp/abort.ts","../src/mcp/result.ts","../src/mcp/tool.ts","../src/mcp/url-safety.ts","../src/mcp/client-group.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport type { JsonObject } from \"../completion/index\";\nimport { abortError, throwIfAborted } from \"../internal/abort\";\nimport { linkAbortSignal } from \"./abort\";\nimport { createMcpTool } from \"./tool\";\nimport type { McpClientOptions, McpConnectOptions, McpServer, McpServerInfo } from \"./types\";\nimport { createSafeMcpFetch, parseAndValidateMcpUrl, parseMcpHttpUrl } from \"./url-safety\";\n\nlet coreClientVersion: string | undefined;\n\ntype ClientResource = {\n readonly client: Client;\n closePromise?: Promise<void> | undefined;\n};\n\ntype McpFetch = NonNullable<\n NonNullable<ConstructorParameters<typeof StreamableHTTPClientTransport>[1]>[\"fetch\"]\n>;\n\nconst transportOwnedHttpHeaders = new Set([\n \"accept\",\n \"content-type\",\n \"last-event-id\",\n \"mcp-protocol-version\",\n \"mcp-session-id\",\n]);\n\nexport class McpClient {\n readonly name: string;\n\n readonly #options: McpClientOptions;\n #closed = false;\n #connectAbortController?: AbortController | undefined;\n #connecting?: Promise<McpServer> | undefined;\n #resource?: ClientResource | undefined;\n #server?: McpServer | undefined;\n\n constructor(options: McpClientOptions) {\n if (options.name.trim() === \"\") {\n throw new TypeError(\"MCP client name must not be empty\");\n }\n this.name = options.name;\n this.#options = options;\n }\n\n connect(options: McpConnectOptions = {}): Promise<McpServer> {\n if (this.#closed) {\n return Promise.reject(new Error(`MCP client \"${this.name}\" is closed`));\n }\n if (this.#server !== undefined) {\n return Promise.resolve(this.#server);\n }\n if (this.#connecting !== undefined) {\n return this.#connecting;\n }\n\n if (options.abortSignal?.aborted === true) {\n return Promise.reject(abortError(options.abortSignal.reason));\n }\n\n const abortController = new AbortController();\n const unlinkAbortSignal = linkAbortSignal(options.abortSignal, abortController);\n this.#connectAbortController = abortController;\n const connecting = this.#initialize(abortController.signal);\n this.#connecting = connecting;\n const clearConnecting = () => {\n unlinkAbortSignal();\n if (this.#connecting === connecting) {\n this.#connecting = undefined;\n }\n if (this.#connectAbortController === abortController) {\n this.#connectAbortController = undefined;\n }\n };\n void connecting.then(clearConnecting, clearConnecting);\n return connecting;\n }\n\n async close(): Promise<void> {\n this.#closed = true;\n this.#connectAbortController?.abort(\n abortError(new Error(`MCP client \"${this.name}\" was closed during connection`)),\n );\n\n const resource = this.#resource;\n if (resource !== undefined) {\n await closeResource(resource);\n }\n }\n\n async #initialize(abortSignal: AbortSignal): Promise<McpServer> {\n const client = createSdkClient();\n const resource: ClientResource = { client };\n this.#resource = resource;\n\n try {\n throwIfAborted(abortSignal);\n const transport = await createTransport(this.#options, { abortSignal });\n throwIfAborted(abortSignal);\n await client.connect(transport, requestOptions(abortSignal));\n throwIfAborted(abortSignal);\n const definitions = await listAllTools(client, abortSignal);\n throwIfAborted(abortSignal);\n const tools = definitions.map((definition) =>\n createMcpTool({\n definition,\n client,\n serverName: this.name,\n prefix: this.#options.tools?.prefix,\n }),\n );\n assertUniqueToolNames(tools, this.name);\n\n if (this.#closed) {\n throw new Error(`MCP client \"${this.name}\" was closed during connection`);\n }\n\n const serverInfo = copyServerInfo(client.getServerVersion());\n const capabilities = copyJsonObject(client.getServerCapabilities());\n const instructions = client.getInstructions();\n let registration: McpServer = {\n name: this.name,\n tools,\n };\n if (serverInfo !== undefined) registration = { ...registration, serverInfo };\n if (capabilities !== undefined) registration = { ...registration, capabilities };\n if (instructions !== undefined) registration = { ...registration, instructions };\n const server = freezeServer(registration);\n this.#server = server;\n return server;\n } catch (error) {\n try {\n await closeResource(resource);\n } catch {\n // Preserve the actionable connection or discovery failure.\n }\n if (this.#resource === resource) {\n this.#resource = undefined;\n }\n this.#server = undefined;\n throw error;\n }\n }\n}\n\nasync function createTransport(\n options: McpClientOptions,\n connectOptions: McpConnectOptions,\n): Promise<Transport> {\n const transport = options.transport;\n if (transport.type === \"custom\") {\n return transport.create({ abortSignal: connectOptions.abortSignal });\n }\n if (transport.type === \"stdio\") {\n let parameters: ConstructorParameters<typeof StdioClientTransport>[0] = {\n command: transport.command,\n };\n if (transport.args !== undefined) parameters = { ...parameters, args: transport.args };\n if (transport.env !== undefined) parameters = { ...parameters, env: transport.env };\n if (transport.cwd !== undefined) parameters = { ...parameters, cwd: transport.cwd };\n if (transport.stderr !== undefined) parameters = { ...parameters, stderr: transport.stderr };\n if (transport.maxBufferSize !== undefined) {\n parameters = { ...parameters, maxBufferSize: transport.maxBufferSize };\n }\n return new StdioClientTransport(parameters);\n }\n\n const ssrfProtection = transport.ssrfProtection ?? \"strict\";\n if (ssrfProtection !== \"strict\" && ssrfProtection !== \"disabled\") {\n throw new TypeError(\"MCP Streamable HTTP ssrfProtection must be strict or disabled\");\n }\n let parameters: ConstructorParameters<typeof StreamableHTTPClientTransport>[1] = {};\n let url: URL;\n let transportFetch: McpFetch | undefined;\n if (ssrfProtection === \"strict\") {\n transportFetch = createSafeMcpFetch();\n url = parseAndValidateMcpUrl(transport.url);\n } else {\n url = parseMcpHttpUrl(transport.url);\n }\n if (transport.headers !== undefined) {\n const headers = copyMcpHeaders(transport.headers, transport.authProvider !== undefined);\n const fetchRequest = transportFetch ?? defaultMcpFetch;\n transportFetch = createMcpEndpointFetch(url, headers, fetchRequest);\n }\n if (transportFetch !== undefined) parameters = { ...parameters, fetch: transportFetch };\n if (transport.authProvider !== undefined) {\n parameters = { ...parameters, authProvider: transport.authProvider };\n }\n if (transport.reconnectionOptions !== undefined) {\n parameters = { ...parameters, reconnectionOptions: transport.reconnectionOptions };\n }\n if (transport.sessionId !== undefined) {\n parameters = { ...parameters, sessionId: transport.sessionId };\n }\n return asSdkTransport(new StreamableHTTPClientTransport(url, parameters));\n}\n\nfunction copyMcpHeaders(\n value: Readonly<Record<string, string>>,\n hasAuthProvider: boolean,\n): Headers {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(\"MCP Streamable HTTP headers must be a plain object\");\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError(\"MCP Streamable HTTP headers must be a plain object\");\n }\n const headers = new Headers();\n for (const [name, headerValue] of Object.entries(value)) {\n if (typeof headerValue !== \"string\") {\n throw new TypeError(`MCP Streamable HTTP header ${name} must be a string`);\n }\n const normalizedName = name.toLowerCase();\n if (transportOwnedHttpHeaders.has(normalizedName)) {\n throw new TypeError(`MCP Streamable HTTP header ${name} is owned by the transport`);\n }\n if (hasAuthProvider && normalizedName === \"authorization\") {\n throw new TypeError(\n \"MCP Streamable HTTP authorization header cannot be combined with authProvider\",\n );\n }\n headers.set(name, headerValue);\n }\n return headers;\n}\n\nfunction createMcpEndpointFetch(\n endpoint: URL,\n configuredHeaders: Headers,\n fetchRequest: McpFetch,\n): McpFetch {\n return (input, init) => {\n const requestUrl = input instanceof Request ? new URL(input.url) : new URL(input);\n if (requestUrl.href !== endpoint.href) return fetchRequest(input, init);\n\n const requestHeaders = new Headers(\n init?.headers ?? (input instanceof Request ? input.headers : undefined),\n );\n configuredHeaders.forEach((value, name) => {\n requestHeaders.set(name, value);\n });\n return fetchRequest(input, { ...init, headers: requestHeaders, redirect: \"error\" });\n };\n}\n\nconst defaultMcpFetch: McpFetch = (input, init) => globalThis.fetch(input, init);\n\nasync function listAllTools(\n client: Client,\n abortSignal?: AbortSignal | undefined,\n): Promise<Awaited<ReturnType<Client[\"listTools\"]>>[\"tools\"]> {\n const tools: Awaited<ReturnType<Client[\"listTools\"]>>[\"tools\"] = [];\n const seenCursors = new Set<string>();\n let cursor: string | undefined;\n\n do {\n const page = await client.listTools(\n cursor === undefined ? undefined : { cursor },\n requestOptions(abortSignal),\n );\n tools.push(...page.tools);\n cursor = page.nextCursor;\n if (cursor !== undefined && seenCursors.has(cursor)) {\n throw new Error(`MCP server returned a repeated tools cursor: ${cursor}`);\n }\n if (cursor !== undefined) {\n seenCursors.add(cursor);\n }\n } while (cursor !== undefined);\n\n return tools;\n}\n\nfunction assertUniqueToolNames(tools: readonly { name: string }[], serverName: string): void {\n const names = new Set<string>();\n for (const tool of tools) {\n if (names.has(tool.name)) {\n throw new Error(`Duplicate MCP tool name \"${tool.name}\" from server \"${serverName}\"`);\n }\n names.add(tool.name);\n }\n}\n\nfunction createSdkClient(): Client {\n return new Client({\n name: \"@anvia/core\",\n version: getCoreClientVersion(),\n });\n}\n\nfunction getCoreClientVersion(): string {\n if (coreClientVersion === undefined) {\n coreClientVersion = readCorePackageVersion();\n }\n return coreClientVersion;\n}\n\nfunction requestOptions(signal?: AbortSignal | undefined): { signal?: AbortSignal } {\n return signal === undefined ? {} : { signal };\n}\n\nfunction asSdkTransport(transport: unknown): Transport {\n return transport as Transport;\n}\n\nfunction closeResource(resource: ClientResource): Promise<void> {\n resource.closePromise ??= resource.client.close();\n return resource.closePromise;\n}\n\nfunction readCorePackageVersion(): string {\n try {\n const packageJson = JSON.parse(\n readFileSync(new URL(\"../../package.json\", import.meta.url), \"utf8\"),\n ) as { version?: unknown };\n return typeof packageJson.version === \"string\" ? packageJson.version : \"0.0.0\";\n } catch {\n return \"0.0.0\";\n }\n}\n\nfunction copyServerInfo(value: ReturnType<Client[\"getServerVersion\"]>): McpServerInfo | undefined {\n if (value === undefined) {\n return undefined;\n }\n return deepFreeze(structuredClone(value)) as McpServerInfo;\n}\n\nfunction copyJsonObject(value: unknown): JsonObject | undefined {\n if (value === undefined) {\n return undefined;\n }\n return deepFreeze(structuredClone(value)) as JsonObject;\n}\n\nfunction freezeServer(server: McpServer): McpServer {\n Object.freeze(server.tools);\n return Object.freeze(server);\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (typeof value !== \"object\" || value === null || Object.isFrozen(value)) {\n return value;\n }\n for (const child of Object.values(value)) {\n deepFreeze(child);\n }\n return Object.freeze(value);\n}\n","export function linkAbortSignal(\n source: AbortSignal | undefined,\n target: AbortController,\n): () => void {\n if (source === undefined) {\n return () => undefined;\n }\n if (source.aborted) {\n target.abort(source.reason);\n return () => undefined;\n }\n\n const onAbort = () => target.abort(source.reason);\n source.addEventListener(\"abort\", onAbort, { once: true });\n return () => source.removeEventListener(\"abort\", onAbort);\n}\n","import type { ToolResultContentPart } from \"../completion/index\";\nimport { isRecord } from \"../internal/record\";\n\ntype McpResultContent =\n | { type: \"text\"; text: string }\n | { type: \"image\"; data: string; mimeType: string }\n | { type: \"audio\"; data: string; mimeType: string }\n | {\n type: \"resource\";\n resource:\n | { uri: string; text: string; mimeType?: string | undefined }\n | { uri: string; blob: string; mimeType?: string | undefined };\n }\n | {\n type: \"resource_link\";\n uri: string;\n name: string;\n mimeType?: string | undefined;\n };\n\nexport type McpToolCallResult =\n | {\n content: McpResultContent[];\n structuredContent?: Record<string, unknown> | undefined;\n isError?: boolean | undefined;\n }\n | {\n toolResult: unknown;\n };\n\nexport function createCallToolParams(\n name: string,\n args: unknown,\n): { name: string; arguments?: Record<string, unknown> } {\n if (args === null || args === undefined) {\n return { name };\n }\n\n if (!isRecord(args)) {\n throw new Error(\"MCP tool arguments must be a JSON object\");\n }\n\n return { name, arguments: args };\n}\n\nexport function mapMcpToolResult(result: McpToolCallResult): readonly ToolResultContentPart[] {\n if (\"toolResult\" in result) {\n return [{ type: \"text\", text: serializeMcpValue(result.toolResult) }];\n }\n\n if (result.isError === true) {\n throw new Error(mcpErrorMessage(result.content));\n }\n\n const content = result.content.map(mapMcpContent);\n if (content.length === 0 && result.structuredContent !== undefined) {\n content.push({ type: \"text\", text: serializeMcpValue(result.structuredContent) });\n }\n return content;\n}\n\nfunction mcpErrorMessage(content: McpResultContent[]): string {\n const text = content\n .map((item) => (item.type === \"text\" ? item.text : undefined))\n .filter((item): item is string => item !== undefined)\n .join(\"\\n\");\n\n return text === \"\" ? \"MCP tool returned an error\" : text;\n}\n\nfunction mapMcpContent(content: McpResultContent): ToolResultContentPart {\n if (content.type === \"text\") {\n return { type: \"text\", text: content.text };\n }\n\n if (content.type === \"image\") {\n return {\n type: \"file\",\n data: { type: \"data\", data: content.data },\n mediaType: content.mimeType,\n };\n }\n\n if (content.type === \"resource\") {\n return { type: \"text\", text: serializeResource(content.resource) };\n }\n\n if (content.type === \"audio\") {\n throw new Error(`Unsupported MCP tool result content type: audio (${content.mimeType})`);\n }\n\n throw new Error(`Unsupported MCP tool result content type: resource_link (${content.uri})`);\n}\n\nfunction serializeResource(\n resource:\n | { uri: string; text: string; mimeType?: string | undefined }\n | { uri: string; blob: string; mimeType?: string | undefined },\n): string {\n const mediaType =\n resource.mimeType ?? (\"text\" in resource ? \"text/plain\" : \"application/octet-stream\");\n const encoding = \"text\" in resource ? \"text\" : \"base64\";\n const data = \"text\" in resource ? resource.text : resource.blob;\n return `MCP resource (${resource.uri}; ${mediaType}; ${encoding})\\n${data}`;\n}\n\nfunction serializeMcpValue(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n\n let serialized: string | undefined;\n try {\n serialized = JSON.stringify(value);\n } catch (error) {\n throw new TypeError(\"MCP tool results must be JSON-serializable.\", { cause: error });\n }\n if (serialized === undefined) {\n throw new TypeError(\"MCP tool results must be JSON-serializable.\");\n }\n return serialized;\n}\n","import type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { JsonObject, ToolDefinition } from \"../completion/index\";\nimport { ToolOutput } from \"../tool\";\nimport { createCallToolParams, mapMcpToolResult } from \"./result\";\nimport type { McpTool } from \"./types\";\n\ntype SdkMcpToolDefinition = Awaited<ReturnType<Client[\"listTools\"]>>[\"tools\"][number];\n\nexport function createMcpTool(options: {\n definition: SdkMcpToolDefinition;\n client: Client;\n serverName: string;\n prefix?: string | undefined;\n}): McpTool {\n const { definition, client, serverName, prefix = \"\" } = options;\n const exposedName = `${prefix}${definition.name}`;\n const provenance = Object.freeze({\n serverName,\n remoteName: definition.name,\n });\n const toolDefinition = Object.freeze<ToolDefinition>({\n name: exposedName,\n description: definition.description ?? \"\",\n parameters: deepFreeze(structuredClone(definition.inputSchema)) as unknown as JsonObject,\n });\n const tool: McpTool = {\n name: exposedName,\n mcp: provenance,\n definition(): ToolDefinition {\n return toolDefinition;\n },\n async call(args, context) {\n const result = await client.callTool(\n createCallToolParams(definition.name, args),\n undefined,\n context?.abortSignal === undefined ? {} : { signal: context.abortSignal },\n );\n return ToolOutput.content(mapMcpToolResult(result));\n },\n };\n return Object.freeze(tool);\n}\n\nexport function isMcpTool(tool: unknown): tool is McpTool {\n if (typeof tool !== \"object\" || tool === null || !(\"mcp\" in tool)) {\n return false;\n }\n const mcp = tool.mcp;\n return (\n typeof mcp === \"object\" &&\n mcp !== null &&\n \"serverName\" in mcp &&\n typeof mcp.serverName === \"string\" &&\n mcp.serverName.length > 0 &&\n \"remoteName\" in mcp &&\n typeof mcp.remoteName === \"string\" &&\n mcp.remoteName.length > 0\n );\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (typeof value !== \"object\" || value === null || Object.isFrozen(value)) {\n return value;\n }\n for (const child of Object.values(value)) {\n deepFreeze(child);\n }\n return Object.freeze(value);\n}\n","import type { LookupAddress } from \"node:dns\";\nimport { lookup } from \"node:dns/promises\";\nimport type { LookupFunction } from \"node:net\";\nimport { BlockList, isIP } from \"node:net\";\nimport type { StreamableHTTPClientTransportOptions } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { Agent, Pool, fetch as undiciFetch } from \"undici\";\n\ntype FetchLike = NonNullable<StreamableHTTPClientTransportOptions[\"fetch\"]>;\n\nexport type McpAddressResolver = (hostname: string) => Promise<LookupAddress[]>;\n\nconst blockedIpv4Addresses = new BlockList();\nconst blockedIpv6Addresses = new BlockList();\n\nfor (const [network, prefix] of [\n [\"0.0.0.0\", 8],\n [\"10.0.0.0\", 8],\n [\"100.64.0.0\", 10],\n [\"127.0.0.0\", 8],\n [\"169.254.0.0\", 16],\n [\"172.16.0.0\", 12],\n [\"192.0.0.0\", 24],\n [\"192.0.2.0\", 24],\n [\"192.88.99.0\", 24],\n [\"192.168.0.0\", 16],\n [\"198.18.0.0\", 15],\n [\"198.51.100.0\", 24],\n [\"203.0.113.0\", 24],\n [\"224.0.0.0\", 4],\n [\"240.0.0.0\", 4],\n] as const) {\n blockedIpv4Addresses.addSubnet(network, prefix, \"ipv4\");\n}\n\nfor (const [network, prefix] of [\n [\"::\", 96],\n [\"::ffff:0:0\", 96],\n [\"64:ff9b::\", 96],\n [\"64:ff9b:1::\", 48],\n [\"100::\", 64],\n [\"2001::\", 32],\n [\"2001:2::\", 48],\n [\"2001:10::\", 28],\n [\"2001:20::\", 28],\n [\"2001:db8::\", 32],\n [\"2002::\", 16],\n [\"fc00::\", 7],\n [\"fe80::\", 10],\n [\"fec0::\", 10],\n [\"ff00::\", 8],\n] as const) {\n blockedIpv6Addresses.addSubnet(network, prefix, \"ipv6\");\n}\n\nconst defaultAddressResolver: McpAddressResolver = (hostname) =>\n lookup(hostname, { all: true, verbatim: true });\n\nexport function parseAndValidateMcpUrl(url: string | URL): URL {\n const parsed = parseMcpHttpUrl(url);\n validateMcpHostname(parsed.hostname);\n return parsed;\n}\n\nexport function parseMcpHttpUrl(url: string | URL): URL {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`Invalid MCP URL: ${url}`);\n }\n\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw new Error(`MCP URL blocked: only HTTP(S) URLs are allowed (${parsed.protocol})`);\n }\n\n return parsed;\n}\n\nexport async function resolveAndValidateMcpHostname(\n hostname: string,\n resolveAddresses: McpAddressResolver = defaultAddressResolver,\n): Promise<LookupAddress[]> {\n const normalizedHostname = normalizeHostname(hostname);\n validateMcpHostname(normalizedHostname);\n\n const family = isIP(normalizedHostname);\n if (family !== 0) {\n return [{ address: normalizedHostname, family }];\n }\n\n let addresses: LookupAddress[];\n try {\n addresses = await resolveAddresses(normalizedHostname);\n } catch (cause) {\n throw new Error(`Unable to resolve MCP URL hostname (${normalizedHostname})`, { cause });\n }\n\n if (addresses.length === 0) {\n throw new Error(`Unable to resolve MCP URL hostname (${normalizedHostname})`);\n }\n\n for (const { address } of addresses) {\n validateMcpHostname(address);\n }\n\n return addresses;\n}\n\nexport function createSafeMcpLookup(\n resolveAddresses: McpAddressResolver = defaultAddressResolver,\n): LookupFunction {\n return (hostname, options, callback) => {\n void resolveAndValidateMcpHostname(hostname, resolveAddresses).then(\n (addresses) => {\n const requestedFamily = normalizeRequestedFamily(options.family);\n const matchingAddresses =\n requestedFamily === 0\n ? addresses\n : addresses.filter(({ family }) => family === requestedFamily);\n\n if (matchingAddresses.length === 0) {\n const error = new Error(`No matching address family for MCP URL (${hostname})`);\n Object.assign(error, { code: \"EAI_ADDRFAMILY\" });\n callback(error, []);\n return;\n }\n\n if (options.all) {\n callback(null, matchingAddresses);\n return;\n }\n\n const address = matchingAddresses[0];\n if (!address) {\n callback(new Error(`Unable to resolve MCP URL hostname (${hostname})`), []);\n return;\n }\n callback(null, address.address, address.family);\n },\n (cause: unknown) => {\n callback(asError(cause), []);\n },\n );\n };\n}\n\nexport function createSafeMcpFetch(): FetchLike {\n return (url, init) => {\n parseAndValidateMcpUrl(url);\n return undiciFetch(url as Parameters<typeof undiciFetch>[0], {\n ...(init as Parameters<typeof undiciFetch>[1]),\n dispatcher: safeMcpDispatcher,\n }) as unknown as ReturnType<FetchLike>;\n };\n}\n\nfunction validateMcpHostname(hostname: string): void {\n const normalizedHostname = normalizeHostname(hostname);\n\n if (normalizedHostname === \"localhost\" || normalizedHostname.endsWith(\".localhost\")) {\n throw new Error(`MCP URL blocked: localhost not allowed (${normalizedHostname})`);\n }\n\n const family = isIP(normalizedHostname);\n if (family === 0) {\n return;\n }\n\n if (\n (family === 4 && normalizedHostname.startsWith(\"127.\")) ||\n (family === 6 && normalizedHostname === \"::1\")\n ) {\n throw new Error(`MCP URL blocked: localhost not allowed (${normalizedHostname})`);\n }\n\n if (normalizedHostname === \"169.254.169.254\" || normalizedHostname === \"fd00:ec2::254\") {\n throw new Error(`MCP URL blocked: cloud metadata endpoint not allowed (${normalizedHostname})`);\n }\n\n if (\n (family === 4 && blockedIpv4Addresses.check(normalizedHostname, \"ipv4\")) ||\n (family === 6 && blockedIpv6Addresses.check(normalizedHostname, \"ipv6\"))\n ) {\n const range = family === 4 ? \"IP\" : \"IPv6\";\n throw new Error(`MCP URL blocked: private ${range} range not allowed (${normalizedHostname})`);\n }\n}\n\nfunction normalizeHostname(hostname: string): string {\n const withoutBrackets =\n hostname.startsWith(\"[\") && hostname.endsWith(\"]\") ? hostname.slice(1, -1) : hostname;\n return withoutBrackets.toLowerCase().replace(/\\.+$/, \"\");\n}\n\nfunction normalizeRequestedFamily(family: number | string | undefined): 0 | 4 | 6 {\n if (family === 4 || family === \"IPv4\") {\n return 4;\n }\n if (family === 6 || family === \"IPv6\") {\n return 6;\n }\n return 0;\n}\n\nfunction asError(cause: unknown): Error {\n return cause instanceof Error ? cause : new Error(String(cause));\n}\n\nconst safeMcpDispatcher = new Agent({\n autoSelectFamily: true,\n connect: {\n lookup: createSafeMcpLookup(),\n },\n factory(origin, options) {\n parseAndValidateMcpUrl(origin);\n return new Pool(origin, options as Pool.Options);\n },\n});\n","import { linkAbortSignal } from \"./abort\";\nimport type { McpClient } from \"./client\";\nimport type { McpClientGroupConnectOptions, McpServer } from \"./types\";\n\nexport class McpClientGroup {\n readonly clients: readonly McpClient[];\n readonly servers: readonly McpServer[];\n\n #closePromise?: Promise<void> | undefined;\n\n private constructor(clients: readonly McpClient[], servers: readonly McpServer[]) {\n this.clients = Object.freeze([...clients]);\n this.servers = Object.freeze([...servers]);\n }\n\n static async connect(options: McpClientGroupConnectOptions): Promise<McpClientGroup> {\n const clients = [...options.clients];\n assertUniqueClientNames(clients);\n\n const abortController = new AbortController();\n const unlinkAbortSignal = linkAbortSignal(options.abortSignal, abortController);\n let firstConnectionFailure: unknown;\n let connectionFailed = false;\n const connections = clients.map((client) =>\n client.connect({ abortSignal: abortController.signal }).catch((error: unknown) => {\n if (!connectionFailed) {\n connectionFailed = true;\n firstConnectionFailure = error;\n abortController.abort(error);\n }\n throw error;\n }),\n );\n const settled = await Promise.allSettled(connections).finally(unlinkAbortSignal);\n const firstFailure = settled.find(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n if (firstFailure !== undefined) {\n await rollbackSuccessfulClients(clients, settled);\n throw connectionFailed ? firstConnectionFailure : firstFailure.reason;\n }\n\n const servers = settled.map((result) => (result as PromiseFulfilledResult<McpServer>).value);\n try {\n assertUniqueServerAndToolNames(servers);\n } catch (error) {\n try {\n await closeAll(clients);\n } catch {\n // Preserve the registration validation failure that caused rollback.\n }\n throw error;\n }\n\n return new McpClientGroup(clients, servers);\n }\n\n close(): Promise<void> {\n this.#closePromise ??= closeAll(this.clients);\n return this.#closePromise;\n }\n}\n\nfunction assertUniqueClientNames(clients: readonly McpClient[]): void {\n const names = new Set<string>();\n for (const client of clients) {\n if (names.has(client.name)) {\n throw new Error(`Duplicate MCP client name \"${client.name}\"`);\n }\n names.add(client.name);\n }\n}\n\nfunction assertUniqueServerAndToolNames(servers: readonly McpServer[]): void {\n const serverNames = new Set<string>();\n const toolNames = new Map<string, string>();\n for (const server of servers) {\n if (serverNames.has(server.name)) {\n throw new Error(`Duplicate MCP server name \"${server.name}\"`);\n }\n serverNames.add(server.name);\n\n for (const tool of server.tools) {\n const existing = toolNames.get(tool.name);\n if (existing !== undefined) {\n throw new Error(\n `Duplicate MCP tool name \"${tool.name}\" from servers \"${existing}\" and \"${server.name}\"`,\n );\n }\n toolNames.set(tool.name, server.name);\n }\n }\n}\n\nasync function rollbackSuccessfulClients(\n clients: readonly McpClient[],\n settled: readonly PromiseSettledResult<McpServer>[],\n): Promise<void> {\n const successful = clients.filter((_, index) => settled[index]?.status === \"fulfilled\");\n try {\n await closeAll(successful);\n } catch {\n // Preserve the connection failure that caused rollback.\n }\n}\n\nasync function closeAll(clients: readonly McpClient[]): Promise<void> {\n const settled = await Promise.allSettled(clients.map((client) => client.close()));\n const errors = settled.flatMap((result) => (result.status === \"rejected\" ? [result.reason] : []));\n if (errors.length > 0) {\n throw new AggregateError(errors, \"Failed to close one or more MCP clients\");\n }\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,qCAAqC;;;ACHvC,SAAS,gBACd,QACA,QACY;AACZ,MAAI,WAAW,QAAW;AACxB,WAAO,MAAM;AAAA,EACf;AACA,MAAI,OAAO,SAAS;AAClB,WAAO,MAAM,OAAO,MAAM;AAC1B,WAAO,MAAM;AAAA,EACf;AAEA,QAAM,UAAU,MAAM,OAAO,MAAM,OAAO,MAAM;AAChD,SAAO,iBAAiB,SAAS,SA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C9D;AACA,gBAAY,IAAI,OAAO,IAAI;AAE3B,eAAW,QAAQ,OAAO,OAAO;AAC/B,YAAM,WAAW,UAAU,IAAI,KAAK,IAAI;AACxC,UAAI,aAAa,QAAW;AAC1B,cAAM,IAAI;AAAA,UACR,4BAA4B,KAAK,IAAI,mBAAmB,QAAQ,UAAU,OAAO,IAAI;AAAA,QACvF;AAAA,MACF;AACA,gBAAU,IAAI,KAAK,MAAM,OAAO,IAAI;AAAA,IACtC;AAAA,EACF;AACF;AAEA,eAAe,0BACb,SACA,SACe;AACf,QAAM,aAAa,QAAQ,OAAO,CAAC,GAAG,UAAU,QAAQ,KAAK,GAAG,WAAW,WAAW;AACtF,MAAI;AACF,UAAM,SAAS,UAAU;AAAA,EAC3B,QAAQ;AAAA,EAER;AACF;AAEA,eAAe,SAAS,SAA8C;AACpE,QAAM,UAAU,MAAM,QAAQ,WAAW,QAAQ,IAAI,CAAC,WAAW,OAAO,MAAM,CAAC,CAAC;AAChF,QAAM,SAAS,QAAQ,QAAQ,CAAC,WAAY,OAAO,WAAW,aAAa,CAAC,OAAO,MAAM,IAAI,CAAC,CAAE;AAChG,MAAI,OAAO,SAAS,GAAG;AACrB,UAAM,IAAI,eAAe,QAAQ,yCAAyC;AAAA,EAC5E;AACF;","names":["parameters","deepFreeze"]}
@@ -1,4 +1,28 @@
1
- // src/guardrails/index.ts
1
+ // src/guardrails/actions.ts
2
+ function allow(options = {}) {
3
+ return { action: "allow", ...options };
4
+ }
5
+ function block(options) {
6
+ return { action: "block", ...options };
7
+ }
8
+ var commonActions = {
9
+ allow,
10
+ block
11
+ };
12
+ var inputActions = {
13
+ ...commonActions,
14
+ rewrite(options) {
15
+ return { action: "rewrite", ...options };
16
+ }
17
+ };
18
+ var outputActions = {
19
+ ...commonActions,
20
+ rewrite(options) {
21
+ return { action: "rewrite", ...options };
22
+ }
23
+ };
24
+
25
+ // src/guardrails/policy.ts
2
26
  function defineGuardrailPolicy(options) {
3
27
  return {
4
28
  id: options.id,
@@ -13,16 +37,6 @@ function defineInputGuardrail(guardrail) {
13
37
  function defineOutputGuardrail(guardrail) {
14
38
  return guardrail;
15
39
  }
16
- function allow(options = {}) {
17
- return { action: "allow", ...options };
18
- }
19
- function block(options) {
20
- return { action: "block", ...options };
21
- }
22
- var guardrails = {
23
- blockText,
24
- redactText
25
- };
26
40
  function normalizeGuardrailPolicies(policies) {
27
41
  if (policies === void 0) {
28
42
  return [];
@@ -35,6 +49,65 @@ function appendGuardrailPolicies(current, next) {
35
49
  function hasEnforcedOutputGuardrails(policies) {
36
50
  return policies.some((policy) => policy.mode === "enforce" && policy.output.length > 0);
37
51
  }
52
+
53
+ // src/guardrails/message.ts
54
+ function textFromMessage(message) {
55
+ if (message.role === "system") {
56
+ return message.content;
57
+ }
58
+ if (typeof message.content === "string") {
59
+ return message.content;
60
+ }
61
+ return message.content.flatMap((content) => {
62
+ if (content.type === "text") {
63
+ return [content.text];
64
+ }
65
+ if (content.type === "file" && content.data.type === "text") {
66
+ return [content.data.text];
67
+ }
68
+ if (content.type === "tool-result") {
69
+ return textFromToolResult(content.output);
70
+ }
71
+ return [];
72
+ }).join("\n");
73
+ }
74
+ function rewriteMessageText(message, text) {
75
+ if (message.role === "system") {
76
+ return { ...message, content: text };
77
+ }
78
+ if (message.role === "user") {
79
+ const content = typeof message.content === "string" ? [] : message.content;
80
+ return {
81
+ ...message,
82
+ content: [
83
+ { type: "text", text },
84
+ ...content.filter(
85
+ (item) => item.type !== "text" && !(item.type === "file" && item.data.type === "text")
86
+ )
87
+ ]
88
+ };
89
+ }
90
+ if (message.role === "assistant") {
91
+ return { ...message, content: [{ type: "text", text }] };
92
+ }
93
+ return message;
94
+ }
95
+ function textFromToolResult(output) {
96
+ switch (output.type) {
97
+ case "text":
98
+ case "error-text":
99
+ return [output.value];
100
+ case "json":
101
+ case "error-json":
102
+ return [JSON.stringify(output.value)];
103
+ case "content":
104
+ return output.value.flatMap((part) => part.type === "text" ? [part.text] : []);
105
+ case "execution-denied":
106
+ return output.reason === void 0 ? [] : [output.reason];
107
+ }
108
+ }
109
+
110
+ // src/guardrails/runtime.ts
38
111
  async function runInputGuardrails(policies, context) {
39
112
  let prompt = context.prompt;
40
113
  let inputText = context.inputText;
@@ -157,21 +230,11 @@ function decisionRecord(args) {
157
230
  if (args.action.metadata !== void 0) record.metadata = args.action.metadata;
158
231
  return record;
159
232
  }
160
- var commonActions = {
161
- allow,
162
- block
163
- };
164
- var inputActions = {
165
- ...commonActions,
166
- rewrite(options) {
167
- return { action: "rewrite", ...options };
168
- }
169
- };
170
- var outputActions = {
171
- ...commonActions,
172
- rewrite(options) {
173
- return { action: "rewrite", ...options };
174
- }
233
+
234
+ // src/guardrails/text.ts
235
+ var guardrails = {
236
+ blockText,
237
+ redactText
175
238
  };
176
239
  function blockText(options) {
177
240
  return textPatternGuardrail(options, "block");
@@ -240,73 +303,18 @@ function replaceTextPattern(text, pattern, replacement) {
240
303
  const globalFlags = flags.includes("g") ? flags : `${flags}g`;
241
304
  return text.replace(new RegExp(pattern.source, globalFlags), replacement);
242
305
  }
243
- function textFromMessage(message) {
244
- if (message.role === "system") {
245
- return message.content;
246
- }
247
- if (typeof message.content === "string") {
248
- return message.content;
249
- }
250
- return message.content.flatMap((content) => {
251
- if (content.type === "text") {
252
- return [content.text];
253
- }
254
- if (content.type === "file" && content.data.type === "text") {
255
- return [content.data.text];
256
- }
257
- if (content.type === "tool-result") {
258
- return textFromToolResult(content.output);
259
- }
260
- return [];
261
- }).join("\n");
262
- }
263
- function rewriteMessageText(message, text) {
264
- if (message.role === "system") {
265
- return { ...message, content: text };
266
- }
267
- if (message.role === "user") {
268
- const content = typeof message.content === "string" ? [] : message.content;
269
- return {
270
- ...message,
271
- content: [
272
- { type: "text", text },
273
- ...content.filter(
274
- (item) => item.type !== "text" && !(item.type === "file" && item.data.type === "text")
275
- )
276
- ]
277
- };
278
- }
279
- if (message.role === "assistant") {
280
- return { ...message, content: [{ type: "text", text }] };
281
- }
282
- return message;
283
- }
284
- function textFromToolResult(output) {
285
- switch (output.type) {
286
- case "text":
287
- case "error-text":
288
- return [output.value];
289
- case "json":
290
- case "error-json":
291
- return [JSON.stringify(output.value)];
292
- case "content":
293
- return output.value.flatMap((part) => part.type === "text" ? [part.text] : []);
294
- case "execution-denied":
295
- return output.reason === void 0 ? [] : [output.reason];
296
- }
297
- }
298
306
 
299
307
  export {
308
+ allow,
309
+ block,
300
310
  defineGuardrailPolicy,
301
311
  defineInputGuardrail,
302
312
  defineOutputGuardrail,
303
- allow,
304
- block,
305
- guardrails,
306
313
  normalizeGuardrailPolicies,
307
314
  appendGuardrailPolicies,
308
315
  hasEnforcedOutputGuardrails,
309
316
  runInputGuardrails,
310
- runOutputGuardrails
317
+ runOutputGuardrails,
318
+ guardrails
311
319
  };
312
- //# sourceMappingURL=chunk-KIDGIJM7.js.map
320
+ //# sourceMappingURL=chunk-AZB6N7P4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/guardrails/actions.ts","../src/guardrails/policy.ts","../src/guardrails/message.ts","../src/guardrails/runtime.ts","../src/guardrails/text.ts"],"sourcesContent":["import type {\n GuardrailActionBase,\n GuardrailAllow,\n GuardrailBlock,\n GuardrailCommonActions,\n InputGuardrailActions,\n OutputGuardrailActions,\n} from \"./types\";\n\nexport function allow(options: GuardrailActionBase = {}): GuardrailAllow {\n return { action: \"allow\", ...options };\n}\n\nexport function block(options: Omit<GuardrailBlock, \"action\">): GuardrailBlock {\n return { action: \"block\", ...options };\n}\n\nconst commonActions: GuardrailCommonActions = {\n allow,\n block,\n};\n\nexport const inputActions: InputGuardrailActions = {\n ...commonActions,\n rewrite(options) {\n return { action: \"rewrite\", ...options };\n },\n};\n\nexport const outputActions: OutputGuardrailActions = {\n ...commonActions,\n rewrite(options) {\n return { action: \"rewrite\", ...options };\n },\n};\n","import type {\n GuardrailPolicy,\n GuardrailPolicyInput,\n GuardrailPolicyOptions,\n InputGuardrail,\n OutputGuardrail,\n} from \"./types\";\n\nexport function defineGuardrailPolicy(options: GuardrailPolicyOptions): GuardrailPolicy {\n return {\n id: options.id,\n mode: options.mode ?? \"enforce\",\n input: options.input ?? [],\n output: options.output ?? [],\n };\n}\n\nexport function defineInputGuardrail(guardrail: InputGuardrail): InputGuardrail {\n return guardrail;\n}\n\nexport function defineOutputGuardrail(guardrail: OutputGuardrail): OutputGuardrail {\n return guardrail;\n}\n\nexport function normalizeGuardrailPolicies(\n policies: GuardrailPolicyInput | undefined,\n): GuardrailPolicy[] {\n if (policies === undefined) {\n return [];\n }\n return Array.isArray(policies) ? policies : [policies];\n}\n\nexport function appendGuardrailPolicies(\n current: GuardrailPolicy[],\n next: GuardrailPolicyInput,\n): GuardrailPolicy[] {\n return [...current, ...normalizeGuardrailPolicies(next)];\n}\n\nexport function hasEnforcedOutputGuardrails(policies: GuardrailPolicy[]): boolean {\n return policies.some((policy) => policy.mode === \"enforce\" && policy.output.length > 0);\n}\n","import type { Message, ToolResultPart } from \"../completion\";\n\nexport function textFromMessage(message: Message): string {\n if (message.role === \"system\") {\n return message.content;\n }\n if (typeof message.content === \"string\") {\n return message.content;\n }\n return message.content\n .flatMap((content) => {\n if (content.type === \"text\") {\n return [content.text];\n }\n if (content.type === \"file\" && content.data.type === \"text\") {\n return [content.data.text];\n }\n if (content.type === \"tool-result\") {\n return textFromToolResult(content.output);\n }\n return [];\n })\n .join(\"\\n\");\n}\n\nexport function rewriteMessageText(message: Message, text: string): Message {\n if (message.role === \"system\") {\n return { ...message, content: text };\n }\n if (message.role === \"user\") {\n const content = typeof message.content === \"string\" ? [] : message.content;\n return {\n ...message,\n content: [\n { type: \"text\", text },\n ...content.filter(\n (item) => item.type !== \"text\" && !(item.type === \"file\" && item.data.type === \"text\"),\n ),\n ],\n };\n }\n if (message.role === \"assistant\") {\n return { ...message, content: [{ type: \"text\", text }] };\n }\n return message;\n}\n\nfunction textFromToolResult(output: ToolResultPart[\"output\"]): string[] {\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n return [output.value];\n case \"json\":\n case \"error-json\":\n return [JSON.stringify(output.value)];\n case \"content\":\n return output.value.flatMap((part) => (part.type === \"text\" ? [part.text] : []));\n case \"execution-denied\":\n return output.reason === undefined ? [] : [output.reason];\n }\n}\n","import type { MaybePromise } from \"../internal/type-utils\";\nimport { allow, inputActions, outputActions } from \"./actions\";\nimport { rewriteMessageText, textFromMessage } from \"./message\";\nimport type {\n GuardrailActionBase,\n GuardrailActionName,\n GuardrailAllow,\n GuardrailBlock,\n GuardrailBoundary,\n GuardrailDecisionRecord,\n GuardrailPolicy,\n InputGuardrailContext,\n InputGuardrailRunResult,\n OutputGuardrailContext,\n OutputGuardrailRunResult,\n} from \"./types\";\n\nexport async function runInputGuardrails(\n policies: GuardrailPolicy[],\n context: InputGuardrailContext,\n): Promise<InputGuardrailRunResult> {\n let prompt = context.prompt;\n let inputText = context.inputText;\n const decisions: GuardrailDecisionRecord[] = [];\n\n for (const policy of policies) {\n for (const guardrail of policy.input) {\n const currentContext = { ...context, prompt, inputText };\n const result = await runGuardrail(policy, guardrail.id, \"input\", () =>\n guardrail.check(currentContext, inputActions),\n );\n decisions.push(result.decision);\n\n if (policy.mode === \"observe\") {\n continue;\n }\n if (result.action.action === \"block\") {\n return {\n prompt,\n inputText,\n blocked: true,\n message: result.action.message,\n decisions,\n };\n }\n if (result.action.action === \"rewrite\") {\n if (result.action.prompt !== undefined) {\n prompt = result.action.prompt;\n inputText = textFromMessage(prompt);\n } else if (result.action.inputText !== undefined) {\n inputText = result.action.inputText;\n prompt = rewriteMessageText(prompt, inputText);\n }\n }\n }\n }\n\n return { prompt, inputText, blocked: false, decisions };\n}\n\nexport async function runOutputGuardrails(\n policies: GuardrailPolicy[],\n context: OutputGuardrailContext,\n): Promise<OutputGuardrailRunResult> {\n let outputText = context.outputText;\n const decisions: GuardrailDecisionRecord[] = [];\n\n for (const policy of policies) {\n for (const guardrail of policy.output) {\n const currentContext = { ...context, outputText };\n const result = await runGuardrail(policy, guardrail.id, \"output\", () =>\n guardrail.check(currentContext, outputActions),\n );\n decisions.push(result.decision);\n\n if (policy.mode === \"observe\") {\n continue;\n }\n if (result.action.action === \"block\") {\n return {\n outputText,\n blocked: true,\n message: result.action.message,\n decisions,\n };\n }\n if (result.action.action === \"rewrite\") {\n outputText = result.action.outputText;\n }\n }\n }\n\n return { outputText, blocked: false, decisions };\n}\n\ntype RunGuardrailResult<TAction extends { action: GuardrailActionName }> = {\n action: TAction;\n decision: GuardrailDecisionRecord;\n};\n\nasync function runGuardrail<TAction extends { action: GuardrailActionName } & GuardrailActionBase>(\n policy: GuardrailPolicy,\n guardrailId: string,\n boundary: GuardrailBoundary,\n run: () => MaybePromise<TAction | undefined>,\n): Promise<RunGuardrailResult<TAction | GuardrailAllow>> {\n const startedAt = Date.now();\n try {\n const action = (await run()) ?? allow();\n return {\n action,\n decision: decisionRecord({\n policy,\n guardrailId,\n boundary,\n action,\n latencyMs: Date.now() - startedAt,\n }),\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (policy.mode === \"observe\") {\n return {\n action: allow(),\n decision: {\n policyId: policy.id,\n guardrailId,\n boundary,\n mode: policy.mode,\n action: \"error\",\n applied: false,\n reason: message,\n latencyMs: Date.now() - startedAt,\n },\n };\n }\n throw error;\n }\n}\n\nfunction decisionRecord(args: {\n policy: GuardrailPolicy;\n guardrailId: string;\n boundary: GuardrailBoundary;\n action: GuardrailAllow | GuardrailBlock | ({ action: GuardrailActionName } & GuardrailActionBase);\n latencyMs: number;\n}): GuardrailDecisionRecord {\n const applied = args.policy.mode === \"enforce\" && args.action.action !== \"allow\";\n const record: GuardrailDecisionRecord = {\n policyId: args.policy.id,\n guardrailId: args.guardrailId,\n boundary: args.boundary,\n mode: args.policy.mode,\n action: args.action.action,\n applied,\n latencyMs: args.latencyMs,\n };\n if (args.action.reason !== undefined) record.reason = args.action.reason;\n if (\"message\" in args.action && typeof args.action.message === \"string\") {\n record.message = args.action.message;\n }\n if (args.action.metadata !== undefined) record.metadata = args.action.metadata;\n return record;\n}\n","import { allow, block } from \"./actions\";\nimport { defineInputGuardrail, defineOutputGuardrail } from \"./policy\";\nimport type { GuardrailAllow, GuardrailBlock, InputGuardrail, OutputGuardrail } from \"./types\";\n\nexport const guardrails = {\n blockText,\n redactText,\n};\n\ntype TextPatternBoundary = \"input\" | \"output\";\n\ntype TextPatternGuardrailFor<Boundary extends TextPatternBoundary> = Boundary extends \"input\"\n ? InputGuardrail\n : OutputGuardrail;\n\ntype TextPatternGuardrailOptions<Boundary extends TextPatternBoundary = TextPatternBoundary> = {\n id: string;\n boundary: Boundary;\n patterns: Array<string | RegExp>;\n reason: string;\n message?: string | undefined;\n};\n\ntype TextPatternRedactOptions<Boundary extends TextPatternBoundary = TextPatternBoundary> =\n TextPatternGuardrailOptions<Boundary> & { replacement?: string | undefined };\n\nfunction blockText<Boundary extends TextPatternBoundary>(\n options: TextPatternGuardrailOptions<Boundary>,\n): TextPatternGuardrailFor<Boundary> {\n return textPatternGuardrail(options, \"block\");\n}\n\nfunction redactText<Boundary extends TextPatternBoundary>(\n options: TextPatternRedactOptions<Boundary>,\n): TextPatternGuardrailFor<Boundary> {\n return textPatternGuardrail(options, \"rewrite\");\n}\n\nfunction textPatternGuardrail<Boundary extends TextPatternBoundary>(\n options: TextPatternRedactOptions<Boundary>,\n action: \"block\" | \"rewrite\",\n): TextPatternGuardrailFor<Boundary> {\n if (options.boundary === \"input\") {\n return defineInputGuardrail({\n id: options.id,\n check(ctx, actions) {\n return textPatternAction(ctx.inputText, options, action, (value) =>\n actions.rewrite({ inputText: value, reason: options.reason }),\n );\n },\n }) as TextPatternGuardrailFor<Boundary>;\n }\n return defineOutputGuardrail({\n id: options.id,\n check(ctx, actions) {\n return textPatternAction(ctx.outputText, options, action, (value) =>\n actions.rewrite({ outputText: value, reason: options.reason }),\n );\n },\n }) as TextPatternGuardrailFor<Boundary>;\n}\n\nfunction textPatternAction<TRewrite>(\n text: string,\n options: TextPatternGuardrailOptions & { replacement?: string | undefined },\n action: \"block\" | \"rewrite\",\n rewrite: (value: string) => TRewrite,\n): GuardrailAllow | GuardrailBlock | TRewrite {\n const matched = options.patterns.some((pattern) => textPatternMatches(text, pattern));\n if (!matched) {\n return allow();\n }\n if (action === \"block\") {\n return block({\n reason: options.reason,\n message: options.message,\n });\n }\n let current = text;\n for (const pattern of options.patterns) {\n current = replaceTextPattern(current, pattern, options.replacement ?? \"[redacted]\");\n }\n return rewrite(current);\n}\n\nfunction textPatternMatches(text: string, pattern: string | RegExp): boolean {\n if (typeof pattern === \"string\") {\n return text.includes(pattern);\n }\n pattern.lastIndex = 0;\n const matched = pattern.test(text);\n pattern.lastIndex = 0;\n return matched;\n}\n\nfunction replaceTextPattern(text: string, pattern: string | RegExp, replacement: string): string {\n if (typeof pattern === \"string\") {\n return text.split(pattern).join(replacement);\n }\n pattern.lastIndex = 0;\n const flags = pattern.flags.replace(\"y\", \"\");\n const globalFlags = flags.includes(\"g\") ? flags : `${flags}g`;\n return text.replace(new RegExp(pattern.source, globalFlags), replacement);\n}\n"],"mappings":";AASO,SAAS,MAAM,UAA+B,CAAC,GAAmB;AACvE,SAAO,EAAE,QAAQ,SAAS,GAAG,QAAQ;AACvC;AAEO,SAAS,MAAM,SAAyD;AAC7E,SAAO,EAAE,QAAQ,SAAS,GAAG,QAAQ;AACvC;AAEA,IAAM,gBAAwC;AAAA,EAC5C;AAAA,EACA;AACF;AAEO,IAAM,eAAsC;AAAA,EACjD,GAAG;AAAA,EACH,QAAQ,SAAS;AACf,WAAO,EAAE,QAAQ,WAAW,GAAG,QAAQ;AAAA,EACzC;AACF;AAEO,IAAM,gBAAwC;AAAA,EACnD,GAAG;AAAA,EACH,QAAQ,SAAS;AACf,WAAO,EAAE,QAAQ,WAAW,GAAG,QAAQ;AAAA,EACzC;AACF;;;AC1BO,SAAS,sBAAsB,SAAkD;AACtF,SAAO;AAAA,IACL,IAAI,QAAQ;AAAA,IACZ,MAAM,QAAQ,QAAQ;AAAA,IACtB,OAAO,QAA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