@anvia/core 0.26.0 → 1.0.0-rc.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/README.md +21 -11
- package/dist/agent/index.d.ts +26 -68
- package/dist/agent/index.js +20 -17
- package/dist/agent-DGYY_onS.d.ts +145 -0
- package/dist/audio-generation/index.d.ts +12 -14
- package/dist/audio-generation/index.js +5 -39
- package/dist/audio-generation/index.js.map +1 -1
- package/dist/{chunk-MRQLEK2B.js → chunk-5XKDW36Z.js} +30 -7
- package/dist/chunk-5XKDW36Z.js.map +1 -0
- package/dist/chunk-6WGGTJE6.js +139 -0
- package/dist/chunk-6WGGTJE6.js.map +1 -0
- package/dist/chunk-A3UBYTJT.js +157 -0
- package/dist/chunk-A3UBYTJT.js.map +1 -0
- package/dist/{chunk-NCPN4SJR.js → chunk-DMPUP4R3.js} +10 -10
- package/dist/chunk-DMPUP4R3.js.map +1 -0
- package/dist/{chunk-MNWK2USR.js → chunk-DZ3CKYTH.js} +29 -5
- package/dist/chunk-DZ3CKYTH.js.map +1 -0
- package/dist/{chunk-CWUJUSOS.js → chunk-FNQB2JEH.js} +1 -1
- package/dist/chunk-FNQB2JEH.js.map +1 -0
- package/dist/chunk-I6G7BC42.js +41 -0
- package/dist/chunk-I6G7BC42.js.map +1 -0
- package/dist/{chunk-BALBBVI3.js → chunk-IL3ZSNJI.js} +2720 -1704
- package/dist/chunk-IL3ZSNJI.js.map +1 -0
- package/dist/chunk-J6GNQART.js +122 -0
- package/dist/chunk-J6GNQART.js.map +1 -0
- package/dist/{chunk-MC3CCKEB.js → chunk-M3IOWB4Y.js} +124 -65
- package/dist/chunk-M3IOWB4Y.js.map +1 -0
- package/dist/chunk-QY5GZ7HR.js +39 -0
- package/dist/chunk-QY5GZ7HR.js.map +1 -0
- package/dist/{chunk-MELYDKWQ.js → chunk-R2LJSQUW.js} +190 -20
- package/dist/chunk-R2LJSQUW.js.map +1 -0
- package/dist/{chunk-WQKHFADH.js → chunk-RFDVKCIE.js} +3 -3
- package/dist/chunk-RFDVKCIE.js.map +1 -0
- package/dist/chunk-RMUBRRSK.js +34 -0
- package/dist/chunk-RMUBRRSK.js.map +1 -0
- package/dist/{chunk-I6XOQ4LK.js → chunk-RXKHOYEH.js} +1 -1
- package/dist/chunk-RXKHOYEH.js.map +1 -0
- package/dist/chunk-XDRSPSR7.js +38 -0
- package/dist/chunk-XDRSPSR7.js.map +1 -0
- package/dist/completion/index.d.ts +5 -36
- package/dist/completion/index.js +4 -5
- package/dist/dynamic-tools-i9woysFa.d.ts +33 -0
- package/dist/embeddings/index.d.ts +2 -2
- package/dist/embeddings/index.js +1 -2
- package/dist/{errors-2moLDuuN.d.ts → errors-CYKUcU89.d.ts} +2 -2
- package/dist/evals/index.d.ts +22 -15
- package/dist/evals/index.js +57 -35
- package/dist/evals/index.js.map +1 -1
- package/dist/extractor/index.d.ts +23 -35
- package/dist/extractor/index.js +7 -21
- package/dist/guardrails/index.d.ts +2 -2
- package/dist/guardrails/index.js +1 -1
- package/dist/image-generation/index.d.ts +12 -14
- package/dist/image-generation/index.js +5 -39
- package/dist/image-generation/index.js.map +1 -1
- package/dist/index-DxB74ybJ.d.ts +349 -0
- package/dist/index.d.ts +20 -17
- package/dist/index.js +31 -36
- package/dist/internal/agent.d.ts +152 -9
- package/dist/internal/agent.js +22 -17
- package/dist/{json-BVPssigK.d.ts → json-Zo7K3xmt.d.ts} +12 -11
- package/dist/loaders/index.d.ts +5 -10
- package/dist/loaders/index.js.map +1 -1
- package/dist/mcp/index.d.ts +4 -4
- package/dist/mcp/index.js.map +1 -1
- package/dist/memory/index.d.ts +4 -4
- package/dist/memory/index.js +6 -7
- package/dist/middleware-KynLg_RW.d.ts +56 -0
- package/dist/observability/index.d.ts +6 -3
- package/dist/observability/index.js.map +1 -1
- package/dist/pipeline/index.d.ts +40 -47
- package/dist/pipeline/index.js +99 -99
- package/dist/pipeline/index.js.map +1 -1
- package/dist/retry-D3Ruy-ba.d.ts +15 -0
- package/dist/skills/index.d.ts +4 -4
- package/dist/skills/index.js +5 -6
- package/dist/streaming/index.js +37 -3
- package/dist/streaming/index.js.map +1 -1
- package/dist/{think-tool-DfCMuO8e.d.ts → think-tool-DZqZj2LV.d.ts} +5 -5
- package/dist/tool/index.d.ts +8 -6
- package/dist/tool/index.js +12 -15
- package/dist/tool-C_8GudXn.d.ts +49 -0
- package/dist/transcription/index.d.ts +14 -16
- package/dist/transcription/index.js +5 -57
- package/dist/transcription/index.js.map +1 -1
- package/dist/type-utils-CtHVDRn_.d.ts +6 -0
- package/dist/{types-G12i56s2.d.ts → types-B3A4YxaA.d.ts} +1 -1
- package/dist/{types-BrLbKnEz.d.ts → types-BBEGKB9m.d.ts} +1 -1
- package/dist/{types-O-abTIin.d.ts → types-DT3nEemY.d.ts} +3 -3
- package/dist/{types-04LqWrmy.d.ts → types-DhQfwiZn.d.ts} +1 -1
- package/dist/{types-JJCxRnaZ.d.ts → types-DulRCYdB.d.ts} +2 -2
- package/dist/{types-BCTRUGex.d.ts → types-p55Jc-sr.d.ts} +1 -1
- package/dist/ui/index.d.ts +1 -1
- package/dist/ui/index.js +1 -1
- package/dist/vector-store/index.d.ts +5 -5
- package/dist/vector-store/index.js +4 -4
- package/package.json +2 -10
- package/dist/agent-x3YTyv5i.d.ts +0 -222
- package/dist/chunk-2ODTMRHP.js +0 -54
- package/dist/chunk-2ODTMRHP.js.map +0 -1
- package/dist/chunk-BALBBVI3.js.map +0 -1
- package/dist/chunk-CWUJUSOS.js.map +0 -1
- package/dist/chunk-DALYP4PX.js +0 -225
- package/dist/chunk-DALYP4PX.js.map +0 -1
- package/dist/chunk-HYUYZEAJ.js +0 -223
- package/dist/chunk-HYUYZEAJ.js.map +0 -1
- package/dist/chunk-I6XOQ4LK.js.map +0 -1
- package/dist/chunk-JI5YZWNT.js +0 -220
- package/dist/chunk-JI5YZWNT.js.map +0 -1
- package/dist/chunk-MC3CCKEB.js.map +0 -1
- package/dist/chunk-MELYDKWQ.js.map +0 -1
- package/dist/chunk-MNWK2USR.js.map +0 -1
- package/dist/chunk-MRQLEK2B.js.map +0 -1
- package/dist/chunk-NCPN4SJR.js.map +0 -1
- package/dist/chunk-OIMLU4SF.js +0 -20
- package/dist/chunk-OIMLU4SF.js.map +0 -1
- package/dist/chunk-Q25IWLBT.js +0 -138
- package/dist/chunk-Q25IWLBT.js.map +0 -1
- package/dist/chunk-UQX6EXWG.js +0 -33
- package/dist/chunk-UQX6EXWG.js.map +0 -1
- package/dist/chunk-WQKHFADH.js.map +0 -1
- package/dist/chunk-XUUY2L2D.js +0 -42
- package/dist/chunk-XUUY2L2D.js.map +0 -1
- package/dist/chunk-YLMDBQO4.js +0 -141
- package/dist/chunk-YLMDBQO4.js.map +0 -1
- package/dist/hooks/index.d.ts +0 -12
- package/dist/hooks/index.js +0 -17
- package/dist/hooks/index.js.map +0 -1
- package/dist/index-BxSbmOMr.d.ts +0 -257
- package/dist/middleware-Dp3d_pxi.d.ts +0 -90
- package/dist/request/index.d.ts +0 -28
- package/dist/request/index.js +0 -25
- package/dist/request/index.js.map +0 -1
- package/dist/tool-Cohdv5GC.d.ts +0 -65
- package/dist/types-D9JpeAPF.d.ts +0 -114
package/dist/mcp/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/mcp/result.ts","../../src/mcp/tool.ts","../../src/mcp/connect.ts","../../src/mcp/connections.ts","../../src/mcp/url-safety.ts"],"sourcesContent":["import { isRecord } from \"../internal/record\";\nimport type { McpToolCallContent, McpToolCallResult } from \"./types\";\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): string {\n if (\"toolResult\" in result) {\n return serializeMcpValue(result.toolResult);\n }\n\n if (result.isError === true) {\n throw new Error(mcpErrorMessage(result.content));\n }\n\n return result.content.map(mapMcpContent).join(\"\");\n}\n\nfunction mcpErrorMessage(content: McpToolCallContent[]): 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: McpToolCallContent): string {\n if (content.type === \"text\") {\n return content.text;\n }\n\n if (content.type === \"image\") {\n return `data:${content.mimeType};base64,${content.data}`;\n }\n\n if (content.type === \"resource\") {\n const mimeType =\n content.resource.mimeType === undefined ? \"\" : `data:${content.resource.mimeType};`;\n if (\"text\" in content.resource) {\n return `${mimeType}${content.resource.uri}:${content.resource.text}`;\n }\n\n return `${mimeType}${content.resource.uri}:${content.resource.blob}`;\n }\n\n throw new Error(`Unsupported MCP tool result content: ${serializeMcpValue(content)}`);\n}\n\nfunction serializeMcpValue(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n\n const serialized = JSON.stringify(value);\n return serialized === undefined ? String(value) : serialized;\n}\n","import type { ToolDefinition } from \"../completion/index\";\nimport type { Tool } from \"../tool/index\";\nimport { createCallToolParams, mapMcpToolResult } from \"./result\";\nimport type { McpClient, McpToolDefinition } from \"./types\";\n\nconst MCP_TOOL_METADATA_KEY = Symbol.for(\"anvia.mcp.tool.metadata\");\n\nexport function createMcpTool(\n definition: McpToolDefinition,\n client: McpClient,\n serverName?: string,\n): Tool {\n const tool: Tool = {\n name: definition.name,\n definition(): ToolDefinition {\n return {\n name: definition.name,\n description: definition.description ?? \"\",\n parameters: definition.inputSchema,\n };\n },\n async call(args): Promise<string> {\n const result = await client.callTool(createCallToolParams(definition.name, args));\n return mapMcpToolResult(result);\n },\n };\n if (serverName !== undefined) {\n Object.defineProperty(tool, MCP_TOOL_METADATA_KEY, {\n value: { serverName },\n enumerable: false,\n });\n }\n return tool;\n}\n","import { createMcpTool } from \"./tool\";\nimport type { McpConnection, McpServer } from \"./types\";\n\nexport async function connectMcp(connection: McpConnection): Promise<McpServer> {\n const client = await connection.connect();\n let tools: Awaited<ReturnType<typeof client.listTools>>[\"tools\"];\n try {\n ({ tools } = await client.listTools());\n } catch (error) {\n try {\n await client.close();\n } catch {\n // Preserve the initialization failure so callers see the actionable MCP error.\n }\n throw error;\n }\n\n return {\n name: connection.name,\n tools: tools.map((tool) => createMcpTool(tool, client, connection.name)),\n close: () => client.close(),\n };\n}\n","import { readFileSync } from \"node:fs\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport type {\n McpClient,\n McpConnection,\n McpHttpOptions,\n McpSseOptions,\n McpStdioOptions,\n} from \"./types\";\nimport { createSafeMcpFetch, parseAndValidateMcpUrl } from \"./url-safety\";\n\nconst CORE_CLIENT_VERSION = readCorePackageVersion();\n\nexport const mcp = {\n stdio(options: McpStdioOptions): McpConnection {\n return {\n name: options.name,\n async connect(): Promise<McpClient> {\n const { name: _name, ...server } = options;\n const client = createSdkClient();\n await client.connect(asSdkTransport(new StdioClientTransport(server)));\n return client as McpClient;\n },\n };\n },\n\n http(options: McpHttpOptions): McpConnection {\n return {\n name: options.name,\n async connect(): Promise<McpClient> {\n assertNoCustomMcpFetch(options.transport?.fetch);\n const url = parseAndValidateMcpUrl(options.url);\n const client = createSdkClient();\n await client.connect(\n asSdkTransport(\n new StreamableHTTPClientTransport(url, {\n ...options.transport,\n fetch: createSafeMcpFetch(),\n }),\n ),\n );\n return client as McpClient;\n },\n };\n },\n\n sse(options: McpSseOptions): McpConnection {\n return {\n name: options.name,\n async connect(): Promise<McpClient> {\n assertNoCustomMcpFetch(options.transport?.fetch);\n const url = parseAndValidateMcpUrl(options.url);\n const client = createSdkClient();\n await client.connect(\n asSdkTransport(\n new SSEClientTransport(url, {\n ...options.transport,\n fetch: createSafeMcpFetch(),\n }),\n ),\n );\n return client as McpClient;\n },\n };\n },\n};\n\nfunction assertNoCustomMcpFetch(fetch: unknown): void {\n if (fetch !== undefined) {\n throw new Error(\n \"Custom MCP transport fetch implementations are not allowed because they can bypass SSRF protection\",\n );\n }\n}\n\nfunction createSdkClient(): Client {\n return new Client({\n name: \"@anvia/core\",\n version: CORE_CLIENT_VERSION,\n });\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 asSdkTransport(transport: unknown): Parameters<Client[\"connect\"]>[0] {\n return transport as Parameters<Client[\"connect\"]>[0];\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 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 validateMcpHostname(parsed.hostname);\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 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"],"mappings":";;;;;AAGO,SAAS,qBACd,MACA,MACuD;AACvD,MAAI,SAAS,QAAQ,SAAS,QAAW;AACvC,WAAO,EAAE,KAAK;AAAA,EAChB;AAEA,MAAI,CAAC,SAAS,IAAI,GAAG;AACnB,UAAM,IAAI,MAAM,0CAA0C;AAAA,EAC5D;AAEA,SAAO,EAAE,MAAM,WAAW,KAAK;AACjC;AAEO,SAAS,iBAAiB,QAAmC;AAClE,MAAI,gBAAgB,QAAQ;AAC1B,WAAO,kBAAkB,OAAO,UAAU;AAAA,EAC5C;AAEA,MAAI,OAAO,YAAY,MAAM;AAC3B,UAAM,IAAI,MAAM,gBAAgB,OAAO,OAAO,CAAC;AAAA,EACjD;AAEA,SAAO,OAAO,QAAQ,IAAI,aAAa,EAAE,KAAK,EAAE;AAClD;AAEA,SAAS,gBAAgB,SAAuC;AAC9D,QAAM,OAAO,QACV,IAAI,CAAC,SAAU,KAAK,SAAS,SAAS,KAAK,OAAO,MAAU,EAC5D,OAAO,CAAC,SAAyB,SAAS,MAAS,EACnD,KAAK,IAAI;AAEZ,SAAO,SAAS,KAAK,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;AAAA,YAC5B,CAAC;AAAA,UACH;AAAA,QACF;AACA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,uBAAuB,OAAsB;AACpD,MAAI,UAAU,QAAW;AACvB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,kBAA0B;AACjC,SAAO,IAAI,OAAO;AAAA,IAChB,MAAM;AAAA,IACN,SAAS;AAAA,EACX,CAAC;AACH;AAEA,SAAS,yBAAiC;AACxC,MAAI;AACF,UAAM,cAAc,KAAK;AAAA,MACvB,aAAa,IAAI,IAAI,sBAAsB,YAAY,GAAG,GAAG,MAAM;AAAA,IACrE;AACA,WAAO,OAAO,YAAY,YAAY,WAAW,YAAY,UAAU;AAAA,EACzE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,eAAe,WAAsD;AAC5E,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/mcp/result.ts","../../src/mcp/tool.ts","../../src/mcp/connect.ts","../../src/mcp/connections.ts","../../src/mcp/url-safety.ts"],"sourcesContent":["import { isRecord } from \"../internal/record\";\nimport type { McpToolCallContent, McpToolCallResult } from \"./types\";\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): string {\n if (\"toolResult\" in result) {\n return serializeMcpValue(result.toolResult);\n }\n\n if (result.isError === true) {\n throw new Error(mcpErrorMessage(result.content));\n }\n\n return result.content.map(mapMcpContent).join(\"\");\n}\n\nfunction mcpErrorMessage(content: McpToolCallContent[]): 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: McpToolCallContent): string {\n if (content.type === \"text\") {\n return content.text;\n }\n\n if (content.type === \"image\") {\n return `data:${content.mimeType};base64,${content.data}`;\n }\n\n if (content.type === \"resource\") {\n const mimeType =\n content.resource.mimeType === undefined ? \"\" : `data:${content.resource.mimeType};`;\n if (\"text\" in content.resource) {\n return `${mimeType}${content.resource.uri}:${content.resource.text}`;\n }\n\n return `${mimeType}${content.resource.uri}:${content.resource.blob}`;\n }\n\n throw new Error(`Unsupported MCP tool result content: ${serializeMcpValue(content)}`);\n}\n\nfunction serializeMcpValue(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n\n const serialized = JSON.stringify(value);\n return serialized === undefined ? String(value) : serialized;\n}\n","import type { ToolDefinition } from \"../completion/index\";\nimport type { Tool } from \"../tool/index\";\nimport { createCallToolParams, mapMcpToolResult } from \"./result\";\nimport type { McpClient, McpToolDefinition } from \"./types\";\n\nconst MCP_TOOL_METADATA_KEY = Symbol.for(\"anvia.mcp.tool.metadata\");\n\nexport function createMcpTool(\n definition: McpToolDefinition,\n client: McpClient,\n serverName?: string,\n): Tool {\n const tool: Tool = {\n name: definition.name,\n definition(): ToolDefinition {\n return {\n name: definition.name,\n description: definition.description ?? \"\",\n parameters: definition.inputSchema,\n };\n },\n async call(args): Promise<string> {\n const result = await client.callTool(createCallToolParams(definition.name, args));\n return mapMcpToolResult(result);\n },\n };\n if (serverName !== undefined) {\n Object.defineProperty(tool, MCP_TOOL_METADATA_KEY, {\n value: { serverName },\n enumerable: false,\n });\n }\n return tool;\n}\n","import { createMcpTool } from \"./tool\";\nimport type { McpConnection, McpServer } from \"./types\";\n\nexport async function connectMcp(connection: McpConnection): Promise<McpServer> {\n const client = await connection.connect();\n let tools: Awaited<ReturnType<typeof client.listTools>>[\"tools\"];\n try {\n ({ tools } = await client.listTools());\n } catch (error) {\n try {\n await client.close();\n } catch {\n // Preserve the initialization failure so callers see the actionable MCP error.\n }\n throw error;\n }\n\n return {\n name: connection.name,\n tools: tools.map((tool) => createMcpTool(tool, client, connection.name)),\n close: () => client.close(),\n };\n}\n","import { readFileSync } from \"node:fs\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport type {\n McpClient,\n McpConnection,\n McpHttpOptions,\n McpSseOptions,\n McpStdioOptions,\n} from \"./types\";\nimport { createSafeMcpFetch, parseAndValidateMcpUrl } from \"./url-safety\";\n\nconst CORE_CLIENT_VERSION = readCorePackageVersion();\n\nexport const mcp = {\n stdio(options: McpStdioOptions): McpConnection {\n return {\n name: options.name,\n async connect(): Promise<McpClient> {\n const { name: _name, ...server } = options;\n const client = createSdkClient();\n await client.connect(asSdkTransport(new StdioClientTransport(server)));\n return client as McpClient;\n },\n };\n },\n\n http(options: McpHttpOptions): McpConnection {\n return {\n name: options.name,\n async connect(): Promise<McpClient> {\n assertNoCustomMcpFetch(options.transport?.fetch);\n const url = parseAndValidateMcpUrl(options.url);\n const client = createSdkClient();\n await client.connect(\n asSdkTransport(\n new StreamableHTTPClientTransport(url, {\n ...options.transport,\n fetch: createSafeMcpFetch(),\n }),\n ),\n );\n return client as McpClient;\n },\n };\n },\n\n sse(options: McpSseOptions): McpConnection {\n return {\n name: options.name,\n async connect(): Promise<McpClient> {\n assertNoCustomMcpFetch(options.transport?.fetch);\n const url = parseAndValidateMcpUrl(options.url);\n const client = createSdkClient();\n await client.connect(\n asSdkTransport(\n new SSEClientTransport(url, {\n ...options.transport,\n fetch: createSafeMcpFetch(),\n }),\n ),\n );\n return client as McpClient;\n },\n };\n },\n};\n\nfunction assertNoCustomMcpFetch(fetch: unknown): void {\n if (fetch !== undefined) {\n throw new Error(\n \"Custom MCP transport fetch implementations are not allowed because they can bypass SSRF protection\",\n );\n }\n}\n\nfunction createSdkClient(): Client {\n return new Client({\n name: \"@anvia/core\",\n version: CORE_CLIENT_VERSION,\n });\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 asSdkTransport(transport: unknown): Parameters<Client[\"connect\"]>[0] {\n return transport as Parameters<Client[\"connect\"]>[0];\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 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 validateMcpHostname(parsed.hostname);\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"],"mappings":";;;;;AAGO,SAAS,qBACd,MACA,MACuD;AACvD,MAAI,SAAS,QAAQ,SAAS,QAAW;AACvC,WAAO,EAAE,KAAK;AAAA,EAChB;AAEA,MAAI,CAAC,SAAS,IAAI,GAAG;AACnB,UAAM,IAAI,MAAM,0CAA0C;AAAA,EAC5D;AAEA,SAAO,EAAE,MAAM,WAAW,KAAK;AACjC;AAEO,SAAS,iBAAiB,QAAmC;AAClE,MAAI,gBAAgB,QAAQ;AAC1B,WAAO,kBAAkB,OAAO,UAAU;AAAA,EAC5C;AAEA,MAAI,OAAO,YAAY,MAAM;AAC3B,UAAM,IAAI,MAAM,gBAAgB,OAAO,OAAO,CAAC;AAAA,EACjD;AAEA,SAAO,OAAO,QAAQ,IAAI,aAAa,EAAE,KAAK,EAAE;AAClD;AAEA,SAAS,gBAAgB,SAAuC;AAC9D,QAAM,OAAO,QACV,IAAI,CAAC,SAAU,KAAK,SAAS,SAAS,KAAK,OAAO,MAAU,EAC5D,OAAO,CAAC,SAAyB,SAAS,MAAS,EACnD,KAAK,IAAI;AAEZ,SAAO,SAAS,KAAK,+BAA+B;AACtD;AAEA,SAAS,cAAc,SAAqC;AAC1D,MAAI,QAAQ,SAAS,QAAQ;AAC3B,WAAO,QAAQ;AAAA,EACjB;AAEA,MAAI,QAAQ,SAAS,SAAS;AAC5B,WAAO,QAAQ,QAAQ,QAAQ,WAAW,QAAQ,IAAI;AAAA,EACxD;AAEA,MAAI,QAAQ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jC,SAAO,IAAI,OAAO;AAAA,IAChB,MAAM;AAAA,IACN,SAAS;AAAA,EACX,CAAC;AACH;AAEA,SAAS,yBAAiC;AACxC,MAAI;AACF,UAAM,cAAc,KAAK;AAAA,MACvB,aAAa,IAAI,IAAI,sBAAsB,YAAY,GAAG,GAAG,MAAM;AAAA,IACrE;AACA,WAAO,OAAO,YAAY,YAAY,WAAW,YAAY,UAAU;AAAA,EACzE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,eAAe,WAAsD;AAC5E,SAAO;AACT;","names":[]}
|
package/dist/memory/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { M as MemoryCompactionConflictError, a as MemoryCompactionError, c as createSummaryMemoryCompactor, i as isMemoryCompactionSummary } from '../errors-
|
|
2
|
-
import { n as MemoryOptions, o as ResolvedMemoryOptions } from '../types-
|
|
3
|
-
export { p as MemoryAppendInput, M as MemoryCompactionCommitInput, a as MemoryCompactionCommitResult, b as MemoryCompactionOptions, c as MemoryCompactionSnapshot, d as MemoryCompactionStore, e as MemoryCompactor, f as MemoryCompactorInput, g as MemoryCompactorResult, q as MemoryContext, h as MemoryConversation, i as MemoryConversationListOptions, j as MemoryConversationMessage, k as MemoryConversationSummary, r as MemoryErrorInput, l as MemoryInspector, s as MemoryRegistration, t as MemorySavePolicy, m as MemoryStore, R as ResolvedMemoryCompactionOptions, u as SessionOptions, S as SummaryMemoryCompactorOptions } from '../types-
|
|
4
|
-
import '../types-
|
|
1
|
+
export { M as MemoryCompactionConflictError, a as MemoryCompactionError, c as createSummaryMemoryCompactor, i as isMemoryCompactionSummary } from '../errors-CYKUcU89.js';
|
|
2
|
+
import { n as MemoryOptions, o as ResolvedMemoryOptions } from '../types-BBEGKB9m.js';
|
|
3
|
+
export { p as MemoryAppendInput, M as MemoryCompactionCommitInput, a as MemoryCompactionCommitResult, b as MemoryCompactionOptions, c as MemoryCompactionSnapshot, d as MemoryCompactionStore, e as MemoryCompactor, f as MemoryCompactorInput, g as MemoryCompactorResult, q as MemoryContext, h as MemoryConversation, i as MemoryConversationListOptions, j as MemoryConversationMessage, k as MemoryConversationSummary, r as MemoryErrorInput, l as MemoryInspector, s as MemoryRegistration, t as MemorySavePolicy, m as MemoryStore, R as ResolvedMemoryCompactionOptions, u as SessionOptions, S as SummaryMemoryCompactorOptions } from '../types-BBEGKB9m.js';
|
|
4
|
+
import '../types-B3A4YxaA.js';
|
|
5
5
|
|
|
6
6
|
declare function resolveMemoryOptions(options?: MemoryOptions): ResolvedMemoryOptions;
|
|
7
7
|
|
package/dist/memory/index.js
CHANGED
|
@@ -1,16 +1,15 @@
|
|
|
1
1
|
import "../chunk-XWUC7CIT.js";
|
|
2
|
-
import {
|
|
3
|
-
resolveMemoryOptions
|
|
4
|
-
} from "../chunk-UQX6EXWG.js";
|
|
5
2
|
import {
|
|
6
3
|
MemoryCompactionConflictError,
|
|
7
4
|
MemoryCompactionError,
|
|
8
5
|
createSummaryMemoryCompactor,
|
|
9
|
-
isMemoryCompactionSummary
|
|
10
|
-
|
|
11
|
-
|
|
6
|
+
isMemoryCompactionSummary,
|
|
7
|
+
resolveMemoryOptions
|
|
8
|
+
} from "../chunk-5XKDW36Z.js";
|
|
9
|
+
import "../chunk-M3IOWB4Y.js";
|
|
10
|
+
import "../chunk-RFDVKCIE.js";
|
|
12
11
|
import "../chunk-ADH7NNCS.js";
|
|
13
|
-
import "../chunk-
|
|
12
|
+
import "../chunk-A3UBYTJT.js";
|
|
14
13
|
export {
|
|
15
14
|
MemoryCompactionConflictError,
|
|
16
15
|
MemoryCompactionError,
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { f as CompletionRequest, g as CompletionResponse, l as JsonValue, u as ToolResultContent } from './types-B3A4YxaA.js';
|
|
2
|
+
import { M as MaybePromise } from './type-utils-CtHVDRn_.js';
|
|
3
|
+
|
|
4
|
+
type CompletionRequestMiddlewareArgs = {
|
|
5
|
+
turn: number;
|
|
6
|
+
request: CompletionRequest;
|
|
7
|
+
originalRequest: CompletionRequest;
|
|
8
|
+
};
|
|
9
|
+
type CompletionRequestMiddlewareResult = {
|
|
10
|
+
request: CompletionRequest;
|
|
11
|
+
} | undefined;
|
|
12
|
+
type CompletionResponseMiddlewareArgs<RawResponse = unknown> = {
|
|
13
|
+
turn: number;
|
|
14
|
+
request: CompletionRequest;
|
|
15
|
+
response: CompletionResponse<RawResponse>;
|
|
16
|
+
originalResponse: CompletionResponse<RawResponse>;
|
|
17
|
+
};
|
|
18
|
+
type CompletionResponseMiddlewareResult<RawResponse = unknown> = {
|
|
19
|
+
response: CompletionResponse<RawResponse>;
|
|
20
|
+
} | undefined;
|
|
21
|
+
type ToolInputMiddlewareArgs = {
|
|
22
|
+
toolName: string;
|
|
23
|
+
args: string;
|
|
24
|
+
originalArgs: string;
|
|
25
|
+
turn: number;
|
|
26
|
+
toolCallId?: string | undefined;
|
|
27
|
+
internalCallId: string;
|
|
28
|
+
};
|
|
29
|
+
type ToolInputMiddlewareResult = {
|
|
30
|
+
args: JsonValue | string;
|
|
31
|
+
} | undefined;
|
|
32
|
+
type ToolResultMiddlewareArgs = {
|
|
33
|
+
toolName: string;
|
|
34
|
+
args: string;
|
|
35
|
+
result: string;
|
|
36
|
+
originalResult: string;
|
|
37
|
+
structuredResult?: ToolResultContent[] | undefined;
|
|
38
|
+
originalStructuredResult?: ToolResultContent[] | undefined;
|
|
39
|
+
turn: number;
|
|
40
|
+
toolCallId?: string | undefined;
|
|
41
|
+
internalCallId: string;
|
|
42
|
+
};
|
|
43
|
+
type ToolOutputMiddlewareArgs = ToolResultMiddlewareArgs;
|
|
44
|
+
type ToolOutputMiddlewareResult = string | {
|
|
45
|
+
result?: string | undefined;
|
|
46
|
+
structuredResult?: ToolResultContent[] | undefined;
|
|
47
|
+
} | undefined;
|
|
48
|
+
interface AgentMiddleware<RawResponse = unknown> {
|
|
49
|
+
onCompletionRequest?(args: CompletionRequestMiddlewareArgs): MaybePromise<CompletionRequestMiddlewareResult>;
|
|
50
|
+
onCompletionResponse?(args: CompletionResponseMiddlewareArgs<RawResponse>): MaybePromise<CompletionResponseMiddlewareResult<RawResponse>>;
|
|
51
|
+
onToolInput?(args: ToolInputMiddlewareArgs): MaybePromise<ToolInputMiddlewareResult>;
|
|
52
|
+
onToolOutput?(args: ToolOutputMiddlewareArgs): MaybePromise<ToolOutputMiddlewareResult>;
|
|
53
|
+
}
|
|
54
|
+
declare function createMiddleware<RawResponse = unknown>(middleware: AgentMiddleware<RawResponse>): AgentMiddleware<RawResponse>;
|
|
55
|
+
|
|
56
|
+
export { type AgentMiddleware as A, type CompletionRequestMiddlewareArgs as C, type ToolInputMiddlewareArgs as T, type CompletionRequestMiddlewareResult as a, type CompletionResponseMiddlewareArgs as b, type CompletionResponseMiddlewareResult as c, type ToolInputMiddlewareResult as d, type ToolOutputMiddlewareArgs as e, type ToolOutputMiddlewareResult as f, type ToolResultMiddlewareArgs as g, createMiddleware as h };
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
export {
|
|
2
|
-
import '../
|
|
1
|
+
export { C as AgentGenerationEndArgs, D as AgentGenerationErrorArgs, E as AgentGenerationModelInfo, F as AgentGenerationObserver, G as AgentGenerationStartArgs, H as AgentGenerationUpdateArgs, z as AgentObserver, B as AgentObserverRegistration, I as AgentRunEndArgs, J as AgentRunErrorArgs, K as AgentRunEventArgs, L as AgentRunObserver, M as AgentRunPromptRef, N as AgentRunStartArgs, P as AgentToolEndArgs, Q as AgentToolErrorArgs, R as AgentToolObserver, S as AgentToolStartArgs, T as AgentToolStreamEventArgs, U as AgentTraceInfo, V as AgentTraceOptions, O as ObserveOptions, W as createObserver } from '../index-DxB74ybJ.js';
|
|
2
|
+
import '../retry-D3Ruy-ba.js';
|
|
3
|
+
import '../types-B3A4YxaA.js';
|
|
3
4
|
import '../guardrails/index.js';
|
|
4
|
-
import '../
|
|
5
|
+
import '../type-utils-CtHVDRn_.js';
|
|
6
|
+
import '../middleware-KynLg_RW.js';
|
|
7
|
+
import '../tool-C_8GudXn.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/observability/types.ts"],"sourcesContent":["import type {\n CompletionModelCapabilities,\n CompletionRequest,\n CompletionResponse,\n CompletionSource,\n JsonObject,\n JsonValue,\n Message,\n ProviderToolCall,\n ToolCall,\n ToolDefinition,\n ToolResultContent,\n Usage,\n} from \"../completion\";\nimport type {
|
|
1
|
+
{"version":3,"sources":["../../src/observability/types.ts"],"sourcesContent":["import type { AgentDeltaEvent } from \"../agent/run-types\";\nimport type {\n CompletionModelCapabilities,\n CompletionRequest,\n CompletionResponse,\n CompletionSource,\n JsonObject,\n JsonValue,\n Message,\n ProviderToolCall,\n ToolCall,\n ToolDefinition,\n ToolResultContent,\n Usage,\n} from \"../completion\";\nimport type { DeepReadonly } from \"../internal/type-utils\";\nimport type { ToolCallStreamEvent } from \"../tool\";\n\nexport type AgentTraceInfo = {\n readonly traceId?: string | undefined;\n readonly observationId?: string | undefined;\n};\n\nexport type AgentTraceOptions = {\n readonly name?: string | undefined;\n readonly userId?: string | undefined;\n readonly sessionId?: string | undefined;\n readonly metadata?: Readonly<Record<string, unknown>> | undefined;\n readonly tags?: readonly string[] | undefined;\n readonly version?: string | undefined;\n readonly traceId?: string | undefined;\n readonly failOnObserverError?: boolean | undefined;\n readonly promptRef?: AgentRunPromptRef | undefined;\n};\n\nexport type AgentRunPromptRef = {\n readonly name: string;\n readonly version?: number | undefined;\n};\n\nexport type AgentRunStartArgs = {\n readonly runId: string;\n readonly agentName?: string | undefined;\n readonly agentDescription?: string | undefined;\n readonly instructions?: string | undefined;\n readonly trace?: DeepReadonly<AgentTraceOptions> | undefined;\n readonly prompt: DeepReadonly<Message>;\n readonly promptRef?: DeepReadonly<AgentRunPromptRef> | undefined;\n readonly history: readonly DeepReadonly<Message>[];\n readonly maxTurns: number;\n};\n\nexport type AgentRunEndArgs = {\n readonly output: string;\n readonly usage: DeepReadonly<Usage>;\n readonly messages: readonly DeepReadonly<Message>[];\n readonly sources?: readonly DeepReadonly<CompletionSource>[] | undefined;\n readonly providerToolCalls?: readonly DeepReadonly<ProviderToolCall>[] | undefined;\n};\n\nexport type AgentRunErrorArgs = {\n readonly error: unknown;\n readonly usage: DeepReadonly<Usage>;\n readonly messages: readonly DeepReadonly<Message>[];\n};\n\nexport type AgentGenerationModelInfo = {\n readonly provider: string;\n readonly defaultModel: string;\n readonly capabilities?: DeepReadonly<CompletionModelCapabilities> | undefined;\n};\n\nexport type AgentGenerationStartArgs = {\n readonly turn: number;\n readonly request: DeepReadonly<CompletionRequest>;\n readonly providerRequest?: DeepReadonly<JsonObject> | undefined;\n readonly modelInfo?: DeepReadonly<AgentGenerationModelInfo> | undefined;\n};\n\nexport type AgentGenerationEndArgs<RawResponse = unknown> = {\n readonly turn: number;\n readonly response: DeepReadonly<CompletionResponse<RawResponse>>;\n readonly firstDeltaMs?: number | undefined;\n};\n\nexport type AgentGenerationErrorArgs = {\n readonly turn: number;\n readonly error: unknown;\n};\n\nexport type AgentGenerationUpdateArgs = {\n readonly turn: number;\n readonly delta: DeepReadonly<AgentDeltaEvent>;\n};\n\nexport type AgentRunEventArgs = {\n readonly name: string;\n readonly attributes?: Readonly<Record<string, DeepReadonly<JsonValue> | undefined>> | undefined;\n readonly level?: \"DEFAULT\" | \"WARNING\" | \"ERROR\" | undefined;\n readonly timestamp?: Date | string | undefined;\n};\n\nexport type AgentToolStartArgs = {\n readonly turn: number;\n readonly toolCall: DeepReadonly<ToolCall>;\n readonly toolName: string;\n readonly args: string;\n readonly internalCallId: string;\n readonly toolCallId?: string | undefined;\n readonly toolDefinition?: DeepReadonly<ToolDefinition> | undefined;\n readonly toolMetadata?: DeepReadonly<JsonObject> | undefined;\n};\n\nexport type AgentToolEndArgs = AgentToolStartArgs & {\n readonly result: string;\n readonly structuredResult?: readonly DeepReadonly<ToolResultContent>[] | undefined;\n readonly skipped: boolean;\n};\n\nexport type AgentToolErrorArgs = AgentToolStartArgs & {\n readonly error: unknown;\n};\n\nexport type AgentToolStreamEventArgs = AgentToolStartArgs & {\n readonly event: DeepReadonly<ToolCallStreamEvent>;\n};\n\nexport interface AgentGenerationObserver {\n end(args: AgentGenerationEndArgs): void | Promise<void>;\n error?(args: AgentGenerationErrorArgs): void | Promise<void>;\n update?(args: AgentGenerationUpdateArgs): void | Promise<void>;\n}\n\nexport interface AgentToolObserver {\n streamEvent?(args: AgentToolStreamEventArgs): void | Promise<void>;\n end(args: AgentToolEndArgs): void | Promise<void>;\n error?(args: AgentToolErrorArgs): void | Promise<void>;\n}\n\nexport interface AgentRunObserver {\n readonly trace?: AgentTraceInfo | undefined;\n startGeneration?(\n args: AgentGenerationStartArgs,\n ): AgentGenerationObserver | undefined | Promise<AgentGenerationObserver | undefined>;\n startTool?(\n args: AgentToolStartArgs,\n ): AgentToolObserver | undefined | Promise<AgentToolObserver | undefined>;\n end(args: AgentRunEndArgs): void | Promise<void>;\n error?(args: AgentRunErrorArgs): void | Promise<void>;\n event?(args: AgentRunEventArgs): void | Promise<void>;\n}\n\nexport interface AgentObserver {\n startRun(\n args: AgentRunStartArgs,\n ): AgentRunObserver | undefined | Promise<AgentRunObserver | undefined>;\n flush?(): void | Promise<void>;\n shutdown?(): void | Promise<void>;\n}\n\nexport type AgentObserverRegistration = {\n readonly observer: AgentObserver;\n readonly failOnObserverError?: boolean | undefined;\n};\n\nexport type ObserveOptions = {\n readonly failOnObserverError?: boolean | undefined;\n};\n\nexport function createObserver(observer: AgentObserver): AgentObserver {\n return observer;\n}\n"],"mappings":";AAyKO,SAAS,eAAe,UAAwC;AACrE,SAAO;AACT;","names":[]}
|
package/dist/pipeline/index.d.ts
CHANGED
|
@@ -1,16 +1,23 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { J as JsonObject, C as CompletionModel } from '../types-G12i56s2.js';
|
|
1
|
+
import { A as Agent } from '../agent-DGYY_onS.js';
|
|
2
|
+
import { J as JsonObject, C as CompletionModel } from '../types-B3A4YxaA.js';
|
|
4
3
|
import { Extractor } from '../extractor/index.js';
|
|
4
|
+
import { z } from 'zod';
|
|
5
5
|
import '../guardrails/index.js';
|
|
6
|
-
import '../
|
|
7
|
-
import '../types-
|
|
8
|
-
import '../index-
|
|
9
|
-
import '../
|
|
10
|
-
import '../middleware-
|
|
11
|
-
import '../
|
|
12
|
-
import '../types-O-abTIin.js';
|
|
6
|
+
import '../type-utils-CtHVDRn_.js';
|
|
7
|
+
import '../types-BBEGKB9m.js';
|
|
8
|
+
import '../index-DxB74ybJ.js';
|
|
9
|
+
import '../retry-D3Ruy-ba.js';
|
|
10
|
+
import '../middleware-KynLg_RW.js';
|
|
11
|
+
import '../tool-C_8GudXn.js';
|
|
13
12
|
import '../zod-schema-C7F4clpm.js';
|
|
13
|
+
import '../types-DulRCYdB.js';
|
|
14
|
+
import '@modelcontextprotocol/sdk/client/sse.js';
|
|
15
|
+
import '@modelcontextprotocol/sdk/client/stdio.js';
|
|
16
|
+
import '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
17
|
+
import '../types-DhQfwiZn.js';
|
|
18
|
+
import '../dynamic-tools-i9woysFa.js';
|
|
19
|
+
import '../types-p55Jc-sr.js';
|
|
20
|
+
import '../types-DT3nEemY.js';
|
|
14
21
|
|
|
15
22
|
/** Minimal interface for anything that can run as a pipeline stage. */
|
|
16
23
|
interface PipelineOp<Input = unknown, Output = unknown> {
|
|
@@ -30,6 +37,13 @@ type PipelineMetadata = {
|
|
|
30
37
|
description?: string | undefined;
|
|
31
38
|
metadata?: JsonObject | undefined;
|
|
32
39
|
};
|
|
40
|
+
type PipelineOptions<Input, Parsed = Input> = {
|
|
41
|
+
id: string;
|
|
42
|
+
inputSchema: z.ZodType<Parsed, Input>;
|
|
43
|
+
name?: string | undefined;
|
|
44
|
+
description?: string | undefined;
|
|
45
|
+
metadata?: JsonObject | undefined;
|
|
46
|
+
};
|
|
33
47
|
type PipelineStageMetadata = {
|
|
34
48
|
id?: string | undefined;
|
|
35
49
|
name?: string | undefined;
|
|
@@ -78,55 +92,34 @@ type PipelineRunObserver = {
|
|
|
78
92
|
type PipelineRunOptions = {
|
|
79
93
|
observer?: PipelineRunObserver | undefined;
|
|
80
94
|
};
|
|
81
|
-
type PipelineRunContext = {
|
|
82
|
-
observer?: PipelineRunObserver | undefined;
|
|
83
|
-
};
|
|
84
|
-
type PipelineExecutor<Input, Output> = (input: Input, context: PipelineRunContext) => Output | Promise<Output>;
|
|
85
|
-
type PipelineBuilderState = {
|
|
86
|
-
graph: PipelineGraph;
|
|
87
|
-
terminalNodeId: string;
|
|
88
|
-
terminalNodeIds: string[];
|
|
89
|
-
nextNodeIndex: number;
|
|
90
|
-
nextEdgeIndex: number;
|
|
91
|
-
};
|
|
92
95
|
|
|
93
|
-
/**
|
|
94
|
-
declare class Pipeline<Input, Output> implements PipelineOp<Input, Awaited<Output>> {
|
|
95
|
-
private readonly executor;
|
|
96
|
-
private readonly pipelineGraph;
|
|
96
|
+
/** Immutable, typed pipeline that can be composed and run directly. */
|
|
97
|
+
declare class Pipeline<Input, Output = Input> implements PipelineOp<Input, Awaited<Output>> {
|
|
97
98
|
readonly id: string;
|
|
98
99
|
readonly name: string | undefined;
|
|
99
100
|
readonly description: string | undefined;
|
|
100
101
|
readonly metadata: JsonObject | undefined;
|
|
101
|
-
constructor(executor: PipelineExecutor<Input, Output>, pipelineGraph?: PipelineGraph);
|
|
102
|
-
/** Run one input through the built pipeline and return the final stage output. */
|
|
103
|
-
run(input: Input, options?: PipelineRunOptions): Promise<Awaited<Output>>;
|
|
104
|
-
/** Run many inputs through the same pipeline with bounded concurrency. */
|
|
105
|
-
batch<I extends Iterable<Input>>(inputs: I, options: PipelineBatchOptions): Promise<Array<Awaited<Output>>>;
|
|
106
|
-
graph(): PipelineGraph;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/** Builds a typed pipeline from an original input type to an inferred output type. */
|
|
110
|
-
declare class PipelineBuilder<Input, Output = Input> {
|
|
111
102
|
private readonly executor;
|
|
112
103
|
private readonly state;
|
|
113
|
-
constructor(
|
|
114
|
-
constructor(schema: z.ZodType<Output, Input>, metadata: PipelineMetadata);
|
|
115
|
-
constructor(executor: (input: Input) => Output | Promise<Output>);
|
|
116
|
-
constructor(executor: PipelineExecutor<Input, Output>, state: PipelineBuilderState);
|
|
104
|
+
constructor(options: PipelineOptions<Input, Output>);
|
|
117
105
|
/** Add a synchronous or asynchronous transform stage. */
|
|
118
|
-
step<Next>(fn: (input: Awaited<Output>) => Next | Promise<Next>, metadata?: PipelineStageMetadata):
|
|
106
|
+
step<Next>(fn: (input: Awaited<Output>) => Next | Promise<Next>, metadata?: PipelineStageMetadata): Pipeline<Input, Awaited<Next>>;
|
|
119
107
|
/** Compose another pipeline operation after the current stage. */
|
|
120
|
-
use<Next>(op: PipelineOp<Awaited<Output>, Next>, metadata?: PipelineStageMetadata):
|
|
108
|
+
use<Next>(op: PipelineOp<Awaited<Output>, Next>, metadata?: PipelineStageMetadata): Pipeline<Input, Awaited<Next>>;
|
|
121
109
|
/** Run named branch operations concurrently from the current value. */
|
|
122
|
-
parallel<Branches extends Record<string, PipelineOp<Awaited<Output>, unknown>>>(branches: Branches, metadata?: PipelineStageMetadata):
|
|
110
|
+
parallel<Branches extends Record<string, PipelineOp<Awaited<Output>, unknown>>>(branches: Branches, metadata?: PipelineStageMetadata): Pipeline<Input, ParallelOutput<Branches>>;
|
|
123
111
|
/** Send the current value to an agent as text and continue with the agent output. */
|
|
124
|
-
|
|
112
|
+
agent(agent: Agent<CompletionModel>, metadata?: PipelineStageMetadata): Pipeline<Input, string>;
|
|
125
113
|
/** Send the current value to an extractor as text and continue with typed schema data. */
|
|
126
|
-
extract<T>(extractor: Extractor<T, CompletionModel>, metadata?: PipelineStageMetadata):
|
|
127
|
-
/**
|
|
128
|
-
|
|
114
|
+
extract<T>(extractor: Extractor<T, CompletionModel>, metadata?: PipelineStageMetadata): Pipeline<Input, T>;
|
|
115
|
+
/** Run one input through the pipeline and return the final stage output. */
|
|
116
|
+
run(input: Input, options?: PipelineRunOptions): Promise<Awaited<Output>>;
|
|
117
|
+
/** Run many inputs through the same pipeline with bounded concurrency. */
|
|
118
|
+
batch<I extends Iterable<Input>>(inputs: I, options: PipelineBatchOptions): Promise<Array<Awaited<Output>>>;
|
|
119
|
+
/** Return an isolated graph snapshot for the current pipeline stages. */
|
|
120
|
+
graph(): PipelineGraph;
|
|
121
|
+
private derive;
|
|
129
122
|
private runStep;
|
|
130
123
|
}
|
|
131
124
|
|
|
132
|
-
export { Pipeline, type PipelineBatchOptions,
|
|
125
|
+
export { Pipeline, type PipelineBatchOptions, type PipelineGraph, type PipelineGraphEdge, type PipelineGraphNode, type PipelineMetadata, type PipelineOp, type PipelineOptions, type PipelineRunEvent, type PipelineRunObserver, type PipelineRunOptions, type PipelineStageKind, type PipelineStageMetadata };
|