@zuora/agent-toolkit 0.1.0-alpha.0 → 0.1.0-alpha.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 +15 -1
- package/dist/langchain/index.js +18 -9
- package/dist/langchain/index.js.map +1 -1
- package/dist/openai/index.js +18 -9
- package/dist/openai/index.js.map +1 -1
- package/dist/openai-agents/index.d.ts +30 -1
- package/dist/openai-agents/index.js +92 -9
- package/dist/openai-agents/index.js.map +1 -1
- package/dist/shared/toolkit-core.js +18 -9
- package/dist/shared/toolkit-core.js.map +1 -1
- package/dist/vercel-ai/index.js +18 -9
- package/dist/vercel-ai/index.js.map +1 -1
- package/package.json +15 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/openai-agents/toolkit.ts","../../src/shared/errors.ts","../../src/shared/types.ts","../../src/shared/utils/zuora-url.ts","../../src/shared/approval-policy.ts","../../src/shared/utils/adapter-name.ts","../../src/shared/async-jobs.ts","../../src/shared/bundles.ts","../../src/shared/utils/values.ts","../../src/shared/tools/operation-metadata.ts","../../src/shared/utils/event-sanitizer.ts","../../src/shared/observability/events.ts","../../src/shared/observability/async-poll-events.ts","../../src/shared/observability/payloads.ts","../../src/shared/transport/request-metadata.ts","../../src/shared/observability/request-metadata.ts","../../src/shared/tools/native/file-artifacts/config.ts","../../src/shared/tools/native/config.ts","../../src/shared/tools/native/metadata.ts","../../src/shared/tools/native/file-artifacts/definitions.ts","../../src/shared/tools/native/file-artifacts/download-service.ts","../../src/shared/tools/native/file-artifacts/errors.ts","../../src/shared/tools/native/file-artifacts/path-policy.ts","../../src/shared/tools/native/file-artifacts/manifest.ts","../../src/shared/tools/native/file-artifacts/url-policy.ts","../../src/shared/tools/native/file-artifacts/helpers.ts","../../src/shared/tools/native/registry-source.ts","../../src/shared/tools/native/file-artifacts/index.ts","../../src/shared/tools/native/resolve-native-file-tools-input.ts","../../src/shared/tools/native/query-result-download/config.ts","../../src/shared/tools/native/query-result-download/helpers/status-resolver.ts","../../src/shared/tools/native/query-result-download/definitions.ts","../../src/shared/tools/native/query-result-download/helpers/index.ts","../../src/shared/tools/native/query-result-download/index.ts","../../src/shared/tools/native/zuora-file-download/config.ts","../../src/shared/tools/native/zuora-file-download/definitions.ts","../../src/shared/tools/native/zuora-file-download/helpers/index.ts","../../src/shared/tools/native/zuora-file-download/index.ts","../../src/shared/tools/mcp-tool-definition.ts","../../src/shared/utils/redaction.ts","../../src/shared/transport/oauth-token-provider.ts","../../src/shared/transport/request-headers.ts","../../src/shared/transport/resolve-connection-config.ts","../../src/shared/transport/zuora-client.ts","../../src/shared/transport/zuora-rest-client.ts","../../src/shared/tool-selection.ts","../../src/shared/transport/mcp-tool-error.ts","../../src/shared/transport/json-rpc.ts","../../src/shared/transport/mcp-client.ts","../../src/shared/toolkit-core.ts","../../src/shared/configuration.ts","../../src/shared/agent-tool-follow-ups.ts","../../src/shared/utils/strict-schema.ts","../../src/openai-agents/build-tools.ts"],"sourcesContent":["import { tool } from \"@openai/agents\";\nimport { ToolkitCore } from \"../shared/toolkit-core.js\";\nimport { sanitizeAdapterToolName } from \"../shared/utils/adapter-name.js\";\nimport { resolveZuoraAgentToolkitConfig } from \"../shared/configuration.js\";\nimport {\n buildToolMessagePayload,\n resolveAgentToolFollowUps,\n QUERY_RESULT_DOWNLOAD_TOOL,\n} from \"../shared/agent-tool-follow-ups.js\";\nimport { strictifySchema } from \"../shared/utils/strict-schema.js\";\nimport type {\n ZuoraAgentToolkitConfigInput,\n ZuoraToolDefinition,\n} from \"../shared/types.js\";\nimport { isAsyncJobResult } from \"../shared/async-jobs.js\";\nimport {\n findDownloadUrl,\n findQueryStatus,\n} from \"../shared/tools/native/query-result-download/helpers/index.js\";\nimport {\n DEFAULT_ASYNC_JOB_TERMINAL_STATUSES,\n matchesAsyncJobTerminalStatus,\n} from \"../shared/async-jobs.js\";\n\n/** Native tool type returned by `tool()` from `@openai/agents`. */\ntype AgentsFunctionTool = ReturnType<typeof tool>;\n\n\n/**\n * Extracts a query job ID from a raw MCP response for tools that don't have\n * `asyncOperation` metadata registered on the server (e.g. ZOQL submit_query).\n * Looks for `jobId` or `queryJobId` fields only — avoids the generic `id`\n * field to prevent false positives on ordinary synchronous responses.\n *\n * @internal Exported for unit testing only.\n */\nexport const findRawJobId = (data: unknown, depth = 0): string | undefined => {\n if (depth > 5 || typeof data !== \"object\" || data === null) return undefined;\n if (Array.isArray(data)) {\n for (const item of data) {\n const found = findRawJobId(item, depth + 1);\n if (found) return found;\n }\n return undefined;\n }\n const record = data as Record<string, unknown>;\n\n // Primary: explicit job ID field names — unambiguous, no false positives.\n for (const key of [\"jobId\", \"queryJobId\"]) {\n if (typeof record[key] === \"string\" && (record[key] as string).trim()) {\n return (record[key] as string).trim();\n }\n }\n\n // Secondary: bare `id` field is a job ID when a `queryStatus` sibling\n // field is present (e.g. get_query_job response: id + queryStatus:\"accepted\").\n // `queryStatus` is ZOQL-specific — it does NOT appear on ordinary Zuora\n // object records (which use `status` / `Status` for their lifecycle field).\n // Using `status` here caused false positives on account/subscription records\n // returned by query_objects, which have `id` + `status:\"Active\"`.\n const hasQueryStatus = typeof record[\"queryStatus\"] === \"string\";\n if (hasQueryStatus && typeof record[\"id\"] === \"string\" && (record[\"id\"] as string).trim()) {\n return (record[\"id\"] as string).trim();\n }\n\n for (const value of Object.values(record)) {\n const found = findRawJobId(value, depth + 1);\n if (found) return found;\n }\n return undefined;\n};\n\n\n/**\n * OpenAI Agents SDK adapter for the Zuora Agent Kit.\n *\n * Extends `ToolkitCore` so all shared capabilities (auth, approval policy,\n * observability, async job handling, native file tools) are inherited.\n * `convertTools()` is the only override — it wraps each `ZuoraToolDefinition`\n * in an `@openai/agents` `tool()` object whose `execute()` function:\n *\n * 1. Calls `this.callTool()` (MCP execution + approval policy enforcement)\n * 2. Blocks on `this.waitForJob()` if the tool started an async job\n * 3. Embeds `recommendedNextTool` hints for the download chain\n *\n * Schema strictification for the OpenAI Responses API is applied\n * automatically inside `convertTools()` — callers do not need to know about it.\n */\nexport class ZuoraOpenAIAgentsToolkit extends ToolkitCore<AgentsFunctionTool> {\n /**\n * Serialises the agent tool response, emits an `agent.tool.response`\n * observability event (with the response in `metadata` when\n * `includePayloads` is enabled), and returns the JSON string to execute().\n *\n * This surfaces what the LLM actually receives — which may differ from the\n * raw `callTool` output when execute() adds directives or download hints.\n */\n private emitAgentToolResponse(\n toolName: string,\n def: ZuoraToolDefinition,\n response: Record<string, unknown>,\n ): string {\n const includePayloads = this.config.observability?.includePayloads === true;\n this.emit({\n name: \"agent.tool.response\",\n toolName,\n access: def.meta.access,\n bundle: def.meta.bundle,\n riskLevel: def.meta.riskLevel,\n ...(includePayloads ? { metadata: { agentResponse: response } } : {}),\n });\n return JSON.stringify(response);\n }\n\n protected convertTools(tools: ZuoraToolDefinition[]): AgentsFunctionTool[] {\n return tools.map((def) => {\n const sanitizedName = sanitizeAdapterToolName(def.name);\n\n return tool({\n name: sanitizedName,\n description: def.description,\n\n // Strictify the schema for the Responses API (adds additionalProperties:false\n // and required[] to all nested objects). Invisible to the caller.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- raw JSON schema accepted by tool()\n parameters: strictifySchema(def.inputSchema as Record<string, unknown>) as any,\n\n // strict:false at the API level as a belt-and-suspenders safeguard\n // against 400 errors from any edge case the schema transform misses.\n strict: false as const,\n\n // Write tools pause the run for human review via SDK interruptions.\n // For merged tools, check the per-operation access at call time so\n // read operations (e.g. get_bill_run) don't trigger approval when\n // the merged tool's aggregate access is write.\n needsApproval:\n def.meta.operationAccess && def.meta.operationSelector\n ? (_ctx: unknown, input: unknown) => {\n const op =\n input != null &&\n typeof input === \"object\" &&\n def.meta.operationSelector\n ? String(\n (input as Record<string, unknown>)[\n def.meta.operationSelector\n ] ?? \"\",\n )\n : \"\";\n const access =\n (op && def.meta.operationAccess?.[op]) ?? def.meta.access;\n return Promise.resolve(access === \"write\");\n }\n : def.meta.access === \"write\",\n\n execute: async (args: unknown): Promise<string> => {\n const input = args as Record<string, unknown>;\n // 1. Execute the Zuora MCP tool. approvalPolicy is the governance backstop.\n const result = await this.callTool(def.name, input);\n\n // 2. Follow-up hints take priority.\n // resolveAgentToolFollowUps handles completed downloads (artifactId →\n // read_downloaded_file), Zuora file resources, and completed jobs with\n // a visible download URL. If it finds a recommendation, use it —\n // this prevents the job-detection logic below from incorrectly\n // triggering on results that already contain a jobId + terminal status\n // (e.g. the download_query_result response which includes both).\n const followUp = resolveAgentToolFollowUps(result, {});\n if (followUp.recommendedNextTool) {\n const payload = buildToolMessagePayload(result, followUp);\n return this.emitAgentToolResponse(def.name, def, payload);\n }\n\n // 3. Async job guidance — only when the tool declares asyncOperation\n // in its server metadata. If the tool is declared async, callTool()\n // already called buildAsyncJobResult() and result.data is a shaped\n // ZuoraAsyncJobResult with all routing fields populated.\n //\n // We intentionally do NOT apply heuristic field-name detection here.\n // Tools without asyncOperation metadata are not async from the SDK's\n // perspective; the LLM follows the instructions for those responses.\n // (This eliminates false positives on ordinary object query results\n // that happen to contain id/status/jobId-like fields.)\n if (def.meta.asyncOperation && isAsyncJobResult(result.data)) {\n const { jobId: asyncJobId, pollingToolName } = result.data;\n\n // Detect completion via download URL or terminal status.\n const hasDownloadUrl = findDownloadUrl(result.data) !== undefined;\n const jobStatus = findQueryStatus(result.data);\n const isTerminal =\n hasDownloadUrl ||\n (jobStatus !== undefined &&\n matchesAsyncJobTerminalStatus(\n jobStatus,\n DEFAULT_ASYNC_JOB_TERMINAL_STATUSES,\n ));\n\n if (isTerminal) {\n return this.emitAgentToolResponse(def.name, def, {\n action: `Job complete. Call ${QUERY_RESULT_DOWNLOAD_TOOL} with the jobId to retrieve the data.`,\n jobId: asyncJobId,\n recommendedNextTool: QUERY_RESULT_DOWNLOAD_TOOL,\n recommendedNextArgs: { jobId: asyncJobId },\n });\n }\n\n return this.emitAgentToolResponse(def.name, def, {\n action: `Job is still running. Call ${pollingToolName} with the same jobId to check status.`,\n jobId: asyncJobId,\n recommendedNextTool: pollingToolName,\n recommendedNextArgs: { jobId: asyncJobId },\n });\n }\n\n // 4. No job, no specific follow-up: return the raw result.\n const payload = buildToolMessagePayload(result, followUp);\n return this.emitAgentToolResponse(def.name, def, payload);\n },\n });\n });\n }\n}\n\n/**\n * Creates and initialises a `ZuoraOpenAIAgentsToolkit`.\n *\n * @example\n * ```ts\n * import { Agent, run } from \"@openai/agents\";\n * import { createZuoraOpenAIAgentsToolkit } from \"@zuora/agent-toolkit/openai-agents\";\n *\n * const toolkit = await createZuoraOpenAIAgentsToolkit({ env: true });\n * const tools = await toolkit.getTools({ bundles: [\"query\"], mode: SafetyMode.ReadOnly });\n * const agent = new Agent({ name: \"Cli Agent\", tools });\n * const result = await run(agent, \"How many active accounts?\");\n * ```\n */\nexport const createZuoraOpenAIAgentsToolkit = async (\n config: ZuoraAgentToolkitConfigInput,\n): Promise<ZuoraOpenAIAgentsToolkit> => {\n const toolkit = new ZuoraOpenAIAgentsToolkit(\n resolveZuoraAgentToolkitConfig(config),\n );\n await toolkit.initialize();\n return toolkit;\n};\n","export type ZuoraAgentToolkitP0ErrorCode =\n | \"TOOL_EXECUTION_ERROR\"\n | \"TOOL_NOT_FOUND\"\n | \"BUNDLE_NOT_FOUND\"\n | \"APPROVAL_REJECTED\"\n | \"MALFORMED_METADATA\"\n | \"OAUTH_TOKEN_ERROR\"\n | \"ASYNC_JOB_TIMEOUT\";\n\nexport type ZuoraAgentToolkitErrorCode =\n | ZuoraAgentToolkitP0ErrorCode\n | (string & {});\n\nexport type ZuoraAgentToolkitP0ErrorCategory =\n | \"tool_execution\"\n | \"approval\"\n | \"metadata\"\n | \"auth\";\n\nexport type ZuoraAgentToolkitErrorCategory =\n | ZuoraAgentToolkitP0ErrorCategory\n | \"permission\"\n | \"validation\"\n | \"zuora\"\n | \"mcp\"\n | \"configuration\"\n | \"native_file_tools\";\n\nexport class ZuoraAgentToolkitError extends Error {\n readonly code: ZuoraAgentToolkitErrorCode;\n\n readonly category: ZuoraAgentToolkitErrorCategory;\n\n readonly retryable: boolean;\n\n readonly recoverable: boolean;\n\n readonly requestId?: string | undefined;\n\n readonly details?: unknown;\n\n constructor(params: {\n code: ZuoraAgentToolkitErrorCode;\n message: string;\n category: ZuoraAgentToolkitErrorCategory;\n retryable?: boolean;\n recoverable?: boolean;\n requestId?: string;\n details?: unknown;\n }) {\n super(params.message);\n this.name = \"ZuoraAgentToolkitError\";\n this.code = params.code;\n this.category = params.category;\n this.recoverable = params.recoverable ?? params.retryable ?? false;\n this.retryable = params.retryable ?? false;\n this.requestId = params.requestId;\n this.details = params.details;\n }\n}\n","import type { McpReadResourceResult, McpTool } from \"./transport/mcp-types.js\";\nimport type { EventSanitizerLimits } from \"./utils/event-sanitizer.js\";\n\nexport type { McpReadResourceResult, McpTool } from \"./transport/mcp-types.js\";\nexport type { EventSanitizerLimits } from \"./utils/event-sanitizer.js\";\n\nexport type ZuoraEnvironment = \"sandbox\" | \"production\";\n\nexport const SafetyMode = {\n ReadOnly: \"readOnly\",\n WriteEnabled: \"writeEnabled\",\n} as const;\n\nexport type ZuoraSafetyMode = (typeof SafetyMode)[keyof typeof SafetyMode];\n\nexport type ZuoraToolOperation = \"read\" | \"write\";\n\nexport type ZuoraRiskLevel = \"low\" | \"medium\" | \"high\";\n\n/**\n * Well-known Zuora bundle names. Provided for autocompletion in\n * `ToolSelection.bundles` and `ZuoraToolkitConfiguration.bundles`.\n *\n * The `string & {}` tail widens the type to accept any string (so new\n * server-side bundles are never rejected) while preserving IDE autocomplete\n * for the known literal members.\n *\n * `ZuoraToolDefinition.meta.bundle` is plain `string` — the server value\n * is passed through as-is with no normalisation or fallback.\n */\nexport type ZuoraBundleName =\n | \"accounts\"\n | \"catalog\"\n | \"subscriptions\"\n | \"orders\"\n | \"billing\"\n | \"payments\"\n | \"usage\"\n | \"revenue\"\n | \"finance\"\n | \"workflows\"\n | \"query\"\n | \"admin\"\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n | (string & {});\n\n// ── Async operation metadata — directly from _meta.asyncOperations[op] ──\nexport type ZuoraAsyncOperationMeta = {\n /** Operation on the polling MCP tool. Omitted when pollingTool is the standalone poll target. */\n pollingOperation?: string;\n /** Source MCP tool for cross-tool polling, or standalone poll tool when pollingOperation is omitted. */\n pollingTool?: string;\n jobIdPath: string;\n statusPath: string;\n pollingArgs?: Record<string, string>;\n terminalStatuses: {\n success: string[];\n failure: string[];\n canceled?: string[];\n };\n recommendedPollIntervalMs?: number;\n defaultTimeoutMs?: number;\n maxPollAttempts?: number;\n};\n\n// ── Service permission — directly from _meta.requiredServicePermissions[] ──\nexport type ZuoraServicePermission = {\n scope: string;\n name: string;\n};\n\n// ── The only public tool type ──\nexport type ZuoraToolDefinition = {\n name: string; // operation name, e.g. \"run_reports\"\n description: string;\n inputSchema: JsonSchema;\n outputSchema?: JsonSchema;\n meta: {\n bundle: string; // from _meta.bundle or SDK-native tool config; passed through as-is\n access: ZuoraToolOperation; // from _meta.operationPermissions[op]\n riskLevel: ZuoraRiskLevel; // from _meta.riskLevels[op]\n asyncOperation?: ZuoraAsyncOperationMeta; // from _meta.asyncOperations[op] — set on split/single-op tools\n /** Present on multi-op merged tools (splitOperations: false). Keyed by operation name. Used at\n * call time to look up the async meta for the operation the LLM actually invoked. */\n asyncOperations?: Record<string, ZuoraAsyncOperationMeta>;\n /** Per-operation access levels for merged tools. Used at call time to enforce the correct access for the invoked operation. */\n operationAccess?: Record<string, ZuoraToolOperation>;\n /** Per-operation risk levels for merged tools. Used at call time to enforce the correct risk for the invoked operation. */\n operationRiskLevel?: Record<string, ZuoraRiskLevel>;\n requiredServicePermissions: ZuoraServicePermission[]; // from _meta.requiredServicePermissions\n limitations: string[];\n sourceName: string; // original MCP tool name for execution routing\n /** Present on split multi-operation tools — MCP input field auto-injected at call time. */\n operationSelector?: string;\n /** Present on split multi-operation tools — the underlying MCP operation name. */\n operationName?: string;\n };\n};\n\n// ── Native file tools — config ──\n\nexport type NativeToolMetadataConfig = {\n enabled?: boolean;\n operationAccess?: ZuoraToolOperation;\n riskLevel?: ZuoraRiskLevel;\n description?: string;\n};\n\nexport type NativeFileToolsConfig = {\n enabled?: boolean;\n bundleName?: string;\n tools?: {\n downloadFile?: NativeToolMetadataConfig;\n readDownloadedFile?: NativeToolMetadataConfig;\n downloadQueryResult?: NativeToolMetadataConfig;\n downloadZuoraFile?: NativeToolMetadataConfig;\n extractDownloadedArchive?: NativeToolMetadataConfig;\n readResource?: NativeToolMetadataConfig;\n };\n rootDir?: string;\n userHomeDir?: string;\n requireRootUnderUserHome?: boolean;\n allowOverwrite?: boolean;\n maxDownloadBytes?: number;\n maxReadBytes?: number;\n maxReadLines?: number;\n maxExtractedFiles?: number;\n maxExtractedBytes?: number;\n downloadTimeoutMs?: number;\n allowedProtocols?: string[];\n allowedHosts?: string[];\n allowedUrlPrefixes?: string[];\n zuoraDownloadHosts?: string[];\n allowZuoraAuthenticatedDownload?: boolean;\n allowS3PresignedDownload?: boolean;\n allowArchiveExtraction?: boolean;\n};\n\n// ── Native tool approval metadata ──\n\nexport type NativeFileApprovalMetadata = {\n source: \"native\";\n nativeToolType: \"fileArtifacts\";\n filesystemRoot: string;\n sideEffects: Array<\"networkRead\" | \"localFileWrite\" | \"localFileRead\">;\n urlHost?: string;\n urlProtocol?: string;\n urlPath?: string;\n urlKind?: string;\n outputRelativePath?: string;\n artifactId?: string;\n relativePath?: string;\n};\n\nexport type NativeToolApprovalMetadata = NativeFileApprovalMetadata;\n\n// ── Bundle types — used by PR-3 ToolkitCore ──\nexport type ToolkitBundleName = string;\n\nexport type ZuoraBundleDefinition = {\n name: ToolkitBundleName;\n description: string;\n examples: string[];\n commonObjects: string[];\n keywords: string[];\n toolCount: number;\n readToolCount: number;\n writeToolCount: number;\n tools: ZuoraToolDefinition[];\n};\n\nexport type JsonSchema = {\n type?: string;\n properties?: Record<string, JsonSchema>;\n items?: JsonSchema;\n required?: string[];\n enum?: string[];\n description?: string;\n additionalProperties?: boolean | JsonSchema;\n [key: string]: unknown;\n};\n\nexport type ZuoraAuthConfig = {\n clientId: string;\n clientSecret: string;\n};\n\ntype ZuoraTenantAuthConfig =\n | {\n enabled: true;\n tenantId: string;\n tokenId: string;\n userId: string;\n }\n | {\n enabled?: false;\n };\n\ntype EnabledZuoraTenantAuthConfig = Extract<\n ZuoraTenantAuthConfig,\n { enabled: true }\n>;\n\nexport type BundleConfiguration = {\n include?: string[];\n exclude?: string[];\n};\n\nexport type ZuoraToolkitConfiguration = {\n mode?: ZuoraSafetyMode;\n bundles?: Partial<Record<ZuoraBundleName, boolean | BundleConfiguration>>;\n tools?: Record<string, boolean>;\n context?: Record<string, string | undefined>;\n // Controls whether multi-operation MCP tools are split into one tool per operation.\n // Default: true. When false, multi-op tools are presented as a single tool.\n splitOperations?: boolean;\n};\n\nexport type ToolSelection = {\n bundles?: ZuoraBundleName[];\n include?: string[];\n exclude?: string[];\n mode?: ZuoraSafetyMode;\n};\n\nexport type ZuoraExecutionRequestMetadata = {\n requestId?: string;\n zuoraRequestId?: string;\n environment?: ZuoraEnvironment;\n tenantId?: string;\n entityIds?: string[];\n orgIds?: string[];\n};\n\nexport type ZuoraToolExecutionResult<TData = unknown> = {\n toolName: string;\n data: TData;\n riskLevel?: ZuoraRiskLevel;\n requestId?: string;\n request?: ZuoraExecutionRequestMetadata;\n warnings?: string[];\n};\n\nexport type ZuoraMcpClient = {\n initialize?: () => Promise<void>;\n listTools: () => Promise<McpTool[]>;\n callTool: (\n name: string,\n input: Record<string, unknown>,\n ) => Promise<ZuoraToolExecutionResult>;\n readResource?: (uri: string) => Promise<McpReadResourceResult>;\n getTenantId?: () => string | undefined;\n getSensitiveValues?: () => readonly string[];\n close?: () => Promise<void>;\n};\n\ntype ZuoraConnectionConfigBase = {\n headers?: Record<string, string | undefined>;\n entityIds?: string | string[];\n orgIds?: string | string[];\n zuoraVersion?: string;\n protocolVersion?: string;\n};\n\ntype ZuoraTenantAuthConnectionConfig = ZuoraConnectionConfigBase & {\n tenantAuth: EnabledZuoraTenantAuthConfig;\n};\n\ntype ZuoraStandardConnectionConfig = ZuoraConnectionConfigBase & {\n tenantAuth?: Exclude<ZuoraTenantAuthConfig, EnabledZuoraTenantAuthConfig>;\n};\n\nexport type ZuoraConnectionConfig =\n | ZuoraStandardConnectionConfig\n | ZuoraTenantAuthConnectionConfig;\n\ntype ZuoraHttpMcpClientConfigBase = ZuoraConnectionConfigBase & {\n url: string;\n clientName?: string;\n clientVersion?: string;\n};\n\nexport type ZuoraHttpMcpClientConfig =\n | (ZuoraHttpMcpClientConfigBase &\n ZuoraStandardConnectionConfig & {\n auth: ZuoraAuthConfig;\n })\n | (ZuoraHttpMcpClientConfigBase &\n ZuoraTenantAuthConnectionConfig & {\n auth?: ZuoraAuthConfig;\n });\n\nexport const ApprovalPolicyPreset = {\n Off: \"off\",\n AllWrites: \"all_writes\",\n HighRisk: \"high_risk\",\n ProductionWrites: \"production_writes\",\n ProductionHighRisk: \"production_high_risk\",\n} as const;\n\nexport type ApprovalPolicyPresetValue =\n (typeof ApprovalPolicyPreset)[keyof typeof ApprovalPolicyPreset];\n\nexport type ApprovalPolicyResult =\n | \"allow\"\n | \"deny\"\n | { decision: \"allow\" | \"deny\"; reason?: string };\n\nexport type ApprovalPolicyHandler = (\n request: ApprovalRequest,\n) => ApprovalPolicyResult | Promise<ApprovalPolicyResult>;\n\nexport type ApprovalPolicy = ApprovalPolicyPresetValue | ApprovalPolicyHandler;\n\nexport type ApprovalRequest = {\n tool: ZuoraToolDefinition;\n input: Record<string, unknown>;\n environment: ZuoraEnvironment;\n /** Present only for SDK-native tools (e.g. download_file). Undefined for MCP-sourced tools. */\n native?: NativeToolApprovalMetadata;\n};\n\n// ── Observability event types ──\n\nexport type ZuoraToolkitEventName =\n | \"tool.called\"\n | \"tool.completed\"\n | \"tool.failed\"\n | \"approval.requested\"\n /**\n * Internal name used when emitting the approval outcome from\n * `enforceApproval()`. It is normalised to the `\"approval.decided\"` type\n * by `normalizeToolkitEvent()` before being delivered to observers.\n * @see ZuoraToolkitEventType\n */\n | \"approval.resolved\"\n | \"approval.decided\"\n | \"metadata.loaded\"\n | \"async.poll.checked\"\n | \"observability.sink_failed\"\n /**\n * Emitted by framework adapters (e.g. the Agents SDK adapter) after\n * `execute()` finishes post-processing the raw MCP result. The `metadata`\n * field carries the actual response the LLM receives, which may differ from\n * the raw `callTool` output (e.g. async-job directives, download hints).\n * Consumers can subscribe to this event to audit what the LLM was told.\n */\n | \"agent.tool.response\";\n\n/**\n * The canonical event type delivered to `onEvent` / `emit` sinks.\n *\n * Note the asymmetry with `ZuoraToolkitEventName`: the internal name\n * `\"approval.resolved\"` is normalised to `\"approval.decided\"` before\n * delivery. Consumers should match on `type`, not `name`, when they need\n * a stable identifier for approval-outcome events.\n */\nexport type ZuoraToolkitEventType =\n | \"tool.called\"\n | \"tool.completed\"\n | \"tool.failed\"\n | \"approval.requested\"\n | \"approval.decided\"\n | \"metadata.loaded\"\n | \"async.poll.checked\"\n | \"observability.sink_failed\"\n | \"agent.tool.response\";\n\nexport type ZuoraToolkitApprovalDecision =\n | \"allow\"\n | \"deny\";\n\nexport type ZuoraToolkitApprovalStatus =\n | \"requested\"\n | \"rejected\"\n | \"not_required\";\n\nexport type ZuoraToolkitEventError = {\n code: string;\n category: string;\n recoverable: boolean;\n retryable?: boolean;\n requestId?: string;\n message?: string;\n};\n\nexport type ZuoraToolExecutionPhase = \"primary\" | \"async_poll\";\n\nexport type ZuoraToolkitEvent = {\n type: ZuoraToolkitEventType;\n name: ZuoraToolkitEventName;\n timestamp: string;\n toolName?: string;\n access?: ZuoraToolOperation;\n bundle?: string;\n executionPhase?: ZuoraToolExecutionPhase;\n input?: Record<string, unknown>;\n output?: Record<string, unknown>;\n requestId?: string;\n zuoraRequestId?: string;\n riskLevel?: ZuoraRiskLevel;\n latencyMs?: number;\n environment?: ZuoraEnvironment;\n tenantId?: string;\n entityIds?: string[];\n orgIds?: string[];\n approvalDecision?: ZuoraToolkitApprovalDecision;\n approvalStatus?: ZuoraToolkitApprovalStatus;\n error?: ZuoraToolkitEventError;\n metadata?: Record<string, unknown>;\n};\n\nexport type ZuoraToolkitLogger = {\n debug?: (message: string, event?: ZuoraToolkitEvent) => void;\n info?: (message: string, event?: ZuoraToolkitEvent) => void;\n warn?: (message: string, event?: ZuoraToolkitEvent) => void;\n error?: (message: string, event?: ZuoraToolkitEvent) => void;\n};\n\ntype ZuoraAgentToolkitConfigBase = {\n baseUrl: string;\n configuration?: ZuoraToolkitConfiguration;\n approvalPolicy?: ApprovalPolicy;\n /**\n * SDK-internal overrides for native file download/read infrastructure.\n * Auto-enabled when the query bundle is configured — agents never set this.\n */\n nativeFileTools?: NativeFileToolsConfig;\n observability?: {\n logger?: ZuoraToolkitLogger;\n emit?: (event: ZuoraToolkitEvent) => void | Promise<void>;\n onEvent?: (event: ZuoraToolkitEvent) => void;\n /**\n * When true, tool.called/tool.completed/tool.failed events include\n * sanitized input and output payloads. Defaults to false.\n */\n includePayloads?: boolean;\n /**\n * Limits applied when sanitizing event metadata fields.\n * Use `resolveEventSanitizerLimits(process.env)` to populate from\n * environment variables, or supply explicit values.\n * Defaults to built-in conservative limits when omitted.\n */\n sanitizerLimits?: EventSanitizerLimits;\n };\n};\n\nexport type ZuoraAgentToolkitEnvSource =\n | true\n | {\n env?: Record<string, string | undefined>;\n };\n\nexport type ZuoraAgentToolkitEnvConfig = Omit<\n ZuoraAgentToolkitConfigBase,\n \"baseUrl\"\n> & {\n env: ZuoraAgentToolkitEnvSource;\n};\n\nexport type ZuoraAgentToolkitConfig =\n | (ZuoraAgentToolkitConfigBase & {\n auth: ZuoraAuthConfig;\n })\n | (ZuoraAgentToolkitConfigBase & {\n auth?: ZuoraAuthConfig;\n connection: ZuoraTenantAuthConnectionConfig;\n });\n\nexport type ZuoraAgentToolkitConfigInput =\n | ZuoraAgentToolkitConfig\n | ZuoraAgentToolkitEnvConfig;\n\n// ── Async job polling types ──\n\n/**\n * Terminal state of a completed async job.\n */\nexport type ZuoraAsyncJobTerminalState = \"success\" | \"failure\" | \"canceled\";\n\n/**\n * Configuration for which status strings are considered terminal for each outcome.\n */\nexport type ZuoraAsyncJobTerminalStatuses = {\n success: string[];\n failure: string[];\n canceled?: string[];\n};\n\n/**\n * Rich resolution of the current async job status returned by resolveAsyncJobStatusDetails.\n */\nexport type ZuoraAsyncJobStatusResolution = {\n /** Raw status string extracted from the tool result, if any. */\n status: string | undefined;\n /** True if the job has reached a terminal state. */\n isTerminal: boolean;\n /** The resolved terminal state, or undefined if not yet terminal. */\n terminalState: ZuoraAsyncJobTerminalState | undefined;\n};\n\n/**\n * Options for waitForJob() — all fields override the async meta defaults.\n */\nexport type ZuoraWaitForJobOptions = {\n /**\n * Maximum number of polling attempts before giving up.\n * Overrides asyncMeta.maxPollAttempts.\n */\n maxPollAttempts?: number;\n /**\n * Interval in milliseconds between polling attempts.\n * Overrides asyncMeta.recommendedPollIntervalMs.\n */\n pollIntervalMs?: number;\n /**\n * Absolute timeout in milliseconds from when waitForJob() was called.\n * Overrides asyncMeta.defaultTimeoutMs.\n *\n * **Note:** the timeout is checked at the start of each loop iteration,\n * before the poll is issued. A value of `0` will therefore cause\n * `waitForJob` to throw `ASYNC_JOB_TIMEOUT` immediately without ever\n * making a poll attempt.\n */\n timeoutMs?: number;\n /**\n * Custom terminal status sets. When provided, overrides the terminal statuses\n * defined in the async operation meta.\n */\n terminalStatuses?: ZuoraAsyncJobTerminalStatuses;\n};\n","import type { ZuoraEnvironment } from \"../types.js\";\n\nexport type ZuoraMcpUrlInfo = {\n remoteUrl: string;\n restBaseUrl: string;\n};\n\nexport const normalizeZuoraMcpUrl = (raw: string): ZuoraMcpUrlInfo => {\n const trimmed = raw.replace(/\\/+$/, \"\");\n const parsed = new URL(trimmed);\n\n let restBaseUrl: string;\n\n if (trimmed.endsWith(\"/mcp\")) {\n if (!isZuoraHost(parsed.hostname)) {\n return {\n remoteUrl: trimmed,\n restBaseUrl: trimmed.slice(0, -\"/mcp\".length),\n };\n }\n\n const stagingHostMatch = parsed.hostname.match(/^staging(\\d+)\\.zuora\\.com$/);\n\n if (stagingHostMatch?.[1]) {\n restBaseUrl = `${parsed.protocol}//rest-staging${stagingHostMatch[1]}.zuora.com`;\n } else if (parsed.hostname.startsWith(\"rest.\")) {\n restBaseUrl = `${parsed.protocol}//${parsed.hostname}`;\n } else if (parsed.hostname.startsWith(\"rest-\")) {\n restBaseUrl = `${parsed.protocol}//${parsed.hostname}`;\n } else {\n restBaseUrl = `${parsed.protocol}//rest.${parsed.hostname}`;\n }\n } else {\n restBaseUrl = trimmed;\n }\n\n return {\n remoteUrl: `${restBaseUrl}/mcp`,\n restBaseUrl,\n };\n};\n\nconst isZuoraHost = (hostname: string): boolean => {\n const lower = hostname.toLowerCase();\n return lower === \"zuora.com\" || lower.endsWith(\".zuora.com\");\n};\n\nexport const isStagingZuoraBaseUrl = (baseUrl: string): boolean => {\n try {\n const hostname = new URL(baseUrl).hostname.toLowerCase();\n return (\n hostname.includes(\"staging\") ||\n hostname.includes(\".stg.\") ||\n hostname.includes(\"-stg\")\n );\n } catch {\n const lower = baseUrl.toLowerCase();\n return (\n lower.includes(\"staging\") ||\n lower.includes(\".stg.\") ||\n lower.includes(\"-stg\")\n );\n }\n};\n\nexport const inferZuoraEnvironment = (\n baseUrl: string,\n): ZuoraEnvironment | undefined => {\n let hostname: string;\n\n try {\n hostname = new URL(normalizeZuoraMcpUrl(baseUrl).restBaseUrl).hostname\n .toLowerCase();\n } catch {\n return undefined;\n }\n\n if (PRODUCTION_ZUORA_HOSTS.has(hostname)) {\n return \"production\";\n }\n\n if (SANDBOX_ZUORA_HOSTS.has(hostname) || isStagingZuoraBaseUrl(baseUrl)) {\n return \"sandbox\";\n }\n\n return undefined;\n};\n\nexport const resolveZuoraEnvironment = (\n baseUrl: string,\n): ZuoraEnvironment =>\n inferZuoraEnvironment(baseUrl) ?? \"sandbox\";\n\nconst SANDBOX_ZUORA_HOSTS = new Set([\n \"rest.apisandbox.zuora.com\",\n \"rest.sandbox.na.zuora.com\",\n \"rest.sandbox.eu.zuora.com\",\n \"rest.test.zuora.com\",\n \"rest.test.eu.zuora.com\",\n \"rest.test.ap.zuora.com\",\n]);\n\nconst PRODUCTION_ZUORA_HOSTS = new Set([\n \"rest.zuora.com\",\n \"rest.na.zuora.com\",\n \"rest.eu.zuora.com\",\n \"rest.ap.zuora.com\",\n]);\n","import { ZuoraAgentToolkitError } from \"./errors.js\";\nimport type { InternalToolkitEvent } from \"./observability/events.js\";\nimport type {\n ApprovalPolicyPresetValue,\n ApprovalPolicyResult,\n ApprovalRequest,\n NativeToolApprovalMetadata,\n ZuoraAgentToolkitConfig,\n ZuoraToolDefinition,\n ZuoraToolkitApprovalStatus,\n} from \"./types.js\";\nimport { ApprovalPolicyPreset } from \"./types.js\";\nimport { inferZuoraEnvironment } from \"./utils/zuora-url.js\";\n\nconst normalizeApprovalPolicyResult = (\n result: ApprovalPolicyResult,\n): \"allow\" | \"deny\" => {\n if (typeof result === \"string\") {\n return result;\n }\n\n return result.decision;\n};\n\nconst evaluatePreset = (\n preset: ApprovalPolicyPresetValue,\n request: ApprovalRequest,\n): \"allow\" | \"deny\" => {\n const { tool, environment } = request;\n const isWrite = tool.meta.access === \"write\";\n const isHighRisk = tool.meta.riskLevel === \"high\";\n const isProduction = environment === \"production\";\n\n switch (preset) {\n case ApprovalPolicyPreset.Off:\n return \"allow\";\n case ApprovalPolicyPreset.AllWrites:\n return isWrite ? \"deny\" : \"allow\";\n case ApprovalPolicyPreset.HighRisk:\n return isHighRisk ? \"deny\" : \"allow\";\n case ApprovalPolicyPreset.ProductionWrites:\n return isProduction && isWrite ? \"deny\" : \"allow\";\n case ApprovalPolicyPreset.ProductionHighRisk:\n return isProduction && isHighRisk ? \"deny\" : \"allow\";\n }\n};\n\nconst throwApprovalRejected = (tool: ZuoraToolDefinition): never => {\n throw new ZuoraAgentToolkitError({\n code: \"APPROVAL_REJECTED\",\n message: `Tool \"${tool.name}\" was denied by approval policy.`,\n category: \"approval\",\n recoverable: false,\n });\n};\n\nexport const enforceApproval = async (\n tool: ZuoraToolDefinition,\n input: Record<string, unknown>,\n config: ZuoraAgentToolkitConfig,\n emit?: (event: InternalToolkitEvent) => void,\n native?: NativeToolApprovalMetadata,\n): Promise<void> => {\n const { approvalPolicy } = config;\n\n if (!approvalPolicy) {\n return;\n }\n\n const environment = inferZuoraEnvironment(config.baseUrl) ?? \"sandbox\";\n const request: ApprovalRequest = {\n tool,\n input,\n environment,\n ...(native ? { native } : {}),\n };\n\n emit?.({\n name: \"approval.requested\",\n toolName: tool.name,\n access: tool.meta.access,\n bundle: tool.meta.bundle,\n riskLevel: tool.meta.riskLevel,\n environment,\n approvalStatus: \"requested\",\n });\n\n const decision =\n typeof approvalPolicy === \"function\"\n ? normalizeApprovalPolicyResult(await approvalPolicy(request))\n : evaluatePreset(approvalPolicy, request);\n\n const resolvedStatus: ZuoraToolkitApprovalStatus =\n decision === \"deny\" ? \"rejected\" : \"not_required\";\n\n emit?.({\n name: \"approval.resolved\",\n toolName: tool.name,\n access: tool.meta.access,\n bundle: tool.meta.bundle,\n riskLevel: tool.meta.riskLevel,\n environment,\n approvalDecision: decision === \"deny\" ? \"deny\" : \"allow\",\n approvalStatus: resolvedStatus,\n });\n\n if (decision === \"deny\") {\n throwApprovalRejected(tool);\n }\n};\n","const MAX_ADAPTER_TOOL_NAME_LENGTH = 64;\nconst SAFE_ADAPTER_TOOL_NAME_PATTERN = /^[A-Za-z0-9_-]+$/;\n\nexport const createOperationAdapterToolName = (\n sourceToolName: string,\n operationName: string,\n): string => {\n const rawName = `${sourceToolName}__${operationName}`;\n\n if (\n rawName.length <= MAX_ADAPTER_TOOL_NAME_LENGTH &&\n SAFE_ADAPTER_TOOL_NAME_PATTERN.test(rawName)\n ) {\n return rawName;\n }\n\n return sanitizeAdapterToolName(rawName);\n};\n\nexport const stableNameHash = (value: string): string => {\n let hash = 0x811c9dc5;\n\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n\n return (hash >>> 0).toString(36).padStart(7, \"0\").slice(-7);\n};\n\nexport const sanitizeAdapterToolName = (name: string): string => {\n if (\n name.length <= MAX_ADAPTER_TOOL_NAME_LENGTH &&\n SAFE_ADAPTER_TOOL_NAME_PATTERN.test(name)\n ) {\n return name;\n }\n\n const sanitized = name\n .replace(/[^A-Za-z0-9_-]+/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\n const candidate = sanitized || \"tool\";\n\n if (\n candidate.length <= MAX_ADAPTER_TOOL_NAME_LENGTH &&\n SAFE_ADAPTER_TOOL_NAME_PATTERN.test(candidate)\n ) {\n return candidate;\n }\n\n const hash = stableNameHash(name);\n const suffix = `_${hash}`;\n const maxPrefixLength = MAX_ADAPTER_TOOL_NAME_LENGTH - suffix.length;\n const prefix = candidate.slice(0, maxPrefixLength) || \"tool\";\n\n return `${prefix}${suffix}`;\n};\n","import { ZuoraAgentToolkitError } from \"./errors.js\";\nimport { createOperationAdapterToolName } from \"./utils/adapter-name.js\";\nimport type {\n ZuoraAsyncJobStatusResolution,\n ZuoraAsyncJobTerminalState,\n ZuoraAsyncJobTerminalStatuses,\n ZuoraAsyncOperationMeta,\n ZuoraToolExecutionResult,\n} from \"./types.js\";\n\nexport type BuildAsyncJobResultContext = {\n sourceToolName: string;\n operationSelector?: string;\n /** Split operation names registered for sourceToolName. */\n sourceOperationNames?: string[];\n};\n\nexport type ZuoraAsyncJobResult = {\n toolName: string;\n status: \"pending\";\n jobId: string;\n /** Resolved toolkit tool name to call when polling or auto-waiting. */\n pollingToolName: string;\n /** Original MCP pollingOperation metadata, when present. */\n pollingOperation?: string;\n pollingArgs?: Record<string, string>;\n /** Dot-path to the status field in the poll result (e.g. \"data.status\"). Populated from asyncMeta.statusPath at job-start time. */\n statusPath?: string;\n /** Terminal status sets for this job. Populated from asyncMeta.terminalStatuses at job-start time. */\n terminalStatuses?: ZuoraAsyncJobTerminalStatuses;\n recommendedPollIntervalMs?: number;\n maxPollAttempts?: number;\n defaultTimeoutMs?: number;\n};\n\n/**\n * Default terminal statuses applied when the async operation meta does not\n * specify its own terminal status sets and no override is provided to waitForJob.\n */\nexport const DEFAULT_ASYNC_JOB_TERMINAL_STATUSES: ZuoraAsyncJobTerminalStatuses = {\n success: [\"Completed\", \"Success\", \"Succeeded\", \"Done\"],\n failure: [\"Failed\", \"Error\", \"Errored\", \"Aborted\"],\n canceled: [\"Canceled\", \"Cancelled\"],\n};\n\n/**\n * Returns `true` when `data` is a `ZuoraAsyncJobResult` — a pending async job\n * result produced by `ToolkitCore.callTool()` via `buildAsyncJobResult()`.\n *\n * The check requires `status === \"pending\"`, a non-empty `jobId` string, and\n * at least one of `pollingToolName` or `pollingOperation`. Those routing fields\n * are only present on data shaped by `buildAsyncJobResult` — plain API responses\n * that happen to contain a job-ID-like field will not pass this guard.\n */\nexport const isAsyncJobResult = (data: unknown): data is ZuoraAsyncJobResult =>\n data != null &&\n typeof data === \"object\" &&\n (data as ZuoraAsyncJobResult).status === \"pending\" &&\n typeof (data as ZuoraAsyncJobResult).jobId === \"string\" &&\n (data as ZuoraAsyncJobResult).jobId.trim().length > 0 &&\n (typeof (data as ZuoraAsyncJobResult).pollingToolName === \"string\" ||\n typeof (data as ZuoraAsyncJobResult).pollingOperation === \"string\");\n\n/**\n * Normalizes MCP JSONPath-style expressions (e.g. \"$.data.jobId\") to the\n * dot-path form used by resolveByPath (e.g. \"data.jobId\").\n */\nexport const normalizeMetadataPath = (path: string): string => {\n const trimmed = path.trim();\n if (trimmed.startsWith(\"$.\")) {\n return trimmed.slice(2);\n }\n if (trimmed.startsWith(\"$\")) {\n return trimmed.slice(1);\n }\n return trimmed;\n};\n\n/**\n * Resolves a dot-path expression (e.g. \"data.jobId\") against an object.\n * Returns undefined if any segment is missing.\n */\nfunction resolveByPath(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- dynamic dot-path traversal requires any\n obj: any,\n path: string,\n): unknown {\n return path.split(\".\").reduce(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- same reason as above\n (current: any, segment: string) =>\n current != null && typeof current === \"object\" ? current[segment] : undefined,\n obj,\n );\n}\n\n/**\n * Resolves the toolkit tool name to invoke when polling an async job.\n * Mirrors legacy `resolveAsyncJobPollingToolName()`.\n */\nexport function resolveAsyncJobPollingToolNameFromMeta(\n asyncMeta: ZuoraAsyncOperationMeta,\n context: BuildAsyncJobResultContext,\n): string {\n const pollingOperation = asyncMeta.pollingOperation;\n const pollingTool = asyncMeta.pollingTool;\n\n if (!pollingOperation) {\n return pollingTool ?? context.sourceToolName;\n }\n\n if (pollingTool) {\n return createOperationAdapterToolName(pollingTool, pollingOperation);\n }\n\n if (\n context.operationSelector &&\n context.sourceOperationNames?.includes(pollingOperation)\n ) {\n return createOperationAdapterToolName(\n context.sourceToolName,\n pollingOperation,\n );\n }\n\n // Same-source, unsplit tool: pollingOperation lives on the source tool itself\n // (splitOperations: false). Return the source tool name so callTool can find\n // it in the registry; the operation is injected into pollingArgs by\n // buildAsyncJobResult so the MCP server routes to the correct operation.\n return context.sourceToolName;\n}\n\n/**\n * Builds a structured async-pending result to return to the agent when a tool\n * call produces a job that requires polling.\n *\n * @throws ZuoraAgentToolkitError with TOOL_EXECUTION_ERROR if jobIdPath\n * resolves to undefined or null on the raw result.\n */\nexport function buildAsyncJobResult(\n result: ZuoraToolExecutionResult,\n asyncMeta: ZuoraAsyncOperationMeta,\n context: BuildAsyncJobResultContext,\n): ZuoraAsyncJobResult {\n const payload = result.data;\n // asyncMeta.jobIdPath is already normalized at parse time by parseAsyncOperationMeta.\n const jobId = resolveByPath(payload, asyncMeta.jobIdPath);\n\n if (jobId == null) {\n throw new ZuoraAgentToolkitError({\n code: \"TOOL_EXECUTION_ERROR\",\n message: `Async job ID not found at path \"${asyncMeta.jobIdPath}\" in tool result for \"${result.toolName}\".`,\n category: \"tool_execution\",\n });\n }\n\n const pollingToolName = resolveAsyncJobPollingToolNameFromMeta(\n asyncMeta,\n context,\n );\n\n const pending: ZuoraAsyncJobResult = {\n toolName: result.toolName,\n status: \"pending\",\n jobId: String(jobId),\n pollingToolName,\n ...(asyncMeta.pollingOperation\n ? { pollingOperation: asyncMeta.pollingOperation }\n : {}),\n statusPath: asyncMeta.statusPath,\n terminalStatuses: asyncMeta.terminalStatuses,\n };\n\n // For same-source unsplit tools (pollingTool absent, no operationSelector),\n // the polling call targets the merged source tool, so the operation name must\n // be included in pollingArgs for the MCP server to route it correctly.\n const needsOperationInjection =\n !!asyncMeta.pollingOperation &&\n !asyncMeta.pollingTool &&\n !context.operationSelector;\n\n if (needsOperationInjection) {\n pending.pollingArgs = {\n ...asyncMeta.pollingArgs,\n operation: asyncMeta.pollingOperation!,\n };\n } else if (asyncMeta.pollingArgs !== undefined) {\n pending.pollingArgs = asyncMeta.pollingArgs;\n }\n\n if (asyncMeta.recommendedPollIntervalMs !== undefined) {\n pending.recommendedPollIntervalMs = asyncMeta.recommendedPollIntervalMs;\n }\n\n if (asyncMeta.maxPollAttempts !== undefined) {\n pending.maxPollAttempts = asyncMeta.maxPollAttempts;\n }\n\n if (asyncMeta.defaultTimeoutMs !== undefined) {\n pending.defaultTimeoutMs = asyncMeta.defaultTimeoutMs;\n }\n\n return pending;\n}\n\n// ── Async job status utilities ────────────────────────────────────────────────\n\n/**\n * Returns true when the given status string matches any status in the success,\n * failure, or canceled sets of the provided terminal statuses config.\n *\n * The comparison is case-insensitive.\n */\nexport function matchesAsyncJobTerminalStatus(\n status: string,\n statuses: ZuoraAsyncJobTerminalStatuses,\n): boolean {\n const lower = status.toLowerCase();\n if (statuses.success.some((s) => s.toLowerCase() === lower)) return true;\n if (statuses.failure.some((s) => s.toLowerCase() === lower)) return true;\n if (statuses.canceled?.some((s) => s.toLowerCase() === lower)) return true;\n return false;\n}\n\n/**\n * Resolves the terminal state (\"success\" | \"failure\" | \"canceled\") for the\n * given status string against the provided terminal statuses config.\n *\n * Returns undefined when the status has not yet reached a terminal state.\n */\nexport function resolveAsyncJobTerminalState(\n status: string,\n statuses: ZuoraAsyncJobTerminalStatuses,\n): ZuoraAsyncJobTerminalState | undefined {\n const lower = status.toLowerCase();\n if (statuses.success.some((s) => s.toLowerCase() === lower)) return \"success\";\n if (statuses.failure.some((s) => s.toLowerCase() === lower)) return \"failure\";\n if (statuses.canceled?.some((s) => s.toLowerCase() === lower)) return \"canceled\";\n return undefined;\n}\n\n/**\n * Returns true when the given async job result has reached a terminal state\n * according to the provided terminal statuses config.\n *\n * The job is considered terminal only when a non-null, non-empty status string\n * is present in the result data and that status matches one of the terminal sets.\n */\nexport function isAsyncJobTerminal(\n result: ZuoraToolExecutionResult,\n statusPath: string,\n statuses: ZuoraAsyncJobTerminalStatuses,\n): boolean {\n const status = resolveAsyncJobStatus(result, statusPath);\n if (status == null || status === \"\") return false;\n return matchesAsyncJobTerminalStatus(status, statuses);\n}\n\n/**\n * Extracts the current job status string from a polling tool result.\n *\n * @param result - The result returned by the polling tool.\n * @param statusPath - Dot-path to the status field within result.data,\n * e.g. \"status\" or \"job.state\". Paths are normalized at parse time by\n * parseAsyncOperationMeta, so callers within the SDK should always pass\n * already-normalized paths here.\n * @returns The extracted status string, or undefined if not present.\n */\nexport function resolveAsyncJobStatus(\n result: ZuoraToolExecutionResult,\n statusPath: string,\n): string | undefined {\n const raw = resolveByPath(result.data, statusPath);\n if (raw == null || typeof raw !== \"string\") return undefined;\n return raw;\n}\n\n/**\n * Extracts the job ID from a ZuoraAsyncJobResult embedded inside a tool\n * execution result, or returns the jobId directly from a ZuoraAsyncJobResult.\n *\n * Supports two calling patterns:\n * - resolveAsyncJobId(asyncJobResult)\n * - resolveAsyncJobId(toolResult, jobIdPath)\n */\nexport function resolveAsyncJobId(\n result: ZuoraAsyncJobResult | ZuoraToolExecutionResult,\n jobIdPath?: string,\n): string | undefined {\n // If we have a ZuoraAsyncJobResult (has status: \"pending\")\n if (\"status\" in result && result.status === \"pending\" && \"jobId\" in result) {\n return (result as ZuoraAsyncJobResult).jobId;\n }\n\n // Otherwise treat as ZuoraToolExecutionResult and extract via path.\n // Paths sourced from asyncMeta are already normalized at parse time by\n // parseAsyncOperationMeta, so no further normalization is needed here.\n if (jobIdPath && \"data\" in result) {\n const raw = resolveByPath(result.data, jobIdPath);\n if (raw != null && typeof raw === \"string\") return raw;\n if (raw != null) return String(raw);\n }\n\n return undefined;\n}\n\n/**\n * Extracts the name of the next polling tool from a ZuoraAsyncJobResult.\n * Returns undefined if result is not a ZuoraAsyncJobResult.\n *\n * pollingToolName is always set on ZuoraAsyncJobResult (resolved at job-start\n * time by resolveAsyncJobPollingToolNameFromMeta), so it is returned directly.\n */\nexport function resolveAsyncJobPollingToolName(\n result: ZuoraAsyncJobResult | ZuoraToolExecutionResult,\n): string | undefined {\n if (\"status\" in result && result.status === \"pending\") {\n return (result as ZuoraAsyncJobResult).pollingToolName;\n }\n return undefined;\n}\n\n/**\n * Returns a rich ZuoraAsyncJobStatusResolution describing the current status\n * of an async job, including whether it has reached a terminal state and what\n * the terminal state is.\n *\n * @param result - The result returned by the polling tool.\n * @param statusPath - Dot-path to the status field (e.g. \"data.status\").\n * @param terminalStatuses - Terminal status configuration to match against.\n */\nexport function resolveAsyncJobStatusDetails(\n result: ZuoraToolExecutionResult,\n statusPath: string,\n terminalStatuses: ZuoraAsyncJobTerminalStatuses,\n): ZuoraAsyncJobStatusResolution {\n const status = resolveAsyncJobStatus(result, statusPath);\n\n if (status == null || status === \"\") {\n return { status: undefined, isTerminal: false, terminalState: undefined };\n }\n\n const terminalState = resolveAsyncJobTerminalState(status, terminalStatuses);\n const isTerminal = terminalState !== undefined;\n\n return { status, isTerminal, terminalState };\n}\n","import bundleCatalog from \"./resources/bundle-catalog.json\" with { type: \"json\" };\nimport type {\n ZuoraBundleDefinition,\n ZuoraBundleName,\n ZuoraToolDefinition,\n} from \"./types.js\";\nimport { isRecord } from \"./utils/values.js\";\n\nexport const ZUORA_BUNDLE_NAMES = [\n \"accounts\",\n \"catalog\",\n \"subscriptions\",\n \"orders\",\n \"billing\",\n \"payments\",\n \"usage\",\n \"revenue\",\n \"finance\",\n \"workflows\",\n \"query\",\n \"admin\",\n] as const satisfies readonly ZuoraBundleName[];\n\nexport type BundleCatalogEntry = {\n description: string;\n examples: string[];\n commonObjects: string[];\n keywords: string[];\n};\n\nexport type BundleCatalog = {\n version: number;\n bundles: Record<ZuoraBundleName, BundleCatalogEntry>;\n};\n\nconst readStringArrayField = (\n record: Record<string, unknown>,\n fieldName: string,\n bundleName: ZuoraBundleName,\n): string[] => {\n const value = record[fieldName];\n\n if (\n !Array.isArray(value) ||\n value.length === 0 ||\n value.some((item) => typeof item !== \"string\" || item.trim() === \"\")\n ) {\n throw new Error(\n `Invalid bundle catalog entry for ${bundleName}: ${fieldName} must be a non-empty string array.`,\n );\n }\n\n return value.map((item) => item.trim());\n};\n\nconst readBundleCatalogEntry = (\n value: unknown,\n bundleName: ZuoraBundleName,\n): BundleCatalogEntry => {\n if (!isRecord(value)) {\n throw new Error(`Missing bundle catalog entry for ${bundleName}.`);\n }\n\n const description = value.description;\n\n if (typeof description !== \"string\" || description.trim() === \"\") {\n throw new Error(\n `Invalid bundle catalog entry for ${bundleName}: description is required.`,\n );\n }\n\n return {\n description: description.trim(),\n examples: readStringArrayField(value, \"examples\", bundleName),\n commonObjects: readStringArrayField(value, \"commonObjects\", bundleName),\n keywords: readStringArrayField(value, \"keywords\", bundleName),\n };\n};\n\nconst loadBundleCatalog = (): BundleCatalog => {\n const raw = bundleCatalog as unknown;\n\n if (!isRecord(raw)) {\n throw new Error(\"Invalid bundle catalog: expected an object.\");\n }\n\n const rawBundles = raw.bundles;\n\n if (!isRecord(rawBundles)) {\n throw new Error(\"Invalid bundle catalog: expected a bundles object.\");\n }\n\n const version = raw.version;\n\n if (typeof version !== \"number\" || !Number.isInteger(version)) {\n throw new Error(\"Invalid bundle catalog: version must be an integer.\");\n }\n\n const bundles = Object.fromEntries(\n ZUORA_BUNDLE_NAMES.map((name) => [\n name,\n readBundleCatalogEntry(rawBundles[name], name),\n ]),\n ) as Record<ZuoraBundleName, BundleCatalogEntry>;\n\n return {\n version,\n bundles,\n };\n};\n\nexport const BUNDLE_CATALOG: BundleCatalog = loadBundleCatalog();\n\nexport const ZUORA_BUNDLE_NAME_SET = new Set<ZuoraBundleName>(ZUORA_BUNDLE_NAMES);\n\nexport const hasBundleDefinition = (\n name: string,\n): name is ZuoraBundleName => ZUORA_BUNDLE_NAME_SET.has(name as ZuoraBundleName);\n\nexport const getBundleDefinition = (\n name: ZuoraBundleName,\n tools: ZuoraToolDefinition[] = [],\n): ZuoraBundleDefinition => {\n const metadata = BUNDLE_CATALOG.bundles[name];\n const bundleTools = tools.filter((tool) => tool.meta.bundle === name);\n const description = metadata?.description ?? name;\n const examples = metadata ? [...metadata.examples] : [];\n const commonObjects = metadata ? [...metadata.commonObjects] : [];\n const keywords = metadata ? [...metadata.keywords] : [];\n\n return {\n name,\n description,\n examples,\n commonObjects,\n keywords,\n toolCount: bundleTools.length,\n readToolCount: bundleTools.filter((tool) => tool.meta.access === \"read\")\n .length,\n writeToolCount: bundleTools.filter((tool) => tool.meta.access === \"write\")\n .length,\n tools: bundleTools,\n };\n};\n","export const nonEmptyString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport const normalizeIdList = (value: unknown): string[] | undefined => {\n const values = Array.isArray(value)\n ? value\n : typeof value === \"string\"\n ? value.split(\",\")\n : [];\n const normalized = values.flatMap((entry) => {\n const normalizedEntry = nonEmptyString(entry);\n return normalizedEntry ? [normalizedEntry] : [];\n });\n\n return normalized.length > 0 ? normalized : undefined;\n};\n","import { ZuoraAgentToolkitError } from \"../errors.js\";\nimport type { JsonSchema, ZuoraToolDefinition, ZuoraToolOperation } from \"../types.js\";\n\nexport const inferOperationSelector = (\n inputSchema: JsonSchema | undefined,\n operationPermissions: Record<string, ZuoraToolOperation> | undefined,\n): string | undefined => {\n const operationNames = Object.keys(operationPermissions ?? {});\n\n if (operationNames.length <= 1) {\n return undefined;\n }\n\n const properties = inputSchema?.properties;\n\n if (!properties) {\n return undefined;\n }\n\n const candidates = Object.entries(properties).flatMap(\n ([propertyName, propertySchema]) =>\n isOperationSelectorSchema(propertySchema, operationNames)\n ? [propertyName]\n : [],\n );\n\n return candidates.length === 1 ? candidates[0] : undefined;\n};\n\nexport const omitSchemaProperty = (\n schema: JsonSchema,\n propertyName: string,\n): JsonSchema => {\n if (!schema.properties?.[propertyName]) {\n return schema;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { [propertyName]: _removed, ...properties } = schema.properties;\n const nextSchema: JsonSchema = {\n ...schema,\n properties,\n };\n\n if (schema.required) {\n const required = schema.required.filter((name) => name !== propertyName);\n\n if (required.length > 0) {\n nextSchema.required = required;\n } else {\n delete nextSchema.required;\n }\n }\n\n return nextSchema;\n};\n\nexport const enforceOperationSelector = (\n tool: ZuoraToolDefinition,\n input: Record<string, unknown>,\n): void => {\n const selector = tool.meta.operationSelector;\n\n // Only enforce on split tools that are bound to a single operation.\n // Merged tools have operationSelector set for runtime async lookup but are\n // not bound to one operation — the LLM's input value passes through as-is.\n if (!selector || !tool.meta.operationName) {\n return;\n }\n\n if (!Object.prototype.hasOwnProperty.call(input, selector)) {\n return;\n }\n\n const providedOperation = input[selector];\n\n const expectedOperation = tool.meta.operationName;\n\n if (providedOperation === expectedOperation) {\n return;\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"OPERATION_SELECTOR_MISMATCH\",\n message: `Tool ${tool.name} is bound to ${selector}=${expectedOperation}.`,\n category: \"validation\",\n recoverable: true,\n details: {\n selector,\n expected: expectedOperation,\n received: providedOperation,\n sourceName: tool.meta.sourceName,\n },\n });\n};\n\nexport const createMcpToolInput = (\n tool: ZuoraToolDefinition,\n input: Record<string, unknown>,\n): Record<string, unknown> => {\n const selector = tool.meta.operationSelector;\n\n // Only inject the operation on split tools bound to a single operation.\n // Merged tools pass through input unchanged — the LLM provides the value.\n if (!selector || !tool.meta.operationName) {\n return input;\n }\n\n return { ...input, [selector]: tool.meta.operationName };\n};\n\nconst isOperationSelectorSchema = (\n schema: JsonSchema,\n operationNames: string[],\n): boolean => {\n const enumValues = stringEnumValues(schema);\n\n if (!enumValues) {\n return false;\n }\n\n return haveSameStringSet(enumValues, operationNames);\n};\n\nconst stringEnumValues = (schema: JsonSchema): string[] | undefined => {\n if (schema.type !== \"string\" || !Array.isArray(schema.enum)) {\n return undefined;\n }\n\n return schema.enum.every((value): value is string => typeof value === \"string\")\n ? schema.enum\n : undefined;\n};\n\nconst haveSameStringSet = (left: string[], right: string[]): boolean => {\n if (left.length !== right.length) {\n return false;\n }\n\n const rightSet = new Set(right);\n return left.every((value) => rightSet.has(value));\n};\n","import { isRecord } from \"./values.js\";\n\nconst REDACTED_EVENT_VALUE = \"[REDACTED]\";\nconst TRUNCATED_EVENT_VALUE = \"[TRUNCATED]\";\n\nconst DEFAULT_EVENT_SANITIZER_LIMITS = {\n maxDepth: 4,\n maxArrayLength: 20,\n maxObjectKeys: 50,\n maxStringLength: 512,\n} as const;\n\nexport type EventSanitizerLimits = {\n maxDepth: number;\n maxArrayLength: number;\n maxObjectKeys: number;\n maxStringLength: number;\n};\n\nexport const resolveEventSanitizerLimits = (\n env: Record<string, string | undefined>,\n): EventSanitizerLimits => ({\n maxDepth: readPositiveIntegerEnv(\n env,\n \"MAX_EVENT_METADATA_DEPTH\",\n DEFAULT_EVENT_SANITIZER_LIMITS.maxDepth,\n ),\n maxArrayLength: readPositiveIntegerEnv(\n env,\n \"MAX_EVENT_METADATA_ARRAY_LENGTH\",\n DEFAULT_EVENT_SANITIZER_LIMITS.maxArrayLength,\n ),\n maxObjectKeys: readPositiveIntegerEnv(\n env,\n \"MAX_EVENT_METADATA_OBJECT_KEYS\",\n DEFAULT_EVENT_SANITIZER_LIMITS.maxObjectKeys,\n ),\n maxStringLength: readPositiveIntegerEnv(\n env,\n \"MAX_EVENT_METADATA_STRING_LENGTH\",\n DEFAULT_EVENT_SANITIZER_LIMITS.maxStringLength,\n ),\n});\n\nexport const sanitizeEventRecord = (\n value: Record<string, unknown>,\n limits: EventSanitizerLimits = DEFAULT_EVENT_SANITIZER_LIMITS,\n): Record<string, unknown> => {\n const sanitized = sanitizeEventValue(value, \"\", 0, limits);\n\n return isRecord(sanitized) ? sanitized : { value: sanitized };\n};\n\nconst sanitizeEventValue = (\n value: unknown,\n key: string,\n depth: number,\n limits: EventSanitizerLimits,\n): unknown => {\n if (isSensitiveEventKey(key)) {\n return REDACTED_EVENT_VALUE;\n }\n\n if (value === null) {\n return null;\n }\n\n if (typeof value === \"string\") {\n if (looksSensitiveString(value)) {\n return REDACTED_EVENT_VALUE;\n }\n\n return value.length > limits.maxStringLength\n ? `${value.slice(0, limits.maxStringLength)}...`\n : value;\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n if (value === undefined || typeof value === \"function\" || typeof value === \"symbol\") {\n return undefined;\n }\n\n if (depth >= limits.maxDepth) {\n return TRUNCATED_EVENT_VALUE;\n }\n\n if (Array.isArray(value)) {\n const entries = value\n .slice(0, limits.maxArrayLength)\n .map((entry) => sanitizeEventValue(entry, \"\", depth + 1, limits));\n\n return value.length > limits.maxArrayLength\n ? [...entries, TRUNCATED_EVENT_VALUE]\n : entries;\n }\n\n if (!isRecord(value)) {\n return String(value);\n }\n\n return Object.fromEntries(\n Object.entries(value)\n .slice(0, limits.maxObjectKeys)\n .flatMap(([entryKey, entryValue]) => {\n const sanitizedEntry = sanitizeEventValue(\n entryValue,\n entryKey,\n depth + 1,\n limits,\n );\n\n return sanitizedEntry === undefined ? [] : [[entryKey, sanitizedEntry]];\n }),\n );\n};\n\nconst readPositiveIntegerEnv = (\n env: Record<string, string | undefined>,\n name: string,\n fallback: number,\n): number => {\n const value = env[name];\n\n if (!value?.trim()) {\n return fallback;\n }\n\n const parsed = Number.parseInt(value, 10);\n\n if (!Number.isInteger(parsed) || parsed < 1) {\n return fallback;\n }\n\n return parsed;\n};\n\nconst isSensitiveEventKey = (key: string): boolean =>\n /authorization|client[_-]?secret|access[_-]?token|refresh[_-]?token|api[_-]?key|private[_-]?key|password|secret|token|signed[_-]?url|card[_-]?number|cvv|cvc|iban|bank[_-]?account|routing[_-]?number/i.test(\n key,\n );\n\nconst looksSensitiveString = (value: string): boolean =>\n /^(Bearer|Basic)\\s+\\S+/i.test(value) ||\n looksSignedUrl(value) ||\n /(?:access_token|refresh_token|client_secret|signature|x-amz-signature)=/i.test(\n value,\n ) ||\n /^sk-[A-Za-z0-9_-]{12,}/.test(value) ||\n /^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/.test(value);\n\nconst looksSignedUrl = (value: string): boolean => {\n let parsed: URL;\n\n try {\n parsed = new URL(value);\n } catch {\n return false;\n }\n\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return false;\n }\n\n for (const key of parsed.searchParams.keys()) {\n if (\n /^(sig|signature|token|access_token|security-token|x-amz-.+|x-goog-.+|expires|expires_in)$/i.test(\n key,\n )\n ) {\n return true;\n }\n }\n\n return false;\n};\n","import { ZuoraAgentToolkitError } from \"../errors.js\";\nimport type {\n EventSanitizerLimits,\n ToolkitBundleName,\n ZuoraToolDefinition,\n ZuoraToolkitEvent,\n ZuoraToolkitLogger,\n} from \"../types.js\";\nimport { sanitizeEventRecord } from \"../utils/event-sanitizer.js\";\n\nexport type InternalToolkitEvent = Omit<\n ZuoraToolkitEvent,\n \"type\" | \"timestamp\"\n> &\n Partial<Pick<ZuoraToolkitEvent, \"type\" | \"timestamp\">>;\n\nexport type EventRequestMetadata = Pick<\n ZuoraToolkitEvent,\n | \"requestId\"\n | \"zuoraRequestId\"\n | \"environment\"\n | \"tenantId\"\n | \"entityIds\"\n | \"orgIds\"\n>;\n\nexport const reportObservabilitySinkError = (\n logger: ZuoraToolkitLogger | undefined,\n error: unknown,\n): void => {\n try {\n logger?.error?.(\"[zuora-agent-toolkit] observability sink failed\", {\n name: \"observability.sink_failed\",\n type: \"observability.sink_failed\",\n timestamp: new Date().toISOString(),\n error: {\n code: \"OBSERVABILITY_SINK_ERROR\",\n category: \"configuration\",\n recoverable: true,\n },\n metadata: sanitizeEventRecord({\n message: error instanceof Error ? error.message : String(error),\n }),\n });\n } catch {\n // Ignore logger failures.\n }\n};\n\nexport const normalizeToolkitEvent = (\n event: InternalToolkitEvent,\n sanitizerLimits?: EventSanitizerLimits,\n): ZuoraToolkitEvent => {\n const { metadata, timestamp, type, ...rest } = event;\n\n return {\n ...rest,\n type: type ?? toolkitEventTypeForName(event.name),\n timestamp: timestamp ?? new Date().toISOString(),\n ...(metadata\n ? { metadata: sanitizeEventRecord(metadata, sanitizerLimits) }\n : {}),\n } as ZuoraToolkitEvent;\n};\n\nexport const compactToolkitError = (\n error: ZuoraAgentToolkitError,\n): NonNullable<ZuoraToolkitEvent[\"error\"]> => ({\n code: error.code,\n category: error.category,\n recoverable: error.recoverable,\n retryable: error.retryable,\n message: error.message,\n ...(error.requestId ? { requestId: error.requestId } : {}),\n});\n\nexport const metadataLoadedEventMetadata = (\n tools: ZuoraToolDefinition[],\n): Record<string, unknown> => {\n const bundleCounts = tools.reduce<Partial<Record<ToolkitBundleName, number>>>(\n (counts, tool) => {\n counts[tool.meta.bundle] = (counts[tool.meta.bundle] ?? 0) + 1;\n return counts;\n },\n {},\n );\n return {\n toolCount: tools.length,\n bundleCounts,\n };\n};\n\nconst toolkitEventTypeForName = (\n name: ZuoraToolkitEvent[\"name\"],\n): ZuoraToolkitEvent[\"type\"] =>\n name === \"approval.resolved\" ? \"approval.decided\" : name;\n","import type { ZuoraToolkitEvent, ZuoraToolkitLogger } from \"../types.js\";\nimport { sanitizeEventRecord } from \"../utils/event-sanitizer.js\";\n\nexport type AsyncPollTerminationDecision =\n | \"success\"\n | \"failure\"\n | \"canceled\"\n | \"continue\"\n | \"no_status\";\n\nexport type AsyncPollCheckedDetails = {\n jobId: string;\n attempt: number;\n maxAttempts: number;\n pollingToolName: string;\n statusPath: string;\n statusSource: \"asyncJob.status\" | \"statusPath\" | \"fallback.status\" | \"none\";\n resolvedValue: unknown;\n resolvedStatus?: string;\n terminalStatuses: {\n success: string[];\n failure: string[];\n canceled?: string[];\n };\n matchedSuccess: boolean;\n matchedFailure: boolean;\n matchedCanceled: boolean;\n decision: AsyncPollTerminationDecision;\n};\n\n/**\n * Logs an `async.poll.checked` debug event directly to the toolkit logger.\n *\n * This function intentionally bypasses the central `ToolkitCore.emit()` path\n * (and therefore skips `onEvent`/`emit` sink hooks) because async-poll checks\n * are high-frequency, debug-only telemetry. Routing them through the full\n * sink chain would require threading the `ToolkitCore` instance into the async\n * polling loop, adding complexity with little benefit for production consumers.\n * If you need to capture these events in a sink, subscribe via the `logger`\n * option in the observability config.\n */\nexport const logAsyncPollChecked = (\n logger: ZuoraToolkitLogger | undefined,\n details: AsyncPollCheckedDetails,\n): void => {\n if (!logger?.debug) {\n return;\n }\n\n const message = \"[zuora-agent-toolkit] async.poll.checked\";\n const event: ZuoraToolkitEvent = {\n name: \"async.poll.checked\",\n type: \"async.poll.checked\",\n timestamp: new Date().toISOString(),\n executionPhase: \"async_poll\",\n toolName: details.pollingToolName,\n metadata: sanitizeEventRecord({\n jobId: details.jobId,\n attempt: details.attempt,\n maxAttempts: details.maxAttempts,\n pollingToolName: details.pollingToolName,\n statusPath: details.statusPath,\n statusSource: details.statusSource,\n resolvedValue: details.resolvedValue,\n ...(details.resolvedStatus\n ? { resolvedStatus: details.resolvedStatus }\n : {}),\n terminalStatuses: details.terminalStatuses,\n matchedSuccess: details.matchedSuccess,\n matchedFailure: details.matchedFailure,\n matchedCanceled: details.matchedCanceled,\n decision: details.decision,\n }),\n };\n\n try {\n logger.debug(message, event);\n } catch {\n // Best-effort observability only.\n }\n};\n","import type { ZuoraToolExecutionResult } from \"../types.js\";\nimport { sanitizeEventRecord } from \"../utils/event-sanitizer.js\";\n\nexport const compactToolInputForEvent = (\n input: Record<string, unknown>,\n): Record<string, unknown> => sanitizeEventRecord(input);\n\nexport const compactToolOutputForEvent = (\n result: ZuoraToolExecutionResult,\n): Record<string, unknown> =>\n sanitizeEventRecord({\n toolName: result.toolName,\n ...(result.requestId ? { requestId: result.requestId } : {}),\n ...(result.request ? { request: result.request } : {}),\n riskLevel: result.riskLevel,\n data: result.data,\n ...(result.warnings?.length ? { warnings: result.warnings } : {}),\n });\n","import type { ZuoraEnvironment, ZuoraExecutionRequestMetadata } from \"../types.js\";\nimport {\n nonEmptyString,\n normalizeIdList,\n} from \"../utils/values.js\";\n\n/**\n * Shared normalizer for Zuora request-metadata fields across both the\n * transport layer (`ZuoraExecutionRequestMetadata`) and the observability\n * layer (`EventRequestMetadata`). Both use the same field aliases\n * (camelCase / snake_case), so a single implementation avoids drift.\n *\n * Returns a partial record containing only the fields that were present and\n * non-empty in the source object. Returns `undefined` when the source is not\n * an object or contains no recognisable fields.\n */\nexport const normalizeRequestMetadataFields = (\n value: unknown,\n): ZuoraExecutionRequestMetadata | undefined => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n const requestId = nonEmptyString(record.requestId) ?? nonEmptyString(record.request_id);\n const zuoraRequestId =\n nonEmptyString(record.zuoraRequestId) ??\n nonEmptyString(record.zuora_request_id);\n const tenantId = nonEmptyString(record.tenantId) ?? nonEmptyString(record.tenant_id);\n const entityIds =\n normalizeIdList(record.entityIds) ??\n normalizeIdList(record.entity_ids) ??\n normalizeIdList(record.entityId) ??\n normalizeIdList(record.entity_id);\n const orgIds =\n normalizeIdList(record.orgIds) ??\n normalizeIdList(record.org_ids) ??\n normalizeIdList(record.orgId) ??\n normalizeIdList(record.org_id);\n const environment = normalizeRequestEnvironment(record.environment);\n const metadata = {\n ...(requestId ? { requestId } : {}),\n ...(zuoraRequestId ? { zuoraRequestId } : {}),\n ...(environment ? { environment } : {}),\n ...(tenantId ? { tenantId } : {}),\n ...(entityIds ? { entityIds } : {}),\n ...(orgIds ? { orgIds } : {}),\n };\n\n return Object.keys(metadata).length > 0 ? metadata : undefined;\n};\n\n/** @deprecated Use `normalizeRequestMetadataFields` directly. */\nexport const normalizeExecutionRequestMetadata = normalizeRequestMetadataFields;\n\nconst normalizeRequestEnvironment = (\n value: unknown,\n): ZuoraEnvironment | undefined => {\n const normalized = nonEmptyString(value)?.toLowerCase();\n\n return normalized === \"sandbox\" || normalized === \"production\"\n ? normalized\n : undefined;\n};\n","import type {\n ZuoraToolExecutionResult,\n} from \"../types.js\";\nimport { normalizeRequestMetadataFields } from \"../transport/request-metadata.js\";\nimport type { EventRequestMetadata } from \"./events.js\";\n\nexport const extractExecutionRequestMetadata = (\n result: ZuoraToolExecutionResult,\n): EventRequestMetadata => {\n const explicitRequest = normalizeRequestMetadataFields(result.request) ?? {};\n const nestedRequest = extractNestedRequestMetadata(result.data);\n const fallbackRequestId = result.requestId ?? extractRequestId(result.data);\n const requestId =\n explicitRequest.requestId ??\n nestedRequest.requestId ??\n fallbackRequestId ??\n explicitRequest.zuoraRequestId ??\n nestedRequest.zuoraRequestId;\n const zuoraRequestId =\n explicitRequest.zuoraRequestId ??\n nestedRequest.zuoraRequestId ??\n extractZuoraRequestId(result.data) ??\n requestId;\n const metadata: EventRequestMetadata = {\n ...(requestId ? { requestId } : {}),\n ...(zuoraRequestId ? { zuoraRequestId } : {}),\n ...(explicitRequest.environment ?? nestedRequest.environment\n ? { environment: explicitRequest.environment ?? nestedRequest.environment }\n : {}),\n ...(explicitRequest.tenantId ?? nestedRequest.tenantId\n ? { tenantId: explicitRequest.tenantId ?? nestedRequest.tenantId }\n : {}),\n ...(explicitRequest.entityIds ?? nestedRequest.entityIds\n ? { entityIds: explicitRequest.entityIds ?? nestedRequest.entityIds }\n : {}),\n ...(explicitRequest.orgIds ?? nestedRequest.orgIds\n ? { orgIds: explicitRequest.orgIds ?? nestedRequest.orgIds }\n : {}),\n };\n\n return metadata;\n};\n\nconst extractNestedRequestMetadata = (value: unknown): EventRequestMetadata => {\n if (!value || typeof value !== \"object\") {\n return {};\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n const request = extractNestedRequestMetadata(item);\n\n if (Object.keys(request).length > 0) {\n return request;\n }\n }\n\n return {};\n }\n\n const record = value as Record<string, unknown>;\n const request = normalizeRequestMetadataFields(record.request) ?? {};\n\n if (Object.keys(request).length > 0) {\n return request;\n }\n\n for (const entry of Object.values(record)) {\n const nestedRequest = extractNestedRequestMetadata(entry);\n\n if (Object.keys(nestedRequest).length > 0) {\n return nestedRequest;\n }\n }\n\n return {};\n};\n\n/**\n * Generic recursive search: traverses `value` (object/array) looking for the\n * first string field whose key matches one of `keys`. Returns the first match.\n */\nconst extractFirstMatchingStringField = (\n value: unknown,\n keys: readonly string[],\n): string | undefined => {\n if (!value || typeof value !== \"object\") {\n return undefined;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n const found = extractFirstMatchingStringField(item, keys);\n\n if (found) {\n return found;\n }\n }\n\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n\n for (const key of keys) {\n if (key in record && typeof record[key] === \"string\") {\n return record[key] as string;\n }\n }\n\n for (const entry of Object.values(record)) {\n const found = extractFirstMatchingStringField(entry, keys);\n\n if (found) {\n return found;\n }\n }\n\n return undefined;\n};\n\n/** Extracts any request-correlation ID from a result payload. */\nexport const extractRequestId = (value: unknown): string | undefined =>\n extractFirstMatchingStringField(value, [\n \"zuoraRequestId\",\n \"zuora_request_id\",\n \"requestId\",\n \"request_id\",\n ]);\n\n/** Extracts a Zuora server-assigned trace ID from a result payload. */\nconst extractZuoraRequestId = (value: unknown): string | undefined =>\n extractFirstMatchingStringField(value, [\n \"zuoraRequestId\",\n \"zuora_request_id\",\n ]);\n","import os from \"node:os\";\nimport path from \"node:path\";\n\nimport { ZuoraAgentToolkitError } from \"../../../errors.js\";\nimport type { NativeFileToolsConfig } from \"../../../types.js\";\nimport { nonEmptyString } from \"../../../utils/values.js\";\nimport {\n resolveNativeToolMetadata,\n type ResolvedNativeToolMetadataConfig,\n} from \"../config.js\";\n\nexport type ResolvedNativeFileToolsConfig = {\n enabled: boolean;\n bundleName: \"query\";\n tools: {\n downloadFile: ResolvedNativeToolMetadataConfig;\n readDownloadedFile: ResolvedNativeToolMetadataConfig;\n extractDownloadedArchive: ResolvedNativeToolMetadataConfig;\n readResource: ResolvedNativeToolMetadataConfig;\n };\n rootDir: string;\n rootDirAbsolute: string;\n userHomeDir: string;\n userHomeDirAbsolute: string;\n requireRootUnderUserHome: boolean;\n allowOverwrite: boolean;\n maxDownloadBytes: number;\n maxReadBytes: number;\n maxReadLines: number;\n maxExtractedFiles: number;\n maxExtractedBytes: number;\n downloadTimeoutMs: number;\n allowedProtocols: string[];\n allowedHosts: string[];\n allowedUrlPrefixes: string[];\n zuoraDownloadHosts: string[];\n allowZuoraAuthenticatedDownload: boolean;\n allowS3PresignedDownload: boolean;\n allowArchiveExtraction: boolean;\n};\n\nconst DEFAULT_MAX_DOWNLOAD_BYTES = 10 * 1024 * 1024;\nconst DEFAULT_MAX_READ_BYTES = 64 * 1024;\nconst DEFAULT_MAX_READ_LINES = 200;\nconst DEFAULT_DOWNLOAD_TIMEOUT_MS = 30_000;\n\nexport const resolveNativeFileToolsConfig = (\n input: NativeFileToolsConfig | undefined,\n): ResolvedNativeFileToolsConfig => {\n const enabled = input?.enabled ?? false;\n const bundleName: \"query\" = (input?.bundleName ?? \"query\") as \"query\";\n const userHomeDir = nonEmptyString(input?.userHomeDir) ?? os.homedir();\n const userHomeDirAbsolute = path.resolve(userHomeDir);\n const rootDir = nonEmptyString(input?.rootDir) ?? \"\";\n // When rootDir is empty and enabled=false, rootDirAbsolute is intentionally\n // left as \"\" rather than resolving against process.cwd(). The validation gate\n // in validateEnabledConfig() rejects an empty rootDir whenever enabled=true,\n // so no code path that calls path.resolve(rootDirAbsolute, ...) can reach a\n // live filesystem operation with an empty string.\n const rootDirAbsolute = rootDir ? path.resolve(rootDir) : \"\";\n const requireRootUnderUserHome = input?.requireRootUnderUserHome ?? true;\n const allowedProtocols = normalizeProtocols(input?.allowedProtocols);\n const allowedHosts = normalizeStringList(input?.allowedHosts).map((host) =>\n host.toLowerCase(),\n );\n const allowedUrlPrefixes = normalizeStringList(input?.allowedUrlPrefixes);\n const zuoraDownloadHosts = normalizeStringList(input?.zuoraDownloadHosts).map(\n (host) => host.toLowerCase(),\n );\n const config: ResolvedNativeFileToolsConfig = {\n enabled,\n bundleName,\n tools: {\n downloadFile: resolveNativeToolMetadata(input?.tools?.downloadFile, {\n enabled: false,\n operationAccess: \"read\",\n riskLevel: \"medium\",\n }),\n readDownloadedFile: resolveNativeToolMetadata(input?.tools?.readDownloadedFile, {\n enabled: true,\n operationAccess: \"read\",\n riskLevel: \"low\",\n }),\n extractDownloadedArchive: resolveNativeToolMetadata(\n input?.tools?.extractDownloadedArchive,\n {\n enabled: false,\n operationAccess: \"read\",\n riskLevel: \"medium\",\n },\n ),\n readResource: resolveNativeToolMetadata(input?.tools?.readResource, {\n enabled: true,\n operationAccess: \"read\",\n riskLevel: \"low\",\n }),\n },\n rootDir,\n rootDirAbsolute,\n userHomeDir,\n userHomeDirAbsolute,\n requireRootUnderUserHome,\n allowOverwrite: input?.allowOverwrite ?? false,\n maxDownloadBytes: positiveInteger(\n input?.maxDownloadBytes,\n DEFAULT_MAX_DOWNLOAD_BYTES,\n \"maxDownloadBytes\",\n ),\n maxReadBytes: positiveInteger(\n input?.maxReadBytes,\n DEFAULT_MAX_READ_BYTES,\n \"maxReadBytes\",\n ),\n maxReadLines: positiveInteger(\n input?.maxReadLines,\n DEFAULT_MAX_READ_LINES,\n \"maxReadLines\",\n ),\n maxExtractedFiles: positiveInteger(\n input?.maxExtractedFiles,\n 0,\n \"maxExtractedFiles\",\n true,\n ),\n maxExtractedBytes: positiveInteger(\n input?.maxExtractedBytes,\n 0,\n \"maxExtractedBytes\",\n true,\n ),\n downloadTimeoutMs: positiveInteger(\n input?.downloadTimeoutMs,\n DEFAULT_DOWNLOAD_TIMEOUT_MS,\n \"downloadTimeoutMs\",\n ),\n allowedProtocols,\n allowedHosts,\n allowedUrlPrefixes,\n zuoraDownloadHosts,\n allowZuoraAuthenticatedDownload:\n input?.allowZuoraAuthenticatedDownload ?? false,\n allowS3PresignedDownload: input?.allowS3PresignedDownload ?? true,\n allowArchiveExtraction: input?.allowArchiveExtraction ?? false,\n };\n\n if (!enabled) {\n return config;\n }\n\n validateEnabledConfig(config);\n\n return config;\n};\n\nconst validateEnabledConfig = (config: ResolvedNativeFileToolsConfig): void => {\n if (config.bundleName !== \"query\") {\n throw nativeFileConfigError(\n `Unsupported native file bundle: ${config.bundleName}. Only \"query\" is supported.`,\n );\n }\n\n if (!config.rootDir) {\n throw nativeFileConfigError(\n \"nativeFileTools.rootDir is required when native file tools are enabled.\",\n );\n }\n\n if (\n config.allowedHosts.length === 0 &&\n config.allowedUrlPrefixes.length === 0\n ) {\n throw nativeFileConfigError(\n \"nativeFileTools.allowedHosts or nativeFileTools.allowedUrlPrefixes is required when native file tools are enabled.\",\n );\n }\n\n for (const protocol of config.allowedProtocols) {\n if (protocol !== \"http:\" && protocol !== \"https:\") {\n throw nativeFileConfigError(\n `Unsupported native file download protocol: ${protocol}. This MVP supports HTTP(S) only.`,\n );\n }\n }\n\n if (config.allowedProtocols.length === 0) {\n throw nativeFileConfigError(\n \"nativeFileTools.allowedProtocols must include at least one protocol.\",\n );\n }\n\n if (\n config.requireRootUnderUserHome &&\n !isPathInside(config.rootDirAbsolute, config.userHomeDirAbsolute)\n ) {\n throw nativeFileConfigError(\n \"nativeFileTools.rootDir must be under nativeFileTools.userHomeDir when requireRootUnderUserHome is true.\",\n );\n }\n\n if (config.tools.readDownloadedFile.operationAccess !== \"read\") {\n throw nativeFileConfigError(\n \"read_downloaded_file must be configured with operationAccess \\\"read\\\".\",\n );\n }\n\n if (config.tools.downloadFile.operationAccess !== \"read\") {\n throw nativeFileConfigError(\n \"download_file must be configured with operationAccess \\\"read\\\".\",\n );\n }\n\n if (config.tools.extractDownloadedArchive.operationAccess !== \"read\") {\n throw nativeFileConfigError(\n \"extract_downloaded_archive must be configured with operationAccess \\\"read\\\".\",\n );\n }\n\n for (const prefix of config.allowedUrlPrefixes) {\n validateConfiguredPrefix(prefix);\n }\n\n if (config.allowZuoraAuthenticatedDownload) {\n throw nativeFileConfigError(\n \"Authenticated Zuora file downloads are not supported by the native file tools MVP. Use public or presigned HTTPS links.\",\n );\n }\n\n if (config.allowArchiveExtraction) {\n throw nativeFileConfigError(\n \"Archive extraction is not supported by the native file tools MVP.\",\n );\n }\n};\n\nconst normalizeProtocols = (values: string[] | undefined): string[] => {\n const protocols = normalizeStringList(values ?? [\"https:\"]).map((value) => {\n const normalized = value.toLowerCase();\n return normalized.endsWith(\":\") ? normalized : `${normalized}:`;\n });\n\n return [...new Set(protocols)];\n};\n\nconst normalizeStringList = (values: string[] | undefined): string[] =>\n [...new Set((values ?? []).map((value) => value.trim()).filter(Boolean))];\n\nconst positiveInteger = (\n value: number | undefined,\n fallback: number,\n name: string,\n allowZero = false,\n): number => {\n const candidate = value ?? fallback;\n const minimum = allowZero ? 0 : 1;\n\n if (!Number.isInteger(candidate) || candidate < minimum) {\n throw nativeFileConfigError(\n `nativeFileTools.${name} must be ${allowZero ? \"zero or \" : \"\"}a positive integer.`,\n );\n }\n\n return candidate;\n};\n\nconst validateConfiguredPrefix = (prefix: string): void => {\n let parsed: URL;\n\n try {\n parsed = new URL(prefix);\n } catch {\n throw nativeFileConfigError(\n `Invalid native file allowedUrlPrefixes entry: ${prefix}`,\n );\n }\n\n if (parsed.username || parsed.password) {\n throw nativeFileConfigError(\n \"nativeFileTools.allowedUrlPrefixes entries must not include URL userinfo.\",\n );\n }\n\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw nativeFileConfigError(\n \"nativeFileTools.allowedUrlPrefixes entries must use HTTP(S).\",\n );\n }\n\n if (!parsed.hostname) {\n throw nativeFileConfigError(\n \"nativeFileTools.allowedUrlPrefixes entries must include a host.\",\n );\n }\n\n if (parsed.search || parsed.hash) {\n throw nativeFileConfigError(\n \"nativeFileTools.allowedUrlPrefixes entries must not include query strings or fragments.\",\n );\n }\n};\n\nconst isPathInside = (candidate: string, root: string): boolean => {\n const relative = path.relative(root, candidate);\n\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n};\n\nconst nativeFileConfigError = (message: string): ZuoraAgentToolkitError =>\n new ZuoraAgentToolkitError({\n code: \"NATIVE_FILE_CONFIG_INVALID\",\n message,\n category: \"configuration\",\n recoverable: true,\n });\n","import type {\n NativeToolMetadataConfig,\n ZuoraRiskLevel,\n ZuoraToolOperation,\n} from \"../../types.js\";\nimport { nonEmptyString } from \"../../utils/values.js\";\n\nexport type ResolvedNativeToolMetadataConfig = {\n enabled: boolean;\n operationAccess: ZuoraToolOperation;\n riskLevel: ZuoraRiskLevel;\n description?: string;\n};\n\nexport const resolveNativeToolMetadata = (\n input: NativeToolMetadataConfig | undefined,\n defaults: Omit<ResolvedNativeToolMetadataConfig, \"description\">,\n): ResolvedNativeToolMetadataConfig => {\n const description = nonEmptyString(input?.description);\n\n return {\n enabled: input?.enabled ?? defaults.enabled,\n operationAccess: input?.operationAccess ?? defaults.operationAccess,\n riskLevel: input?.riskLevel ?? defaults.riskLevel,\n ...(description ? { description } : {}),\n };\n};\n","import type { JsonSchema } from \"../../types.js\";\n\nexport const nativeObjectSchema = (\n properties: Record<string, JsonSchema>,\n required: string[] = [],\n): JsonSchema => ({\n type: \"object\",\n properties,\n required,\n additionalProperties: false,\n});\n","import type { ZuoraToolDefinition } from \"../../../types.js\";\nimport { nativeObjectSchema } from \"../metadata.js\";\nimport type { ResolvedNativeFileToolsConfig } from \"./config.js\";\n\nexport const createDownloadFileToolDefinition = (\n config: ResolvedNativeFileToolsConfig,\n): ZuoraToolDefinition => {\n const toolConfig = config.tools.downloadFile;\n\n return {\n name: \"download_file\",\n description:\n toolConfig.description ??\n [\n \"Download a remote file into the configured local artifact folder.\",\n \"Use this when the user asks to download, save, or fetch a file URL from prior tool output.\",\n \"For presigned URLs, pass the exact raw URL including the full query string; do not use redacted, shortened, decoded, or assistant-summarized links.\",\n \"If the URL appears in a field such as dataFile, resultUrl, downloadUrl, fileUrl, or href, use that field value exactly.\",\n \"If the result requires confirmation, ask the user before retrying with overwrite:true.\",\n ].join(\" \"),\n inputSchema: nativeObjectSchema(\n {\n url: {\n type: \"string\",\n description:\n \"Absolute HTTP(S) file URL. For presigned S3 or similar URLs, provide the exact original URL including every query parameter and signature token.\",\n },\n fileName: {\n type: \"string\",\n description:\n \"Optional relative artifact file name under the configured artifact root.\",\n },\n overwrite: {\n type: \"boolean\",\n description:\n \"Replace an existing local artifact at fileName. Set to true only after download_file returned requiresConfirmation:true and the user explicitly confirmed overwrite.\",\n },\n },\n [\"url\"],\n ),\n outputSchema: nativeObjectSchema(\n {\n status: {\n type: \"string\",\n enum: [\n \"downloaded\",\n \"existing\",\n \"requires_confirmation\",\n \"overwritten\",\n ],\n },\n message: { type: \"string\" },\n requiresConfirmation: { type: \"boolean\" },\n artifactId: { type: \"string\" },\n path: { type: \"string\" },\n bytes: { type: \"number\" },\n existingBytes: { type: \"number\" },\n remoteBytes: { type: \"number\" },\n sha256: { type: \"string\" },\n contentType: { type: \"string\" },\n source: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n [\"status\", \"path\", \"source\"],\n ),\n meta: {\n bundle: config.bundleName,\n access: toolConfig.operationAccess,\n riskLevel: toolConfig.riskLevel,\n requiredServicePermissions: [],\n limitations: [],\n sourceName: \"download_file\",\n },\n };\n};\n\nexport const createReadDownloadedFileToolDefinition = (\n config: ResolvedNativeFileToolsConfig,\n): ZuoraToolDefinition => {\n const toolConfig = config.tools.readDownloadedFile;\n\n return {\n name: \"read_downloaded_file\",\n description:\n toolConfig.description ??\n \"Read bounded text content from a registered downloaded file artifact.\",\n inputSchema: nativeObjectSchema({\n artifactId: {\n type: \"string\",\n description:\n \"Artifact id returned by download_query_result or another native download tool.\",\n },\n path: {\n type: \"string\",\n description:\n \"Relative artifact path from a prior download result. Used only when artifactId is omitted.\",\n },\n startLine: {\n type: \"number\",\n description: \"One-based line number to start reading from.\",\n },\n maxLines: {\n type: \"number\",\n description: \"Maximum number of text lines to return.\",\n },\n maxBytes: {\n type: \"number\",\n description: \"Maximum number of bytes to inspect, capped by SDK config.\",\n },\n }),\n outputSchema: nativeObjectSchema(\n {\n artifactId: { type: \"string\" },\n path: { type: \"string\" },\n content: { type: \"string\" },\n startLine: { type: \"number\" },\n endLine: { type: \"number\" },\n linesReturned: { type: \"number\" },\n bytesRead: { type: \"number\" },\n truncated: { type: \"boolean\" },\n },\n [\n \"artifactId\",\n \"path\",\n \"content\",\n \"startLine\",\n \"linesReturned\",\n \"bytesRead\",\n \"truncated\",\n ],\n ),\n meta: {\n bundle: config.bundleName,\n access: toolConfig.operationAccess,\n riskLevel: toolConfig.riskLevel,\n requiredServicePermissions: [],\n limitations: [\n \"Only files registered by this toolkit instance can be read.\",\n \"Reads are bounded by configured byte and line limits.\",\n \"Binary-looking files are rejected.\",\n ],\n sourceName: \"read_downloaded_file\",\n },\n };\n};\n\nexport const createReadResourceToolDefinition = (\n config: ResolvedNativeFileToolsConfig,\n description?: string,\n): ZuoraToolDefinition => {\n return {\n name: \"read_resource\",\n description:\n description ??\n \"Read content from an MCP resource URI returned by Zuora tools. Use this to access files referenced via resourceUri (e.g., zuora://files/{fileId}) in tool results.\",\n inputSchema: nativeObjectSchema({\n uri: {\n type: \"string\",\n description:\n \"The MCP resource URI to read, typically in the format zuora://files/{fileId} or zuora://objects/{type}/{id}.\",\n },\n }),\n outputSchema: nativeObjectSchema(\n {\n uri: { type: \"string\" },\n mimeType: { type: \"string\" },\n content: {\n type: \"string\",\n description: \"Text content if the resource is text-based (JSON, XML, text).\",\n },\n data: {\n type: \"string\",\n description: \"Base64-encoded binary data if the resource is binary (PDF, images, etc.).\",\n },\n },\n [\"uri\", \"mimeType\"],\n ),\n meta: {\n bundle: config.bundleName,\n access: \"read\",\n riskLevel: \"low\",\n requiredServicePermissions: [],\n limitations: [\n \"Resource URIs must be valid MCP resource URIs returned by Zuora tools.\",\n \"Binary content is returned as base64-encoded data.\",\n \"Resource availability depends on the underlying Zuora service.\",\n ],\n sourceName: \"read_resource\",\n },\n };\n};\n","import { createHash, randomBytes } from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { ZuoraAgentToolkitError } from \"../../../errors.js\";\nimport type { ZuoraRiskLevel, ZuoraToolExecutionResult } from \"../../../types.js\";\nimport type { ResolvedNativeFileToolsConfig } from \"./config.js\";\nimport { nativeFileError } from \"./errors.js\";\nimport {\n type FileArtifactRecord,\n FileArtifactManifest,\n} from \"./manifest.js\";\nimport {\n prepareOutputArtifactPath,\n resolveOutputRelativePath,\n} from \"./path-policy.js\";\nimport {\n type NativeFileSafeSource,\n type ValidatedNativeFileUrl,\n validateDownloadUrl,\n validateRedirectUrl,\n} from \"./url-policy.js\";\n\ntype DownloadedResponse = {\n response: Response;\n source: NativeFileSafeSource;\n};\n\nexport type NativeFileDownloadServiceConfig = {\n config: ResolvedNativeFileToolsConfig;\n manifest: FileArtifactManifest;\n};\n\nconst MAX_REDIRECTS = 5;\nconst MAX_GUIDED_DOWNLOAD_FAILURE_ATTEMPTS = 3;\n\nconst PRESIGNED_URL_403_GUIDANCE =\n \"For presigned S3 or similar URLs, provide the exact original URL including every query parameter and signature token. A 403 usually means the URL was stripped, edited, expired, or the signature no longer matches.\";\n\nexport class NativeFileDownloadService {\n /**\n * Per-instance failure counter for guided download retries.\n * Kept as an instance field (not a module-level singleton) so that\n * different toolkit instances and multi-tenant server contexts do not\n * share failure state with each other.\n */\n private readonly guidedDownloadFailureAttempts = new Map<string, number>();\n\n constructor(private readonly serviceConfig: NativeFileDownloadServiceConfig) {}\n\n async downloadFile(\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n const { config } = this.serviceConfig;\n const validatedUrl = validateDownloadUrl(input.url, config);\n const overwrite = readOverwriteInput(input.overwrite);\n const artifactId = createArtifactId();\n const relativePath = resolveOutputRelativePath(\n input.fileName ??\n `${artifactId}-${fallbackFileNameForExecution(validatedUrl.url)}`,\n validatedUrl.url,\n );\n const outputPath = await prepareOutputArtifactPath(config, relativePath, {\n allowExistingFile: true,\n });\n const existingFile = await inspectExistingOutputFile(outputPath);\n const controller = new AbortController();\n const timeout = setTimeout(() => {\n controller.abort();\n }, config.downloadTimeoutMs);\n\n try {\n const { response, source } = await fetchAllowedResponse(\n validatedUrl,\n config,\n controller.signal,\n this.guidedDownloadFailureAttempts,\n );\n const contentType = response.headers.get(\"content-type\") ?? undefined;\n const contentLengthBytes = readContentLengthBytes(response);\n\n if (\n Number.isFinite(contentLengthBytes) &&\n contentLengthBytes > config.maxDownloadBytes\n ) {\n throw createDownloadTooLargeError({\n contentLengthBytes,\n maxDownloadBytes: config.maxDownloadBytes,\n });\n }\n\n if (\n existingFile &&\n !overwrite &&\n Number.isFinite(contentLengthBytes) &&\n existingFile.bytes === contentLengthBytes\n ) {\n await cancelResponseBody(response);\n\n const artifact = await this.registerExistingArtifact({\n artifactId,\n outputPath,\n bytes: existingFile.bytes,\n contentType,\n source,\n });\n\n return {\n toolName: \"download_file\",\n riskLevel: config.tools.downloadFile.riskLevel,\n data: downloadOutput(artifact, {\n status: \"existing\",\n message:\n \"Local file already exists with the same size. The download was skipped and the existing file was registered as an artifact.\",\n }),\n };\n }\n\n if (\n existingFile &&\n !overwrite &&\n Number.isFinite(contentLengthBytes) &&\n existingFile.bytes !== contentLengthBytes\n ) {\n await cancelResponseBody(response);\n\n return {\n toolName: \"download_file\",\n riskLevel: config.tools.downloadFile.riskLevel,\n data: existingFileRequiresConfirmationOutput({\n outputPath,\n source,\n existingBytes: existingFile.bytes,\n remoteBytes: contentLengthBytes,\n }),\n };\n }\n\n // When Content-Length is absent (streaming or chunked responses), we\n // cannot compare sizes before reading. We consume the full body up to\n // maxDownloadBytes here and then decide whether to keep or discard it.\n // This means up to maxDownloadBytes of data is downloaded before the\n // \"requires confirmation\" check fires for the no-Content-Length path.\n // Size-first short-circuiting is not possible without Content-Length.\n const body = await readBoundedResponseBody(response, config);\n const sha256 = createHash(\"sha256\").update(body).digest(\"hex\");\n\n if (existingFile && !overwrite) {\n if (existingFile.bytes === body.byteLength) {\n const artifact = await this.registerExistingArtifact({\n artifactId,\n outputPath,\n bytes: existingFile.bytes,\n contentType,\n source,\n });\n\n return {\n toolName: \"download_file\",\n riskLevel: config.tools.downloadFile.riskLevel,\n data: downloadOutput(artifact, {\n status: \"existing\",\n message:\n \"Local file already exists with the same size. The download was skipped and the existing file was registered as an artifact.\",\n }),\n };\n }\n\n return {\n toolName: \"download_file\",\n riskLevel: config.tools.downloadFile.riskLevel,\n data: existingFileRequiresConfirmationOutput({\n outputPath,\n source,\n existingBytes: existingFile.bytes,\n remoteBytes: body.byteLength,\n }),\n };\n }\n\n try {\n await fs.writeFile(outputPath.absolutePath, body, {\n flag: overwrite ? \"w\" : \"wx\",\n });\n } catch (error) {\n if (isNodeErrorCode(error, \"EEXIST\")) {\n const racedExistingFile = await inspectExistingOutputFile(outputPath);\n\n if (racedExistingFile?.bytes === body.byteLength) {\n const artifact = await this.registerExistingArtifact({\n artifactId,\n outputPath,\n bytes: racedExistingFile.bytes,\n contentType,\n source,\n });\n\n return {\n toolName: \"download_file\",\n riskLevel: config.tools.downloadFile.riskLevel,\n data: downloadOutput(artifact, {\n status: \"existing\",\n message:\n \"Local file already exists with the same size. The download was skipped and the existing file was registered as an artifact.\",\n }),\n };\n }\n\n return {\n toolName: \"download_file\",\n riskLevel: config.tools.downloadFile.riskLevel,\n data: existingFileRequiresConfirmationOutput({\n outputPath,\n source,\n existingBytes: racedExistingFile?.bytes,\n remoteBytes: body.byteLength,\n }),\n };\n }\n\n throw nativeFilesystemError(\n \"FILE_DOWNLOAD_FAILED\",\n \"download_file could not write the local artifact.\",\n error,\n {\n relativePath: outputPath.relativePath,\n },\n );\n }\n\n const artifact = this.serviceConfig.manifest.register({\n artifactId,\n relativePath: outputPath.relativePath,\n bytes: body.byteLength,\n sha256,\n ...(contentType ? { contentType } : {}),\n source,\n createdAt: new Date().toISOString(),\n });\n\n return {\n toolName: \"download_file\",\n riskLevel: config.tools.downloadFile.riskLevel,\n data: downloadOutput(artifact, {\n status: existingFile && overwrite ? \"overwritten\" : \"downloaded\",\n message:\n existingFile && overwrite\n ? \"Existing local file was overwritten after overwrite:true.\"\n : \"Remote file was downloaded into the local artifact root.\",\n }),\n };\n } catch (error) {\n if (isAbortError(error)) {\n throw nativeFileError({\n code: \"FILE_DOWNLOAD_TIMEOUT\",\n message: `download_file exceeded ${config.downloadTimeoutMs}ms.`,\n retryable: true,\n recoverable: true,\n });\n }\n\n throw error;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n async persistBufferedDownload({\n input,\n toolName,\n riskLevel,\n body,\n contentType,\n source,\n defaultFileName,\n }: {\n input: Record<string, unknown>;\n toolName: string;\n riskLevel: ZuoraRiskLevel;\n body: Buffer;\n contentType?: string;\n source: NativeFileSafeSource;\n defaultFileName: string;\n }): Promise<ZuoraToolExecutionResult> {\n const { config } = this.serviceConfig;\n\n if (body.byteLength > config.maxDownloadBytes) {\n throw createDownloadTooLargeError({\n contentLengthBytes: body.byteLength,\n maxDownloadBytes: config.maxDownloadBytes,\n });\n }\n\n const overwrite = readOverwriteInput(input.overwrite);\n const artifactId = createArtifactId();\n const relativePath = resolveOutputRelativePath(\n input.fileName ?? defaultFileName,\n new URL(`https://zuora.local/${encodeURIComponent(defaultFileName)}`),\n );\n const outputPath = await prepareOutputArtifactPath(config, relativePath, {\n allowExistingFile: true,\n });\n const existingFile = await inspectExistingOutputFile(outputPath);\n const remoteBytes = body.byteLength;\n\n if (\n existingFile &&\n !overwrite &&\n existingFile.bytes === remoteBytes\n ) {\n const artifact = await this.registerExistingArtifact({\n artifactId,\n outputPath,\n bytes: existingFile.bytes,\n contentType,\n source,\n });\n\n return {\n toolName,\n riskLevel,\n data: downloadOutput(artifact, {\n status: \"existing\",\n message:\n \"Local file already exists with the same size. The download was skipped and the existing file was registered as an artifact.\",\n }),\n };\n }\n\n if (existingFile && !overwrite && existingFile.bytes !== remoteBytes) {\n return {\n toolName,\n riskLevel,\n data: existingFileRequiresConfirmationOutput({\n outputPath,\n source,\n existingBytes: existingFile.bytes,\n remoteBytes,\n }),\n };\n }\n\n const sha256 = createHash(\"sha256\").update(body).digest(\"hex\");\n\n try {\n await fs.writeFile(outputPath.absolutePath, body, {\n flag: overwrite ? \"w\" : \"wx\",\n });\n } catch (error) {\n if (isNodeErrorCode(error, \"EEXIST\")) {\n const racedExistingFile = await inspectExistingOutputFile(outputPath);\n\n if (racedExistingFile?.bytes === body.byteLength) {\n const artifact = await this.registerExistingArtifact({\n artifactId,\n outputPath,\n bytes: racedExistingFile.bytes,\n contentType,\n source,\n });\n\n return {\n toolName,\n riskLevel,\n data: downloadOutput(artifact, {\n status: \"existing\",\n message:\n \"Local file already exists with the same size. The download was skipped and the existing file was registered as an artifact.\",\n }),\n };\n }\n\n return {\n toolName,\n riskLevel,\n data: existingFileRequiresConfirmationOutput({\n outputPath,\n source,\n existingBytes: racedExistingFile?.bytes,\n remoteBytes: body.byteLength,\n }),\n };\n }\n\n throw nativeFilesystemError(\n \"FILE_DOWNLOAD_FAILED\",\n `${toolName} could not write the local artifact.`,\n error,\n {\n relativePath: outputPath.relativePath,\n },\n );\n }\n\n const artifact = this.serviceConfig.manifest.register({\n artifactId,\n relativePath: outputPath.relativePath,\n bytes: body.byteLength,\n sha256,\n ...(contentType ? { contentType } : {}),\n source,\n createdAt: new Date().toISOString(),\n });\n\n return {\n toolName,\n riskLevel,\n data: downloadOutput(artifact, {\n status: existingFile && overwrite ? \"overwritten\" : \"downloaded\",\n message:\n existingFile && overwrite\n ? \"Existing local file was overwritten after overwrite:true.\"\n : \"Remote file was downloaded into the local artifact root.\",\n }),\n };\n }\n\n private async registerExistingArtifact({\n artifactId,\n outputPath,\n bytes,\n contentType,\n source,\n }: {\n artifactId: string;\n outputPath: { relativePath: string; absolutePath: string };\n bytes: number;\n contentType: string | undefined;\n source: NativeFileSafeSource;\n }): Promise<FileArtifactRecord> {\n const sha256 = await sha256File(outputPath.absolutePath);\n\n return this.serviceConfig.manifest.register({\n artifactId,\n relativePath: outputPath.relativePath,\n bytes,\n sha256,\n ...(contentType ? { contentType } : {}),\n source,\n createdAt: new Date().toISOString(),\n });\n }\n}\n\nconst fetchAllowedResponse = async (\n initialUrl: ValidatedNativeFileUrl,\n config: ResolvedNativeFileToolsConfig,\n signal: AbortSignal,\n failureAttempts: Map<string, number>,\n): Promise<DownloadedResponse> => {\n let currentUrl = initialUrl;\n\n for (let redirectCount = 0; redirectCount <= MAX_REDIRECTS; redirectCount += 1) {\n let response: Response;\n\n try {\n response = await fetch(currentUrl.url, {\n redirect: \"manual\",\n signal,\n });\n } catch (error) {\n if (isAbortError(error)) {\n throw error;\n }\n\n throw nativeFileError({\n code: \"FILE_DOWNLOAD_FAILED\",\n message: \"download_file could not open the remote URL.\",\n retryable: true,\n recoverable: true,\n details: {\n source: currentUrl.source,\n cause: error instanceof Error ? error.message : String(error),\n },\n });\n }\n\n if (isRedirectResponse(response.status)) {\n const location = response.headers.get(\"location\");\n\n if (!location) {\n throw nativeFileError({\n code: \"FILE_DOWNLOAD_FAILED\",\n message: \"Download redirect response did not include a location.\",\n retryable: true,\n recoverable: true,\n details: {\n source: currentUrl.source,\n status: response.status,\n },\n });\n }\n\n currentUrl = validateRedirectUrl(location, currentUrl.url, config);\n continue;\n }\n\n if (!response.ok) {\n const failure = recordGuidedDownloadFailure(currentUrl.source, response.status, failureAttempts);\n const guidance = downloadFailureGuidance(response.status, failure.attempt);\n\n throw nativeFileError({\n code: \"FILE_DOWNLOAD_FAILED\",\n message: guidance\n ? `Download failed with HTTP status ${response.status}. ${guidance}`\n : `Download failed with HTTP status ${response.status}.`,\n retryable: response.status >= 500,\n recoverable: guidance ? failure.shouldRetry : true,\n details: {\n source: currentUrl.source,\n status: response.status,\n downloadAttempt: failure.attempt,\n maxSuggestedAttempts: MAX_GUIDED_DOWNLOAD_FAILURE_ATTEMPTS,\n ...(guidance ? { guidance } : {}),\n },\n });\n }\n\n clearGuidedDownloadFailure(currentUrl.source, failureAttempts);\n\n return {\n response,\n source: currentUrl.source,\n };\n }\n\n throw nativeFileError({\n code: \"FILE_DOWNLOAD_FAILED\",\n message: `Download exceeded ${MAX_REDIRECTS} redirects.`,\n recoverable: true,\n details: {\n source: initialUrl.source,\n },\n });\n};\n\nconst recordGuidedDownloadFailure = (\n source: NativeFileSafeSource,\n status: number,\n failureAttempts: Map<string, number>,\n): {\n attempt: number;\n shouldRetry: boolean;\n} => {\n const key = guidedDownloadFailureKey(source, status);\n const attempt = (failureAttempts.get(key) ?? 0) + 1;\n\n failureAttempts.set(key, attempt);\n\n return {\n attempt,\n shouldRetry: attempt < MAX_GUIDED_DOWNLOAD_FAILURE_ATTEMPTS,\n };\n};\n\nconst clearGuidedDownloadFailure = (\n source: NativeFileSafeSource,\n failureAttempts: Map<string, number>,\n): void => {\n failureAttempts.delete(guidedDownloadFailureKey(source, 403));\n};\n\nconst guidedDownloadFailureKey = (\n source: NativeFileSafeSource,\n status: number,\n): string => `${status}:${source.redactedUrl}`;\n\nconst downloadFailureGuidance = (\n status: number,\n attempt: number,\n): string | undefined => {\n if (status !== 403) {\n return undefined;\n }\n\n if (attempt >= MAX_GUIDED_DOWNLOAD_FAILURE_ATTEMPTS) {\n return `${PRESIGNED_URL_403_GUIDANCE} This is the third failed attempt for this download, so stop retrying this URL and ask the user for a fresh exact dataFile URL or to rerun the query.`;\n }\n\n return `${PRESIGNED_URL_403_GUIDANCE} Retry only with the exact dataFile/download URL from the tool result. Stop retrying after ${MAX_GUIDED_DOWNLOAD_FAILURE_ATTEMPTS} failed attempts.`;\n};\n\nconst readBoundedResponseBody = async (\n response: Response,\n config: ResolvedNativeFileToolsConfig,\n): Promise<Buffer> => {\n const contentLengthBytes = readContentLengthBytes(response);\n\n if (\n Number.isFinite(contentLengthBytes) &&\n contentLengthBytes > config.maxDownloadBytes\n ) {\n throw createDownloadTooLargeError({\n contentLengthBytes,\n maxDownloadBytes: config.maxDownloadBytes,\n });\n }\n\n if (!response.body) {\n return Buffer.alloc(0);\n }\n\n const reader = response.body.getReader();\n const chunks: Buffer[] = [];\n let totalBytes = 0;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n totalBytes += value.byteLength;\n\n if (totalBytes > config.maxDownloadBytes) {\n throw nativeFileError({\n code: \"FILE_DOWNLOAD_TOO_LARGE\",\n message: `Remote file exceeded the configured ${config.maxDownloadBytes} byte download limit.`,\n recoverable: true,\n details: {\n maxDownloadBytes: config.maxDownloadBytes,\n },\n });\n }\n\n chunks.push(Buffer.from(value));\n }\n\n return Buffer.concat(chunks, totalBytes);\n};\n\nconst readContentLengthBytes = (response: Response): number => {\n const contentLength = response.headers.get(\"content-length\");\n\n if (!contentLength) {\n return Number.NaN;\n }\n\n const parsed = Number.parseInt(contentLength, 10);\n\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : Number.NaN;\n};\n\nconst createDownloadTooLargeError = ({\n contentLengthBytes,\n maxDownloadBytes,\n}: {\n contentLengthBytes: number;\n maxDownloadBytes: number;\n}): ZuoraAgentToolkitError =>\n nativeFileError({\n code: \"FILE_DOWNLOAD_TOO_LARGE\",\n message: `Remote file is larger than the configured ${maxDownloadBytes} byte download limit.`,\n recoverable: true,\n details: {\n contentLengthBytes,\n maxDownloadBytes,\n },\n });\n\nconst cancelResponseBody = async (response: Response): Promise<void> => {\n try {\n await response.body?.cancel();\n } catch {\n // Best-effort cleanup after making a decision from response headers.\n }\n};\n\nconst readOverwriteInput = (value: unknown): boolean => {\n if (value === undefined) {\n return false;\n }\n\n if (typeof value !== \"boolean\") {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"download_file overwrite must be a boolean.\",\n recoverable: true,\n });\n }\n\n return value;\n};\n\nconst inspectExistingOutputFile = async (outputPath: {\n absolutePath: string;\n relativePath: string;\n}): Promise<{ bytes: number } | undefined> => {\n try {\n const stat = await fs.stat(outputPath.absolutePath);\n\n if (!stat.isFile()) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"download_file output path already exists and is not a file.\",\n recoverable: true,\n details: {\n relativePath: outputPath.relativePath,\n },\n });\n }\n\n return {\n bytes: stat.size,\n };\n } catch (error) {\n if (isNodeErrorCode(error, \"ENOENT\")) {\n return undefined;\n }\n\n if (error instanceof ZuoraAgentToolkitError) {\n throw error;\n }\n\n throw nativeFilesystemError(\n \"FILE_PATH_NOT_ALLOWED\",\n \"Could not inspect the native file artifact output path.\",\n error,\n {\n relativePath: outputPath.relativePath,\n },\n );\n }\n};\n\nconst sha256File = async (absolutePath: string): Promise<string> => {\n const body = await fs.readFile(absolutePath);\n\n return createHash(\"sha256\").update(body).digest(\"hex\");\n};\n\nconst downloadOutput = (\n artifact: FileArtifactRecord,\n metadata: {\n status: \"downloaded\" | \"existing\" | \"overwritten\";\n message: string;\n },\n): Record<string, unknown> => ({\n status: metadata.status,\n message: metadata.message,\n requiresConfirmation: false,\n artifactId: artifact.artifactId,\n path: artifact.relativePath,\n bytes: artifact.bytes,\n sha256: artifact.sha256,\n ...(artifact.contentType ? { contentType: artifact.contentType } : {}),\n source: artifact.source,\n});\n\nconst existingFileRequiresConfirmationOutput = ({\n outputPath,\n source,\n existingBytes,\n remoteBytes,\n}: {\n outputPath: { relativePath: string };\n source: NativeFileSafeSource;\n existingBytes?: number | undefined;\n remoteBytes: number;\n}): Record<string, unknown> => ({\n status: \"requires_confirmation\",\n message:\n \"Local file already exists with a different size. Ask the user whether to overwrite it, then retry download_file with the same url, same fileName, and overwrite:true only if the user confirms.\",\n requiresConfirmation: true,\n path: outputPath.relativePath,\n ...(typeof existingBytes === \"number\" ? { existingBytes } : {}),\n remoteBytes,\n source,\n});\n\nconst createArtifactId = (): string =>\n `artifact_${Date.now().toString(36)}_${randomBytes(6).toString(\"hex\")}`;\n\nconst fallbackFileNameForExecution = (url: URL): string => {\n const rawBaseName = path.posix.basename(url.pathname) || \"downloaded-file\";\n\n try {\n return decodeURIComponent(rawBaseName);\n } catch {\n return rawBaseName;\n }\n};\n\nconst isRedirectResponse = (status: number): boolean =>\n status >= 300 && status < 400;\n\nconst isAbortError = (error: unknown): boolean =>\n error instanceof Error && error.name === \"AbortError\";\n\nconst isNodeErrorCode = (error: unknown, code: string): boolean =>\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === code;\n\nconst nativeFilesystemError = (\n code: \"FILE_DOWNLOAD_FAILED\" | \"FILE_PATH_NOT_ALLOWED\",\n message: string,\n error: unknown,\n details: Record<string, unknown>,\n): ZuoraAgentToolkitError =>\n nativeFileError({\n code,\n message,\n recoverable: true,\n details: {\n ...details,\n cause: error instanceof Error ? error.message : String(error),\n },\n });\n","import { ZuoraAgentToolkitError } from \"../../../errors.js\";\n\nexport type NativeFileErrorCode =\n | \"NATIVE_FILE_TOOLS_DISABLED\"\n | \"NATIVE_FILE_CONFIG_INVALID\"\n | \"FILE_URL_NOT_ALLOWED\"\n | \"FILE_URL_INVALID\"\n | \"FILE_DOWNLOAD_TOO_LARGE\"\n | \"FILE_DOWNLOAD_TIMEOUT\"\n | \"FILE_DOWNLOAD_FAILED\"\n | \"FILE_PATH_NOT_ALLOWED\"\n | \"FILE_ARTIFACT_NOT_FOUND\"\n | \"FILE_READ_TOO_LARGE\"\n | \"FILE_ARCHIVE_NOT_ALLOWED\"\n | \"FILE_ARCHIVE_UNSAFE_ENTRY\"\n | \"FILE_ARCHIVE_TOO_LARGE\";\n\nexport const nativeFileError = (params: {\n code: NativeFileErrorCode;\n message: string;\n retryable?: boolean;\n recoverable?: boolean;\n details?: unknown;\n}): ZuoraAgentToolkitError =>\n new ZuoraAgentToolkitError({\n code: params.code,\n message: params.message,\n category: \"native_file_tools\",\n ...(params.retryable !== undefined ? { retryable: params.retryable } : {}),\n recoverable: params.recoverable ?? true,\n ...(params.details !== undefined ? { details: params.details } : {}),\n });\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { ZuoraAgentToolkitError } from \"../../../errors.js\";\nimport type { ResolvedNativeFileToolsConfig } from \"./config.js\";\nimport { nativeFileError } from \"./errors.js\";\nimport { normalizeManifestPath } from \"./manifest.js\";\n\nexport type ResolvedArtifactPath = {\n rootRealPath: string;\n absolutePath: string;\n relativePath: string;\n};\n\nexport type PrepareOutputArtifactPathOptions = {\n allowExistingFile?: boolean;\n};\n\nexport const resolveOutputRelativePath = (\n inputFileName: unknown,\n sourceUrl: URL,\n): string => {\n const requested =\n typeof inputFileName === \"string\" && inputFileName.trim()\n ? inputFileName.trim()\n : fallbackFileNameFromUrl(sourceUrl);\n\n return normalizeSafeRelativePath(requested);\n};\n\nexport const resolveInputRelativePath = (inputPath: unknown): string => {\n if (typeof inputPath !== \"string\" || !inputPath.trim()) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"A non-empty artifact path is required.\",\n });\n }\n\n return normalizeSafeRelativePath(inputPath.trim());\n};\n\nexport const prepareOutputArtifactPath = async (\n config: ResolvedNativeFileToolsConfig,\n relativePath: string,\n options: PrepareOutputArtifactPathOptions = {},\n): Promise<ResolvedArtifactPath> => {\n const rootRealPath = await prepareRoot(config);\n const resolved = resolveUnderRoot(rootRealPath, relativePath);\n\n await assertNoSymlinkComponents(rootRealPath, relativePath, {\n includeLeaf: true,\n missingLeafOk: true,\n });\n\n try {\n await fs.mkdir(path.dirname(resolved.absolutePath), { recursive: true });\n } catch (error) {\n throw nativePathFilesystemError(\n \"Could not create the native file artifact output directory.\",\n error,\n {\n relativePath,\n },\n );\n }\n\n await assertNoSymlinkComponents(rootRealPath, relativePath, {\n includeLeaf: true,\n missingLeafOk: true,\n });\n\n if (!config.allowOverwrite && !options.allowExistingFile) {\n try {\n await fs.lstat(resolved.absolutePath);\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message:\n \"download_file would overwrite an existing artifact and allowOverwrite is false.\",\n details: {\n relativePath,\n },\n });\n } catch (error) {\n if (isNodeErrorCode(error, \"ENOENT\")) {\n return resolved;\n }\n\n if (error instanceof ZuoraAgentToolkitError) {\n throw error;\n }\n\n throw nativePathFilesystemError(\n \"Could not inspect the native file artifact output path.\",\n error,\n {\n relativePath,\n },\n );\n }\n }\n\n return resolved;\n};\n\nexport const resolveRegisteredArtifactPath = async (\n config: ResolvedNativeFileToolsConfig,\n relativePath: string,\n): Promise<ResolvedArtifactPath> => {\n const rootRealPath = await prepareRoot(config);\n const resolved = resolveUnderRoot(rootRealPath, relativePath);\n\n await assertNoSymlinkComponents(rootRealPath, relativePath, {\n includeLeaf: true,\n missingLeafOk: false,\n });\n\n let realPath: string;\n\n try {\n realPath = await fs.realpath(resolved.absolutePath);\n } catch (error) {\n if (isNodeErrorCode(error, \"ENOENT\")) {\n throw error;\n }\n\n throw nativePathFilesystemError(\n \"Could not resolve the registered native file artifact path.\",\n error,\n {\n relativePath,\n },\n );\n }\n\n if (!isPathInside(realPath, rootRealPath)) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"Artifact path resolves outside the configured file artifact root.\",\n details: {\n relativePath,\n },\n });\n }\n\n return {\n ...resolved,\n absolutePath: realPath,\n };\n};\n\nexport const assertRootPolicy = async (\n config: ResolvedNativeFileToolsConfig,\n): Promise<string> => prepareRoot(config);\n\nconst prepareRoot = async (\n config: ResolvedNativeFileToolsConfig,\n): Promise<string> => {\n const userHomeRealPath = await resolveRealPathIfPossible(\n config.userHomeDirAbsolute,\n );\n const userHomeAbsolutePath = path.resolve(config.userHomeDirAbsolute);\n\n if (\n config.requireRootUnderUserHome &&\n !isPathInside(config.rootDirAbsolute, userHomeAbsolutePath)\n ) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message:\n \"Configured native file artifact root resolves outside the configured user home directory.\",\n details: {\n rootDir: config.rootDirAbsolute,\n userHomeDir: config.userHomeDirAbsolute,\n },\n });\n }\n\n if (config.requireRootUnderUserHome) {\n await assertNoExistingSymlinkComponents(\n userHomeAbsolutePath,\n config.rootDirAbsolute,\n );\n }\n\n try {\n await fs.mkdir(config.rootDirAbsolute, { recursive: true });\n } catch (error) {\n throw nativePathFilesystemError(\n \"Could not create the native file artifact root directory.\",\n error,\n {\n rootDir: config.rootDirAbsolute,\n },\n );\n }\n\n let rootRealPath: string;\n\n try {\n rootRealPath = await fs.realpath(config.rootDirAbsolute);\n } catch (error) {\n throw nativePathFilesystemError(\n \"Could not resolve the native file artifact root directory.\",\n error,\n {\n rootDir: config.rootDirAbsolute,\n },\n );\n }\n\n if (\n config.requireRootUnderUserHome &&\n !isPathInside(rootRealPath, userHomeRealPath)\n ) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message:\n \"Configured native file artifact root resolves outside the configured user home directory.\",\n details: {\n rootDir: config.rootDirAbsolute,\n userHomeDir: config.userHomeDirAbsolute,\n },\n });\n }\n\n return rootRealPath;\n};\n\nconst resolveRealPathIfPossible = async (targetPath: string): Promise<string> => {\n try {\n return await fs.realpath(targetPath);\n } catch {\n return path.resolve(targetPath);\n }\n};\n\nconst resolveUnderRoot = (\n rootRealPath: string,\n relativePath: string,\n): ResolvedArtifactPath => {\n const normalizedRelativePath = normalizeSafeRelativePath(relativePath);\n const absolutePath = path.resolve(rootRealPath, normalizedRelativePath);\n\n if (!isPathInside(absolutePath, rootRealPath)) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"Artifact path must stay under the configured file artifact root.\",\n details: {\n relativePath: normalizedRelativePath,\n },\n });\n }\n\n return {\n rootRealPath,\n absolutePath,\n relativePath: normalizedRelativePath,\n };\n};\n\nconst assertNoSymlinkComponents = async (\n rootRealPath: string,\n relativePath: string,\n options: {\n includeLeaf: boolean;\n missingLeafOk: boolean;\n },\n): Promise<void> => {\n const components = normalizeManifestPath(relativePath).split(\"/\").filter(Boolean);\n const componentsToCheck = options.includeLeaf\n ? components\n : components.slice(0, -1);\n let current = rootRealPath;\n\n for (let index = 0; index < componentsToCheck.length; index += 1) {\n current = path.join(current, componentsToCheck[index]!);\n\n try {\n const stat = await fs.lstat(current);\n\n if (stat.isSymbolicLink()) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"File artifact paths must not traverse symlinks.\",\n details: {\n relativePath,\n },\n });\n }\n } catch (error) {\n if (\n isNodeErrorCode(error, \"ENOENT\") &&\n (options.missingLeafOk || index < componentsToCheck.length - 1)\n ) {\n // A missing component means the path (or a sub-path of it) does not yet\n // exist on disk, so there is nothing to resolve as a symlink right now.\n // Returning early here is safe because:\n // 1. A non-existent directory cannot be a symlink, and future components\n // under it cannot exist either.\n // 2. `prepareOutputArtifactPath` calls this function a second time after\n // `fs.mkdir()` has created any necessary parent directories, catching\n // any symlink introduced between the two checks (TOCTOU mitigation).\n return;\n }\n\n if (error instanceof ZuoraAgentToolkitError) {\n throw error;\n }\n\n throw nativePathFilesystemError(\n \"Could not inspect native file artifact path components.\",\n error,\n {\n relativePath,\n },\n );\n }\n }\n};\n\nconst assertNoExistingSymlinkComponents = async (\n rootRealPath: string,\n candidatePath: string,\n): Promise<void> => {\n const relative = path.relative(rootRealPath, candidatePath);\n\n if (relative === \"\") {\n return;\n }\n\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"Configured native file artifact root must stay under user home.\",\n details: {\n rootDir: candidatePath,\n userHomeDir: rootRealPath,\n },\n });\n }\n\n await assertNoSymlinkComponents(rootRealPath, relative, {\n includeLeaf: true,\n missingLeafOk: true,\n });\n};\n\nconst normalizeSafeRelativePath = (rawPath: string): string => {\n if (rawPath.includes(\"\\0\")) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"Artifact paths must not contain null bytes.\",\n });\n }\n\n const slashPath = rawPath.replace(/\\\\/g, \"/\");\n\n if (path.isAbsolute(slashPath) || slashPath.startsWith(\"/\")) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"Artifact paths must be relative.\",\n details: {\n relativePath: rawPath,\n },\n });\n }\n\n const normalized = normalizeManifestPath(path.posix.normalize(slashPath));\n\n if (!normalized || normalized === \".\") {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"Artifact paths must not be empty.\",\n });\n }\n\n if (\n normalized === \"..\" ||\n normalized.startsWith(\"../\") ||\n normalized.split(\"/\").includes(\"..\")\n ) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"Artifact paths must not traverse outside the artifact root.\",\n details: {\n relativePath: rawPath,\n },\n });\n }\n\n return normalized;\n};\n\nconst fallbackFileNameFromUrl = (url: URL): string => {\n const rawBaseName = path.posix.basename(url.pathname) || \"downloaded-file\";\n const decodedBaseName = safeDecodeURIComponent(rawBaseName);\n const sanitized = decodedBaseName\n .replace(/[^A-Za-z0-9._-]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\n return sanitized || \"downloaded-file\";\n};\n\nconst safeDecodeURIComponent = (value: string): string => {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n};\n\nconst isPathInside = (candidate: string, root: string): boolean => {\n const relative = path.relative(root, candidate);\n\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n};\n\nconst isNodeErrorCode = (error: unknown, code: string): boolean =>\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === code;\n\nconst nativePathFilesystemError = (\n message: string,\n error: unknown,\n details: Record<string, unknown>,\n): ZuoraAgentToolkitError =>\n nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message,\n recoverable: true,\n details: {\n ...details,\n cause: error instanceof Error ? error.message : String(error),\n },\n });\n","import type { NativeFileSafeSource } from \"./url-policy.js\";\n\nexport type FileArtifactRecord = {\n artifactId: string;\n relativePath: string;\n bytes: number;\n sha256: string;\n contentType?: string;\n source: NativeFileSafeSource;\n createdAt: string;\n};\n\nexport class FileArtifactManifest {\n private readonly byId = new Map<string, FileArtifactRecord>();\n\n private readonly byPath = new Map<string, FileArtifactRecord>();\n\n register(record: FileArtifactRecord): FileArtifactRecord {\n this.byId.set(record.artifactId, record);\n this.byPath.set(normalizeManifestPath(record.relativePath), record);\n\n return record;\n }\n\n getById(artifactId: string): FileArtifactRecord | undefined {\n return this.byId.get(artifactId);\n }\n\n getByRelativePath(relativePath: string): FileArtifactRecord | undefined {\n return this.byPath.get(normalizeManifestPath(relativePath));\n }\n}\n\nexport const normalizeManifestPath = (relativePath: string): string =>\n relativePath.replace(/\\\\/g, \"/\").replace(/^\\/+/, \"\");\n","import type { ResolvedNativeFileToolsConfig } from \"./config.js\";\nimport { nativeFileError } from \"./errors.js\";\n\nexport type NativeFileSafeSource = {\n protocol: string;\n host: string;\n path: string;\n redactedUrl: string;\n kind: \"s3-presigned\" | \"zuora-public\" | \"http\";\n};\n\nexport type ValidatedNativeFileUrl = {\n url: URL;\n source: NativeFileSafeSource;\n};\n\nexport const validateDownloadUrl = (\n rawUrl: unknown,\n config: ResolvedNativeFileToolsConfig,\n): ValidatedNativeFileUrl => {\n if (typeof rawUrl !== \"string\" || !rawUrl.trim()) {\n throw nativeFileError({\n code: \"FILE_URL_INVALID\",\n message: \"download_file requires a non-empty absolute URL.\",\n details: {\n expected: \"absolute HTTP(S) URL\",\n },\n });\n }\n\n let url: URL;\n\n try {\n url = new URL(rawUrl.trim());\n } catch {\n throw nativeFileError({\n code: \"FILE_URL_INVALID\",\n message: \"download_file received an invalid URL.\",\n details: {\n expected: \"absolute HTTP(S) URL\",\n },\n });\n }\n\n return validateParsedDownloadUrl(url, config);\n};\n\nexport const validateRedirectUrl = (\n rawUrl: string,\n baseUrl: URL,\n config: ResolvedNativeFileToolsConfig,\n): ValidatedNativeFileUrl => {\n let url: URL;\n\n try {\n url = new URL(rawUrl, baseUrl);\n } catch {\n throw nativeFileError({\n code: \"FILE_URL_INVALID\",\n message: \"Download redirect returned an invalid URL.\",\n details: {\n source: safeSourceFromUrl(baseUrl, config),\n },\n });\n }\n\n return validateParsedDownloadUrl(url, config);\n};\n\nexport const redactUrl = (url: URL): string => {\n const redacted = new URL(url.toString());\n redacted.username = \"\";\n redacted.password = \"\";\n redacted.search = \"\";\n redacted.hash = \"\";\n\n return redacted.toString();\n};\n\nconst validateParsedDownloadUrl = (\n url: URL,\n config: ResolvedNativeFileToolsConfig,\n): ValidatedNativeFileUrl => {\n if (!url.protocol || !url.hostname) {\n throw nativeFileError({\n code: \"FILE_URL_INVALID\",\n message: \"download_file requires an absolute URL with a host.\",\n });\n }\n\n if (url.username || url.password) {\n throw nativeFileError({\n code: \"FILE_URL_INVALID\",\n message: \"download_file rejects URLs with embedded credentials.\",\n details: {\n source: safeSourceFromUrl(url, config),\n },\n });\n }\n\n if (!config.allowedProtocols.includes(url.protocol)) {\n throw nativeFileError({\n code: \"FILE_URL_NOT_ALLOWED\",\n message: `URL protocol ${url.protocol} is not allowed for native file downloads.`,\n details: {\n source: safeSourceFromUrl(url, config),\n allowedProtocols: config.allowedProtocols,\n },\n });\n }\n\n // `allowedUrlPrefixes` is an independent allowlist, not a supplement to\n // `allowedHosts`. A URL is accepted if EITHER its host is in `allowedHosts`\n // (including S3 virtual-hosted matching) OR its full URL prefix matches an\n // entry in `allowedUrlPrefixes`. The two lists are evaluated with OR semantics\n // so that callers can configure one, the other, or both.\n if (!hostAllowed(url, config) && !prefixMatches(url, config.allowedUrlPrefixes)) {\n throw nativeFileError({\n code: \"FILE_URL_NOT_ALLOWED\",\n message: \"URL host or prefix is not allowed for native file downloads.\",\n details: {\n source: safeSourceFromUrl(url, config),\n },\n });\n }\n\n return {\n url,\n source: safeSourceFromUrl(url, config),\n };\n};\n\nconst safeSourceFromUrl = (\n url: URL,\n config: ResolvedNativeFileToolsConfig,\n): NativeFileSafeSource => ({\n protocol: url.protocol,\n host: url.host.toLowerCase(),\n path: url.pathname,\n redactedUrl: redactUrl(url),\n kind: classifySource(url, config),\n});\n\nconst classifySource = (\n url: URL,\n config: ResolvedNativeFileToolsConfig,\n): NativeFileSafeSource[\"kind\"] => {\n const host = url.hostname.toLowerCase();\n\n if (config.zuoraDownloadHosts.includes(host)) {\n return \"zuora-public\";\n }\n\n if (\n config.allowS3PresignedDownload &&\n (host.includes(\".s3.\") ||\n host.endsWith(\".s3.amazonaws.com\") ||\n host.endsWith(\".amazonaws.com\")) &&\n hasPresignedUrlQuery(url)\n ) {\n return \"s3-presigned\";\n }\n\n return \"http\";\n};\n\nconst hasPresignedUrlQuery = (url: URL): boolean => {\n for (const key of url.searchParams.keys()) {\n if (/^(x-amz-|x-goog-|signature|sig|expires|token)/i.test(key)) {\n return true;\n }\n }\n\n return false;\n};\n\nconst hostAllowed = (\n url: URL,\n config: ResolvedNativeFileToolsConfig,\n): boolean =>\n hostMatches(url.host, config.allowedHosts) ||\n hostMatches(url.hostname, config.allowedHosts) ||\n s3VirtualHostedEndpointMatches(url, config);\n\nconst hostMatches = (host: string, allowedHosts: string[]): boolean => {\n const normalizedHost = host.toLowerCase();\n\n return allowedHosts.some((allowedHost) => {\n const normalizedAllowedHost = allowedHost.toLowerCase();\n\n if (normalizedAllowedHost.startsWith(\"*.\")) {\n const suffix = normalizedAllowedHost.slice(1);\n\n return (\n normalizedHost.length > suffix.length && normalizedHost.endsWith(suffix)\n );\n }\n\n return normalizedHost === normalizedAllowedHost;\n });\n};\n\nconst s3VirtualHostedEndpointMatches = (\n url: URL,\n config: ResolvedNativeFileToolsConfig,\n): boolean => {\n if (!config.allowS3PresignedDownload || !hasPresignedUrlQuery(url)) {\n return false;\n }\n\n const host = url.hostname.toLowerCase();\n\n return config.allowedHosts.some((allowedHost) => {\n const normalizedAllowedHost = allowedHost.toLowerCase();\n\n return (\n isS3RegionalEndpointHost(normalizedAllowedHost) &&\n host.length > normalizedAllowedHost.length + 1 &&\n host.endsWith(`.${normalizedAllowedHost}`)\n );\n });\n};\n\nconst isS3RegionalEndpointHost = (host: string): boolean =>\n host === \"s3.amazonaws.com\" || /^s3[.-][a-z0-9-]+\\.amazonaws\\.com$/.test(host);\n\nconst prefixMatches = (url: URL, allowedPrefixes: string[]): boolean =>\n allowedPrefixes.some((prefix) => {\n let allowedUrl: URL;\n\n try {\n allowedUrl = new URL(prefix);\n } catch {\n return false;\n }\n\n if (url.protocol !== allowedUrl.protocol) {\n return false;\n }\n\n if (url.host.toLowerCase() !== allowedUrl.host.toLowerCase()) {\n return false;\n }\n\n return pathPrefixMatches(url.pathname, allowedUrl.pathname);\n });\n\nconst pathPrefixMatches = (pathName: string, allowedPathName: string): boolean => {\n if (!allowedPathName || allowedPathName === \"/\") {\n return true;\n }\n\n const normalizedAllowedPath = allowedPathName.endsWith(\"/\")\n ? allowedPathName\n : `${allowedPathName}/`;\n\n return pathName === allowedPathName || pathName.startsWith(normalizedAllowedPath);\n};\n","import fs from \"node:fs/promises\";\n\nimport type { ZuoraAgentToolkitError } from \"../../../errors.js\";\nimport { nativeFileError } from \"./errors.js\";\n\nexport const readFilePrefix = async (\n absolutePath: string,\n maxBytes: number,\n): Promise<{\n buffer: Buffer;\n bytesRead: number;\n truncatedByBytes: boolean;\n}> => {\n const handle = await fs.open(absolutePath, \"r\");\n\n try {\n const buffer = Buffer.alloc(maxBytes + 1);\n const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);\n const boundedBytes = Math.min(bytesRead, maxBytes);\n\n return {\n buffer: buffer.subarray(0, boundedBytes),\n bytesRead: boundedBytes,\n truncatedByBytes: bytesRead > maxBytes,\n };\n } finally {\n await handle.close();\n }\n};\n\nexport const capPositiveInteger = (\n value: unknown,\n fallback: number,\n maximum: number,\n name: string,\n): number => {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 1) {\n throw nativeFileError({\n code: \"FILE_READ_TOO_LARGE\",\n message: `read_downloaded_file ${name} must be a positive integer.`,\n recoverable: true,\n });\n }\n\n return Math.min(value, maximum);\n};\n\nexport const looksBinary = (buffer: Buffer): boolean => buffer.includes(0);\n\nexport const isNodeErrorCode = (error: unknown, code: string): boolean =>\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === code;\n\nexport const nativeFilesystemError = (\n code: \"FILE_DOWNLOAD_FAILED\" | \"FILE_PATH_NOT_ALLOWED\",\n message: string,\n error: unknown,\n details: Record<string, unknown>,\n): ZuoraAgentToolkitError =>\n nativeFileError({\n code,\n message,\n recoverable: true,\n details: {\n ...details,\n cause: error instanceof Error ? error.message : String(error),\n },\n });\n","import type {\n NativeToolApprovalMetadata,\n ZuoraToolDefinition,\n ZuoraToolExecutionResult,\n} from \"../../types.js\";\n\nexport type NativeToolExecutor = (\n input: Record<string, unknown>,\n) => Promise<ZuoraToolExecutionResult>;\n\nexport type NativeToolApprovalMetadataFactory = (\n input: Record<string, unknown>,\n) => NativeToolApprovalMetadata | undefined;\n\nexport type NativeRuntimeTool = {\n definition: ZuoraToolDefinition;\n execute: NativeToolExecutor;\n approvalMetadata: NativeToolApprovalMetadataFactory;\n};\n\nexport type NativeToolSet = {\n listTools: () => NativeRuntimeTool[];\n};\n\nexport const createNativeRuntimeTool = ({\n definition,\n execute,\n approvalMetadata = () => undefined,\n}: {\n definition: ZuoraToolDefinition;\n execute: NativeToolExecutor;\n approvalMetadata?: NativeToolApprovalMetadataFactory;\n}): NativeRuntimeTool => ({\n definition,\n execute,\n approvalMetadata,\n});\n","import type {\n NativeFileApprovalMetadata,\n NativeFileToolsConfig,\n ZuoraMcpClient,\n ZuoraToolExecutionResult,\n} from \"../../../types.js\";\nimport {\n type ResolvedNativeFileToolsConfig,\n resolveNativeFileToolsConfig,\n} from \"./config.js\";\nimport {\n createDownloadFileToolDefinition,\n createReadDownloadedFileToolDefinition,\n createReadResourceToolDefinition,\n} from \"./definitions.js\";\nimport { NativeFileDownloadService } from \"./download-service.js\";\nimport { nativeFileError } from \"./errors.js\";\nimport {\n capPositiveInteger,\n isNodeErrorCode,\n looksBinary,\n nativeFilesystemError,\n readFilePrefix,\n} from \"./helpers.js\";\nimport {\n type FileArtifactRecord,\n FileArtifactManifest,\n} from \"./manifest.js\";\nimport {\n resolveInputRelativePath,\n resolveOutputRelativePath,\n resolveRegisteredArtifactPath,\n} from \"./path-policy.js\";\nimport { validateDownloadUrl } from \"./url-policy.js\";\nimport {\n createNativeRuntimeTool,\n type NativeRuntimeTool,\n type NativeToolSet,\n} from \"../registry-source.js\";\n\nexport type NativeFileArtifactToolsOptions = {\n /**\n * Optional MCP client used by read_resource to resolve MCP resource URIs.\n * When absent, read_resource will throw a runtime error.\n */\n mcpClient?: ZuoraMcpClient;\n};\n\nexport class NativeFileArtifactTools implements NativeToolSet {\n private readonly config: ResolvedNativeFileToolsConfig;\n\n private readonly manifest = new FileArtifactManifest();\n\n private readonly downloadService: NativeFileDownloadService;\n\n private readonly mcpClient: ZuoraMcpClient | undefined;\n\n constructor(\n config: NativeFileToolsConfig | undefined,\n options: NativeFileArtifactToolsOptions = {},\n ) {\n this.config = resolveNativeFileToolsConfig(config);\n this.mcpClient = options.mcpClient;\n this.downloadService = new NativeFileDownloadService({\n config: this.config,\n manifest: this.manifest,\n });\n }\n\n listTools(): NativeRuntimeTool[] {\n if (!this.config.enabled) {\n return [];\n }\n\n return [\n ...(this.config.tools.downloadFile.enabled\n ? [this.createDownloadFileTool()]\n : []),\n ...(this.config.tools.readDownloadedFile.enabled\n ? [this.createReadDownloadedFileTool()]\n : []),\n ...(this.config.tools.readResource.enabled\n ? [this.createReadResourceTool()]\n : []),\n ];\n }\n\n isEnabled(): boolean {\n return this.config.enabled;\n }\n\n private createDownloadFileTool(): NativeRuntimeTool {\n return createNativeRuntimeTool({\n definition: createDownloadFileToolDefinition(this.config),\n execute: (input) => this.downloadFile(input),\n approvalMetadata: (input) => this.createDownloadApprovalMetadata(input),\n });\n }\n\n private createReadDownloadedFileTool(): NativeRuntimeTool {\n return createNativeRuntimeTool({\n definition: createReadDownloadedFileToolDefinition(this.config),\n execute: (input) => this.readDownloadedFile(input),\n approvalMetadata: (input) => this.createReadApprovalMetadata(input),\n });\n }\n\n private createReadResourceTool(): NativeRuntimeTool {\n return createNativeRuntimeTool({\n definition: createReadResourceToolDefinition(this.config),\n execute: (input) => this.readResource(input),\n });\n }\n\n async downloadFile(\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n return this.downloadService.downloadFile(input);\n }\n\n async persistBufferedDownload(\n options: Parameters<NativeFileDownloadService[\"persistBufferedDownload\"]>[0],\n ): Promise<ZuoraToolExecutionResult> {\n return this.downloadService.persistBufferedDownload(options);\n }\n\n private async readDownloadedFile(\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n const artifact = this.resolveArtifact(input);\n const maxBytes = capPositiveInteger(\n input.maxBytes,\n this.config.maxReadBytes,\n this.config.maxReadBytes,\n \"maxBytes\",\n );\n const maxLines = capPositiveInteger(\n input.maxLines,\n this.config.maxReadLines,\n this.config.maxReadLines,\n \"maxLines\",\n );\n const startLine = capPositiveInteger(\n input.startLine,\n 1,\n Number.MAX_SAFE_INTEGER,\n \"startLine\",\n );\n\n let artifactPath;\n\n try {\n artifactPath = await resolveRegisteredArtifactPath(\n this.config,\n artifact.relativePath,\n );\n } catch (error) {\n if (isNodeErrorCode(error, \"ENOENT\")) {\n throw nativeFileError({\n code: \"FILE_ARTIFACT_NOT_FOUND\",\n message: \"The registered artifact file no longer exists.\",\n details: {\n artifactId: artifact.artifactId,\n path: artifact.relativePath,\n },\n });\n }\n\n throw error;\n }\n\n let filePrefix;\n\n try {\n filePrefix = await readFilePrefix(artifactPath.absolutePath, maxBytes);\n } catch (error) {\n if (isNodeErrorCode(error, \"ENOENT\")) {\n throw nativeFileError({\n code: \"FILE_ARTIFACT_NOT_FOUND\",\n message: \"The registered artifact file no longer exists.\",\n details: {\n artifactId: artifact.artifactId,\n path: artifact.relativePath,\n },\n });\n }\n\n throw nativeFilesystemError(\n \"FILE_PATH_NOT_ALLOWED\",\n \"read_downloaded_file could not read the local artifact.\",\n error,\n {\n artifactId: artifact.artifactId,\n path: artifact.relativePath,\n },\n );\n }\n\n const { buffer, bytesRead, truncatedByBytes } = filePrefix;\n\n if (looksBinary(buffer)) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"read_downloaded_file only supports text-like artifacts.\",\n recoverable: true,\n details: {\n artifactId: artifact.artifactId,\n path: artifact.relativePath,\n },\n });\n }\n\n const text = buffer.toString(\"utf8\");\n const lines = text.split(/\\r?\\n/);\n const startIndex = startLine - 1;\n const selectedLines = lines.slice(startIndex, startIndex + maxLines);\n const truncatedByLines = lines.length > startIndex + selectedLines.length;\n\n return {\n toolName: \"read_downloaded_file\",\n riskLevel: this.config.tools.readDownloadedFile.riskLevel,\n data: {\n artifactId: artifact.artifactId,\n path: artifact.relativePath,\n content: selectedLines.join(\"\\n\"),\n startLine,\n ...(selectedLines.length > 0\n ? { endLine: startLine + selectedLines.length - 1 }\n : {}),\n linesReturned: selectedLines.length,\n bytesRead,\n truncated: truncatedByBytes || truncatedByLines,\n },\n };\n }\n\n private async readResource(\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n const uri =\n typeof input.uri === \"string\" && input.uri.trim()\n ? input.uri.trim()\n : undefined;\n\n if (!uri) {\n throw nativeFileError({\n code: \"FILE_DOWNLOAD_FAILED\",\n message: \"read_resource requires a non-empty uri.\",\n recoverable: true,\n });\n }\n\n if (!this.mcpClient?.readResource) {\n throw nativeFileError({\n code: \"NATIVE_FILE_TOOLS_DISABLED\",\n message:\n \"read_resource requires an MCP client that supports resource reading. Configure the toolkit with an MCP client to use this tool.\",\n recoverable: false,\n });\n }\n\n const result = await this.mcpClient.readResource(uri);\n const primaryContent = result.contents[0];\n\n return {\n toolName: \"read_resource\",\n riskLevel: this.config.tools.readResource.riskLevel,\n data: {\n uri,\n mimeType: primaryContent?.mimeType ?? \"application/octet-stream\",\n ...(primaryContent?.text !== undefined ? { content: primaryContent.text } : {}),\n ...(primaryContent?.blob !== undefined ? { data: primaryContent.blob } : {}),\n },\n };\n }\n\n private resolveArtifact(input: Record<string, unknown>): FileArtifactRecord {\n const artifactId =\n typeof input.artifactId === \"string\" && input.artifactId.trim()\n ? input.artifactId.trim()\n : undefined;\n\n if (artifactId) {\n const artifact = this.manifest.getById(artifactId);\n\n if (artifact) {\n return artifact;\n }\n }\n\n const inputPath =\n typeof input.path === \"string\" && input.path.trim()\n ? resolveInputRelativePath(input.path)\n : undefined;\n\n if (inputPath) {\n const artifact = this.manifest.getByRelativePath(inputPath);\n\n if (artifact) {\n return artifact;\n }\n }\n\n throw nativeFileError({\n code: \"FILE_ARTIFACT_NOT_FOUND\",\n message:\n \"read_downloaded_file requires an artifactId or path returned by download_file in this toolkit session.\",\n recoverable: true,\n details: {\n artifactId,\n path: inputPath,\n },\n });\n }\n\n private createDownloadApprovalMetadata(\n input: Record<string, unknown>,\n ): NativeFileApprovalMetadata | undefined {\n try {\n const validatedUrl = validateDownloadUrl(input.url, this.config);\n const outputRelativePath =\n typeof input.fileName === \"string\" && input.fileName.trim()\n ? resolveOutputRelativePath(input.fileName, validatedUrl.url)\n : undefined;\n\n return {\n source: \"native\",\n nativeToolType: \"fileArtifacts\",\n filesystemRoot: this.config.rootDirAbsolute,\n sideEffects: [\"networkRead\", \"localFileWrite\"],\n urlHost: validatedUrl.source.host,\n urlProtocol: validatedUrl.source.protocol,\n urlPath: validatedUrl.source.path,\n urlKind: validatedUrl.source.kind,\n ...(outputRelativePath ? { outputRelativePath } : {}),\n };\n } catch {\n return undefined;\n }\n }\n\n private createReadApprovalMetadata(\n input: Record<string, unknown>,\n ): NativeFileApprovalMetadata {\n const artifactId =\n typeof input.artifactId === \"string\" && input.artifactId.trim()\n ? input.artifactId.trim()\n : undefined;\n const relativePath =\n typeof input.path === \"string\" && input.path.trim()\n ? input.path.trim()\n : undefined;\n\n return {\n source: \"native\",\n nativeToolType: \"fileArtifacts\",\n filesystemRoot: this.config.rootDirAbsolute,\n sideEffects: [\"localFileRead\"],\n ...(artifactId ? { artifactId } : {}),\n ...(relativePath ? { relativePath } : {}),\n };\n }\n}\n","import os from \"node:os\";\nimport path from \"node:path\";\n\nimport type {\n NativeFileToolsConfig,\n NativeToolMetadataConfig,\n} from \"../../types.js\";\nimport { nonEmptyString } from \"../../utils/values.js\";\n\n/** SDK-internal defaults — not exposed to agents. */\nexport const DEFAULT_NATIVE_ARTIFACT_ROOT = path.join(\n os.homedir(),\n \".zuora-agent-artifacts\",\n);\n\nexport const DEFAULT_NATIVE_ALLOWED_HOSTS = [\n \"*.amazonaws.com\",\n \"*.s3.amazonaws.com\",\n \"s3.amazonaws.com\",\n \"s3.us-west-2.amazonaws.com\",\n \"*.s3.us-west-2.amazonaws.com\",\n];\n\nconst AGENT_NATIVE_TOOL_DEFAULTS: NonNullable<\n NativeFileToolsConfig[\"tools\"]\n> = {\n downloadFile: { enabled: false, operationAccess: \"read\" },\n extractDownloadedArchive: { enabled: false, operationAccess: \"read\" },\n downloadQueryResult: { enabled: true, operationAccess: \"read\" },\n readDownloadedFile: { enabled: true, operationAccess: \"read\" },\n downloadZuoraFile: { enabled: true, operationAccess: \"read\" },\n readResource: { enabled: true, operationAccess: \"read\" },\n};\n\nconst readEnvAllowedHosts = (): string[] | undefined => {\n const raw = process.env[\"ZUORA_NATIVE_ALLOWED_HOSTS\"]?.trim();\n\n if (!raw) {\n return undefined;\n }\n\n const hosts = raw\n .split(\",\")\n .map((host) => host.trim())\n .filter(Boolean);\n\n return hosts.length > 0 ? hosts : undefined;\n};\n\n/**\n * Resolves native file tool settings for the SDK runtime.\n *\n * Native tools (download_query_result, read_downloaded_file, …) are always\n * registered in the catalog with safe defaults. Bundle filtering at\n * getTools()/listTools() time controls whether they appear for a given\n * selection — the same as any MCP tool.\n *\n * Only agent-facing tools appear in the catalog; internal helpers such as\n * `download_file` stay hidden.\n */\nexport const resolveNativeFileToolsInput = (\n config: { nativeFileTools?: NativeFileToolsConfig },\n): NativeFileToolsConfig => {\n const explicit = config.nativeFileTools;\n\n if (explicit?.enabled === false) {\n return { enabled: false };\n }\n\n const rootDir =\n nonEmptyString(explicit?.rootDir) ??\n nonEmptyString(process.env[\"ZUORA_NATIVE_FILE_ROOT\"]) ??\n DEFAULT_NATIVE_ARTIFACT_ROOT;\n\n const allowedHosts =\n explicit?.allowedHosts ??\n readEnvAllowedHosts() ??\n DEFAULT_NATIVE_ALLOWED_HOSTS;\n\n return {\n enabled: true,\n bundleName: explicit?.bundleName ?? \"query\",\n rootDir,\n allowedHosts,\n allowS3PresignedDownload:\n explicit?.allowS3PresignedDownload ?? true,\n requireRootUnderUserHome: explicit?.requireRootUnderUserHome ?? true,\n tools: mergeNativeToolOverrides(explicit?.tools, AGENT_NATIVE_TOOL_DEFAULTS),\n ...(explicit?.userHomeDir ? { userHomeDir: explicit.userHomeDir } : {}),\n ...(explicit?.allowOverwrite !== undefined\n ? { allowOverwrite: explicit.allowOverwrite }\n : {}),\n ...(explicit?.maxDownloadBytes !== undefined\n ? { maxDownloadBytes: explicit.maxDownloadBytes }\n : {}),\n ...(explicit?.maxReadBytes !== undefined\n ? { maxReadBytes: explicit.maxReadBytes }\n : {}),\n ...(explicit?.maxReadLines !== undefined\n ? { maxReadLines: explicit.maxReadLines }\n : {}),\n ...(explicit?.downloadTimeoutMs !== undefined\n ? { downloadTimeoutMs: explicit.downloadTimeoutMs }\n : {}),\n ...(explicit?.allowedProtocols\n ? { allowedProtocols: explicit.allowedProtocols }\n : {}),\n ...(explicit?.allowedUrlPrefixes\n ? { allowedUrlPrefixes: explicit.allowedUrlPrefixes }\n : {}),\n };\n};\n\nconst mergeNativeToolOverrides = (\n overrides: NativeFileToolsConfig[\"tools\"] | undefined,\n defaults: NonNullable<NativeFileToolsConfig[\"tools\"]>,\n): NonNullable<NativeFileToolsConfig[\"tools\"]> => ({\n downloadFile: mergeNativeToolMetadata(\n defaults.downloadFile,\n overrides?.downloadFile,\n ),\n extractDownloadedArchive: mergeNativeToolMetadata(\n defaults.extractDownloadedArchive,\n overrides?.extractDownloadedArchive,\n ),\n downloadQueryResult: mergeNativeToolMetadata(\n defaults.downloadQueryResult,\n overrides?.downloadQueryResult,\n ),\n readDownloadedFile: mergeNativeToolMetadata(\n defaults.readDownloadedFile,\n overrides?.readDownloadedFile,\n ),\n downloadZuoraFile: mergeNativeToolMetadata(\n defaults.downloadZuoraFile,\n overrides?.downloadZuoraFile,\n ),\n readResource: mergeNativeToolMetadata(\n defaults.readResource,\n overrides?.readResource,\n ),\n});\n\nconst mergeNativeToolMetadata = (\n defaults: NativeToolMetadataConfig | undefined,\n override: NativeToolMetadataConfig | undefined,\n): NativeToolMetadataConfig => {\n const enabled = override?.enabled ?? defaults?.enabled ?? false;\n const operationAccess =\n override?.operationAccess ?? defaults?.operationAccess ?? \"read\";\n const riskLevel = override?.riskLevel ?? defaults?.riskLevel ?? \"low\";\n const description = override?.description ?? defaults?.description;\n\n return {\n enabled,\n operationAccess,\n riskLevel,\n ...(description ? { description } : {}),\n };\n};\n\n/** Agent-visible native tool names (internal `download_file` excluded). */\nexport const AGENT_NATIVE_TOOL_NAMES = [\n \"download_query_result\",\n \"read_downloaded_file\",\n \"download_zuora_file\",\n \"read_resource\",\n] as const;\n","import { ZuoraAgentToolkitError } from \"../../../errors.js\";\nimport type { NativeFileToolsConfig } from \"../../../types.js\";\nimport {\n resolveNativeToolMetadata,\n type ResolvedNativeToolMetadataConfig,\n} from \"../config.js\";\n\nexport type ResolvedNativeQueryResultDownloadConfig = {\n enabled: boolean;\n tool: ResolvedNativeToolMetadataConfig;\n};\n\nexport const resolveNativeQueryResultDownloadConfig = (\n input: NativeFileToolsConfig | undefined,\n options: {\n fileArtifactsEnabled: boolean;\n },\n): ResolvedNativeQueryResultDownloadConfig => {\n const tool = resolveNativeToolMetadata(input?.tools?.downloadQueryResult, {\n enabled: true,\n operationAccess: \"read\",\n riskLevel: \"medium\",\n });\n\n if (tool.operationAccess !== \"read\") {\n throw new ZuoraAgentToolkitError({\n code: \"NATIVE_FILE_CONFIG_INVALID\",\n message: \"download_query_result must be configured with operationAccess \\\"read\\\".\",\n category: \"configuration\",\n recoverable: true,\n });\n }\n\n const config = {\n enabled: options.fileArtifactsEnabled && tool.enabled,\n tool,\n };\n\n return config;\n};\n\n","import type { JsonSchema, ZuoraToolDefinition } from \"../../../../types.js\";\nimport { isRecord } from \"../../../../utils/values.js\";\n\nexport type QueryResultStatusCall = {\n toolName: string;\n input: Record<string, unknown>;\n};\n\nexport const resolveQueryResultStatusCall = (\n tools: ZuoraToolDefinition[],\n jobId: string,\n): QueryResultStatusCall | undefined => {\n const candidates = tools\n .map((tool) => ({\n tool,\n score: scoreQueryResultStatusTool(tool),\n }))\n .filter(({ score, tool }) => score > 0 && !isSubmitStyleStatusTool(tool))\n .sort((first, second) => second.score - first.score);\n\n const candidate = candidates[0];\n\n if (!candidate) {\n return undefined;\n }\n\n return {\n toolName: candidate.tool.name,\n input: createQueryResultStatusInput(candidate.tool, jobId),\n };\n};\n\nconst scoreQueryResultStatusTool = (tool: ZuoraToolDefinition): number => {\n const haystack = `${tool.name} ${tool.description}`.toLowerCase();\n const operationName = tool.meta.operationName ?? \"\";\n\n if (tool.meta.bundle !== \"query\") {\n return 0;\n }\n\n let score = 0;\n\n if (tool.name === \"manage_dataquery\") {\n score += 200;\n }\n\n if (operationName === \"get_query_job\" || tool.name.endsWith(\"__get_query_job\")) {\n score += 220;\n }\n\n if (/(dataquery|data query|data_query|manage_data_queries)/i.test(haystack)) {\n score += 80;\n }\n\n if (/(query).*(job|status|result)|(job|status|result).*(query)/i.test(haystack)) {\n score += 40;\n }\n\n if (\n operationName &&\n /(get|retrieve|fetch|read|status|poll|download)/i.test(operationName)\n ) {\n score += 50;\n }\n\n return score;\n};\n\nconst isSubmitStyleStatusTool = (tool: ZuoraToolDefinition): boolean => {\n const operationName = tool.meta.operationName ?? tool.name;\n\n if (/^(submit|run|create)_/i.test(operationName)) {\n return true;\n }\n\n return /__(submit|run|create)_/i.test(tool.name);\n};\n\nconst createQueryResultStatusInput = (\n tool: ZuoraToolDefinition,\n jobId: string,\n): Record<string, unknown> => {\n const input: Record<string, unknown> = {};\n\n if (tool.meta.operationSelector) {\n const operationName =\n tool.meta.operationName ??\n resolveStatusOperationName(tool);\n\n if (operationName) {\n input[tool.meta.operationSelector] = operationName;\n }\n }\n\n input[resolveQueryJobIdInputName(tool.inputSchema)] = jobId;\n\n return input;\n};\n\n/**\n * For multi-op merged tools that have no bound operationName, infer the status\n * operation name from meta.asyncOperations — prefer the pollingOperation of any\n * async operation entry (e.g. \"get_query_job\"), falling back to any operation\n * name that looks like a get/status/poll operation.\n */\nconst resolveStatusOperationName = (\n tool: ZuoraToolDefinition,\n): string | undefined => {\n const asyncOperations = tool.meta.asyncOperations;\n\n if (!asyncOperations) {\n return undefined;\n }\n\n // First preference: the pollingOperation value from any async entry.\n for (const meta of Object.values(asyncOperations)) {\n if (meta.pollingOperation) {\n return meta.pollingOperation;\n }\n }\n\n // Second preference: an operation key that looks like a status/get call.\n return Object.keys(asyncOperations).find((name) =>\n /(get|status|poll|retrieve|fetch)/i.test(name),\n );\n};\n\nconst resolveQueryJobIdInputName = (schema: JsonSchema): string => {\n const properties = isRecord(schema.properties) ? schema.properties : {};\n const propertyNames = Object.keys(properties);\n const exactPreferred = [\"jobId\", \"queryJobId\", \"dataQueryJobId\", \"id\"].find(\n (name) => propertyNames.includes(name),\n );\n\n if (exactPreferred) {\n return exactPreferred;\n }\n\n return (\n propertyNames.find((name) => /job.*id|id.*job/i.test(name)) ??\n propertyNames.find((name) => /id$/i.test(name)) ??\n \"jobId\"\n );\n};\n","import type { ZuoraToolDefinition } from \"../../../types.js\";\nimport { nativeObjectSchema } from \"../metadata.js\";\nimport type { ResolvedNativeToolMetadataConfig } from \"../config.js\";\n\nexport const createDownloadQueryResultToolDefinition = (\n toolConfig: ResolvedNativeToolMetadataConfig,\n): ZuoraToolDefinition => ({\n name: \"download_query_result\",\n description:\n toolConfig.description ??\n [\n \"Download a completed Zuora Data Query result by jobId.\",\n \"Use this instead of copying a dataFile URL when the user asks to download a query result and a jobId is available.\",\n \"The SDK fetches the latest query job result, extracts the exact dataFile URL internally, and downloads it to the local artifact folder.\",\n ].join(\" \"),\n inputSchema: nativeObjectSchema(\n {\n jobId: {\n type: \"string\",\n description: \"Zuora Data Query job id.\",\n },\n fileName: {\n type: \"string\",\n description:\n \"Optional relative artifact file name under the configured artifact root.\",\n },\n overwrite: {\n type: \"boolean\",\n description:\n \"Replace an existing local artifact at fileName. Set to true only after the user explicitly confirmed overwrite.\",\n },\n },\n [\"jobId\"],\n ),\n outputSchema: nativeObjectSchema(\n {\n jobId: { type: \"string\" },\n queryStatus: { type: \"string\" },\n download: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n [\"jobId\", \"download\"],\n ),\n meta: {\n bundle: \"query\",\n access: toolConfig.operationAccess,\n riskLevel: toolConfig.riskLevel,\n requiredServicePermissions: [],\n limitations: [],\n sourceName: \"download_query_result\",\n },\n});\n","import { ZuoraAgentToolkitError } from \"../../../../errors.js\";\n\nexport const readJobId = (value: unknown): string => {\n if (typeof value === \"string\" && value.trim()) {\n return value.trim();\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"QUERY_RESULT_JOB_ID_INVALID\",\n message: \"download_query_result requires a non-empty jobId.\",\n category: \"validation\",\n recoverable: true,\n });\n};\n\nexport const findDownloadUrl = (value: unknown): string | undefined =>\n findStringByKey(value, (key, candidate) => {\n if (!DOWNLOAD_URL_KEY_PATTERN.test(key)) {\n return false;\n }\n\n return isHttpUrl(candidate);\n });\n\nexport const findQueryStatus = (value: unknown): string | undefined =>\n findStringByKey(value, (key) => /^(queryStatus|status)$/i.test(key));\n\nconst findStringByKey = (\n value: unknown,\n predicate: (key: string, value: string) => boolean,\n depth = 0,\n): string | undefined => {\n if (depth > 8 || typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n const found = findStringByKey(item, predicate, depth + 1);\n\n if (found) {\n return found;\n }\n }\n\n return undefined;\n }\n\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (typeof item === \"string\" && predicate(key, item)) {\n return item;\n }\n\n const found = findStringByKey(item, predicate, depth + 1);\n\n if (found) {\n return found;\n }\n }\n\n return undefined;\n};\n\nconst isHttpUrl = (value: string): boolean => {\n try {\n const url = new URL(value);\n\n return url.protocol === \"http:\" || url.protocol === \"https:\";\n } catch {\n return false;\n }\n};\n\nconst DOWNLOAD_URL_KEY_PATTERN =\n /^(dataFile|resultFile|downloadFile|fileUrl|downloadUrl|resultUrl|href)$/i;\n","import { ZuoraAgentToolkitError } from \"../../../errors.js\";\nimport type { ZuoraToolExecutionResult } from \"../../../types.js\";\nimport {\n createNativeRuntimeTool,\n type NativeRuntimeTool,\n type NativeToolSet,\n} from \"../registry-source.js\";\nimport type { ResolvedNativeToolMetadataConfig } from \"../config.js\";\nimport { createDownloadQueryResultToolDefinition } from \"./definitions.js\";\nimport {\n findDownloadUrl,\n findQueryStatus,\n readJobId,\n} from \"./helpers/index.js\";\n\nexport type QueryResultFetcher = (\n jobId: string,\n) => Promise<ZuoraToolExecutionResult>;\n\nexport type QueryResultDownloader = (\n input: Record<string, unknown>,\n) => Promise<ZuoraToolExecutionResult>;\n\nexport type NativeQueryResultDownloadToolsConfig = {\n enabled: boolean;\n tool: ResolvedNativeToolMetadataConfig;\n fetchQueryResult: QueryResultFetcher;\n downloadFile: QueryResultDownloader;\n};\n\nexport class NativeQueryResultDownloadTools implements NativeToolSet {\n constructor(private readonly config: NativeQueryResultDownloadToolsConfig) {}\n\n listTools(): NativeRuntimeTool[] {\n if (!this.config.enabled) {\n return [];\n }\n\n return [this.createDownloadQueryResultTool()];\n }\n\n private createDownloadQueryResultTool(): NativeRuntimeTool {\n return createNativeRuntimeTool({\n definition: createDownloadQueryResultToolDefinition(this.config.tool),\n execute: (input) => this.downloadQueryResult(input),\n });\n }\n\n private async downloadQueryResult(\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n const jobId = readJobId(input.jobId);\n const queryResult = await this.config.fetchQueryResult(jobId);\n const dataFile = findDownloadUrl(queryResult.data);\n\n if (!dataFile) {\n throw new ZuoraAgentToolkitError({\n code: \"QUERY_RESULT_DATA_FILE_NOT_FOUND\",\n message:\n \"Query result did not include a dataFile URL. Confirm the job is completed before downloading the result.\",\n category: \"native_file_tools\",\n recoverable: true,\n details: {\n jobId,\n queryStatus: findQueryStatus(queryResult.data),\n },\n });\n }\n\n const download = await this.config.downloadFile({\n url: dataFile,\n ...(typeof input.fileName === \"string\" && input.fileName.trim()\n ? { fileName: input.fileName.trim() }\n : {}),\n ...(typeof input.overwrite === \"boolean\"\n ? { overwrite: input.overwrite }\n : {}),\n });\n\n return {\n toolName: \"download_query_result\",\n riskLevel: this.config.tool.riskLevel,\n data: {\n jobId,\n ...(findQueryStatus(queryResult.data)\n ? { queryStatus: findQueryStatus(queryResult.data) }\n : {}),\n download: download.data,\n },\n warnings: [\n ...(queryResult.warnings ?? []),\n ...(download.warnings ?? []),\n ],\n };\n }\n}\n","import type { NativeFileToolsConfig } from \"../../../types.js\";\nimport {\n resolveNativeToolMetadata,\n type ResolvedNativeToolMetadataConfig,\n} from \"../config.js\";\n\nexport type ResolvedNativeZuoraFileDownloadConfig = {\n enabled: boolean;\n tool: ResolvedNativeToolMetadataConfig;\n};\n\nexport const resolveNativeZuoraFileDownloadConfig = (\n input: NativeFileToolsConfig | undefined,\n options: {\n fileArtifactsEnabled: boolean;\n },\n): ResolvedNativeZuoraFileDownloadConfig => {\n const tool = resolveNativeToolMetadata(input?.tools?.downloadZuoraFile, {\n enabled: true,\n operationAccess: \"read\",\n riskLevel: \"medium\",\n });\n const config = {\n enabled: options.fileArtifactsEnabled && tool.enabled,\n tool,\n };\n\n return config;\n};\n","import type { ZuoraToolDefinition } from \"../../../types.js\";\nimport { nativeObjectSchema } from \"../metadata.js\";\nimport type { ResolvedNativeToolMetadataConfig } from \"../config.js\";\n\nexport const createDownloadZuoraFileToolDefinition = (\n toolConfig: ResolvedNativeToolMetadataConfig,\n): ZuoraToolDefinition => ({\n name: \"download_zuora_file\",\n description:\n toolConfig.description ??\n [\n \"Download a Zuora tenant file by fileId using the Zuora REST Files API.\",\n \"Use this when a prior tool result includes resourceUri zuora://files/{fileId} or an explicit fileId for a generated artifact such as an invoice PDF.\",\n \"The SDK downloads the file with the configured Zuora credentials and saves it to the local artifact folder.\",\n ].join(\" \"),\n inputSchema: nativeObjectSchema(\n {\n fileId: {\n type: \"string\",\n description: \"Zuora file id from a prior tool result.\",\n },\n resourceUri: {\n type: \"string\",\n description:\n \"Optional zuora://files/{fileId} resource URI from a prior tool result.\",\n },\n fileName: {\n type: \"string\",\n description:\n \"Optional relative artifact file name under the configured artifact root.\",\n },\n overwrite: {\n type: \"boolean\",\n description:\n \"Replace an existing local artifact at fileName. Set to true only after the user explicitly confirmed overwrite.\",\n },\n },\n [],\n ),\n outputSchema: nativeObjectSchema(\n {\n fileId: { type: \"string\" },\n download: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n [\"fileId\", \"download\"],\n ),\n meta: {\n bundle: \"query\",\n access: toolConfig.operationAccess,\n riskLevel: toolConfig.riskLevel,\n requiredServicePermissions: [],\n limitations: [],\n sourceName: \"download_zuora_file\",\n },\n});\n","import { ZuoraAgentToolkitError } from \"../../../../errors.js\";\n\nconst ZUORA_FILE_RESOURCE_URI_PATTERN =\n /^zuora:\\/\\/files\\/([A-Za-z0-9]+)$/i;\n\nexport const readZuoraFileId = (\n input: Record<string, unknown>,\n): string => {\n const fileId = typeof input.fileId === \"string\" ? input.fileId.trim() : \"\";\n const resourceUri =\n typeof input.resourceUri === \"string\" ? input.resourceUri.trim() : \"\";\n\n if (fileId) {\n return fileId;\n }\n\n const parsedFileId = parseZuoraFileResourceUri(resourceUri);\n\n if (parsedFileId) {\n return parsedFileId;\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"INVALID_INPUT\",\n message:\n \"download_zuora_file requires fileId or resourceUri zuora://files/{fileId}.\",\n category: \"validation\",\n recoverable: true,\n });\n};\n\nexport const parseZuoraFileResourceUri = (\n resourceUri: string,\n): string | undefined => {\n const match = resourceUri.match(ZUORA_FILE_RESOURCE_URI_PATTERN);\n return match?.[1];\n};\n\nexport const resolveZuoraFileResource = (\n value: unknown,\n keyPath: string[] = [],\n depth = 0,\n): { fileId: string; resourceUri: string } | undefined => {\n if (depth > 6) {\n return undefined;\n }\n\n if (typeof value === \"string\") {\n const fileId = parseZuoraFileResourceUri(value);\n\n if (fileId && keyPath.at(-1) === \"resourceUri\") {\n return { fileId, resourceUri: value };\n }\n\n return undefined;\n }\n\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries()) {\n const resolved = resolveZuoraFileResource(item, [\n ...keyPath,\n String(index),\n ], depth + 1);\n\n if (resolved) {\n return resolved;\n }\n }\n\n return undefined;\n }\n\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n const resourceUri = record.resourceUri;\n\n if (typeof resourceUri === \"string\") {\n const fileId = parseZuoraFileResourceUri(resourceUri);\n\n if (fileId) {\n return { fileId, resourceUri };\n }\n }\n\n const explicitFileId =\n typeof record.fileId === \"string\" ? record.fileId.trim() : \"\";\n\n if (explicitFileId && typeof resourceUri === \"string\") {\n const parsed = parseZuoraFileResourceUri(resourceUri);\n\n if (parsed === explicitFileId) {\n return { fileId: explicitFileId, resourceUri };\n }\n }\n\n for (const [key, item] of Object.entries(record)) {\n const resolved = resolveZuoraFileResource(item, [...keyPath, key], depth + 1);\n\n if (resolved) {\n return resolved;\n }\n }\n\n return undefined;\n};\n\nexport const defaultZuoraFileName = (\n fileId: string,\n contentType?: string,\n): string => {\n if (contentType?.includes(\"pdf\")) {\n return `${fileId}.pdf`;\n }\n\n if (contentType?.includes(\"json\")) {\n return `${fileId}.json`;\n }\n\n return `${fileId}.bin`;\n};\n","import type { ZuoraToolExecutionResult } from \"../../../types.js\";\nimport type { ZuoraRestDownloadFileResult } from \"../../../transport/zuora-rest-client.js\";\nimport type { NativeFileSafeSource } from \"../file-artifacts/url-policy.js\";\nimport {\n createNativeRuntimeTool,\n type NativeRuntimeTool,\n type NativeToolSet,\n} from \"../registry-source.js\";\nimport type { ResolvedNativeToolMetadataConfig } from \"../config.js\";\nimport { createDownloadZuoraFileToolDefinition } from \"./definitions.js\";\nimport {\n defaultZuoraFileName,\n readZuoraFileId,\n} from \"./helpers/index.js\";\n\nexport type ZuoraFileFetcher = (\n fileId: string,\n) => Promise<ZuoraRestDownloadFileResult>;\n\nexport type BufferedDownloadPersister = (options: {\n input: Record<string, unknown>;\n toolName: string;\n riskLevel: ResolvedNativeToolMetadataConfig[\"riskLevel\"];\n body: Buffer;\n contentType?: string;\n source: NativeFileSafeSource;\n defaultFileName: string;\n}) => Promise<ZuoraToolExecutionResult>;\n\nexport type NativeZuoraFileDownloadToolsConfig = {\n enabled: boolean;\n tool: ResolvedNativeToolMetadataConfig;\n fetchZuoraFile: ZuoraFileFetcher;\n persistDownload: BufferedDownloadPersister;\n};\n\nexport class NativeZuoraFileDownloadTools implements NativeToolSet {\n constructor(private readonly config: NativeZuoraFileDownloadToolsConfig) {}\n\n listTools(): NativeRuntimeTool[] {\n if (!this.config.enabled) {\n return [];\n }\n\n return [this.createDownloadZuoraFileTool()];\n }\n\n private createDownloadZuoraFileTool(): NativeRuntimeTool {\n return createNativeRuntimeTool({\n definition: createDownloadZuoraFileToolDefinition(this.config.tool),\n execute: (input) => this.downloadZuoraFile(input),\n });\n }\n\n private async downloadZuoraFile(\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n const fileId = readZuoraFileId(input);\n const fetched = await this.config.fetchZuoraFile(fileId);\n const source: NativeFileSafeSource = {\n protocol: \"zuora:\",\n host: \"files\",\n path: `/${fileId}`,\n redactedUrl: `zuora://files/${fileId}`,\n kind: \"zuora-public\",\n };\n const download = await this.config.persistDownload({\n input,\n toolName: \"download_zuora_file\",\n riskLevel: this.config.tool.riskLevel,\n body: Buffer.from(fetched.bytes),\n ...(fetched.contentType ? { contentType: fetched.contentType } : {}),\n source,\n defaultFileName: defaultZuoraFileName(fileId, fetched.contentType),\n });\n\n return {\n toolName: \"download_zuora_file\",\n riskLevel: this.config.tool.riskLevel,\n data: {\n fileId,\n download: download.data,\n },\n ...(download.warnings ? { warnings: download.warnings } : {}),\n };\n }\n}\n","import type {\n JsonSchema,\n ZuoraAsyncOperationMeta,\n ZuoraRiskLevel,\n ZuoraServicePermission,\n ZuoraToolDefinition,\n ZuoraToolOperation,\n} from \"../types.js\";\nimport { isRecord, nonEmptyString } from \"../utils/values.js\";\n\nexport type McpToolMetadataInput = {\n name: string;\n description?: string;\n inputSchema?: JsonSchema;\n outputSchema?: JsonSchema;\n _meta?: Record<string, unknown>;\n annotations?: {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n };\n};\n\nimport { normalizeMetadataPath } from \"../async-jobs.js\";\nimport { createOperationAdapterToolName } from \"../utils/adapter-name.js\";\nimport {\n inferOperationSelector,\n omitSchemaProperty,\n} from \"./operation-metadata.js\";\n\nconst DEFAULT_ACCESS: ZuoraToolOperation = \"write\";\nconst DEFAULT_RISK_LEVEL: ZuoraRiskLevel = \"high\";\nconst DEFAULT_BUNDLE = \"admin\";\n\nconst RISK_RANK: Record<ZuoraRiskLevel, number> = {\n low: 0,\n medium: 1,\n high: 2,\n};\n\nexport const normalizeMcpTools = (\n tools: McpToolMetadataInput[],\n splitOperations: boolean,\n): ZuoraToolDefinition[] =>\n tools.flatMap((tool) => normalizeSingleTool(tool, splitOperations));\n\nconst normalizeSingleTool = (\n tool: McpToolMetadataInput,\n splitOperations: boolean,\n): ZuoraToolDefinition[] => {\n const extracted = extractToolMetadata(tool);\n const operationPermissions = extracted.operationPermissions;\n const operationNames = operationPermissions\n ? Object.keys(operationPermissions)\n : [];\n\n if (operationNames.length <= 1) {\n const access =\n aggregateOperation(operationPermissions) ?? DEFAULT_ACCESS;\n\n return [\n buildZuoraToolDefinition(tool, extracted, {\n name: tool.name,\n access,\n operationName: operationNames[0],\n isSplit: false,\n }),\n ];\n }\n\n if (splitOperations) {\n return operationNames.map((operationName) =>\n buildZuoraToolDefinition(tool, extracted, {\n name: createOperationAdapterToolName(tool.name, operationName),\n access: operationPermissions![operationName]!,\n operationName,\n isSplit: true,\n }),\n );\n }\n\n const access = aggregateOperation(operationPermissions)!;\n\n return [\n buildZuoraToolDefinition(tool, extracted, {\n name: tool.name,\n access,\n isSplit: false,\n isMultiOpMerged: true,\n }),\n ];\n};\n\ntype ExtractedToolMetadata = {\n bundle: string;\n operationPermissions?: Record<string, ZuoraToolOperation> | undefined;\n operationRiskLevels?: Record<string, ZuoraRiskLevel> | undefined;\n asyncOperations?: Record<string, ZuoraAsyncOperationMeta> | undefined;\n requiredServicePermissions: ZuoraServicePermission[];\n limitations: string[];\n};\n\ntype BuildParams = {\n name: string;\n access: ZuoraToolOperation;\n operationName?: string | undefined;\n isSplit: boolean;\n /** True when the source MCP tool has multiple operations collapsed into one merged tool (splitOperations: false). */\n isMultiOpMerged?: boolean;\n};\n\nconst extractToolMetadata = (tool: McpToolMetadataInput): ExtractedToolMetadata => {\n const meta = isRecord(tool._meta) ? tool._meta : undefined;\n const zuoraMeta = isRecord(meta?.zuora) ? meta.zuora : undefined;\n\n const operationPermissions = normalizeOperationPermissions(\n meta?.[\"operationPermissions\"],\n tool.name,\n );\n const operationRiskLevels = normalizeRiskLevels(\n meta?.[\"riskLevels\"] ?? meta?.[\"operationRiskLevels\"],\n tool.name,\n );\n\n const bundleValue = nonEmptyString(meta?.[\"bundle\"]);\n const bundle: string = bundleValue !== undefined\n ? bundleValue.toLowerCase()\n : DEFAULT_BUNDLE;\n\n const requiredServicePermissions = parseServicePermissions(\n meta?.[\"requiredServicePermissions\"],\n );\n const asyncOperations = parseAsyncOperations(meta?.[\"asyncOperations\"]);\n const limitations =\n normalizeLimitations(\n meta?.[\"knownLimitations\"] ?? zuoraMeta?.[\"limitations\"],\n ) ?? [];\n\n return {\n bundle,\n operationPermissions,\n operationRiskLevels,\n asyncOperations,\n requiredServicePermissions,\n limitations,\n };\n};\n\nconst buildZuoraToolDefinition = (\n tool: McpToolMetadataInput,\n extracted: ExtractedToolMetadata,\n params: BuildParams,\n): ZuoraToolDefinition => {\n const asyncOperation = resolveAsyncOperation(extracted, params);\n const baseInputSchema = tool.inputSchema ?? {\n type: \"object\",\n additionalProperties: true,\n };\n // Infer the operation selector for split tools (to strip from inputSchema)\n // and for multi-op merged tools (to store on meta for runtime async lookup).\n const needsOperationSelector =\n (params.isSplit || params.isMultiOpMerged) &&\n extracted.operationPermissions !== undefined;\n const operationSelector = needsOperationSelector\n ? inferOperationSelector(baseInputSchema, extracted.operationPermissions!)\n : undefined;\n const inputSchema =\n params.isSplit && operationSelector\n ? omitSchemaProperty(baseInputSchema, operationSelector)\n : baseInputSchema;\n\n return {\n name: params.name,\n description: tool.description ?? params.name,\n inputSchema,\n ...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),\n meta: {\n bundle: extracted.bundle,\n access: params.access,\n riskLevel: resolveRiskLevel(extracted, params),\n ...(asyncOperation ? { asyncOperation } : {}),\n // Multi-op merged tool: store per-operation maps so callTool can look up\n // the correct access, risk, and async meta from the runtime input.\n ...(params.isMultiOpMerged && extracted.asyncOperations\n ? { asyncOperations: extracted.asyncOperations }\n : {}),\n ...(params.isMultiOpMerged && extracted.operationPermissions\n ? { operationAccess: extracted.operationPermissions }\n : {}),\n ...(params.isMultiOpMerged && extracted.operationRiskLevels\n ? { operationRiskLevel: extracted.operationRiskLevels }\n : {}),\n requiredServicePermissions: extracted.requiredServicePermissions,\n limitations: extracted.limitations,\n sourceName: tool.name,\n ...(operationSelector ? { operationSelector } : {}),\n ...(params.isSplit && params.operationName\n ? { operationName: params.operationName }\n : {}),\n },\n };\n};\n\nconst resolveRiskLevel = (\n extracted: ExtractedToolMetadata,\n params: BuildParams,\n): ZuoraRiskLevel => {\n const { operationRiskLevels } = extracted;\n\n if (operationRiskLevels) {\n if (params.isSplit && params.operationName) {\n return operationRiskLevels[params.operationName] ?? DEFAULT_RISK_LEVEL;\n }\n\n const highest = highestRiskLevel(Object.values(operationRiskLevels));\n if (highest) {\n return highest;\n }\n }\n\n return DEFAULT_RISK_LEVEL;\n};\n\nconst resolveAsyncOperation = (\n extracted: ExtractedToolMetadata,\n params: BuildParams,\n): ZuoraAsyncOperationMeta | undefined => {\n const { asyncOperations } = extracted;\n\n if (!asyncOperations) {\n return undefined;\n }\n\n if (params.isSplit && params.operationName) {\n return asyncOperations[params.operationName];\n }\n\n // Multi-op merged tool: suppress asyncOperation — the full map is stored\n // in meta.asyncOperations for runtime lookup by callTool.\n if (params.isMultiOpMerged) {\n return undefined;\n }\n\n // Single-op tool (no operationPermissions): unambiguous single async meta.\n return Object.values(asyncOperations)[0];\n};\n\nconst parseServicePermissions = (value: unknown): ZuoraServicePermission[] => {\n if (!Array.isArray(value)) {\n return [];\n }\n\n return value.flatMap((item) => {\n if (!isRecord(item)) {\n return [];\n }\n\n const scope = nonEmptyString(item[\"scope\"]);\n const name = nonEmptyString(item[\"name\"]);\n\n if (!scope || !name) {\n return [];\n }\n\n return [{ scope, name }];\n });\n};\n\nconst parseAsyncOperations = (\n value: unknown,\n): Record<string, ZuoraAsyncOperationMeta> | undefined => {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const result: Record<string, ZuoraAsyncOperationMeta> = {};\n\n for (const [opName, opValue] of Object.entries(value)) {\n const parsed = parseAsyncOperationMeta(opValue);\n if (parsed) {\n result[opName] = parsed;\n }\n }\n\n return Object.keys(result).length > 0 ? result : undefined;\n};\n\nconst parseAsyncOperationMeta = (\n value: unknown,\n): ZuoraAsyncOperationMeta | undefined => {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const pollingOperation = nonEmptyString(value[\"pollingOperation\"]);\n const pollingTool = nonEmptyString(value[\"pollingTool\"]);\n const jobIdPath = nonEmptyString(value[\"jobIdPath\"]);\n const statusPath = nonEmptyString(value[\"statusPath\"]);\n\n if ((!pollingOperation && !pollingTool) || !jobIdPath || !statusPath) {\n return undefined;\n }\n\n const terminalStatuses = parseTerminalStatuses(value[\"terminalStatuses\"]);\n if (!terminalStatuses) {\n return undefined;\n }\n\n const pollingArgs = parsePollingArgs(value[\"pollingArgs\"]);\n\n return {\n ...(pollingOperation ? { pollingOperation } : {}),\n ...(pollingTool ? { pollingTool } : {}),\n jobIdPath: normalizeMetadataPath(jobIdPath),\n statusPath: normalizeMetadataPath(statusPath),\n terminalStatuses,\n ...(pollingArgs ? { pollingArgs } : {}),\n ...(typeof value[\"recommendedPollIntervalMs\"] === \"number\"\n ? { recommendedPollIntervalMs: value[\"recommendedPollIntervalMs\"] }\n : {}),\n ...(typeof value[\"defaultTimeoutMs\"] === \"number\"\n ? { defaultTimeoutMs: value[\"defaultTimeoutMs\"] }\n : {}),\n ...(typeof value[\"maxPollAttempts\"] === \"number\"\n ? { maxPollAttempts: value[\"maxPollAttempts\"] }\n : {}),\n };\n};\n\nconst parsePollingArgs = (\n value: unknown,\n): Record<string, string> | undefined => {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const entries = Object.entries(value).flatMap(([key, entryValue]) =>\n typeof entryValue === \"string\" ? [[key, entryValue] as const] : [],\n );\n\n return entries.length > 0 ? Object.fromEntries(entries) : undefined;\n};\n\nconst parseTerminalStatuses = (\n value: unknown,\n): ZuoraAsyncOperationMeta[\"terminalStatuses\"] | undefined => {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const success = parseStringArray(value[\"success\"]);\n const failure = parseStringArray(value[\"failure\"]);\n\n if (!success || !failure) {\n return undefined;\n }\n\n return {\n success,\n failure,\n ...(Array.isArray(value[\"canceled\"])\n ? { canceled: parseStringArray(value[\"canceled\"]) ?? [] }\n : {}),\n };\n};\n\nconst parseStringArray = (value: unknown): string[] | undefined => {\n if (!Array.isArray(value)) {\n return undefined;\n }\n\n const strings = value.filter((entry): entry is string => typeof entry === \"string\");\n return strings.length > 0 ? strings : undefined;\n};\n\nconst normalizeOperationPermissions = (\n value: unknown,\n toolName: string,\n): Record<string, ZuoraToolOperation> | undefined => {\n const direct = normalizeOperation(value);\n\n if (direct) {\n return { [toolName]: direct };\n }\n\n if (!isRecord(value)) {\n return undefined;\n }\n\n const entries = Object.entries(value).flatMap(([operationName, rawValue]) => {\n const operation = normalizeOperation(rawValue);\n return operation ? [[operationName, operation] as const] : [];\n });\n\n return entries.length > 0 ? Object.fromEntries(entries) : undefined;\n};\n\nconst aggregateOperation = (\n operationPermissions: Record<string, ZuoraToolOperation> | undefined,\n): ZuoraToolOperation | undefined => {\n if (!operationPermissions) {\n return undefined;\n }\n\n return Object.values(operationPermissions).includes(\"write\") ? \"write\" : \"read\";\n};\n\nconst normalizeRiskLevels = (\n value: unknown,\n toolName: string,\n): Record<string, ZuoraRiskLevel> | undefined => {\n const direct = normalizeRiskLevel(value);\n\n if (direct) {\n return { [toolName]: direct };\n }\n\n if (!isRecord(value)) {\n return undefined;\n }\n\n const entries = Object.entries(value).flatMap(([operationName, rawValue]) => {\n const riskLevel = normalizeRiskLevel(rawValue);\n return riskLevel ? [[operationName, riskLevel] as const] : [];\n });\n\n return entries.length > 0 ? Object.fromEntries(entries) : undefined;\n};\n\nconst normalizeRiskLevel = (value: unknown): ZuoraRiskLevel | undefined => {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const normalized = value.trim().toLowerCase();\n\n if (normalized === \"low\" || normalized === \"medium\" || normalized === \"high\") {\n return normalized;\n }\n\n return undefined;\n};\n\nconst highestRiskLevel = (\n riskLevels: ZuoraRiskLevel[],\n): ZuoraRiskLevel | undefined => {\n let highest: ZuoraRiskLevel | undefined;\n\n for (const riskLevel of riskLevels) {\n if (!highest || RISK_RANK[riskLevel] > RISK_RANK[highest]) {\n highest = riskLevel;\n }\n }\n\n return highest;\n};\n\nconst normalizeOperation = (value: unknown): ZuoraToolOperation | undefined => {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const normalized = value.trim().toLowerCase();\n\n if (\n normalized === \"read\" ||\n normalized === \"readonly\" ||\n normalized === \"read_only\"\n ) {\n return \"read\";\n }\n\n if (normalized === \"write\" || normalized === \"mutation\") {\n return \"write\";\n }\n\n return undefined;\n};\n\nconst normalizeStringList = (value: unknown): string[] =>\n uniqueStrings(collectStrings(value));\n\nconst normalizeLimitations = (value: unknown): string[] | undefined => {\n const limitations = normalizeStringList(value);\n return limitations.length > 0 ? limitations : undefined;\n};\n\nconst collectStrings = (value: unknown): string[] => {\n const direct = nonEmptyString(value);\n\n if (direct) {\n return [direct];\n }\n\n if (Array.isArray(value)) {\n return value.flatMap(collectStrings);\n }\n\n if (isRecord(value)) {\n return Object.values(value).flatMap(collectStrings);\n }\n\n return [];\n};\n\nconst uniqueStrings = (values: string[]): string[] => [...new Set(values)];\n","export const redactSensitiveString = (\n value: string,\n sensitiveValues: readonly string[],\n): string =>\n sensitiveValues.reduce(\n (redacted, sensitiveValue) =>\n sensitiveValue ? redacted.split(sensitiveValue).join(\"[REDACTED]\") : redacted,\n value,\n );\n\nexport const redactSensitiveDetails = (\n value: unknown,\n sensitiveValues: readonly string[],\n): unknown => {\n if (typeof value === \"string\") {\n return redactSensitiveString(value, sensitiveValues);\n }\n\n if (value instanceof Error) {\n return {\n name: value.name,\n message: redactSensitiveString(value.message, sensitiveValues),\n };\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => redactSensitiveDetails(item, sensitiveValues));\n }\n\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value).map(([key, entry]) => [\n key,\n redactSensitiveDetails(entry, sensitiveValues),\n ]),\n );\n }\n\n return value;\n};\n","import { ZuoraAgentToolkitError } from \"../errors.js\";\nimport { isStagingZuoraBaseUrl } from \"../utils/zuora-url.js\";\nimport {\n redactSensitiveDetails,\n redactSensitiveString,\n} from \"../utils/redaction.js\";\nimport type {\n OAuthTokenResponse,\n OAuthTokenSuccess,\n ResolvedZuoraConnectionConfig,\n} from \"./connection-types.js\";\n\nconst TOKEN_REFRESH_SKEW_MAX_MS = 60_000;\nconst DEFAULT_TOKEN_EXPIRES_IN_SECONDS = 3600;\n\nexport class OAuthTokenProvider {\n private accessToken: string | undefined;\n\n private tokenIssuedAt = 0;\n\n private tokenExpiresAt = 0;\n\n private tenantId: string | undefined;\n\n private preferredTokenEndpoint: string | undefined;\n\n constructor(\n private readonly config: ResolvedZuoraConnectionConfig,\n private readonly restBaseUrl: string,\n ) {}\n\n async ensureAccessToken(): Promise<string> {\n if (!this.config.auth) {\n throw new ZuoraAgentToolkitError({\n code: \"MISSING_AUTH\",\n message:\n \"Zuora auth configuration is required unless tenant auth is enabled.\",\n category: \"auth\",\n });\n }\n\n const now = Date.now();\n\n if (this.accessToken && this.isAccessTokenFresh(now)) {\n return this.accessToken;\n }\n\n const token = await this.fetchOAuthToken();\n\n this.accessToken = token.access_token;\n this.tokenIssuedAt = now;\n this.tokenExpiresAt =\n now + (token.expires_in ?? DEFAULT_TOKEN_EXPIRES_IN_SECONDS) * 1000;\n this.tenantId = extractTenantId(token.scope);\n\n return this.accessToken;\n }\n\n getTenantId(): string | undefined {\n return this.tenantId;\n }\n\n invalidateAccessToken(): void {\n this.accessToken = undefined;\n this.tokenIssuedAt = 0;\n this.tokenExpiresAt = 0;\n }\n\n sensitiveValues(): string[] {\n const values = [this.accessToken];\n const auth = this.config.auth;\n\n if (auth?.clientSecret) {\n values.push(auth.clientSecret);\n }\n\n return values.filter(\n (value): value is string => typeof value === \"string\" && value.length > 0,\n );\n }\n\n private isAccessTokenFresh(now: number): boolean {\n const tokenLifetimeMs = Math.max(0, this.tokenExpiresAt - this.tokenIssuedAt);\n const refreshSkewMs = Math.min(\n TOKEN_REFRESH_SKEW_MAX_MS,\n Math.floor(tokenLifetimeMs / 10),\n );\n\n return now < this.tokenExpiresAt - refreshSkewMs;\n }\n\n private async fetchOAuthToken(): Promise<OAuthTokenSuccess> {\n const endpoints = await this.resolveTokenEndpoints();\n let lastFailure: ZuoraAgentToolkitError | undefined;\n const attempts: Array<{\n tokenEndpoint: string;\n code: string;\n message: string;\n retryable: boolean;\n details?: unknown;\n }> = [];\n\n for (const endpoint of endpoints) {\n try {\n const token = await this.requestOAuthToken(endpoint);\n this.preferredTokenEndpoint = endpoint;\n return token;\n } catch (error) {\n if (error instanceof ZuoraAgentToolkitError) {\n lastFailure = error;\n attempts.push({\n tokenEndpoint: endpoint,\n code: error.code,\n message: error.message,\n retryable: error.retryable,\n details: error.details,\n });\n } else {\n lastFailure = new ZuoraAgentToolkitError({\n code: \"OAUTH_TOKEN_ERROR\",\n message: this.redactString(\n error instanceof Error ? error.message : String(error),\n ),\n category: \"auth\",\n retryable: true,\n recoverable: true,\n details: this.redactDetails(error),\n });\n attempts.push({\n tokenEndpoint: endpoint,\n code: lastFailure.code,\n message: lastFailure.message,\n retryable: lastFailure.retryable,\n details: lastFailure.details,\n });\n }\n }\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"OAUTH_TOKEN_ERROR\",\n message:\n lastFailure?.message ??\n \"OAuth token request failed against all configured endpoints.\",\n category: \"auth\",\n retryable: attempts.some((attempt) => attempt.retryable),\n recoverable: true,\n details: this.redactDetails({ attempts }),\n });\n }\n\n private async resolveTokenEndpoints(): Promise<string[]> {\n const restEndpoint = `${this.restBaseUrl}/oauth/token`;\n const oneIdEndpoint = isStagingZuoraBaseUrl(this.restBaseUrl)\n ? \"https://one.stg.na.zuora.com/oauth2/token\"\n : \"https://one.zuora.com/oauth2/token\";\n const endpoints = [restEndpoint, oneIdEndpoint];\n const uniqueEndpoints = [...new Set(endpoints)];\n\n if (!this.preferredTokenEndpoint) {\n return uniqueEndpoints;\n }\n\n return [\n this.preferredTokenEndpoint,\n ...uniqueEndpoints.filter(\n (endpoint) => endpoint !== this.preferredTokenEndpoint,\n ),\n ];\n }\n\n private async requestOAuthToken(\n tokenEndpoint: string,\n ): Promise<OAuthTokenSuccess> {\n if (!this.config.auth) {\n throw new ZuoraAgentToolkitError({\n code: \"UNSUPPORTED_AUTH\",\n message: \"Unsupported auth configuration for Zuora HTTP MCP client.\",\n category: \"auth\",\n });\n }\n\n const body = new URLSearchParams({ grant_type: \"client_credentials\" });\n const headers: Record<string, string> = {\n \"content-type\": \"application/x-www-form-urlencoded\",\n accept: \"application/json\",\n };\n const auth = this.config.auth;\n\n // Always use client_secret_post (hardcoded default)\n body.set(\"client_id\", auth.clientId);\n body.set(\"client_secret\", auth.clientSecret);\n\n const response = await fetch(tokenEndpoint, {\n method: \"POST\",\n headers,\n body,\n });\n\n const token = (await response\n .json()\n .catch(() => ({}))) as OAuthTokenResponse;\n\n if (!response.ok || !token.access_token) {\n const oauthError =\n typeof token.error === \"string\" && token.error.trim()\n ? token.error.trim()\n : undefined;\n const oauthDescription =\n typeof token.error_description === \"string\" &&\n token.error_description.trim()\n ? token.error_description.trim()\n : undefined;\n\n const summary = oauthDescription\n ? oauthError && oauthError !== oauthDescription\n ? `${oauthError}: ${oauthDescription}`\n : oauthDescription\n : (oauthError ?? `OAuth token request failed with HTTP ${response.status}.`);\n\n throw new ZuoraAgentToolkitError({\n code: \"OAUTH_TOKEN_ERROR\",\n message: this.redactString(`${summary} (HTTP ${response.status})`),\n category: \"auth\",\n retryable: response.status >= 500,\n recoverable: true,\n details: this.redactDetails({\n tokenEndpoint,\n status: response.status,\n ...(oauthError ? { error: oauthError } : {}),\n ...(oauthDescription ? { errorDescription: oauthDescription } : {}),\n }),\n });\n }\n\n return {\n access_token: token.access_token,\n ...(typeof token.expires_in === \"number\"\n ? { expires_in: token.expires_in }\n : {}),\n ...(token.scope ? { scope: token.scope } : {}),\n };\n }\n\n private redactString(value: string): string {\n return redactSensitiveString(value, this.sensitiveValues());\n }\n\n private redactDetails(value: unknown): unknown {\n return redactSensitiveDetails(value, this.sensitiveValues());\n }\n}\n\nconst extractTenantId = (scope?: string): string | undefined => {\n const tenantMatch = scope?.match(/tenant\\.(\\d+)/);\n return tenantMatch?.[1];\n};\n","import type {\n EnabledTenantAuth,\n ResolvedZuoraConnectionConfig,\n} from \"./connection-types.js\";\n\nconst RESERVED_HEADER_NAMES = new Set([\n \"accept\",\n \"authorization\",\n \"content-type\",\n \"mcp-session-id\",\n \"user-agent\",\n \"zuora-entity-ids\",\n \"zuora-org-ids\",\n \"zuora-tenant-id\",\n \"zuora-token-id\",\n \"zuora-user-id\",\n]);\n\nexport type ZuoraRequestHeaderOptions = {\n accessToken?: string;\n userAgent: string;\n accept: string;\n contentType?: string;\n};\n\nexport const buildZuoraRequestHeaders = (\n config: ResolvedZuoraConnectionConfig,\n options: ZuoraRequestHeaderOptions,\n): Record<string, string> => {\n const tenantAuth = enabledTenantAuth(config);\n\n return {\n ...(options.accessToken\n ? { authorization: `Bearer ${options.accessToken}` }\n : {}),\n ...(options.contentType ? { \"content-type\": options.contentType } : {}),\n accept: options.accept,\n \"user-agent\": options.userAgent,\n ...sanitizeConfiguredHeaders(config),\n ...(config.zuoraVersion ? { \"zuora-version\": config.zuoraVersion } : {}),\n ...(tenantAuth\n ? tenantAuthHeaders(config, tenantAuth)\n : scopeHeaders(config)),\n };\n};\n\nexport const enabledTenantAuth = (\n config: ResolvedZuoraConnectionConfig,\n): EnabledTenantAuth | undefined => {\n const tenantAuth = config.tenantAuth;\n return tenantAuth?.enabled === true ? tenantAuth : undefined;\n};\n\nconst sanitizeConfiguredHeaders = (\n config: ResolvedZuoraConnectionConfig,\n): Record<string, string> =>\n Object.fromEntries(\n Object.entries(config.headers ?? {}).filter(\n (entry): entry is [string, string] =>\n Boolean(entry[1]) && !RESERVED_HEADER_NAMES.has(entry[0].toLowerCase()),\n ),\n );\n\nconst tenantAuthHeaders = (\n config: ResolvedZuoraConnectionConfig,\n tenantAuth: EnabledTenantAuth,\n): Record<string, string> => {\n const entityIds = headerListValue(config.entityIds);\n const orgIds = headerListValue(config.orgIds);\n\n return {\n ...(entityIds ? { \"Zuora-Entity-Ids\": entityIds } : {}),\n ...(orgIds ? { \"Zuora-Org-Ids\": orgIds } : {}),\n \"Zuora-Tenant-Id\": tenantAuth.tenantId,\n \"Zuora-Token-Id\": tenantAuth.tokenId,\n \"Zuora-User-Id\": tenantAuth.userId,\n };\n};\n\nconst scopeHeaders = (\n config: ResolvedZuoraConnectionConfig,\n): Record<string, string> => {\n const entityIds = headerListValue(config.entityIds);\n const orgIds = headerListValue(config.orgIds);\n\n return {\n ...(entityIds ? { \"zuora-entity-ids\": entityIds } : {}),\n ...(orgIds ? { \"zuora-org-ids\": orgIds } : {}),\n };\n};\n\nconst headerListValue = (value?: string | string[]): string | undefined => {\n if (!value) {\n return undefined;\n }\n\n if (Array.isArray(value)) {\n const normalized = value.map((item) => item.trim()).filter(Boolean);\n return normalized.length > 0 ? normalized.join(\",\") : undefined;\n }\n\n const normalized = value.trim();\n return normalized || undefined;\n};\n","import type { ZuoraHttpMcpClientConfig } from \"../types.js\";\nimport type { ResolvedZuoraConnectionConfig } from \"./connection-types.js\";\n\nexport const resolveZuoraConnectionConfig = (\n config: ZuoraHttpMcpClientConfig,\n mcpUrl: string,\n): ResolvedZuoraConnectionConfig => ({\n clientName: config.clientName ?? \"zuora-agent-toolkit\",\n clientVersion: config.clientVersion ?? \"0.1.0\",\n protocolVersion: config.protocolVersion ?? \"2025-03-26\",\n url: mcpUrl,\n ...(config.auth ? { auth: config.auth } : {}),\n ...(config.headers ? { headers: config.headers } : {}),\n ...(config.tenantAuth ? { tenantAuth: config.tenantAuth } : {}),\n ...(config.entityIds ? { entityIds: config.entityIds } : {}),\n ...(config.orgIds ? { orgIds: config.orgIds } : {}),\n ...(config.zuoraVersion ? { zuoraVersion: config.zuoraVersion } : {}),\n});\n","import { ZuoraAgentToolkitError } from \"../errors.js\";\nimport type { ZuoraHttpMcpClientConfig } from \"../types.js\";\nimport { normalizeZuoraMcpUrl } from \"../utils/zuora-url.js\";\nimport type {\n EnabledTenantAuth,\n ResolvedZuoraConnectionConfig,\n} from \"./connection-types.js\";\nimport { OAuthTokenProvider } from \"./oauth-token-provider.js\";\nimport {\n buildZuoraRequestHeaders,\n enabledTenantAuth,\n type ZuoraRequestHeaderOptions,\n} from \"./request-headers.js\";\nimport { resolveZuoraConnectionConfig } from \"./resolve-connection-config.js\";\n\nexport type ZuoraClientSharedState = {\n connection: ResolvedZuoraConnectionConfig;\n tokenProvider: OAuthTokenProvider;\n restBaseUrl: string;\n maxDownloadBytes?: number;\n};\n\nexport type CreateZuoraClientOptions = ZuoraHttpMcpClientConfig & {\n maxDownloadBytes?: number;\n};\n\nexport class ZuoraClient {\n protected constructor(protected readonly shared: ZuoraClientSharedState) {}\n\n static createSharedState(\n config: CreateZuoraClientOptions,\n ): ZuoraClientSharedState {\n const { remoteUrl, restBaseUrl } = normalizeZuoraMcpUrl(config.url);\n const connection = resolveZuoraConnectionConfig(config, remoteUrl);\n const normalizedRestBaseUrl = restBaseUrl.replace(/\\/+$/, \"\");\n\n return {\n connection,\n tokenProvider: new OAuthTokenProvider(\n connection,\n normalizedRestBaseUrl,\n ),\n restBaseUrl: normalizedRestBaseUrl,\n ...(typeof config.maxDownloadBytes === \"number\"\n ? { maxDownloadBytes: config.maxDownloadBytes }\n : {}),\n };\n }\n\n protected get connection(): ResolvedZuoraConnectionConfig {\n return this.shared.connection;\n }\n\n protected get tokenProvider(): OAuthTokenProvider {\n return this.shared.tokenProvider;\n }\n\n protected get restBaseUrl(): string {\n return this.shared.restBaseUrl;\n }\n\n protected get maxDownloadBytes(): number | undefined {\n return this.shared.maxDownloadBytes;\n }\n\n getTenantId(): string | undefined {\n return (\n this.enabledTenantAuth()?.tenantId ?? this.tokenProvider.getTenantId()\n );\n }\n\n protected async restGet(\n path: string,\n options: { signal?: AbortSignal } = {},\n ): Promise<Response> {\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n const url = `${this.restBaseUrl}${normalizedPath}`;\n const retryAttempts = this.enabledTenantAuth() ? [false] : [false, true];\n\n for (const retry of retryAttempts) {\n const response = await fetch(url, {\n method: \"GET\",\n headers: await this.buildHeaders({\n accept: \"*/*\",\n }),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n\n if (\n !retry &&\n (response.status === 401 || response.status === 403) &&\n !this.enabledTenantAuth()\n ) {\n this.tokenProvider.invalidateAccessToken();\n continue;\n }\n\n return response;\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"ZUORA_REST_AUTH_RETRY_FAILED\",\n message: \"Zuora REST request failed after auth retry.\",\n category: \"auth\",\n });\n }\n\n protected async buildHeaders(\n options: Pick<ZuoraRequestHeaderOptions, \"accept\" | \"contentType\">,\n ): Promise<Record<string, string>> {\n const tenantAuth = this.enabledTenantAuth();\n const accessToken = tenantAuth\n ? undefined\n : await this.tokenProvider.ensureAccessToken();\n\n return buildZuoraRequestHeaders(this.connection, {\n ...(accessToken ? { accessToken } : {}),\n userAgent: `${this.connection.clientName}/${this.connection.clientVersion}`,\n accept: options.accept,\n ...(options.contentType ? { contentType: options.contentType } : {}),\n });\n }\n\n protected enabledTenantAuth(): EnabledTenantAuth | undefined {\n return enabledTenantAuth(this.connection);\n }\n}\n","import { ZuoraAgentToolkitError } from \"../errors.js\";\nimport {\n ZuoraClient,\n type ZuoraClientSharedState,\n} from \"./zuora-client.js\";\n\nexport type ZuoraRestDownloadFileResult = {\n bytes: Uint8Array;\n contentType?: string;\n contentDisposition?: string;\n};\n\nexport class ZuoraRestClient extends ZuoraClient {\n constructor(shared: ZuoraClientSharedState) {\n super(shared);\n }\n\n async downloadFile(\n fileId: string,\n options: { signal?: AbortSignal } = {},\n ): Promise<ZuoraRestDownloadFileResult> {\n const normalizedFileId = fileId.trim();\n\n if (!normalizedFileId) {\n throw new ZuoraAgentToolkitError({\n code: \"INVALID_INPUT\",\n message: \"fileId is required for Zuora REST file download.\",\n category: \"validation\",\n recoverable: true,\n });\n }\n\n const response = await this.restGet(\n `/v1/files/${encodeURIComponent(normalizedFileId)}`,\n options,\n );\n\n if (!response.ok) {\n throw new ZuoraAgentToolkitError({\n code: \"ZUORA_REST_FILE_DOWNLOAD_FAILED\",\n message: `Zuora REST file download failed with HTTP ${response.status}.`,\n category: response.status === 404 ? \"validation\" : \"mcp\",\n retryable: response.status >= 500,\n recoverable: response.status === 404,\n details: {\n fileId: normalizedFileId,\n status: response.status,\n },\n });\n }\n\n const bytes = await readResponseBytes(response, this.maxDownloadBytes);\n const contentType = response.headers.get(\"content-type\");\n const contentDisposition = response.headers.get(\"content-disposition\");\n\n return {\n bytes,\n ...(contentType ? { contentType } : {}),\n ...(contentDisposition ? { contentDisposition } : {}),\n };\n }\n}\n\nconst readResponseBytes = async (\n response: Response,\n maxDownloadBytes: number | undefined,\n): Promise<Uint8Array> => {\n if (!response.body) {\n const buffer = new Uint8Array(await response.arrayBuffer());\n\n if (\n typeof maxDownloadBytes === \"number\" &&\n buffer.byteLength > maxDownloadBytes\n ) {\n throw new ZuoraAgentToolkitError({\n code: \"ZUORA_REST_FILE_TOO_LARGE\",\n message: `Zuora REST file download exceeded ${maxDownloadBytes} bytes.`,\n category: \"validation\",\n recoverable: true,\n });\n }\n\n return buffer;\n }\n\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let totalBytes = 0;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (!value) {\n continue;\n }\n\n totalBytes += value.byteLength;\n\n if (typeof maxDownloadBytes === \"number\" && totalBytes > maxDownloadBytes) {\n throw new ZuoraAgentToolkitError({\n code: \"ZUORA_REST_FILE_TOO_LARGE\",\n message: `Zuora REST file download exceeded ${maxDownloadBytes} bytes.`,\n category: \"validation\",\n recoverable: true,\n });\n }\n\n chunks.push(value);\n }\n\n const bytes = new Uint8Array(totalBytes);\n let offset = 0;\n\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return bytes;\n};\n","import { SafetyMode } from \"./types.js\";\nimport type {\n BundleConfiguration,\n ToolkitBundleName,\n ToolSelection,\n ZuoraSafetyMode,\n ZuoraToolkitConfiguration,\n} from \"./types.js\";\n\nexport type ToolSelectionPolicy = {\n mode: ZuoraSafetyMode;\n bundles: Set<ToolkitBundleName>;\n include: Set<string>;\n exclude: Set<string>;\n};\n\nexport const resolveToolSelectionPolicy = (\n configuration: ZuoraToolkitConfiguration | undefined,\n selection?: ToolSelection,\n): ToolSelectionPolicy => ({\n mode: resolveToolMode(configuration, selection),\n bundles: resolveBundles(configuration, selection),\n include: new Set([\n ...resolveIncludedToolNames(configuration),\n ...(selection?.include ?? []),\n ]),\n exclude: new Set([\n ...resolveExcludedToolNames(configuration),\n ...(selection?.exclude ?? []),\n ]),\n});\n\nexport const resolveToolMode = (\n configuration: ZuoraToolkitConfiguration | undefined,\n selection?: ToolSelection,\n): ZuoraSafetyMode => selection?.mode ?? configuration?.mode ?? SafetyMode.ReadOnly;\n\nexport const resolveExcludedToolNames = (\n configuration: ZuoraToolkitConfiguration | undefined,\n): Set<string> =>\n new Set([\n ...resolveConfiguredExcludedToolNames(configuration),\n ...resolveBundleExcludedToolNames(configuration),\n ]);\n\nconst resolveBundles = (\n configuration: ZuoraToolkitConfiguration | undefined,\n selection?: ToolSelection,\n): Set<ToolkitBundleName> => {\n if (selection?.bundles) {\n return new Set(selection.bundles);\n }\n\n const configured = configuration?.bundles;\n\n if (!configured) {\n return new Set();\n }\n\n return new Set(\n Object.entries(configured)\n .filter(([, value]) => Boolean(value))\n .map(([name]) => name as ToolkitBundleName),\n );\n};\n\nconst resolveIncludedToolNames = (\n configuration: ZuoraToolkitConfiguration | undefined,\n): string[] => {\n const tools = configuration?.tools ?? {};\n\n return Object.entries(tools)\n .filter(([, enabled]) => enabled)\n .map(([name]) => name);\n};\n\nconst resolveConfiguredExcludedToolNames = (\n configuration: ZuoraToolkitConfiguration | undefined,\n): string[] => {\n const tools = configuration?.tools ?? {};\n\n return Object.entries(tools)\n .filter(([, enabled]) => !enabled)\n .map(([name]) => name);\n};\n\nconst resolveBundleExcludedToolNames = (\n configuration: ZuoraToolkitConfiguration | undefined,\n): string[] => {\n const bundles = configuration?.bundles ?? {};\n\n return Object.values(bundles).flatMap((value) => {\n if (typeof value === \"object\" && value) {\n const config = value as BundleConfiguration;\n return config.exclude ?? [];\n }\n\n return [];\n });\n};\n","import type { McpToolCallResult } from \"./mcp-types.js\";\n\n/**\n * Extracts a human-readable error message from an MCP tools/call error result.\n */\nexport const extractMcpToolErrorMessage = (\n result: McpToolCallResult,\n): string | undefined => {\n if (Array.isArray(result.content)) {\n for (const item of result.content) {\n if (\n item != null &&\n typeof item === \"object\" &&\n \"text\" in item &&\n typeof (item as { text?: unknown }).text === \"string\"\n ) {\n const text = (item as { text: string }).text.trim();\n if (text) {\n return text;\n }\n }\n }\n }\n\n if (result.structuredContent != null) {\n if (\n typeof result.structuredContent === \"object\" &&\n result.structuredContent !== null &&\n \"message\" in result.structuredContent &&\n typeof (result.structuredContent as { message?: unknown }).message ===\n \"string\"\n ) {\n return (result.structuredContent as { message: string }).message;\n }\n\n // Do not serialize the full structuredContent — it may contain raw MCP\n // response body fields that should not appear in error messages per the\n // security guidance. Use a generic fallback instead.\n return \"MCP tool call returned a structured error response.\";\n }\n\n return undefined;\n};\n","import { ZuoraAgentToolkitError } from \"../errors.js\";\nimport {\n redactSensitiveDetails,\n redactSensitiveString,\n} from \"../utils/redaction.js\";\nimport type { JsonRpcResponse } from \"./mcp-types.js\";\n\nexport const parseJsonRpcResponse = async <T>({\n response,\n sensitiveValues,\n}: {\n response: Response;\n sensitiveValues: readonly string[];\n}): Promise<T> => {\n const text = await response.text();\n\n if (!response.ok) {\n throw new ZuoraAgentToolkitError({\n code: \"MCP_HTTP_ERROR\",\n message: `Zuora MCP request failed with HTTP ${response.status}.`,\n category:\n response.status === 401 || response.status === 403 ? \"auth\" : \"mcp\",\n retryable: response.status >= 500,\n details: redactSensitiveString(text, sensitiveValues),\n });\n }\n\n if (!text.trim()) {\n return {} as T;\n }\n\n const json = parseResponseBody(text, response.headers.get(\"content-type\"));\n\n if (json.error) {\n throw new ZuoraAgentToolkitError({\n code: \"MCP_JSON_RPC_ERROR\",\n message: redactSensitiveString(json.error.message, sensitiveValues),\n category: \"mcp\",\n details: redactSensitiveDetails(json.error, sensitiveValues),\n });\n }\n\n return (json.result ?? {}) as T;\n};\n\nconst parseResponseBody = (\n text: string,\n contentType: string | null,\n): JsonRpcResponse<unknown> => {\n if (contentType?.includes(\"text/event-stream\")) {\n const dataLines = text\n .split(/\\r?\\n/)\n .filter((line) => line.startsWith(\"data:\"))\n .map((line) => line.slice(\"data:\".length).trim())\n .filter((line) => line && line !== \"[DONE]\");\n\n const payload = dataLines.find((line) => line.startsWith(\"{\"));\n\n if (!payload) {\n return {};\n }\n\n return JSON.parse(payload) as JsonRpcResponse<unknown>;\n }\n\n return JSON.parse(text) as JsonRpcResponse<unknown>;\n};\n","import { ZuoraAgentToolkitError } from \"../errors.js\";\nimport type {\n ZuoraHttpMcpClientConfig,\n ZuoraToolExecutionResult,\n} from \"../types.js\";\nimport { extractMcpToolErrorMessage } from \"./mcp-tool-error.js\";\nimport { parseJsonRpcResponse } from \"./json-rpc.js\";\nimport { normalizeExecutionRequestMetadata } from \"./request-metadata.js\";\nimport type {\n McpInitializeResult,\n McpReadResourceResult,\n McpTool,\n McpToolCallResult,\n McpToolsListResult,\n} from \"./mcp-types.js\";\nimport {\n ZuoraClient,\n type ZuoraClientSharedState,\n} from \"./zuora-client.js\";\n\nexport class ZuoraHttpMcpClient extends ZuoraClient {\n private mcpRequestId = 0;\n\n private mcpInitialized = false;\n\n private mcpSessionId: string | undefined;\n\n constructor(config: ZuoraHttpMcpClientConfig) {\n super(ZuoraClient.createSharedState(config));\n }\n\n /** @internal Used by ZuoraRestClient via shared state injection. */\n static fromSharedState(shared: ZuoraClientSharedState): ZuoraHttpMcpClient {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- bypass private constructor\n const instance = Object.create(ZuoraHttpMcpClient.prototype) as ZuoraHttpMcpClient;\n (instance as unknown as { shared: ZuoraClientSharedState }).shared = shared;\n instance.mcpRequestId = 0;\n instance.mcpInitialized = false;\n instance.mcpSessionId = undefined;\n return instance;\n }\n\n async initialize(): Promise<void> {\n if (!this.enabledTenantAuth()) {\n await this.tokenProvider.ensureAccessToken();\n }\n\n if (this.mcpInitialized) {\n return;\n }\n\n await this.postMcpJsonRpc<McpInitializeResult>(\"initialize\", {\n protocolVersion: this.connection.protocolVersion,\n capabilities: {},\n clientInfo: {\n name: this.connection.clientName,\n version: this.connection.clientVersion,\n },\n });\n\n await this.postMcpNotification(\"notifications/initialized\");\n this.mcpInitialized = true;\n }\n\n async listTools(): Promise<McpTool[]> {\n await this.initialize();\n\n const result = await this.postMcpJsonRpc<McpToolsListResult>(\n \"tools/list\",\n {},\n );\n return result.tools ?? [];\n }\n\n async callTool(\n name: string,\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n await this.initialize();\n\n const result = await this.postMcpJsonRpc<McpToolCallResult>(\"tools/call\", {\n name,\n arguments: input,\n });\n\n if (result.isError) {\n const mcpMessage = extractMcpToolErrorMessage(result);\n throw new ZuoraAgentToolkitError({\n code: \"TOOL_EXECUTION_ERROR\",\n message:\n mcpMessage ??\n `Zuora MCP tool \"${name}\" returned an error.`,\n category: \"tool_execution\",\n });\n }\n\n const request = normalizeExecutionRequestMetadata(result.request);\n const requestId = request?.requestId ?? request?.zuoraRequestId;\n\n return {\n toolName: name,\n data: result.structuredContent ?? result.content ?? result,\n ...(requestId ? { requestId } : {}),\n ...(request ? { request } : {}),\n };\n }\n\n async readResource(uri: string): Promise<McpReadResourceResult> {\n await this.initialize();\n\n return this.postMcpJsonRpc<McpReadResourceResult>(\"resources/read\", {\n uri,\n });\n }\n\n getSensitiveValues(): readonly string[] {\n return this.tokenProvider.sensitiveValues();\n }\n\n async close(): Promise<void> {\n this.mcpInitialized = false;\n this.mcpSessionId = undefined;\n }\n\n private async postMcpJsonRpc<T>(\n method: string,\n params: Record<string, unknown>,\n ): Promise<T> {\n const id = ++this.mcpRequestId;\n const retryAttempts = this.enabledTenantAuth() ? [false] : [false, true];\n\n for (const retry of retryAttempts) {\n const response = await fetch(this.connection.url, {\n method: \"POST\",\n headers: await this.buildMcpHeaders(),\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id,\n method,\n params,\n }),\n });\n\n const sessionId = response.headers.get(\"mcp-session-id\");\n if (sessionId) {\n this.mcpSessionId = sessionId;\n }\n\n try {\n return await parseJsonRpcResponse<T>({\n response,\n sensitiveValues: this.tokenProvider.sensitiveValues(),\n });\n } catch (error) {\n if (\n retry ||\n !(error instanceof ZuoraAgentToolkitError) ||\n error.category !== \"auth\"\n ) {\n throw error;\n }\n\n this.tokenProvider.invalidateAccessToken();\n }\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"MCP_AUTH_RETRY_FAILED\",\n message: `MCP request ${method} failed after auth retry.`,\n category: \"auth\",\n });\n }\n\n private async postMcpNotification(method: string): Promise<void> {\n const retryAttempts = this.enabledTenantAuth() ? [false] : [false, true];\n\n for (const retry of retryAttempts) {\n const response = await fetch(this.connection.url, {\n method: \"POST\",\n headers: await this.buildMcpHeaders(),\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n method,\n }),\n });\n\n const sessionId = response.headers.get(\"mcp-session-id\");\n if (sessionId) {\n this.mcpSessionId = sessionId;\n }\n\n if (response.ok) {\n return;\n }\n\n const error = new ZuoraAgentToolkitError({\n code: \"MCP_NOTIFICATION_FAILED\",\n message: `MCP notification ${method} failed with HTTP ${response.status}.`,\n category:\n response.status === 401 || response.status === 403 ? \"auth\" : \"mcp\",\n retryable: response.status >= 500,\n });\n\n if (retry || error.category !== \"auth\") {\n throw error;\n }\n\n this.tokenProvider.invalidateAccessToken();\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"MCP_AUTH_RETRY_FAILED\",\n message: `MCP notification ${method} failed after auth retry.`,\n category: \"auth\",\n });\n }\n\n private async buildMcpHeaders(): Promise<Record<string, string>> {\n const baseHeaders = await this.buildHeaders({\n accept: \"application/json, text/event-stream\",\n contentType: \"application/json\",\n });\n\n return {\n ...baseHeaders,\n ...(this.mcpSessionId ? { \"mcp-session-id\": this.mcpSessionId } : {}),\n };\n }\n}\n","import { enforceApproval } from \"./approval-policy.js\";\nimport {\n buildAsyncJobResult,\n DEFAULT_ASYNC_JOB_TERMINAL_STATUSES,\n resolveAsyncJobStatusDetails,\n type ZuoraAsyncJobResult,\n} from \"./async-jobs.js\";\nimport {\n getBundleDefinition,\n hasBundleDefinition,\n ZUORA_BUNDLE_NAMES,\n} from \"./bundles.js\";\nimport { ZuoraAgentToolkitError } from \"./errors.js\";\nimport {\n createMcpToolInput,\n enforceOperationSelector,\n} from \"./tools/operation-metadata.js\";\nimport {\n compactToolkitError,\n metadataLoadedEventMetadata,\n normalizeToolkitEvent,\n reportObservabilitySinkError,\n type InternalToolkitEvent,\n} from \"./observability/events.js\";\nimport {\n logAsyncPollChecked,\n type AsyncPollTerminationDecision,\n} from \"./observability/async-poll-events.js\";\nimport {\n compactToolInputForEvent,\n compactToolOutputForEvent,\n} from \"./observability/payloads.js\";\nimport { extractExecutionRequestMetadata } from \"./observability/request-metadata.js\";\nimport { NativeFileArtifactTools } from \"./tools/native/file-artifacts/index.js\";\nimport { resolveNativeFileToolsInput } from \"./tools/native/resolve-native-file-tools-input.js\";\nimport { resolveNativeQueryResultDownloadConfig } from \"./tools/native/query-result-download/config.js\";\nimport { resolveQueryResultStatusCall } from \"./tools/native/query-result-download/helpers/status-resolver.js\";\nimport { NativeQueryResultDownloadTools } from \"./tools/native/query-result-download/index.js\";\nimport type { NativeRuntimeTool } from \"./tools/native/registry-source.js\";\nimport { resolveNativeZuoraFileDownloadConfig } from \"./tools/native/zuora-file-download/config.js\";\nimport { NativeZuoraFileDownloadTools } from \"./tools/native/zuora-file-download/index.js\";\nimport { normalizeMcpTools } from \"./tools/mcp-tool-definition.js\";\nimport { ZuoraRestClient } from \"./transport/zuora-rest-client.js\";\nimport { ZuoraClient } from \"./transport/zuora-client.js\";\nimport {\n resolveToolSelectionPolicy,\n type ToolSelectionPolicy,\n} from \"./tool-selection.js\";\nimport { ZuoraHttpMcpClient } from \"./transport/mcp-client.js\";\nimport { isRecord } from \"./utils/values.js\";\nimport { SafetyMode } from \"./types.js\";\nimport type {\n EventSanitizerLimits,\n ZuoraAgentToolkitConfig,\n ZuoraBundleDefinition,\n ZuoraBundleName,\n ZuoraConnectionConfig,\n ZuoraHttpMcpClientConfig,\n ZuoraMcpClient,\n ZuoraToolDefinition,\n ZuoraToolExecutionResult,\n ZuoraToolkitEvent,\n ZuoraWaitForJobOptions,\n ToolSelection,\n} from \"./types.js\";\nimport { normalizeIdList } from \"./utils/values.js\";\nimport { inferZuoraEnvironment } from \"./utils/zuora-url.js\";\n\nconst createHttpMcpClientConfig = (\n config: ZuoraAgentToolkitConfig,\n): ZuoraHttpMcpClientConfig => {\n // Routing IDs from configuration.context take precedence over connection-level values.\n const contextEntityIds = config.configuration?.context?.entityIds;\n const contextOrgIds = config.configuration?.context?.orgIds;\n const contextOverrides = {\n ...(contextEntityIds ? { entityIds: contextEntityIds } : {}),\n ...(contextOrgIds ? { orgIds: contextOrgIds } : {}),\n };\n\n // Narrow to the tenantAuth variant — only that variant carries `connection`.\n const connection = \"connection\" in config ? config.connection : undefined;\n\n if (isTenantAuthConnection(connection)) {\n return {\n url: config.baseUrl,\n ...(config.auth ? { auth: config.auth } : {}),\n ...connection,\n ...contextOverrides,\n };\n }\n\n if (!config.auth) {\n throw new ZuoraAgentToolkitError({\n code: \"MISSING_AUTH\",\n message:\n \"Zuora auth configuration is required unless tenant auth is enabled.\",\n category: \"auth\",\n });\n }\n\n return {\n url: config.baseUrl,\n auth: config.auth,\n ...(connection ?? {}),\n ...contextOverrides,\n };\n};\n\nconst isTenantAuthConnection = (\n connection: ZuoraConnectionConfig | undefined,\n): connection is Extract<\n ZuoraConnectionConfig,\n { tenantAuth: { enabled: true } }\n> => connection?.tenantAuth?.enabled === true;\n\nconst filterCatalogTools = (\n tools: ZuoraToolDefinition[],\n policy: ToolSelectionPolicy,\n): ZuoraToolDefinition[] =>\n tools.filter((tool) => {\n if (policy.mode === SafetyMode.ReadOnly && tool.meta.access === \"write\") {\n return false;\n }\n\n if (policy.bundles.size > 0 && !policy.bundles.has(tool.meta.bundle)) {\n return false;\n }\n\n if (policy.include.size > 0 && !policy.include.has(tool.name)) {\n return false;\n }\n\n if (policy.exclude.has(tool.name)) {\n return false;\n }\n\n return true;\n });\n\n// Generic parameter T is the framework-native tool type each adapter returns.\n// e.g. ToolkitCore<ChatCompletionTool> for OpenAI, ToolkitCore<StructuredTool> for LangChain.\n// Framework adapters extend ToolkitCore and override only convertTools().\n// All other methods are intended to be final — do not override them.\nexport abstract class ToolkitCore<T> {\n protected readonly config: ZuoraAgentToolkitConfig;\n\n protected mcpClient: ZuoraMcpClient;\n\n private catalogTools: ZuoraToolDefinition[] | undefined;\n\n private _initialized = false;\n\n // Resolved once at construction so we never read process.env at runtime.\n private readonly sanitizerLimits: EventSanitizerLimits | undefined;\n\n // SDK-native tool sets (e.g. file-artifacts). Indexed by tool name for O(1) dispatch.\n private readonly nativeFileArtifactTools: NativeFileArtifactTools;\n\n private readonly nativeQueryResultDownloadTools: NativeQueryResultDownloadTools;\n\n private readonly nativeZuoraFileDownloadTools: NativeZuoraFileDownloadTools;\n\n // REST client for Zuora file downloads (used by zuora-file-download sub-module).\n private readonly restClient: ZuoraRestClient;\n\n private nativeToolRegistry: Map<string, NativeRuntimeTool> | undefined;\n\n constructor(config: ZuoraAgentToolkitConfig) {\n this.config = config;\n const nativeFileTools = resolveNativeFileToolsInput(config);\n this.sanitizerLimits = config.observability?.sanitizerLimits;\n this.mcpClient = new ZuoraHttpMcpClient(createHttpMcpClientConfig(config));\n // REST client shares the same connection config as the MCP client.\n const sharedState = ZuoraClient.createSharedState({\n ...createHttpMcpClientConfig(config),\n ...(typeof nativeFileTools?.maxDownloadBytes === \"number\"\n ? { maxDownloadBytes: nativeFileTools.maxDownloadBytes }\n : {}),\n });\n this.restClient = new ZuoraRestClient(sharedState);\n // MCP client is passed so read_resource can forward to the underlying MCP server.\n this.nativeFileArtifactTools = new NativeFileArtifactTools(\n nativeFileTools,\n { mcpClient: this.mcpClient },\n );\n const queryResultDownloadConfig = resolveNativeQueryResultDownloadConfig(\n nativeFileTools,\n { fileArtifactsEnabled: this.nativeFileArtifactTools.isEnabled() },\n );\n this.nativeQueryResultDownloadTools = new NativeQueryResultDownloadTools({\n enabled: queryResultDownloadConfig.enabled,\n tool: queryResultDownloadConfig.tool,\n fetchQueryResult: (jobId) => this.fetchQueryResultForDownload(jobId),\n downloadFile: (input) => this.nativeFileArtifactTools.downloadFile(input),\n });\n const zuoraFileDownloadConfig = resolveNativeZuoraFileDownloadConfig(\n nativeFileTools,\n { fileArtifactsEnabled: this.nativeFileArtifactTools.isEnabled() },\n );\n this.nativeZuoraFileDownloadTools = new NativeZuoraFileDownloadTools({\n enabled: zuoraFileDownloadConfig.enabled,\n tool: zuoraFileDownloadConfig.tool,\n fetchZuoraFile: (fileId) => this.restClient.downloadFile(fileId),\n persistDownload: (options) =>\n this.nativeFileArtifactTools.persistBufferedDownload(options),\n });\n }\n\n async initialize(): Promise<void> {\n if (this._initialized) {\n return;\n }\n\n const startedAt = Date.now();\n await this.mcpClient.initialize?.();\n const rawTools = await this.mcpClient.listTools();\n const mcpCatalogTools = normalizeMcpTools(\n rawTools,\n this.resolveSplitOperations(),\n );\n\n // Build native tool registry and merge definitions into catalog.\n // Collect all native runtime tools from all SDK-native sub-modules.\n const nativeRuntimeTools = [\n ...this.nativeFileArtifactTools.listTools(),\n ...this.nativeQueryResultDownloadTools.listTools(),\n ...this.nativeZuoraFileDownloadTools.listTools(),\n ];\n this.nativeToolRegistry = new Map(\n nativeRuntimeTools.map((runtimeTool) => [\n runtimeTool.definition.name,\n runtimeTool,\n ]),\n );\n const nativeToolDefinitions = nativeRuntimeTools.map(\n (runtimeTool) => runtimeTool.definition,\n );\n\n this.catalogTools = [...mcpCatalogTools, ...nativeToolDefinitions];\n this._initialized = true;\n\n this.emit({\n name: \"metadata.loaded\",\n latencyMs: Date.now() - startedAt,\n ...this.createEventContext(),\n metadata: metadataLoadedEventMetadata(this.catalogTools),\n });\n }\n\n async close(): Promise<void> {\n await this.mcpClient.close?.();\n this._initialized = false;\n this.catalogTools = undefined;\n this.nativeToolRegistry = undefined;\n }\n\n async listTools(selection?: ToolSelection): Promise<ZuoraToolDefinition[]> {\n this.warnIfNotInitialized();\n return filterCatalogTools(\n this.getNormalizedTools(),\n resolveToolSelectionPolicy(this.config.configuration, selection),\n );\n }\n\n /**\n * Returns framework-native tool objects for the given selection.\n *\n * @param selection - Optional filter (bundles, mode) to narrow the catalog.\n * @param maxTools - When provided and greater than zero, limits the result to\n * the first `maxTools` entries after filtering. Values ≤ 0 are treated as\n * no-limit. Does not affect `loadFollowUpTools()`, which always searches\n * the full catalog.\n */\n async getTools(selection?: ToolSelection, maxTools?: number): Promise<T[]> {\n this.warnIfNotInitialized();\n let filtered = filterCatalogTools(\n this.getNormalizedTools(),\n resolveToolSelectionPolicy(this.config.configuration, selection),\n );\n\n if (typeof maxTools === \"number\" && maxTools > 0) {\n filtered = filtered.slice(0, maxTools);\n }\n\n return this.convertTools(filtered);\n }\n\n async listBundles(): Promise<ZuoraBundleDefinition[]> {\n this.warnIfNotInitialized();\n const tools = this.getNormalizedTools();\n\n return ZUORA_BUNDLE_NAMES.map((name) => getBundleDefinition(name, tools));\n }\n\n async describeBundle(name: ZuoraBundleName): Promise<ZuoraBundleDefinition> {\n this.warnIfNotInitialized();\n\n if (!hasBundleDefinition(name)) {\n throw new ZuoraAgentToolkitError({\n code: \"BUNDLE_NOT_FOUND\",\n message: `Unknown Zuora bundle: ${name}`,\n category: \"configuration\",\n });\n }\n\n return getBundleDefinition(name, this.getNormalizedTools());\n }\n\n async describeTool(name: string): Promise<ZuoraToolDefinition | undefined> {\n this.warnIfNotInitialized();\n return this.getNormalizedTools().find((tool) => tool.name === name);\n }\n\n async callTool(\n operationName: string,\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n this.warnIfNotInitialized();\n\n const tool = this.getNormalizedTools().find(\n (candidate) => candidate.name === operationName,\n );\n\n if (!tool) {\n throw new ZuoraAgentToolkitError({\n code: \"TOOL_NOT_FOUND\",\n message: `Unknown Zuora tool: ${operationName}`,\n category: \"configuration\",\n });\n }\n\n const mode = this.config.configuration?.mode ?? SafetyMode.ReadOnly;\n\n if (mode === SafetyMode.ReadOnly && tool.meta.access === \"write\") {\n throw new ZuoraAgentToolkitError({\n code: \"TOOL_EXECUTION_ERROR\",\n message: `Write tool \"${operationName}\" is disabled in readOnly mode.`,\n category: \"tool_execution\",\n });\n }\n\n // Resolve native runtime tool for approval metadata enrichment and execution routing.\n const nativeRuntimeTool = this.nativeToolRegistry?.get(operationName);\n const nativeApprovalMetadata = nativeRuntimeTool?.approvalMetadata(input);\n\n // For merged tools, derive per-operation access and risk from the invoked\n // operation so approval policy and observability events reflect the actual\n // operation rather than the aggregated worst-case values on the merged tool.\n const invokedOperation =\n tool.meta.operationSelector\n ? String(input[tool.meta.operationSelector] ?? \"\")\n : undefined;\n const effectiveAccess: ZuoraToolDefinition[\"meta\"][\"access\"] =\n (invokedOperation\n ? tool.meta.operationAccess?.[invokedOperation]\n : undefined) ?? tool.meta.access;\n const effectiveRiskLevel: ZuoraToolDefinition[\"meta\"][\"riskLevel\"] =\n (invokedOperation\n ? tool.meta.operationRiskLevel?.[invokedOperation]\n : undefined) ?? tool.meta.riskLevel;\n const effectiveTool: ZuoraToolDefinition =\n effectiveAccess === tool.meta.access &&\n effectiveRiskLevel === tool.meta.riskLevel\n ? tool\n : { ...tool, meta: { ...tool.meta, access: effectiveAccess, riskLevel: effectiveRiskLevel } };\n\n await enforceApproval(effectiveTool, input, this.config, (event) =>\n this.emit(event),\n nativeApprovalMetadata);\n\n const startedAt = Date.now();\n const includePayloads = this.config.observability?.includePayloads === true;\n const toolEventBase = {\n toolName: tool.name,\n access: effectiveAccess,\n bundle: tool.meta.bundle,\n riskLevel: effectiveRiskLevel,\n ...this.createEventContext(),\n };\n\n this.emit({\n name: \"tool.called\",\n ...toolEventBase,\n ...(includePayloads ? { input: compactToolInputForEvent(input) } : {}),\n });\n\n // Captured after the MCP call so tool.failed can include the raw\n // response when post-processing (e.g. async job extraction) throws.\n let rawMcpResult: ZuoraToolExecutionResult | undefined;\n\n try {\n let result: ZuoraToolExecutionResult;\n\n if (nativeRuntimeTool) {\n // SDK-native tool: execute locally, no MCP call.\n result = await nativeRuntimeTool.execute(input);\n } else {\n enforceOperationSelector(tool, input);\n const mcpInput = createMcpToolInput(tool, input);\n const rawResult = await this.mcpClient.callTool(\n tool.meta.sourceName,\n mcpInput,\n );\n rawMcpResult = { ...rawResult, riskLevel: tool.meta.riskLevel };\n // For multi-op merged tools, resolve the async meta from the operation\n // the LLM actually invoked (read from the input's operation field).\n const resolvedAsyncOperation: typeof tool.meta.asyncOperation =\n tool.meta.asyncOperation ??\n (tool.meta.asyncOperations && tool.meta.operationSelector\n ? tool.meta.asyncOperations[\n String(input[tool.meta.operationSelector] ?? \"\")\n ]\n : undefined);\n\n // Skip async job extraction when Zuora signals a business-level failure\n // via success:false. The result is a normal (error) response, not a job.\n const isApiFailure =\n isRecord(rawResult.data) && rawResult.data[\"success\"] === false;\n\n if (resolvedAsyncOperation && !isApiFailure) {\n const asyncJobResult = buildAsyncJobResult(\n rawResult,\n resolvedAsyncOperation,\n {\n sourceToolName: tool.meta.sourceName,\n ...(tool.meta.operationSelector\n ? { operationSelector: tool.meta.operationSelector }\n : {}),\n sourceOperationNames: this.getNormalizedTools()\n .filter(\n (candidate) =>\n candidate.meta.sourceName === tool.meta.sourceName,\n )\n .map(\n (candidate) =>\n candidate.meta.operationName ?? candidate.name,\n ),\n },\n );\n // Warn when asyncMeta provides neither pollingOperation nor pollingTool.\n // In this case resolveAsyncJobPollingToolNameFromMeta falls back to\n // sourceToolName, which may not be the intended polling target.\n if (\n resolvedAsyncOperation.pollingOperation === undefined &&\n resolvedAsyncOperation.pollingTool === undefined\n ) {\n this.config.observability?.logger?.warn?.(\n `[zuora-agent-toolkit] async operation metadata for tool \"${tool.name}\" ` +\n `has neither pollingOperation nor pollingTool. ` +\n `Polling will fall back to the source tool \"${tool.meta.sourceName}\" which may be incorrect. ` +\n `Check server metadata.`,\n );\n }\n\n // When the resolved pollingToolName is a split-style name (e.g.\n // \"manage_bill_runs__get_bill_run\") but only the merged tool exists in\n // the registry (splitOperations: false), fall back to the merged base\n // tool and inject the operation into pollingArgs.\n const resolvedPollingTool = this.getNormalizedTools().find(\n (t) => t.name === asyncJobResult.pollingToolName,\n );\n if (!resolvedPollingTool && resolvedAsyncOperation.pollingTool && resolvedAsyncOperation.pollingOperation) {\n const mergedPollingTool = this.getNormalizedTools().find(\n (t) => t.meta.sourceName === resolvedAsyncOperation.pollingTool && t.meta.operationSelector,\n );\n if (mergedPollingTool) {\n asyncJobResult.pollingToolName = mergedPollingTool.name;\n asyncJobResult.pollingArgs = {\n ...asyncJobResult.pollingArgs,\n [mergedPollingTool.meta.operationSelector!]: resolvedAsyncOperation.pollingOperation,\n };\n }\n }\n\n result = {\n toolName: tool.meta.sourceName,\n data: asyncJobResult,\n riskLevel: tool.meta.riskLevel,\n };\n } else {\n result = { ...rawResult, riskLevel: tool.meta.riskLevel };\n }\n }\n\n const requestMetadata = extractExecutionRequestMetadata(result);\n\n this.emit({\n name: \"tool.completed\",\n ...toolEventBase,\n ...requestMetadata,\n latencyMs: Date.now() - startedAt,\n ...(includePayloads ? { output: compactToolOutputForEvent(result) } : {}),\n });\n\n return result;\n } catch (error) {\n if (error instanceof ZuoraAgentToolkitError) {\n const eventError = compactToolkitError(error);\n // error.requestId is a client-side correlation ID, not a Zuora server\n // request ID. Only set requestId here; zuoraRequestId is reserved for\n // server-assigned trace IDs that would appear in the execution result.\n const requestMetadata = error.requestId\n ? { requestId: error.requestId }\n : {};\n\n const rawOutputForEvent =\n includePayloads && rawMcpResult\n ? { output: compactToolOutputForEvent(rawMcpResult) }\n : {};\n\n this.emit({\n name: \"tool.failed\",\n ...toolEventBase,\n ...requestMetadata,\n ...rawOutputForEvent,\n error: eventError,\n metadata: { error: eventError },\n });\n\n throw error;\n }\n\n const wrappedError = new ZuoraAgentToolkitError({\n code: \"TOOL_EXECUTION_ERROR\",\n message: `Tool \"${operationName}\" execution failed: ${\n error instanceof Error ? error.message : String(error)\n }`,\n category: \"tool_execution\",\n recoverable: true,\n });\n const eventError = compactToolkitError(wrappedError);\n\n const rawOutputForEvent =\n includePayloads && rawMcpResult\n ? { output: compactToolOutputForEvent(rawMcpResult) }\n : {};\n\n this.emit({\n name: \"tool.failed\",\n ...toolEventBase,\n ...rawOutputForEvent,\n error: eventError,\n metadata: { error: eventError },\n });\n\n throw wrappedError;\n }\n }\n\n /**\n * Polls an async job to completion using the polling operation specified in\n * the async job result. Returns the final polling tool execution result when\n * the job reaches a terminal state.\n *\n * Polling stops when:\n * - A terminal status is matched (success, failure, or canceled)\n * - The maximum number of poll attempts is exhausted\n * - The absolute timeout is exceeded\n *\n * @param toolName - The name of the tool that started the async job. Used for\n * observability context only.\n * @param asyncResult - The pending async job result from an initial tool call.\n * @param options - Optional overrides for polling behavior.\n * @throws ZuoraAgentToolkitError with ASYNC_JOB_TIMEOUT if the job does not\n * reach a terminal state within the configured limits.\n */\n async waitForJob(\n toolName: string,\n asyncResult: ZuoraAsyncJobResult,\n options?: ZuoraWaitForJobOptions,\n ): Promise<ZuoraToolExecutionResult> {\n this.warnIfNotInitialized();\n\n // Resolve terminal statuses: options override > asyncResult (from originating tool's asyncMeta) > defaults\n const terminalStatuses =\n options?.terminalStatuses ??\n asyncResult.terminalStatuses ??\n DEFAULT_ASYNC_JOB_TERMINAL_STATUSES;\n\n // Resolve statusPath from asyncResult (populated at job-start from the originating tool's asyncMeta),\n // falling back to a common \"status\" path on result.data\n const statusPath = asyncResult.statusPath ?? \"status\";\n\n // Resolve timing from options > asyncResult (from original async meta) > defaults\n const maxPollAttempts =\n options?.maxPollAttempts ??\n asyncResult.maxPollAttempts ??\n 50;\n\n const pollIntervalMs =\n options?.pollIntervalMs ??\n asyncResult.recommendedPollIntervalMs ??\n 2000;\n\n const timeoutMs =\n options?.timeoutMs ??\n asyncResult.defaultTimeoutMs ??\n 300_000; // 5 minutes\n\n const logger = this.config.observability?.logger;\n const startedAt = Date.now();\n\n for (let attempt = 1; attempt <= maxPollAttempts; attempt++) {\n // Check absolute timeout before polling\n if (Date.now() - startedAt >= timeoutMs) {\n throw new ZuoraAgentToolkitError({\n code: \"ASYNC_JOB_TIMEOUT\",\n message: `Async job \"${toolName}\" (id: ${asyncResult.jobId}) timed out after ${timeoutMs}ms.`,\n category: \"tool_execution\",\n recoverable: false,\n details: {\n jobId: asyncResult.jobId,\n toolName,\n pollingOperation: asyncResult.pollingOperation,\n attempt,\n timeoutMs,\n },\n });\n }\n\n // Build polling input: merge pollingArgs substituting jobId where referenced\n const pollingInput = resolvePollingInput(asyncResult);\n\n // Call the polling tool. pollingToolName is always set on ZuoraAsyncJobResult\n // (resolved at job-start time by resolveAsyncJobPollingToolNameFromMeta), so\n // no fallback to pollingOperation is needed here.\n const pollResult = await this.callTool(\n asyncResult.pollingToolName,\n pollingInput,\n );\n\n // Resolve status details\n const statusDetails = resolveAsyncJobStatusDetails(\n pollResult,\n statusPath,\n terminalStatuses,\n );\n\n // Determine decision for observability\n let decision: AsyncPollTerminationDecision;\n if (statusDetails.status == null) {\n decision = \"no_status\";\n } else if (statusDetails.terminalState === \"success\") {\n decision = \"success\";\n } else if (statusDetails.terminalState === \"failure\") {\n decision = \"failure\";\n } else if (statusDetails.terminalState === \"canceled\") {\n decision = \"canceled\";\n } else {\n decision = \"continue\";\n }\n\n logAsyncPollChecked(logger, {\n jobId: asyncResult.jobId,\n attempt,\n maxAttempts: maxPollAttempts,\n // pollingToolName is always set on ZuoraAsyncJobResult\n pollingToolName: asyncResult.pollingToolName,\n statusPath,\n statusSource: statusDetails.status != null ? \"statusPath\" : \"none\",\n resolvedValue: statusDetails.status,\n ...(statusDetails.status != null\n ? { resolvedStatus: statusDetails.status }\n : {}),\n terminalStatuses,\n matchedSuccess: statusDetails.terminalState === \"success\",\n matchedFailure: statusDetails.terminalState === \"failure\",\n matchedCanceled: statusDetails.terminalState === \"canceled\",\n decision,\n });\n\n if (statusDetails.isTerminal) {\n return pollResult;\n }\n\n // Not terminal yet — wait before next attempt (unless this is the last)\n if (attempt < maxPollAttempts) {\n await sleep(pollIntervalMs);\n }\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"ASYNC_JOB_TIMEOUT\",\n message: `Async job \"${toolName}\" (id: ${asyncResult.jobId}) did not reach a terminal state after ${maxPollAttempts} poll attempts.`,\n category: \"tool_execution\",\n recoverable: false,\n details: {\n jobId: asyncResult.jobId,\n toolName,\n pollingOperation: asyncResult.pollingOperation,\n maxPollAttempts,\n },\n });\n }\n\n protected abstract convertTools(tools: ZuoraToolDefinition[]): T[];\n\n /**\n * Returns the full normalized tool catalog after initialization.\n *\n * @internal For use by adapter subclasses only (e.g. to implement\n * follow-up tool resolution against the full catalog). Do not call\n * from outside the class hierarchy.\n */\n protected getNormalizedTools(): ZuoraToolDefinition[] {\n return this.catalogTools ?? [];\n }\n\n private resolveSplitOperations(): boolean {\n return this.config.configuration?.splitOperations ?? false;\n }\n\n private warnIfNotInitialized(): void {\n if (!this._initialized) {\n console.warn(\n \"Zuora Agent Toolkit accessed before initialize(). Call await toolkit.initialize() first.\",\n );\n }\n }\n\n protected emit(event: InternalToolkitEvent): void {\n const normalizedEvent = normalizeToolkitEvent(event, this.sanitizerLimits);\n const logger = this.config.observability?.logger;\n\n try {\n this.config.observability?.onEvent?.(normalizedEvent);\n } catch (error) {\n reportObservabilitySinkError(logger, error);\n }\n\n try {\n const emitResult = this.config.observability?.emit?.(normalizedEvent);\n if (emitResult) {\n void Promise.resolve(emitResult).catch((error) => {\n reportObservabilitySinkError(logger, error);\n });\n }\n } catch (error) {\n reportObservabilitySinkError(logger, error);\n }\n\n const message = `[zuora-agent-toolkit] ${normalizedEvent.name}`;\n\n try {\n if (normalizedEvent.name === \"tool.failed\") {\n logger?.error?.(message, normalizedEvent);\n return;\n }\n if (normalizedEvent.name === \"approval.requested\") {\n logger?.warn?.(message, normalizedEvent);\n return;\n }\n if (\n normalizedEvent.executionPhase === \"async_poll\" &&\n (normalizedEvent.name === \"tool.called\" ||\n normalizedEvent.name === \"tool.completed\" ||\n normalizedEvent.name === \"async.poll.checked\")\n ) {\n logger?.debug?.(message, normalizedEvent);\n return;\n }\n logger?.info?.(message, normalizedEvent);\n } catch {\n // Observability sinks are best-effort.\n }\n }\n\n /**\n * Fetches a Data Query job result to extract the dataFile download URL.\n * Called by NativeQueryResultDownloadTools to resolve the presigned S3 URL\n * for a completed query job before handing off to downloadFile.\n */\n private async fetchQueryResultForDownload(\n jobId: string,\n ): Promise<ZuoraToolExecutionResult> {\n const tools = this.getNormalizedTools();\n const statusCall = resolveQueryResultStatusCall(tools, jobId);\n\n if (!statusCall) {\n throw new ZuoraAgentToolkitError({\n code: \"QUERY_RESULT_STATUS_TOOL_NOT_FOUND\",\n message:\n \"Could not find a Data Query job status tool to resolve the query result dataFile URL.\",\n category: \"native_file_tools\",\n recoverable: true,\n details: {\n jobId,\n expectedTool: \"manage_data_queries__get_query_job\",\n },\n });\n }\n\n return this.callTool(statusCall.toolName, statusCall.input);\n }\n\n private createEventContext(): Pick<\n ZuoraToolkitEvent,\n \"environment\" | \"tenantId\" | \"entityIds\" | \"orgIds\"\n > {\n const configurationContext = this.config.configuration?.context ?? {};\n const entityIds =\n normalizeIdList(configurationContext.entityIds) ??\n normalizeIdList(configurationContext.entityId);\n const orgIds =\n normalizeIdList(configurationContext.orgIds) ??\n normalizeIdList(configurationContext.orgId);\n const environment = inferZuoraEnvironment(this.config.baseUrl) ?? \"sandbox\";\n\n return {\n environment,\n ...(entityIds ? { entityIds } : {}),\n ...(orgIds ? { orgIds } : {}),\n };\n }\n}\n\n/**\n * Builds the input arguments for the polling tool call.\n *\n * When pollingArgs is present, values that reference a path (e.g. \"{{jobId}}\")\n * are substituted with the actual jobId. The bare `jobId` field is always\n * included so that polling tools that accept a plain `jobId` field work out\n * of the box regardless of whether pollingArgs is provided.\n */\nconst JOB_ID_PLACEHOLDERS = new Set([\"{{jobId}}\", \"${jobId}\"]);\n\nconst resolvePollingInput = (\n asyncResult: ZuoraAsyncJobResult,\n): Record<string, unknown> => {\n const base: Record<string, unknown> = { jobId: asyncResult.jobId };\n\n if (!asyncResult.pollingArgs) {\n return base;\n }\n\n const resolved: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(asyncResult.pollingArgs)) {\n // Substitute known job-id placeholders — never replace a static string that\n // happens to equal the current job ID, as that would corrupt literal values.\n if (JOB_ID_PLACEHOLDERS.has(value)) {\n resolved[key] = asyncResult.jobId;\n } else {\n resolved[key] = value;\n }\n }\n\n // Always merge base so jobId is present regardless of pollingArgs mapping\n return { ...resolved, ...base };\n};\n\n/** Returns a promise that resolves after the given number of milliseconds. */\nconst sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n","import { SafetyMode } from \"./types.js\";\nimport type {\n ZuoraAgentToolkitConfig,\n ZuoraAgentToolkitConfigInput,\n ZuoraAgentToolkitEnvConfig,\n ZuoraConnectionConfig,\n ZuoraSafetyMode,\n} from \"./types.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport type ZuoraEnvRecord = Record<string, string | undefined>;\n\nexport const ZUORA_TOOLKIT_ENDPOINT_ENV = \"ZUORA_BASE_URL or ZUORA_MCP_URL\";\n\n// ─── resolve-config ───────────────────────────────────────────────────────────\n\nconst isEnvSourcedConfig = (\n config: ZuoraAgentToolkitConfigInput,\n): config is ZuoraAgentToolkitEnvConfig => \"env\" in config;\n\nconst mergeConfiguration = (\n base: ZuoraAgentToolkitConfig[\"configuration\"],\n overrides: ZuoraAgentToolkitConfig[\"configuration\"],\n): ZuoraAgentToolkitConfig[\"configuration\"] => {\n if (!base && !overrides) {\n return undefined;\n }\n\n return {\n ...(base ?? {}),\n ...(overrides ?? {}),\n ...(overrides?.context || base?.context\n ? {\n context: {\n ...base?.context,\n ...overrides?.context,\n },\n }\n : {}),\n };\n};\n\nconst mergeZuoraAgentToolkitConfig = (\n base: ZuoraAgentToolkitConfig,\n overrides: Omit<ZuoraAgentToolkitEnvConfig, \"env\">,\n): ZuoraAgentToolkitConfig => {\n const { configuration: overrideConfiguration, ...restOverrides } = overrides;\n const configuration = mergeConfiguration(\n base.configuration,\n overrideConfiguration,\n );\n\n return {\n ...base,\n ...restOverrides,\n ...(configuration ? { configuration } : {}),\n };\n};\n\nexport const resolveZuoraAgentToolkitConfig = (\n config: ZuoraAgentToolkitConfigInput,\n): ZuoraAgentToolkitConfig => {\n if (!isEnvSourcedConfig(config)) {\n return config;\n }\n\n const { env: envSource, ...overrides } = config;\n const env =\n envSource === true ? process.env : (envSource.env ?? process.env);\n\n return mergeZuoraAgentToolkitConfig(\n zuoraAgentToolkitConfigFromEnv(env),\n overrides,\n );\n};\n\n// ─── from-env ─────────────────────────────────────────────────────────────────\n\nconst readTrimmedEnv = (\n env: ZuoraEnvRecord,\n name: string,\n): string | undefined => {\n const value = env[name]?.trim();\n return value ? value : undefined;\n};\n\nconst requiredEnv = (env: ZuoraEnvRecord, name: string): string => {\n const value = readTrimmedEnv(env, name);\n\n if (!value) {\n throw new Error(`Missing required environment variable: ${name}`);\n }\n\n return value;\n};\n\nconst readBooleanEnvValue = (\n name: string,\n rawValue: string | undefined,\n): boolean => {\n const value = rawValue?.trim().toLowerCase();\n\n if (!value) {\n return false;\n }\n\n if ([\"true\", \"1\", \"yes\"].includes(value)) {\n return true;\n }\n\n if ([\"false\", \"0\", \"no\"].includes(value)) {\n return false;\n }\n\n throw new Error(`Invalid ${name}: expected true or false.`);\n};\n\nconst readBooleanEnv = (env: ZuoraEnvRecord, name: string): boolean =>\n readBooleanEnvValue(name, env[name]);\n\nconst readZuoraEndpoint = (\n env: ZuoraEnvRecord,\n): string | undefined =>\n readTrimmedEnv(env, \"ZUORA_BASE_URL\") ?? readTrimmedEnv(env, \"ZUORA_MCP_URL\");\n\nconst readToolkitMode = (env: ZuoraEnvRecord): ZuoraSafetyMode => {\n const mode = env.ZUORA_TOOLKIT_MODE?.trim() ?? SafetyMode.ReadOnly;\n\n if (mode === SafetyMode.ReadOnly || mode === SafetyMode.WriteEnabled) {\n return mode;\n }\n\n throw new Error(\n `Invalid ZUORA_TOOLKIT_MODE: ${mode}. Expected ${SafetyMode.ReadOnly} or ${SafetyMode.WriteEnabled}.`,\n );\n};\n\nconst readConnectionOptions = (\n env: ZuoraEnvRecord,\n): ZuoraConnectionConfig => {\n const entityIds = readTrimmedEnv(env, \"ZUORA_ENTITY_IDS\");\n const orgIds = readTrimmedEnv(env, \"ZUORA_ORG_IDS\");\n const zuoraVersion = readTrimmedEnv(env, \"ZUORA_VERSION\");\n\n return {\n ...(entityIds ? { entityIds } : {}),\n ...(orgIds ? { orgIds } : {}),\n ...(zuoraVersion ? { zuoraVersion } : {}),\n };\n};\n\nexport const zuoraAgentToolkitConfigFromEnv = (\n env: ZuoraEnvRecord = process.env,\n): ZuoraAgentToolkitConfig => {\n const baseUrl = readZuoraEndpoint(env);\n\n if (!baseUrl) {\n throw new Error(`Set ${ZUORA_TOOLKIT_ENDPOINT_ENV}.`);\n }\n\n const mode = readToolkitMode(env);\n const connection = readConnectionOptions(env);\n\n if (readBooleanEnv(env, \"ZUORA_TENANT_AUTH\")) {\n const tenantId = requiredEnv(env, \"ZUORA_TENANT_ID\");\n\n return {\n baseUrl,\n connection: {\n ...connection,\n tenantAuth: {\n enabled: true,\n tenantId,\n tokenId: requiredEnv(env, \"ZUORA_TOKEN_ID\"),\n userId: requiredEnv(env, \"ZUORA_USER_ID\"),\n },\n },\n configuration: {\n mode,\n },\n };\n }\n\n return {\n baseUrl,\n auth: {\n clientId: requiredEnv(env, \"ZUORA_CLIENT_ID\"),\n clientSecret: requiredEnv(env, \"ZUORA_CLIENT_SECRET\"),\n },\n ...(Object.keys(connection).length > 0 ? { connection } : {}),\n configuration: {\n mode,\n },\n };\n};\n","import { findDownloadUrl } from \"./tools/native/query-result-download/helpers/index.js\";\nimport { resolveZuoraFileResource } from \"./tools/native/zuora-file-download/helpers/index.js\";\nimport type { ZuoraToolExecutionResult } from \"./types.js\";\n\nexport const QUERY_RESULT_DOWNLOAD_TOOL = \"download_query_result\";\nexport const ZUORA_FILE_DOWNLOAD_TOOL = \"download_zuora_file\";\nexport const READ_DOWNLOADED_FILE_TOOL = \"read_downloaded_file\";\n\nexport type AgentToolFollowUpContext = {\n /** Job id from a pending async job, when the caller already resolved it. */\n asyncJobId?: string;\n};\n\nexport type AgentToolFollowUpResolution = {\n followUpToolNames: string[];\n requireToolOnNextStep: boolean;\n recommendedNextTool?: string;\n recommendedNextArgs?: Record<string, unknown>;\n hasDownloadableOutput: boolean;\n};\n\nexport const resolveAgentToolFollowUps = (\n result: ZuoraToolExecutionResult,\n context: AgentToolFollowUpContext = {},\n): AgentToolFollowUpResolution => {\n const followUpToolNames: string[] = [];\n const data = result.data;\n const jobId = context.asyncJobId ?? findQueryJobId(data);\n const zuoraFile = resolveZuoraFileResource(data);\n const hasDownloadUrl = findDownloadUrl(data) !== undefined;\n const artifactId = findDownloadArtifactId(data);\n\n let recommendedNextTool: string | undefined;\n let recommendedNextArgs: Record<string, unknown> | undefined;\n\n if (zuoraFile) {\n followUpToolNames.push(ZUORA_FILE_DOWNLOAD_TOOL);\n recommendedNextTool = ZUORA_FILE_DOWNLOAD_TOOL;\n recommendedNextArgs = { fileId: zuoraFile.fileId };\n } else if (hasDownloadUrl && jobId) {\n // A download URL is present in the result, and we have a jobId to pass to\n // the download tool. Note: the download URL itself is not included in\n // recommendedNextArgs — the download_query_result tool resolves the URL\n // internally from the jobId via a status-check call. If a download URL is\n // present but no jobId can be resolved (no jobId/queryJobId field in the\n // payload), this branch is skipped and no follow-up is emitted; the caller\n // is expected to supply asyncJobId via context in that case.\n followUpToolNames.push(QUERY_RESULT_DOWNLOAD_TOOL, READ_DOWNLOADED_FILE_TOOL);\n recommendedNextTool = QUERY_RESULT_DOWNLOAD_TOOL;\n recommendedNextArgs = { jobId };\n } else if (\n artifactId &&\n (result.toolName === QUERY_RESULT_DOWNLOAD_TOOL ||\n result.toolName === \"download_file\" ||\n result.toolName === ZUORA_FILE_DOWNLOAD_TOOL)\n ) {\n followUpToolNames.push(READ_DOWNLOADED_FILE_TOOL);\n recommendedNextTool = READ_DOWNLOADED_FILE_TOOL;\n recommendedNextArgs = { artifactId };\n }\n\n const uniqueFollowUps = [...new Set(followUpToolNames)];\n\n return {\n followUpToolNames: uniqueFollowUps,\n requireToolOnNextStep: uniqueFollowUps.length > 0,\n ...(recommendedNextTool ? { recommendedNextTool } : {}),\n ...(recommendedNextArgs ? { recommendedNextArgs } : {}),\n hasDownloadableOutput: hasDownloadUrl || zuoraFile !== undefined,\n };\n};\n\nexport const buildToolMessagePayload = (\n result: ZuoraToolExecutionResult,\n followUp: AgentToolFollowUpResolution,\n): Record<string, unknown> => {\n const baseData =\n typeof result.data === \"object\" && result.data !== null\n ? (result.data as Record<string, unknown>)\n : { value: result.data };\n\n if (!followUp.recommendedNextTool) {\n return baseData;\n }\n\n return {\n ...baseData,\n hasDownloadableOutput: followUp.hasDownloadableOutput,\n recommendedNextTool: followUp.recommendedNextTool,\n ...(followUp.recommendedNextArgs\n ? { recommendedNextArgs: followUp.recommendedNextArgs }\n : {}),\n };\n};\n\nconst findQueryJobId = (value: unknown): string | undefined => {\n const direct = readNonEmptyString(value);\n\n if (direct) {\n return direct;\n }\n\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n const found = findQueryJobId(item);\n\n if (found) {\n return found;\n }\n }\n\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n\n // Check specific job-ID field names. \"id\" is intentionally checked last and\n // only at the top level of the direct object (not recursed into nested\n // objects), because it is too generic and would produce false positives on\n // large MCP responses that contain unrelated \"id\" fields deeper in the tree.\n for (const key of [\"jobId\", \"queryJobId\"]) {\n const candidate = readNonEmptyString(record[key]);\n\n if (candidate) {\n return candidate;\n }\n }\n\n // Recurse into nested objects to find jobId / queryJobId, but do NOT carry\n // the generic \"id\" key through recursion to avoid matching unrelated fields.\n for (const item of Object.values(record)) {\n const found = findQueryJobId(item);\n\n if (found) {\n return found;\n }\n }\n\n // Check \"id\" only at this level (after recursion), as a last resort for\n // responses that use a bare \"id\" field at the top of the data structure.\n const idCandidate = readNonEmptyString(record[\"id\"]);\n\n if (idCandidate) {\n return idCandidate;\n }\n\n return undefined;\n};\n\nconst findDownloadArtifactId = (value: unknown): string | undefined => {\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n const direct = readNonEmptyString(record[\"artifactId\"]);\n\n if (direct) {\n return direct;\n }\n\n const download = record[\"download\"];\n\n if (typeof download === \"object\" && download !== null) {\n const nested = readNonEmptyString(\n (download as Record<string, unknown>)[\"artifactId\"],\n );\n\n if (nested) {\n return nested;\n }\n }\n\n for (const item of Object.values(record)) {\n if (item === record[\"download\"]) {\n continue;\n }\n\n const found = findDownloadArtifactId(item);\n\n if (found) {\n return found;\n }\n }\n\n return undefined;\n};\n\nconst readNonEmptyString = (value: unknown): string | undefined => {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n};\n","/**\n * JSON Schema strictification for the OpenAI Responses API.\n *\n * The Responses API (used by the OpenAI Agents SDK) enforces strict schema\n * mode for all function definitions:\n * - Every object schema must have `additionalProperties: false`\n * - All property keys must appear in `required[]`\n * - Optional properties must be expressed as nullable (`anyOf: [type, null]`)\n * rather than by omission from `required[]`\n *\n * Zuora's raw `inputSchema` objects follow the permissive JSON Schema draft\n * and don't satisfy these constraints. `strictifySchema` transforms a schema\n * tree recursively so it is accepted by the Responses API without any loss of\n * field description information visible to the LLM.\n *\n * @internal Used by the openai-agents adapter. Not part of the public API.\n */\n\nexport type JsonSchemaObject = Record<string, unknown>;\n\n/**\n * Wraps a schema as nullable: `{ anyOf: [schema, { type: \"null\" }] }`.\n * If the schema already has an `anyOf`, the null variant is appended instead\n * of creating a double-wrapped anyOf.\n */\nconst makeNullable = (schema: JsonSchemaObject): JsonSchemaObject => {\n if (Array.isArray(schema[\"anyOf\"])) {\n const anyOf = schema[\"anyOf\"] as JsonSchemaObject[];\n const hasNull = anyOf.some((s) => s[\"type\"] === \"null\");\n return hasNull ? schema : { ...schema, anyOf: [...anyOf, { type: \"null\" }] };\n }\n return { anyOf: [schema, { type: \"null\" }] };\n};\n\n/**\n * Recursively transforms a JSON Schema object to satisfy the OpenAI Responses\n * API strict schema requirements:\n *\n * 1. `additionalProperties: false` is added to every object schema.\n * 2. All property keys are moved into `required[]`.\n * 3. Properties that were NOT originally required are wrapped as nullable\n * (`anyOf: [originalType, { type: \"null\" }]`) so the LLM can omit them\n * by passing `null` rather than omitting the key entirely.\n * 4. `anyOf`, `oneOf`, `allOf`, and `items` are recursed into.\n */\nexport const strictifySchema = (schema: JsonSchemaObject): JsonSchemaObject => {\n if (typeof schema !== \"object\" || schema === null) return schema;\n\n const result: JsonSchemaObject = { ...schema };\n\n // Recurse into combiner keywords\n for (const key of [\"anyOf\", \"oneOf\", \"allOf\"] as const) {\n if (Array.isArray(result[key])) {\n result[key] = (result[key] as JsonSchemaObject[]).map(strictifySchema);\n }\n }\n\n // Recurse into array item schema\n if (typeof result[\"items\"] === \"object\" && result[\"items\"] !== null) {\n result[\"items\"] = strictifySchema(result[\"items\"] as JsonSchemaObject);\n }\n\n // Recurse into schema-form additionalProperties\n if (\n typeof result[\"additionalProperties\"] === \"object\" &&\n result[\"additionalProperties\"] !== null\n ) {\n result[\"additionalProperties\"] = strictifySchema(\n result[\"additionalProperties\"] as JsonSchemaObject,\n );\n }\n\n // Enforce strict rules on object schemas\n if (typeof result[\"properties\"] === \"object\" && result[\"properties\"] !== null) {\n const props = result[\"properties\"] as Record<string, JsonSchemaObject>;\n const required: string[] = Array.isArray(result[\"required\"])\n ? (result[\"required\"] as string[])\n : [];\n const optional = Object.keys(props).filter((k) => !required.includes(k));\n\n const processedProps: Record<string, JsonSchemaObject> = {};\n for (const [key, propSchema] of Object.entries(props)) {\n const strictProp = strictifySchema(propSchema);\n // Optional properties become nullable so the LLM can omit them via null.\n processedProps[key] = optional.includes(key)\n ? makeNullable(strictProp)\n : strictProp;\n }\n\n result[\"properties\"] = processedProps;\n result[\"additionalProperties\"] = false;\n result[\"required\"] = Object.keys(processedProps);\n }\n\n return result;\n};\n","/**\n * Bridge: Zuora toolkit → OpenAI Agents SDK tool() objects.\n *\n * Each Zuora tool becomes a native `tool()` with:\n * - Its full `inputSchema` strictified for the Responses API (invisible to callers)\n * - `strict: false` as an API-level safeguard against residual schema 400 errors\n * - `needsApproval: true` for write tools (SDK-native HITL)\n * - An `execute()` that calls `toolkit.callTool()`, inline `waitForJob()` for\n * async results, and embeds `recommendedNextTool` hints for the download chain\n *\n * @module openai-agents\n */\n\nimport type { ZuoraAsyncJobResult } from \"../shared/async-jobs.js\";\nimport {\n buildToolMessagePayload,\n resolveAgentToolFollowUps,\n} from \"../shared/agent-tool-follow-ups.js\";\nimport { strictifySchema } from \"../shared/utils/strict-schema.js\";\nimport type { ToolSelection, ZuoraToolDefinition } from \"../shared/types.js\";\nimport { ZuoraOpenAIAgentToolkit } from \"../openai/toolkit.js\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- @openai/agents is an optional peer dependency\ntype AgentsTool = any;\n\n/**\n * The minimal interface of `tool()` from `@openai/agents` that we need.\n * Typed as `unknown` so this module compiles without `@openai/agents` installed.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- @openai/agents tool() accepts any options shape\ntype AgentsToolFactory = (options: any) => AgentsTool;\n\nconst isAsyncJobResult = (data: unknown): data is ZuoraAsyncJobResult =>\n data != null &&\n typeof data === \"object\" &&\n (data as ZuoraAsyncJobResult).status === \"pending\" &&\n typeof (data as ZuoraAsyncJobResult).jobId === \"string\";\n\n/**\n * Converts a single `ZuoraToolDefinition` into an `@openai/agents` `tool()`\n * object with the `execute()` function fully wired to the Zuora toolkit.\n *\n * Schema strictification and async-job handling are applied internally —\n * callers receive a ready-to-use tool without needing to know about them.\n *\n * @param toolFactory - The `tool` function imported from `@openai/agents`\n * @param def - The Zuora tool definition\n * @param toolkit - The Zuora toolkit instance (provides callTool / waitForJob)\n */\nexport const buildAgentsTool = (\n toolFactory: AgentsToolFactory,\n sanitizedName: string,\n def: ZuoraToolDefinition,\n toolkit: ZuoraOpenAIAgentToolkit,\n): AgentsTool =>\n toolFactory({\n name: sanitizedName,\n description: def.description,\n // Strictify the schema for the OpenAI Responses API — adds\n // additionalProperties:false and required[] to all nested objects.\n // strict:false is a belt-and-suspenders safeguard at the API level.\n parameters: strictifySchema(def.inputSchema as Record<string, unknown>),\n strict: false,\n\n // Write tools pause the run for CLI / web HITL via SDK interruptions.\n needsApproval: def.meta.access === \"write\",\n\n execute: async (args: Record<string, unknown>): Promise<string> => {\n // 1. Execute the Zuora MCP tool. approvalPolicy fires here as a\n // governance backstop even if needsApproval already allowed the call.\n let result = await toolkit.callTool(def.name, args);\n\n // 2. If the tool started an async job, block until it completes.\n // Capture the jobId before waitForJob() in case the final result\n // omits it at a recognisable path.\n let asyncJobId: string | undefined;\n if (isAsyncJobResult(result.data)) {\n asyncJobId = result.data.jobId;\n result = await toolkit.waitForJob(def.name, result.data);\n }\n\n // 3. Detect downloadable outputs and embed guidance for the model.\n // recommendedNextTool / recommendedNextArgs tell the model to call\n // download_query_result → read_downloaded_file automatically.\n const followUp = resolveAgentToolFollowUps(\n result,\n asyncJobId ? { asyncJobId } : {},\n );\n const payload = buildToolMessagePayload(result, followUp);\n\n return JSON.stringify(payload);\n },\n });\n\n/**\n * Converts the Zuora toolkit's tool catalog into `@openai/agents` `tool()`\n * objects ready to pass to `new Agent({ tools })`.\n *\n * @param toolFactory - The `tool` function imported from `@openai/agents`\n * @param toolkit - An initialised `ZuoraOpenAIAgentToolkit` instance\n * @param selection - Bundle and mode filter (same as `toolkit.getTools()`)\n * @param maxTools - Optional cap on returned tool count\n */\nexport const buildAgentsTools = async (\n toolFactory: AgentsToolFactory,\n toolkit: ZuoraOpenAIAgentToolkit,\n selection?: ToolSelection,\n maxTools?: number,\n): Promise<AgentsTool[]> => {\n const chatTools = await toolkit.getTools(selection, maxTools);\n\n return chatTools.flatMap((chatTool) => {\n if (chatTool.type !== \"function\") return [];\n const sanitizedName = chatTool.function.name;\n const def = toolkit.resolveToolDefinition(sanitizedName);\n if (!def) return [];\n return [buildAgentsTool(toolFactory, sanitizedName, def, toolkit)];\n });\n};\n"],"mappings":";AAAA,SAAS,YAAY;;;AC4Bd,IAAM,yBAAN,cAAqC,MAAM;AAAA,EACvC;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAET,YAAY,QAQT;AACD,UAAM,OAAO,OAAO;AACpB,SAAK,OAAO;AACZ,SAAK,OAAO,OAAO;AACnB,SAAK,WAAW,OAAO;AACvB,SAAK,cAAc,OAAO,eAAe,OAAO,aAAa;AAC7D,SAAK,YAAY,OAAO,aAAa;AACrC,SAAK,YAAY,OAAO;AACxB,SAAK,UAAU,OAAO;AAAA,EACxB;AACF;;;ACnDO,IAAM,aAAa;AAAA,EACxB,UAAU;AAAA,EACV,cAAc;AAChB;AAyRO,IAAM,uBAAuB;AAAA,EAClC,KAAK;AAAA,EACL,WAAW;AAAA,EACX,UAAU;AAAA,EACV,kBAAkB;AAAA,EAClB,oBAAoB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IjB,YAAY,gBAAgB,IAAI,WAAsC;AAAA,EACtE,QAAQ;AAAA;AAAA,EAGR,eAAe,IAAI,KAAK,WAAW;AAAA,EAEnC,SAAS,OAAO,SAAmD;AAGjE,QAAI,SAAS,MAAM,QAAQ,SAAS,IAAI,MAAM,IAAI;AAKlD,QAAI;AACJ,QAAIA,kBAAiB,OAAO,IAAI,GAAG;AACjC,mBAAa,OAAO,KAAK;AACzB,eAAS,MAAM,QAAQ,WAAW,IAAI,MAAM,OAAO,IAAI;AAAA,IACzD;AAKA,UAAM,WAAW;AAAA,MACf;AAAA,MACA,aAAa,EAAE,WAAW,IAAI,CAAC;AAAA,IACjC;AACA,UAAM,UAAU,wBAAwB,QAAQ,QAAQ;AAExD,WAAO,KAAK,UAAU,OAAO;AAAA,EAC/B;AACF,CAAC;AAWI,IAAM,mBAAmB,OAC9B,aACA,SACA,WACA,aAC0B;AAC1B,QAAM,YAAY,MAAM,QAAQ,SAAS,WAAW,QAAQ;AAE5D,SAAO,UAAU,QAAQ,CAAC,aAAa;AACrC,QAAI,SAAS,SAAS,WAAY,QAAO,CAAC;AAC1C,UAAM,gBAAgB,SAAS,SAAS;AACxC,UAAM,MAAM,QAAQ,sBAAsB,aAAa;AACvD,QAAI,CAAC,IAAK,QAAO,CAAC;AAClB,WAAO,CAAC,gBAAgB,aAAa,eAAe,KAAK,OAAO,CAAC;AAAA,EACnE,CAAC;AACH;","names":["tool","path","tool","tool","tool","request","fs","path","path","path","isPathInside","path","isPathInside","artifact","fs","isNodeErrorCode","path","fs","fs","isNodeErrorCode","nativeFilesystemError","isNodeErrorCode","nativeFilesystemError","os","path","path","os","tool","tool","tool","tool","access","normalizeStringList","normalized","path","tool","eventError","rawOutputForEvent","payload","isAsyncJobResult"]}
|
|
1
|
+
{"version":3,"sources":["../../src/openai-agents/toolkit.ts","../../src/shared/errors.ts","../../src/shared/types.ts","../../src/shared/utils/zuora-url.ts","../../src/shared/approval-policy.ts","../../src/shared/utils/adapter-name.ts","../../src/shared/async-jobs.ts","../../src/shared/bundles.ts","../../src/shared/utils/values.ts","../../src/shared/tools/operation-metadata.ts","../../src/shared/utils/event-sanitizer.ts","../../src/shared/observability/events.ts","../../src/shared/observability/async-poll-events.ts","../../src/shared/observability/payloads.ts","../../src/shared/transport/request-metadata.ts","../../src/shared/observability/request-metadata.ts","../../src/shared/tools/native/file-artifacts/config.ts","../../src/shared/tools/native/config.ts","../../src/shared/tools/native/metadata.ts","../../src/shared/tools/native/file-artifacts/definitions.ts","../../src/shared/tools/native/file-artifacts/download-service.ts","../../src/shared/tools/native/file-artifacts/errors.ts","../../src/shared/tools/native/file-artifacts/path-policy.ts","../../src/shared/tools/native/file-artifacts/manifest.ts","../../src/shared/tools/native/file-artifacts/url-policy.ts","../../src/shared/tools/native/file-artifacts/helpers.ts","../../src/shared/tools/native/registry-source.ts","../../src/shared/tools/native/file-artifacts/index.ts","../../src/shared/tools/native/resolve-native-file-tools-input.ts","../../src/shared/tools/native/query-result-download/config.ts","../../src/shared/tools/native/query-result-download/helpers/status-resolver.ts","../../src/shared/tools/native/query-result-download/definitions.ts","../../src/shared/tools/native/query-result-download/helpers/index.ts","../../src/shared/tools/native/query-result-download/index.ts","../../src/shared/tools/native/zuora-file-download/config.ts","../../src/shared/tools/native/zuora-file-download/definitions.ts","../../src/shared/tools/native/zuora-file-download/helpers/index.ts","../../src/shared/tools/native/zuora-file-download/index.ts","../../src/shared/tools/mcp-tool-definition.ts","../../src/shared/utils/redaction.ts","../../src/shared/transport/oauth-token-provider.ts","../../src/shared/transport/request-headers.ts","../../src/shared/transport/resolve-connection-config.ts","../../src/shared/transport/zuora-client.ts","../../src/shared/transport/zuora-rest-client.ts","../../src/shared/tool-selection.ts","../../src/shared/transport/mcp-tool-error.ts","../../src/shared/transport/json-rpc.ts","../../src/shared/transport/mcp-client.ts","../../src/shared/toolkit-core.ts","../../src/shared/configuration.ts","../../src/shared/agent-tool-follow-ups.ts","../../src/shared/utils/strict-schema.ts","../../src/openai-agents/build-tools.ts"],"sourcesContent":["import { tool } from \"@openai/agents\";\nimport { ToolkitCore } from \"../shared/toolkit-core.js\";\nimport { sanitizeAdapterToolName } from \"../shared/utils/adapter-name.js\";\nimport { resolveZuoraAgentToolkitConfig } from \"../shared/configuration.js\";\nimport {\n buildToolMessagePayload,\n resolveAgentToolFollowUps,\n QUERY_RESULT_DOWNLOAD_TOOL,\n} from \"../shared/agent-tool-follow-ups.js\";\nimport { strictifySchema } from \"../shared/utils/strict-schema.js\";\nimport type {\n ZuoraAgentToolkitConfigInput,\n ZuoraToolDefinition,\n ZuoraToolExecutionResult,\n} from \"../shared/types.js\";\nimport { isAsyncJobResult } from \"../shared/async-jobs.js\";\nimport {\n findDownloadUrl,\n findQueryStatus,\n} from \"../shared/tools/native/query-result-download/helpers/index.js\";\nimport {\n DEFAULT_ASYNC_JOB_TERMINAL_STATUSES,\n matchesAsyncJobTerminalStatus,\n} from \"../shared/async-jobs.js\";\n\n/** Native tool type returned by `tool()` from `@openai/agents`. */\ntype AgentsFunctionTool = ReturnType<typeof tool>;\n\n\n/**\n * Extracts a query job ID from a raw MCP response for tools that don't have\n * `asyncOperation` metadata registered on the server (e.g. ZOQL submit_query).\n * Looks for `jobId` or `queryJobId` fields only — avoids the generic `id`\n * field to prevent false positives on ordinary synchronous responses.\n *\n * @internal Exported for unit testing only.\n */\nexport const findRawJobId = (data: unknown, depth = 0): string | undefined => {\n if (depth > 5 || typeof data !== \"object\" || data === null) return undefined;\n if (Array.isArray(data)) {\n for (const item of data) {\n const found = findRawJobId(item, depth + 1);\n if (found) return found;\n }\n return undefined;\n }\n const record = data as Record<string, unknown>;\n\n // Primary: explicit job ID field names — unambiguous, no false positives.\n for (const key of [\"jobId\", \"queryJobId\"]) {\n if (typeof record[key] === \"string\" && (record[key] as string).trim()) {\n return (record[key] as string).trim();\n }\n }\n\n // Secondary: bare `id` field is a job ID when a `queryStatus` sibling\n // field is present (e.g. get_query_job response: id + queryStatus:\"accepted\").\n // `queryStatus` is ZOQL-specific — it does NOT appear on ordinary Zuora\n // object records (which use `status` / `Status` for their lifecycle field).\n // Using `status` here caused false positives on account/subscription records\n // returned by query_objects, which have `id` + `status:\"Active\"`.\n const hasQueryStatus = typeof record[\"queryStatus\"] === \"string\";\n if (hasQueryStatus && typeof record[\"id\"] === \"string\" && (record[\"id\"] as string).trim()) {\n return (record[\"id\"] as string).trim();\n }\n\n for (const value of Object.values(record)) {\n const found = findRawJobId(value, depth + 1);\n if (found) return found;\n }\n return undefined;\n};\n\n\n/**\n * OpenAI Agents SDK adapter for the Zuora Agent Kit.\n *\n * Extends `ToolkitCore` so all shared capabilities (auth, approval policy,\n * observability, async job handling, native file tools) are inherited.\n * `convertTools()` is the only override — it wraps each `ZuoraToolDefinition`\n * in an `@openai/agents` `tool()` object whose `execute()` function:\n *\n * 1. Calls `this.callTool()` (MCP execution + approval policy enforcement)\n * 2. Blocks on `this.waitForJob()` if the tool started an async job\n * 3. Embeds `recommendedNextTool` hints for the download chain\n *\n * Schema strictification for the OpenAI Responses API is applied\n * automatically inside `convertTools()` — callers do not need to know about it.\n */\nexport class ZuoraOpenAIAgentsToolkit extends ToolkitCore<AgentsFunctionTool> {\n /** Maps sanitized adapter tool names back to their original ZuoraToolDefinition. */\n private sanitizedToolMap = new Map<string, ZuoraToolDefinition>();\n\n /**\n * Look up a ZuoraToolDefinition by its sanitized adapter tool name.\n *\n * The OpenAI Agents SDK registers tools with sanitized names (see convertTools),\n * but external code may reference tools by their original MCP names. This method\n * provides resolution in both directions.\n */\n private resolveToolName(name: string): string | undefined {\n // Direct lookup by sanitized name\n if (this.sanitizedToolMap.has(name)) {\n return name;\n }\n // Reverse lookup by original MCP name\n for (const [sanitized, def] of this.sanitizedToolMap) {\n if (def.name === name) {\n return sanitized;\n }\n }\n return undefined;\n }\n\n /**\n * Resolve a tool name that may be either sanitized or original MCP format.\n *\n * This provides additional name normalization to handle cases where:\n * - A tool name contains unsanitized characters (like dots)\n * - A tool name was learned from descriptions or logs\n *\n * We attempt to find a match with relaxed sanitization rules before giving up.\n */\n private normalizeToolName(name: string): string | undefined {\n // First try exact match with sanitized name\n const directMatch = this.resolveToolName(name);\n if (directMatch) {\n return directMatch;\n }\n\n // Try with common character replacements (dots -> underscores)\n const normalized = name.replace(/\\./g, \"_\");\n const normalizedMatch = this.resolveToolName(normalized);\n if (normalizedMatch) {\n return normalizedMatch;\n }\n\n // Try resolving via original name dotted format\n for (const [sanitized, def] of this.sanitizedToolMap) {\n if (def.name === normalized) {\n return sanitized;\n }\n }\n\n return undefined;\n }\n\n /**\n * Override callTool to provide flexible name resolution.\n *\n * The OpenAI Agents SDK may receive tool calls with names that were learned\n * from descriptions or other sources (not directly from tool registration).\n * This override allows us to handle both sanitized and original tool names\n * by falling back to name normalization when the direct lookup fails.\n */\n async callTool(\n operationName: string,\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n // First try the provided name directly (likely already correct for most callers)\n try {\n return await super.callTool(operationName, input);\n } catch (error) {\n // If tool not found, try name normalization\n if (\n error instanceof Error &&\n (error.message.includes(\"Unknown Zuora tool\") ||\n error.message.includes(\"TOOL_NOT_FOUND\"))\n ) {\n const sanitized = this.normalizeToolName(operationName);\n if (sanitized) {\n const def = this.sanitizedToolMap.get(sanitized);\n if (def) {\n // Emit a warning to help diagnose name normalization issues\n console.warn(\n `[zuora-agent-toolkit] Tool name normalized: \"${operationName}\" -> \"${def.name}\" (sanitized: \"${sanitized}\")`,\n );\n return await super.callTool(def.name, input);\n }\n }\n }\n throw error;\n }\n }\n\n /**\n * Serialises the agent tool response, emits an `agent.tool.response`\n * observability event (with the response in `metadata` when\n * `includePayloads` is enabled), and returns the JSON string to execute().\n *\n * This surfaces what the LLM actually receives — which may differ from the\n * raw `callTool` output when execute() adds directives or download hints.\n */\n private emitAgentToolResponse(\n toolName: string,\n def: ZuoraToolDefinition,\n response: Record<string, unknown>,\n ): string {\n const includePayloads = this.config.observability?.includePayloads === true;\n this.emit({\n name: \"agent.tool.response\",\n toolName,\n access: def.meta.access,\n bundle: def.meta.bundle,\n riskLevel: def.meta.riskLevel,\n ...(includePayloads ? { metadata: { agentResponse: response } } : {}),\n });\n return JSON.stringify(response);\n }\n\n protected convertTools(tools: ZuoraToolDefinition[]): AgentsFunctionTool[] {\n return tools.map((def) => {\n const sanitizedName = sanitizeAdapterToolName(def.name);\n // Store mapping for reverse lookup during tool call name resolution\n this.sanitizedToolMap.set(sanitizedName, def);\n\n return tool({\n name: sanitizedName,\n description: def.description,\n\n // Strictify the schema for the Responses API (adds additionalProperties:false\n // and required[] to all nested objects). Invisible to the caller.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- raw JSON schema accepted by tool()\n parameters: strictifySchema(def.inputSchema as Record<string, unknown>) as any,\n\n // strict:false at the API level as a belt-and-suspenders safeguard\n // against 400 errors from any edge case the schema transform misses.\n strict: false as const,\n\n // Write tools pause the run for human review via SDK interruptions.\n // For merged tools, check the per-operation access at call time so\n // read operations (e.g. get_bill_run) don't trigger approval when\n // the merged tool's aggregate access is write.\n needsApproval:\n def.meta.operationAccess && def.meta.operationSelector\n ? (_ctx: unknown, input: unknown) => {\n const op =\n input != null &&\n typeof input === \"object\" &&\n def.meta.operationSelector\n ? String(\n (input as Record<string, unknown>)[\n def.meta.operationSelector\n ] ?? \"\",\n )\n : \"\";\n const access =\n (op && def.meta.operationAccess?.[op]) ?? def.meta.access;\n return Promise.resolve(access === \"write\");\n }\n : def.meta.access === \"write\",\n\n execute: async (args: unknown): Promise<string> => {\n const input = args as Record<string, unknown>;\n // 1. Execute the Zuora MCP tool. approvalPolicy is the governance backstop.\n const result = await this.callTool(def.name, input);\n\n // 2. Follow-up hints take priority.\n // resolveAgentToolFollowUps handles completed downloads (artifactId →\n // read_downloaded_file), Zuora file resources, and completed jobs with\n // a visible download URL. If it finds a recommendation, use it —\n // this prevents the job-detection logic below from incorrectly\n // triggering on results that already contain a jobId + terminal status\n // (e.g. the download_query_result response which includes both).\n const followUp = resolveAgentToolFollowUps(result, {});\n if (followUp.recommendedNextTool) {\n const payload = buildToolMessagePayload(result, followUp);\n return this.emitAgentToolResponse(def.name, def, payload);\n }\n\n // 3. Async job guidance — only when the tool declares asyncOperation\n // in its server metadata. If the tool is declared async, callTool()\n // already called buildAsyncJobResult() and result.data is a shaped\n // ZuoraAsyncJobResult with all routing fields populated.\n //\n // We intentionally do NOT apply heuristic field-name detection here.\n // Tools without asyncOperation metadata are not async from the SDK's\n // perspective; the LLM follows the instructions for those responses.\n // (This eliminates false positives on ordinary object query results\n // that happen to contain id/status/jobId-like fields.)\n if (def.meta.asyncOperation && isAsyncJobResult(result.data)) {\n const { jobId: asyncJobId, pollingToolName } = result.data;\n\n // Detect completion via download URL or terminal status.\n const hasDownloadUrl = findDownloadUrl(result.data) !== undefined;\n const jobStatus = findQueryStatus(result.data);\n const isTerminal =\n hasDownloadUrl ||\n (jobStatus !== undefined &&\n matchesAsyncJobTerminalStatus(\n jobStatus,\n DEFAULT_ASYNC_JOB_TERMINAL_STATUSES,\n ));\n\n if (isTerminal) {\n return this.emitAgentToolResponse(def.name, def, {\n action: `Job complete. Call ${QUERY_RESULT_DOWNLOAD_TOOL} with the jobId to retrieve the data.`,\n jobId: asyncJobId,\n recommendedNextTool: QUERY_RESULT_DOWNLOAD_TOOL,\n recommendedNextArgs: { jobId: asyncJobId },\n });\n }\n\n return this.emitAgentToolResponse(def.name, def, {\n action: `Job is still running. Call ${pollingToolName} with the same jobId to check status.`,\n jobId: asyncJobId,\n recommendedNextTool: pollingToolName,\n recommendedNextArgs: { jobId: asyncJobId },\n });\n }\n\n // 4. No job, no specific follow-up: return the raw result.\n const payload = buildToolMessagePayload(result, followUp);\n return this.emitAgentToolResponse(def.name, def, payload);\n },\n });\n });\n }\n}\n\n/**\n * Creates and initialises a `ZuoraOpenAIAgentsToolkit`.\n *\n * @example\n * ```ts\n * import { Agent, run } from \"@openai/agents\";\n * import { createZuoraOpenAIAgentsToolkit } from \"@zuora/agent-toolkit/openai-agents\";\n *\n * const toolkit = await createZuoraOpenAIAgentsToolkit({ env: true });\n * const tools = await toolkit.getTools({ bundles: [\"query\"], mode: SafetyMode.ReadOnly });\n * const agent = new Agent({ name: \"Cli Agent\", tools });\n * const result = await run(agent, \"How many active accounts?\");\n * ```\n */\nexport const createZuoraOpenAIAgentsToolkit = async (\n config: ZuoraAgentToolkitConfigInput,\n): Promise<ZuoraOpenAIAgentsToolkit> => {\n const toolkit = new ZuoraOpenAIAgentsToolkit(\n resolveZuoraAgentToolkitConfig(config),\n );\n await toolkit.initialize();\n return toolkit;\n};\n","export type ZuoraAgentToolkitP0ErrorCode =\n | \"TOOL_EXECUTION_ERROR\"\n | \"TOOL_NOT_FOUND\"\n | \"BUNDLE_NOT_FOUND\"\n | \"APPROVAL_REJECTED\"\n | \"MALFORMED_METADATA\"\n | \"OAUTH_TOKEN_ERROR\"\n | \"ASYNC_JOB_TIMEOUT\";\n\nexport type ZuoraAgentToolkitErrorCode =\n | ZuoraAgentToolkitP0ErrorCode\n | (string & {});\n\nexport type ZuoraAgentToolkitP0ErrorCategory =\n | \"tool_execution\"\n | \"approval\"\n | \"metadata\"\n | \"auth\";\n\nexport type ZuoraAgentToolkitErrorCategory =\n | ZuoraAgentToolkitP0ErrorCategory\n | \"permission\"\n | \"validation\"\n | \"zuora\"\n | \"mcp\"\n | \"configuration\"\n | \"native_file_tools\";\n\nexport class ZuoraAgentToolkitError extends Error {\n readonly code: ZuoraAgentToolkitErrorCode;\n\n readonly category: ZuoraAgentToolkitErrorCategory;\n\n readonly retryable: boolean;\n\n readonly recoverable: boolean;\n\n readonly requestId?: string | undefined;\n\n readonly details?: unknown;\n\n constructor(params: {\n code: ZuoraAgentToolkitErrorCode;\n message: string;\n category: ZuoraAgentToolkitErrorCategory;\n retryable?: boolean;\n recoverable?: boolean;\n requestId?: string;\n details?: unknown;\n }) {\n super(params.message);\n this.name = \"ZuoraAgentToolkitError\";\n this.code = params.code;\n this.category = params.category;\n this.recoverable = params.recoverable ?? params.retryable ?? false;\n this.retryable = params.retryable ?? false;\n this.requestId = params.requestId;\n this.details = params.details;\n }\n}\n","import type { McpReadResourceResult, McpTool } from \"./transport/mcp-types.js\";\nimport type { EventSanitizerLimits } from \"./utils/event-sanitizer.js\";\n\nexport type { McpReadResourceResult, McpTool } from \"./transport/mcp-types.js\";\nexport type { EventSanitizerLimits } from \"./utils/event-sanitizer.js\";\n\nexport type ZuoraEnvironment = \"sandbox\" | \"production\";\n\nexport const SafetyMode = {\n ReadOnly: \"readOnly\",\n WriteEnabled: \"writeEnabled\",\n} as const;\n\nexport type ZuoraSafetyMode = (typeof SafetyMode)[keyof typeof SafetyMode];\n\nexport type ZuoraToolOperation = \"read\" | \"write\";\n\nexport type ZuoraRiskLevel = \"low\" | \"medium\" | \"high\";\n\n/**\n * Well-known Zuora bundle names. Provided for autocompletion in\n * `ToolSelection.bundles` and `ZuoraToolkitConfiguration.bundles`.\n *\n * The `string & {}` tail widens the type to accept any string (so new\n * server-side bundles are never rejected) while preserving IDE autocomplete\n * for the known literal members.\n *\n * `ZuoraToolDefinition.meta.bundle` is plain `string` — the server value\n * is passed through as-is with no normalisation or fallback.\n */\nexport type ZuoraBundleName =\n | \"accounts\"\n | \"catalog\"\n | \"subscriptions\"\n | \"orders\"\n | \"billing\"\n | \"payments\"\n | \"usage\"\n | \"revenue\"\n | \"finance\"\n | \"workflows\"\n | \"query\"\n | \"admin\"\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n | (string & {});\n\n// ── Async operation metadata — directly from _meta.asyncOperations[op] ──\nexport type ZuoraAsyncOperationMeta = {\n /** Operation on the polling MCP tool. Omitted when pollingTool is the standalone poll target. */\n pollingOperation?: string;\n /** Source MCP tool for cross-tool polling, or standalone poll tool when pollingOperation is omitted. */\n pollingTool?: string;\n jobIdPath: string;\n statusPath: string;\n pollingArgs?: Record<string, string>;\n terminalStatuses: {\n success: string[];\n failure: string[];\n canceled?: string[];\n };\n recommendedPollIntervalMs?: number;\n defaultTimeoutMs?: number;\n maxPollAttempts?: number;\n};\n\n// ── Service permission — directly from _meta.requiredServicePermissions[] ──\nexport type ZuoraServicePermission = {\n scope: string;\n name: string;\n};\n\n// ── The only public tool type ──\nexport type ZuoraToolDefinition = {\n name: string; // operation name, e.g. \"run_reports\"\n description: string;\n inputSchema: JsonSchema;\n outputSchema?: JsonSchema;\n meta: {\n bundle: string; // from _meta.bundle or SDK-native tool config; passed through as-is\n access: ZuoraToolOperation; // from _meta.operationPermissions[op]\n riskLevel: ZuoraRiskLevel; // from _meta.riskLevels[op]\n asyncOperation?: ZuoraAsyncOperationMeta; // from _meta.asyncOperations[op] — set on split/single-op tools\n /** Present on multi-op merged tools (splitOperations: false). Keyed by operation name. Used at\n * call time to look up the async meta for the operation the LLM actually invoked. */\n asyncOperations?: Record<string, ZuoraAsyncOperationMeta>;\n /** Per-operation access levels for merged tools. Used at call time to enforce the correct access for the invoked operation. */\n operationAccess?: Record<string, ZuoraToolOperation>;\n /** Per-operation risk levels for merged tools. Used at call time to enforce the correct risk for the invoked operation. */\n operationRiskLevel?: Record<string, ZuoraRiskLevel>;\n requiredServicePermissions: ZuoraServicePermission[]; // from _meta.requiredServicePermissions\n limitations: string[];\n sourceName: string; // original MCP tool name for execution routing\n /** Present on split multi-operation tools — MCP input field auto-injected at call time. */\n operationSelector?: string;\n /** Present on split multi-operation tools — the underlying MCP operation name. */\n operationName?: string;\n };\n};\n\n// ── Native file tools — config ──\n\nexport type NativeToolMetadataConfig = {\n enabled?: boolean;\n operationAccess?: ZuoraToolOperation;\n riskLevel?: ZuoraRiskLevel;\n description?: string;\n};\n\nexport type NativeFileToolsConfig = {\n enabled?: boolean;\n bundleName?: string;\n tools?: {\n downloadFile?: NativeToolMetadataConfig;\n readDownloadedFile?: NativeToolMetadataConfig;\n downloadQueryResult?: NativeToolMetadataConfig;\n downloadZuoraFile?: NativeToolMetadataConfig;\n extractDownloadedArchive?: NativeToolMetadataConfig;\n readResource?: NativeToolMetadataConfig;\n };\n rootDir?: string;\n userHomeDir?: string;\n requireRootUnderUserHome?: boolean;\n allowOverwrite?: boolean;\n maxDownloadBytes?: number;\n maxReadBytes?: number;\n maxReadLines?: number;\n maxExtractedFiles?: number;\n maxExtractedBytes?: number;\n downloadTimeoutMs?: number;\n allowedProtocols?: string[];\n allowedHosts?: string[];\n allowedUrlPrefixes?: string[];\n zuoraDownloadHosts?: string[];\n allowZuoraAuthenticatedDownload?: boolean;\n allowS3PresignedDownload?: boolean;\n allowArchiveExtraction?: boolean;\n};\n\n// ── Native tool approval metadata ──\n\nexport type NativeFileApprovalMetadata = {\n source: \"native\";\n nativeToolType: \"fileArtifacts\";\n filesystemRoot: string;\n sideEffects: Array<\"networkRead\" | \"localFileWrite\" | \"localFileRead\">;\n urlHost?: string;\n urlProtocol?: string;\n urlPath?: string;\n urlKind?: string;\n outputRelativePath?: string;\n artifactId?: string;\n relativePath?: string;\n};\n\nexport type NativeToolApprovalMetadata = NativeFileApprovalMetadata;\n\n// ── Bundle types — used by PR-3 ToolkitCore ──\nexport type ToolkitBundleName = string;\n\nexport type ZuoraBundleDefinition = {\n name: ToolkitBundleName;\n description: string;\n examples: string[];\n commonObjects: string[];\n keywords: string[];\n toolCount: number;\n readToolCount: number;\n writeToolCount: number;\n tools: ZuoraToolDefinition[];\n};\n\nexport type JsonSchema = {\n type?: string;\n properties?: Record<string, JsonSchema>;\n items?: JsonSchema;\n required?: string[];\n enum?: string[];\n description?: string;\n additionalProperties?: boolean | JsonSchema;\n [key: string]: unknown;\n};\n\nexport type ZuoraAuthConfig = {\n clientId: string;\n clientSecret: string;\n};\n\ntype ZuoraTenantAuthConfig =\n | {\n enabled: true;\n tenantId: string;\n tokenId: string;\n userId: string;\n }\n | {\n enabled?: false;\n };\n\ntype EnabledZuoraTenantAuthConfig = Extract<\n ZuoraTenantAuthConfig,\n { enabled: true }\n>;\n\nexport type BundleConfiguration = {\n include?: string[];\n exclude?: string[];\n};\n\nexport type ZuoraToolkitConfiguration = {\n mode?: ZuoraSafetyMode;\n bundles?: Partial<Record<ZuoraBundleName, boolean | BundleConfiguration>>;\n tools?: Record<string, boolean>;\n context?: Record<string, string | undefined>;\n // Controls whether multi-operation MCP tools are split into one tool per operation.\n // Default: true. When false, multi-op tools are presented as a single tool.\n splitOperations?: boolean;\n};\n\nexport type ToolSelection = {\n bundles?: ZuoraBundleName[];\n include?: string[];\n exclude?: string[];\n mode?: ZuoraSafetyMode;\n};\n\nexport type ZuoraExecutionRequestMetadata = {\n requestId?: string;\n zuoraRequestId?: string;\n environment?: ZuoraEnvironment;\n tenantId?: string;\n entityIds?: string[];\n orgIds?: string[];\n};\n\nexport type ZuoraToolExecutionResult<TData = unknown> = {\n toolName: string;\n data: TData;\n riskLevel?: ZuoraRiskLevel;\n requestId?: string;\n request?: ZuoraExecutionRequestMetadata;\n warnings?: string[];\n};\n\nexport type ZuoraMcpClient = {\n initialize?: () => Promise<void>;\n listTools: () => Promise<McpTool[]>;\n callTool: (\n name: string,\n input: Record<string, unknown>,\n ) => Promise<ZuoraToolExecutionResult>;\n readResource?: (uri: string) => Promise<McpReadResourceResult>;\n getTenantId?: () => string | undefined;\n getSensitiveValues?: () => readonly string[];\n close?: () => Promise<void>;\n};\n\ntype ZuoraConnectionConfigBase = {\n headers?: Record<string, string | undefined>;\n entityIds?: string | string[];\n orgIds?: string | string[];\n zuoraVersion?: string;\n protocolVersion?: string;\n};\n\ntype ZuoraTenantAuthConnectionConfig = ZuoraConnectionConfigBase & {\n tenantAuth: EnabledZuoraTenantAuthConfig;\n};\n\ntype ZuoraStandardConnectionConfig = ZuoraConnectionConfigBase & {\n tenantAuth?: Exclude<ZuoraTenantAuthConfig, EnabledZuoraTenantAuthConfig>;\n};\n\nexport type ZuoraConnectionConfig =\n | ZuoraStandardConnectionConfig\n | ZuoraTenantAuthConnectionConfig;\n\ntype ZuoraHttpMcpClientConfigBase = ZuoraConnectionConfigBase & {\n url: string;\n clientName?: string;\n clientVersion?: string;\n};\n\nexport type ZuoraHttpMcpClientConfig =\n | (ZuoraHttpMcpClientConfigBase &\n ZuoraStandardConnectionConfig & {\n auth: ZuoraAuthConfig;\n })\n | (ZuoraHttpMcpClientConfigBase &\n ZuoraTenantAuthConnectionConfig & {\n auth?: ZuoraAuthConfig;\n });\n\nexport const ApprovalPolicyPreset = {\n Off: \"off\",\n AllWrites: \"all_writes\",\n HighRisk: \"high_risk\",\n ProductionWrites: \"production_writes\",\n ProductionHighRisk: \"production_high_risk\",\n} as const;\n\nexport type ApprovalPolicyPresetValue =\n (typeof ApprovalPolicyPreset)[keyof typeof ApprovalPolicyPreset];\n\nexport type ApprovalPolicyResult =\n | \"allow\"\n | \"deny\"\n | { decision: \"allow\" | \"deny\"; reason?: string };\n\nexport type ApprovalPolicyHandler = (\n request: ApprovalRequest,\n) => ApprovalPolicyResult | Promise<ApprovalPolicyResult>;\n\nexport type ApprovalPolicy = ApprovalPolicyPresetValue | ApprovalPolicyHandler;\n\nexport type ApprovalRequest = {\n tool: ZuoraToolDefinition;\n input: Record<string, unknown>;\n environment: ZuoraEnvironment;\n /** Present only for SDK-native tools (e.g. download_file). Undefined for MCP-sourced tools. */\n native?: NativeToolApprovalMetadata;\n};\n\n// ── Observability event types ──\n\nexport type ZuoraToolkitEventName =\n | \"tool.called\"\n | \"tool.completed\"\n | \"tool.failed\"\n | \"approval.requested\"\n /**\n * Internal name used when emitting the approval outcome from\n * `enforceApproval()`. It is normalised to the `\"approval.decided\"` type\n * by `normalizeToolkitEvent()` before being delivered to observers.\n * @see ZuoraToolkitEventType\n */\n | \"approval.resolved\"\n | \"approval.decided\"\n | \"metadata.loaded\"\n | \"async.poll.checked\"\n | \"observability.sink_failed\"\n /**\n * Emitted by framework adapters (e.g. the Agents SDK adapter) after\n * `execute()` finishes post-processing the raw MCP result. The `metadata`\n * field carries the actual response the LLM receives, which may differ from\n * the raw `callTool` output (e.g. async-job directives, download hints).\n * Consumers can subscribe to this event to audit what the LLM was told.\n */\n | \"agent.tool.response\";\n\n/**\n * The canonical event type delivered to `onEvent` / `emit` sinks.\n *\n * Note the asymmetry with `ZuoraToolkitEventName`: the internal name\n * `\"approval.resolved\"` is normalised to `\"approval.decided\"` before\n * delivery. Consumers should match on `type`, not `name`, when they need\n * a stable identifier for approval-outcome events.\n */\nexport type ZuoraToolkitEventType =\n | \"tool.called\"\n | \"tool.completed\"\n | \"tool.failed\"\n | \"approval.requested\"\n | \"approval.decided\"\n | \"metadata.loaded\"\n | \"async.poll.checked\"\n | \"observability.sink_failed\"\n | \"agent.tool.response\";\n\nexport type ZuoraToolkitApprovalDecision =\n | \"allow\"\n | \"deny\";\n\nexport type ZuoraToolkitApprovalStatus =\n | \"requested\"\n | \"rejected\"\n | \"not_required\";\n\nexport type ZuoraToolkitEventError = {\n code: string;\n category: string;\n recoverable: boolean;\n retryable?: boolean;\n requestId?: string;\n message?: string;\n};\n\nexport type ZuoraToolExecutionPhase = \"primary\" | \"async_poll\";\n\nexport type ZuoraToolkitEvent = {\n type: ZuoraToolkitEventType;\n name: ZuoraToolkitEventName;\n timestamp: string;\n toolName?: string;\n access?: ZuoraToolOperation;\n bundle?: string;\n executionPhase?: ZuoraToolExecutionPhase;\n input?: Record<string, unknown>;\n output?: Record<string, unknown>;\n requestId?: string;\n zuoraRequestId?: string;\n riskLevel?: ZuoraRiskLevel;\n latencyMs?: number;\n environment?: ZuoraEnvironment;\n tenantId?: string;\n entityIds?: string[];\n orgIds?: string[];\n approvalDecision?: ZuoraToolkitApprovalDecision;\n approvalStatus?: ZuoraToolkitApprovalStatus;\n error?: ZuoraToolkitEventError;\n metadata?: Record<string, unknown>;\n};\n\nexport type ZuoraToolkitLogger = {\n debug?: (message: string, event?: ZuoraToolkitEvent) => void;\n info?: (message: string, event?: ZuoraToolkitEvent) => void;\n warn?: (message: string, event?: ZuoraToolkitEvent) => void;\n error?: (message: string, event?: ZuoraToolkitEvent) => void;\n};\n\ntype ZuoraAgentToolkitConfigBase = {\n baseUrl: string;\n configuration?: ZuoraToolkitConfiguration;\n approvalPolicy?: ApprovalPolicy;\n /**\n * SDK-internal overrides for native file download/read infrastructure.\n * Auto-enabled when the query bundle is configured — agents never set this.\n */\n nativeFileTools?: NativeFileToolsConfig;\n observability?: {\n logger?: ZuoraToolkitLogger;\n emit?: (event: ZuoraToolkitEvent) => void | Promise<void>;\n onEvent?: (event: ZuoraToolkitEvent) => void;\n /**\n * When true, tool.called/tool.completed/tool.failed events include\n * sanitized input and output payloads. Defaults to false.\n */\n includePayloads?: boolean;\n /**\n * Limits applied when sanitizing event metadata fields.\n * Use `resolveEventSanitizerLimits(process.env)` to populate from\n * environment variables, or supply explicit values.\n * Defaults to built-in conservative limits when omitted.\n */\n sanitizerLimits?: EventSanitizerLimits;\n };\n};\n\nexport type ZuoraAgentToolkitEnvSource =\n | true\n | {\n env?: Record<string, string | undefined>;\n };\n\nexport type ZuoraAgentToolkitEnvConfig = Omit<\n ZuoraAgentToolkitConfigBase,\n \"baseUrl\"\n> & {\n env: ZuoraAgentToolkitEnvSource;\n};\n\nexport type ZuoraAgentToolkitConfig =\n | (ZuoraAgentToolkitConfigBase & {\n auth: ZuoraAuthConfig;\n })\n | (ZuoraAgentToolkitConfigBase & {\n auth?: ZuoraAuthConfig;\n connection: ZuoraTenantAuthConnectionConfig;\n });\n\nexport type ZuoraAgentToolkitConfigInput =\n | ZuoraAgentToolkitConfig\n | ZuoraAgentToolkitEnvConfig;\n\n// ── Async job polling types ──\n\n/**\n * Terminal state of a completed async job.\n */\nexport type ZuoraAsyncJobTerminalState = \"success\" | \"failure\" | \"canceled\";\n\n/**\n * Configuration for which status strings are considered terminal for each outcome.\n */\nexport type ZuoraAsyncJobTerminalStatuses = {\n success: string[];\n failure: string[];\n canceled?: string[];\n};\n\n/**\n * Rich resolution of the current async job status returned by resolveAsyncJobStatusDetails.\n */\nexport type ZuoraAsyncJobStatusResolution = {\n /** Raw status string extracted from the tool result, if any. */\n status: string | undefined;\n /** True if the job has reached a terminal state. */\n isTerminal: boolean;\n /** The resolved terminal state, or undefined if not yet terminal. */\n terminalState: ZuoraAsyncJobTerminalState | undefined;\n};\n\n/**\n * Options for waitForJob() — all fields override the async meta defaults.\n */\nexport type ZuoraWaitForJobOptions = {\n /**\n * Maximum number of polling attempts before giving up.\n * Overrides asyncMeta.maxPollAttempts.\n */\n maxPollAttempts?: number;\n /**\n * Interval in milliseconds between polling attempts.\n * Overrides asyncMeta.recommendedPollIntervalMs.\n */\n pollIntervalMs?: number;\n /**\n * Absolute timeout in milliseconds from when waitForJob() was called.\n * Overrides asyncMeta.defaultTimeoutMs.\n *\n * **Note:** the timeout is checked at the start of each loop iteration,\n * before the poll is issued. A value of `0` will therefore cause\n * `waitForJob` to throw `ASYNC_JOB_TIMEOUT` immediately without ever\n * making a poll attempt.\n */\n timeoutMs?: number;\n /**\n * Custom terminal status sets. When provided, overrides the terminal statuses\n * defined in the async operation meta.\n */\n terminalStatuses?: ZuoraAsyncJobTerminalStatuses;\n};\n","import type { ZuoraEnvironment } from \"../types.js\";\n\nexport type ZuoraMcpUrlInfo = {\n remoteUrl: string;\n restBaseUrl: string;\n};\n\nexport const normalizeZuoraMcpUrl = (raw: string): ZuoraMcpUrlInfo => {\n const trimmed = raw.replace(/\\/+$/, \"\");\n const parsed = new URL(trimmed);\n\n let restBaseUrl: string;\n\n if (trimmed.endsWith(\"/mcp\")) {\n if (!isZuoraHost(parsed.hostname)) {\n return {\n remoteUrl: trimmed,\n restBaseUrl: trimmed.slice(0, -\"/mcp\".length),\n };\n }\n\n const stagingHostMatch = parsed.hostname.match(/^staging(\\d+)\\.zuora\\.com$/);\n\n if (stagingHostMatch?.[1]) {\n restBaseUrl = `${parsed.protocol}//rest-staging${stagingHostMatch[1]}.zuora.com`;\n } else if (parsed.hostname.startsWith(\"rest.\")) {\n restBaseUrl = `${parsed.protocol}//${parsed.hostname}`;\n } else if (parsed.hostname.startsWith(\"rest-\")) {\n restBaseUrl = `${parsed.protocol}//${parsed.hostname}`;\n } else {\n restBaseUrl = `${parsed.protocol}//rest.${parsed.hostname}`;\n }\n } else {\n restBaseUrl = trimmed;\n }\n\n return {\n remoteUrl: `${restBaseUrl}/mcp`,\n restBaseUrl,\n };\n};\n\nconst isZuoraHost = (hostname: string): boolean => {\n const lower = hostname.toLowerCase();\n return lower === \"zuora.com\" || lower.endsWith(\".zuora.com\");\n};\n\nexport const isStagingZuoraBaseUrl = (baseUrl: string): boolean => {\n try {\n const hostname = new URL(baseUrl).hostname.toLowerCase();\n return (\n hostname.includes(\"staging\") ||\n hostname.includes(\".stg.\") ||\n hostname.includes(\"-stg\")\n );\n } catch {\n const lower = baseUrl.toLowerCase();\n return (\n lower.includes(\"staging\") ||\n lower.includes(\".stg.\") ||\n lower.includes(\"-stg\")\n );\n }\n};\n\nexport const inferZuoraEnvironment = (\n baseUrl: string,\n): ZuoraEnvironment | undefined => {\n let hostname: string;\n\n try {\n hostname = new URL(normalizeZuoraMcpUrl(baseUrl).restBaseUrl).hostname\n .toLowerCase();\n } catch {\n return undefined;\n }\n\n if (PRODUCTION_ZUORA_HOSTS.has(hostname)) {\n return \"production\";\n }\n\n if (SANDBOX_ZUORA_HOSTS.has(hostname) || isStagingZuoraBaseUrl(baseUrl)) {\n return \"sandbox\";\n }\n\n return undefined;\n};\n\nexport const resolveZuoraEnvironment = (\n baseUrl: string,\n): ZuoraEnvironment =>\n inferZuoraEnvironment(baseUrl) ?? \"sandbox\";\n\nconst SANDBOX_ZUORA_HOSTS = new Set([\n \"rest.apisandbox.zuora.com\",\n \"rest.sandbox.na.zuora.com\",\n \"rest.sandbox.eu.zuora.com\",\n \"rest.test.zuora.com\",\n \"rest.test.eu.zuora.com\",\n \"rest.test.ap.zuora.com\",\n]);\n\nconst PRODUCTION_ZUORA_HOSTS = new Set([\n \"rest.zuora.com\",\n \"rest.na.zuora.com\",\n \"rest.eu.zuora.com\",\n \"rest.ap.zuora.com\",\n]);\n","import { ZuoraAgentToolkitError } from \"./errors.js\";\nimport type { InternalToolkitEvent } from \"./observability/events.js\";\nimport type {\n ApprovalPolicyPresetValue,\n ApprovalPolicyResult,\n ApprovalRequest,\n NativeToolApprovalMetadata,\n ZuoraAgentToolkitConfig,\n ZuoraToolDefinition,\n ZuoraToolkitApprovalStatus,\n} from \"./types.js\";\nimport { ApprovalPolicyPreset } from \"./types.js\";\nimport { inferZuoraEnvironment } from \"./utils/zuora-url.js\";\n\nconst normalizeApprovalPolicyResult = (\n result: ApprovalPolicyResult,\n): \"allow\" | \"deny\" => {\n if (typeof result === \"string\") {\n return result;\n }\n\n return result.decision;\n};\n\nconst evaluatePreset = (\n preset: ApprovalPolicyPresetValue,\n request: ApprovalRequest,\n): \"allow\" | \"deny\" => {\n const { tool, environment } = request;\n const isWrite = tool.meta.access === \"write\";\n const isHighRisk = tool.meta.riskLevel === \"high\";\n const isProduction = environment === \"production\";\n\n switch (preset) {\n case ApprovalPolicyPreset.Off:\n return \"allow\";\n case ApprovalPolicyPreset.AllWrites:\n return isWrite ? \"deny\" : \"allow\";\n case ApprovalPolicyPreset.HighRisk:\n return isHighRisk ? \"deny\" : \"allow\";\n case ApprovalPolicyPreset.ProductionWrites:\n return isProduction && isWrite ? \"deny\" : \"allow\";\n case ApprovalPolicyPreset.ProductionHighRisk:\n return isProduction && isHighRisk ? \"deny\" : \"allow\";\n }\n};\n\nconst throwApprovalRejected = (tool: ZuoraToolDefinition): never => {\n throw new ZuoraAgentToolkitError({\n code: \"APPROVAL_REJECTED\",\n message: `Tool \"${tool.name}\" was denied by approval policy.`,\n category: \"approval\",\n recoverable: false,\n });\n};\n\nexport const enforceApproval = async (\n tool: ZuoraToolDefinition,\n input: Record<string, unknown>,\n config: ZuoraAgentToolkitConfig,\n emit?: (event: InternalToolkitEvent) => void,\n native?: NativeToolApprovalMetadata,\n): Promise<void> => {\n const { approvalPolicy } = config;\n\n if (!approvalPolicy) {\n return;\n }\n\n const environment = inferZuoraEnvironment(config.baseUrl) ?? \"sandbox\";\n const request: ApprovalRequest = {\n tool,\n input,\n environment,\n ...(native ? { native } : {}),\n };\n\n emit?.({\n name: \"approval.requested\",\n toolName: tool.name,\n access: tool.meta.access,\n bundle: tool.meta.bundle,\n riskLevel: tool.meta.riskLevel,\n environment,\n approvalStatus: \"requested\",\n });\n\n const decision =\n typeof approvalPolicy === \"function\"\n ? normalizeApprovalPolicyResult(await approvalPolicy(request))\n : evaluatePreset(approvalPolicy, request);\n\n const resolvedStatus: ZuoraToolkitApprovalStatus =\n decision === \"deny\" ? \"rejected\" : \"not_required\";\n\n emit?.({\n name: \"approval.resolved\",\n toolName: tool.name,\n access: tool.meta.access,\n bundle: tool.meta.bundle,\n riskLevel: tool.meta.riskLevel,\n environment,\n approvalDecision: decision === \"deny\" ? \"deny\" : \"allow\",\n approvalStatus: resolvedStatus,\n });\n\n if (decision === \"deny\") {\n throwApprovalRejected(tool);\n }\n};\n","const MAX_ADAPTER_TOOL_NAME_LENGTH = 64;\nconst SAFE_ADAPTER_TOOL_NAME_PATTERN = /^[A-Za-z0-9_-]+$/;\n\nexport const createOperationAdapterToolName = (\n sourceToolName: string,\n operationName: string,\n): string => {\n const rawName = `${sourceToolName}__${operationName}`;\n\n if (\n rawName.length <= MAX_ADAPTER_TOOL_NAME_LENGTH &&\n SAFE_ADAPTER_TOOL_NAME_PATTERN.test(rawName)\n ) {\n return rawName;\n }\n\n return sanitizeAdapterToolName(rawName);\n};\n\nexport const stableNameHash = (value: string): string => {\n let hash = 0x811c9dc5;\n\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n\n return (hash >>> 0).toString(36).padStart(7, \"0\").slice(-7);\n};\n\nexport const sanitizeAdapterToolName = (name: string): string => {\n if (\n name.length <= MAX_ADAPTER_TOOL_NAME_LENGTH &&\n SAFE_ADAPTER_TOOL_NAME_PATTERN.test(name)\n ) {\n return name;\n }\n\n const sanitized = name\n .replace(/[^A-Za-z0-9_-]+/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\n const candidate = sanitized || \"tool\";\n\n if (\n candidate.length <= MAX_ADAPTER_TOOL_NAME_LENGTH &&\n SAFE_ADAPTER_TOOL_NAME_PATTERN.test(candidate)\n ) {\n return candidate;\n }\n\n const hash = stableNameHash(name);\n const suffix = `_${hash}`;\n const maxPrefixLength = MAX_ADAPTER_TOOL_NAME_LENGTH - suffix.length;\n const prefix = candidate.slice(0, maxPrefixLength) || \"tool\";\n\n return `${prefix}${suffix}`;\n};\n","import { ZuoraAgentToolkitError } from \"./errors.js\";\nimport { createOperationAdapterToolName } from \"./utils/adapter-name.js\";\nimport type {\n ZuoraAsyncJobStatusResolution,\n ZuoraAsyncJobTerminalState,\n ZuoraAsyncJobTerminalStatuses,\n ZuoraAsyncOperationMeta,\n ZuoraToolExecutionResult,\n} from \"./types.js\";\n\nexport type BuildAsyncJobResultContext = {\n sourceToolName: string;\n operationSelector?: string;\n /** Split operation names registered for sourceToolName. */\n sourceOperationNames?: string[];\n};\n\nexport type ZuoraAsyncJobResult = {\n toolName: string;\n status: \"pending\";\n jobId: string;\n /** Resolved toolkit tool name to call when polling or auto-waiting. */\n pollingToolName: string;\n /** Original MCP pollingOperation metadata, when present. */\n pollingOperation?: string;\n pollingArgs?: Record<string, string>;\n /** Dot-path to the status field in the poll result (e.g. \"data.status\"). Populated from asyncMeta.statusPath at job-start time. */\n statusPath?: string;\n /** Terminal status sets for this job. Populated from asyncMeta.terminalStatuses at job-start time. */\n terminalStatuses?: ZuoraAsyncJobTerminalStatuses;\n recommendedPollIntervalMs?: number;\n maxPollAttempts?: number;\n defaultTimeoutMs?: number;\n};\n\n/**\n * Default terminal statuses applied when the async operation meta does not\n * specify its own terminal status sets and no override is provided to waitForJob.\n */\nexport const DEFAULT_ASYNC_JOB_TERMINAL_STATUSES: ZuoraAsyncJobTerminalStatuses = {\n success: [\"Completed\", \"Success\", \"Succeeded\", \"Done\"],\n failure: [\"Failed\", \"Error\", \"Errored\", \"Aborted\"],\n canceled: [\"Canceled\", \"Cancelled\"],\n};\n\n/**\n * Returns `true` when `data` is a `ZuoraAsyncJobResult` — a pending async job\n * result produced by `ToolkitCore.callTool()` via `buildAsyncJobResult()`.\n *\n * The check requires `status === \"pending\"`, a non-empty `jobId` string, and\n * at least one of `pollingToolName` or `pollingOperation`. Those routing fields\n * are only present on data shaped by `buildAsyncJobResult` — plain API responses\n * that happen to contain a job-ID-like field will not pass this guard.\n */\nexport const isAsyncJobResult = (data: unknown): data is ZuoraAsyncJobResult =>\n data != null &&\n typeof data === \"object\" &&\n (data as ZuoraAsyncJobResult).status === \"pending\" &&\n typeof (data as ZuoraAsyncJobResult).jobId === \"string\" &&\n (data as ZuoraAsyncJobResult).jobId.trim().length > 0 &&\n (typeof (data as ZuoraAsyncJobResult).pollingToolName === \"string\" ||\n typeof (data as ZuoraAsyncJobResult).pollingOperation === \"string\");\n\n/**\n * Normalizes MCP JSONPath-style expressions (e.g. \"$.data.jobId\") to the\n * dot-path form used by resolveByPath (e.g. \"data.jobId\").\n */\nexport const normalizeMetadataPath = (path: string): string => {\n const trimmed = path.trim();\n if (trimmed.startsWith(\"$.\")) {\n return trimmed.slice(2);\n }\n if (trimmed.startsWith(\"$\")) {\n return trimmed.slice(1);\n }\n return trimmed;\n};\n\n/**\n * Resolves a dot-path expression (e.g. \"data.jobId\") against an object.\n * Returns undefined if any segment is missing.\n */\nfunction resolveByPath(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- dynamic dot-path traversal requires any\n obj: any,\n path: string,\n): unknown {\n return path.split(\".\").reduce(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- same reason as above\n (current: any, segment: string) =>\n current != null && typeof current === \"object\" ? current[segment] : undefined,\n obj,\n );\n}\n\n/**\n * Resolves the toolkit tool name to invoke when polling an async job.\n * Mirrors legacy `resolveAsyncJobPollingToolName()`.\n */\nexport function resolveAsyncJobPollingToolNameFromMeta(\n asyncMeta: ZuoraAsyncOperationMeta,\n context: BuildAsyncJobResultContext,\n): string {\n const pollingOperation = asyncMeta.pollingOperation;\n const pollingTool = asyncMeta.pollingTool;\n\n if (!pollingOperation) {\n return pollingTool ?? context.sourceToolName;\n }\n\n if (pollingTool) {\n return createOperationAdapterToolName(pollingTool, pollingOperation);\n }\n\n if (\n context.operationSelector &&\n context.sourceOperationNames?.includes(pollingOperation)\n ) {\n return createOperationAdapterToolName(\n context.sourceToolName,\n pollingOperation,\n );\n }\n\n // Same-source, unsplit tool: pollingOperation lives on the source tool itself\n // (splitOperations: false). Return the source tool name so callTool can find\n // it in the registry; the operation is injected into pollingArgs by\n // buildAsyncJobResult so the MCP server routes to the correct operation.\n return context.sourceToolName;\n}\n\n/**\n * Builds a structured async-pending result to return to the agent when a tool\n * call produces a job that requires polling.\n *\n * @throws ZuoraAgentToolkitError with TOOL_EXECUTION_ERROR if jobIdPath\n * resolves to undefined or null on the raw result.\n */\nexport function buildAsyncJobResult(\n result: ZuoraToolExecutionResult,\n asyncMeta: ZuoraAsyncOperationMeta,\n context: BuildAsyncJobResultContext,\n): ZuoraAsyncJobResult {\n const payload = result.data;\n // asyncMeta.jobIdPath is already normalized at parse time by parseAsyncOperationMeta.\n const jobId = resolveByPath(payload, asyncMeta.jobIdPath);\n\n if (jobId == null) {\n throw new ZuoraAgentToolkitError({\n code: \"TOOL_EXECUTION_ERROR\",\n message: `Async job ID not found at path \"${asyncMeta.jobIdPath}\" in tool result for \"${result.toolName}\".`,\n category: \"tool_execution\",\n });\n }\n\n const pollingToolName = resolveAsyncJobPollingToolNameFromMeta(\n asyncMeta,\n context,\n );\n\n const pending: ZuoraAsyncJobResult = {\n toolName: result.toolName,\n status: \"pending\",\n jobId: String(jobId),\n pollingToolName,\n ...(asyncMeta.pollingOperation\n ? { pollingOperation: asyncMeta.pollingOperation }\n : {}),\n statusPath: asyncMeta.statusPath,\n terminalStatuses: asyncMeta.terminalStatuses,\n };\n\n // For same-source unsplit tools (pollingTool absent, no operationSelector),\n // the polling call targets the merged source tool, so the operation name must\n // be included in pollingArgs for the MCP server to route it correctly.\n const needsOperationInjection =\n !!asyncMeta.pollingOperation &&\n !asyncMeta.pollingTool &&\n !context.operationSelector;\n\n if (needsOperationInjection) {\n pending.pollingArgs = {\n ...asyncMeta.pollingArgs,\n operation: asyncMeta.pollingOperation!,\n };\n } else if (asyncMeta.pollingArgs !== undefined) {\n pending.pollingArgs = asyncMeta.pollingArgs;\n }\n\n if (asyncMeta.recommendedPollIntervalMs !== undefined) {\n pending.recommendedPollIntervalMs = asyncMeta.recommendedPollIntervalMs;\n }\n\n if (asyncMeta.maxPollAttempts !== undefined) {\n pending.maxPollAttempts = asyncMeta.maxPollAttempts;\n }\n\n if (asyncMeta.defaultTimeoutMs !== undefined) {\n pending.defaultTimeoutMs = asyncMeta.defaultTimeoutMs;\n }\n\n return pending;\n}\n\n// ── Async job status utilities ────────────────────────────────────────────────\n\n/**\n * Returns true when the given status string matches any status in the success,\n * failure, or canceled sets of the provided terminal statuses config.\n *\n * The comparison is case-insensitive.\n */\nexport function matchesAsyncJobTerminalStatus(\n status: string,\n statuses: ZuoraAsyncJobTerminalStatuses,\n): boolean {\n const lower = status.toLowerCase();\n if (statuses.success.some((s) => s.toLowerCase() === lower)) return true;\n if (statuses.failure.some((s) => s.toLowerCase() === lower)) return true;\n if (statuses.canceled?.some((s) => s.toLowerCase() === lower)) return true;\n return false;\n}\n\n/**\n * Resolves the terminal state (\"success\" | \"failure\" | \"canceled\") for the\n * given status string against the provided terminal statuses config.\n *\n * Returns undefined when the status has not yet reached a terminal state.\n */\nexport function resolveAsyncJobTerminalState(\n status: string,\n statuses: ZuoraAsyncJobTerminalStatuses,\n): ZuoraAsyncJobTerminalState | undefined {\n const lower = status.toLowerCase();\n if (statuses.success.some((s) => s.toLowerCase() === lower)) return \"success\";\n if (statuses.failure.some((s) => s.toLowerCase() === lower)) return \"failure\";\n if (statuses.canceled?.some((s) => s.toLowerCase() === lower)) return \"canceled\";\n return undefined;\n}\n\n/**\n * Returns true when the given async job result has reached a terminal state\n * according to the provided terminal statuses config.\n *\n * The job is considered terminal only when a non-null, non-empty status string\n * is present in the result data and that status matches one of the terminal sets.\n */\nexport function isAsyncJobTerminal(\n result: ZuoraToolExecutionResult,\n statusPath: string,\n statuses: ZuoraAsyncJobTerminalStatuses,\n): boolean {\n const status = resolveAsyncJobStatus(result, statusPath);\n if (status == null || status === \"\") return false;\n return matchesAsyncJobTerminalStatus(status, statuses);\n}\n\n/**\n * Extracts the current job status string from a polling tool result.\n *\n * @param result - The result returned by the polling tool.\n * @param statusPath - Dot-path to the status field within result.data,\n * e.g. \"status\" or \"job.state\". Paths are normalized at parse time by\n * parseAsyncOperationMeta, so callers within the SDK should always pass\n * already-normalized paths here.\n * @returns The extracted status string, or undefined if not present.\n */\nexport function resolveAsyncJobStatus(\n result: ZuoraToolExecutionResult,\n statusPath: string,\n): string | undefined {\n const raw = resolveByPath(result.data, statusPath);\n if (raw == null || typeof raw !== \"string\") return undefined;\n return raw;\n}\n\n/**\n * Extracts the job ID from a ZuoraAsyncJobResult embedded inside a tool\n * execution result, or returns the jobId directly from a ZuoraAsyncJobResult.\n *\n * Supports two calling patterns:\n * - resolveAsyncJobId(asyncJobResult)\n * - resolveAsyncJobId(toolResult, jobIdPath)\n */\nexport function resolveAsyncJobId(\n result: ZuoraAsyncJobResult | ZuoraToolExecutionResult,\n jobIdPath?: string,\n): string | undefined {\n // If we have a ZuoraAsyncJobResult (has status: \"pending\")\n if (\"status\" in result && result.status === \"pending\" && \"jobId\" in result) {\n return (result as ZuoraAsyncJobResult).jobId;\n }\n\n // Otherwise treat as ZuoraToolExecutionResult and extract via path.\n // Paths sourced from asyncMeta are already normalized at parse time by\n // parseAsyncOperationMeta, so no further normalization is needed here.\n if (jobIdPath && \"data\" in result) {\n const raw = resolveByPath(result.data, jobIdPath);\n if (raw != null && typeof raw === \"string\") return raw;\n if (raw != null) return String(raw);\n }\n\n return undefined;\n}\n\n/**\n * Extracts the name of the next polling tool from a ZuoraAsyncJobResult.\n * Returns undefined if result is not a ZuoraAsyncJobResult.\n *\n * pollingToolName is always set on ZuoraAsyncJobResult (resolved at job-start\n * time by resolveAsyncJobPollingToolNameFromMeta), so it is returned directly.\n */\nexport function resolveAsyncJobPollingToolName(\n result: ZuoraAsyncJobResult | ZuoraToolExecutionResult,\n): string | undefined {\n if (\"status\" in result && result.status === \"pending\") {\n return (result as ZuoraAsyncJobResult).pollingToolName;\n }\n return undefined;\n}\n\n/**\n * Returns a rich ZuoraAsyncJobStatusResolution describing the current status\n * of an async job, including whether it has reached a terminal state and what\n * the terminal state is.\n *\n * @param result - The result returned by the polling tool.\n * @param statusPath - Dot-path to the status field (e.g. \"data.status\").\n * @param terminalStatuses - Terminal status configuration to match against.\n */\nexport function resolveAsyncJobStatusDetails(\n result: ZuoraToolExecutionResult,\n statusPath: string,\n terminalStatuses: ZuoraAsyncJobTerminalStatuses,\n): ZuoraAsyncJobStatusResolution {\n const status = resolveAsyncJobStatus(result, statusPath);\n\n if (status == null || status === \"\") {\n return { status: undefined, isTerminal: false, terminalState: undefined };\n }\n\n const terminalState = resolveAsyncJobTerminalState(status, terminalStatuses);\n const isTerminal = terminalState !== undefined;\n\n return { status, isTerminal, terminalState };\n}\n","import bundleCatalog from \"./resources/bundle-catalog.json\" with { type: \"json\" };\nimport type {\n ZuoraBundleDefinition,\n ZuoraBundleName,\n ZuoraToolDefinition,\n} from \"./types.js\";\nimport { isRecord } from \"./utils/values.js\";\n\nexport const ZUORA_BUNDLE_NAMES = [\n \"accounts\",\n \"catalog\",\n \"subscriptions\",\n \"orders\",\n \"billing\",\n \"payments\",\n \"usage\",\n \"revenue\",\n \"finance\",\n \"workflows\",\n \"query\",\n \"admin\",\n] as const satisfies readonly ZuoraBundleName[];\n\nexport type BundleCatalogEntry = {\n description: string;\n examples: string[];\n commonObjects: string[];\n keywords: string[];\n};\n\nexport type BundleCatalog = {\n version: number;\n bundles: Record<ZuoraBundleName, BundleCatalogEntry>;\n};\n\nconst readStringArrayField = (\n record: Record<string, unknown>,\n fieldName: string,\n bundleName: ZuoraBundleName,\n): string[] => {\n const value = record[fieldName];\n\n if (\n !Array.isArray(value) ||\n value.length === 0 ||\n value.some((item) => typeof item !== \"string\" || item.trim() === \"\")\n ) {\n throw new Error(\n `Invalid bundle catalog entry for ${bundleName}: ${fieldName} must be a non-empty string array.`,\n );\n }\n\n return value.map((item) => item.trim());\n};\n\nconst readBundleCatalogEntry = (\n value: unknown,\n bundleName: ZuoraBundleName,\n): BundleCatalogEntry => {\n if (!isRecord(value)) {\n throw new Error(`Missing bundle catalog entry for ${bundleName}.`);\n }\n\n const description = value.description;\n\n if (typeof description !== \"string\" || description.trim() === \"\") {\n throw new Error(\n `Invalid bundle catalog entry for ${bundleName}: description is required.`,\n );\n }\n\n return {\n description: description.trim(),\n examples: readStringArrayField(value, \"examples\", bundleName),\n commonObjects: readStringArrayField(value, \"commonObjects\", bundleName),\n keywords: readStringArrayField(value, \"keywords\", bundleName),\n };\n};\n\nconst loadBundleCatalog = (): BundleCatalog => {\n const raw = bundleCatalog as unknown;\n\n if (!isRecord(raw)) {\n throw new Error(\"Invalid bundle catalog: expected an object.\");\n }\n\n const rawBundles = raw.bundles;\n\n if (!isRecord(rawBundles)) {\n throw new Error(\"Invalid bundle catalog: expected a bundles object.\");\n }\n\n const version = raw.version;\n\n if (typeof version !== \"number\" || !Number.isInteger(version)) {\n throw new Error(\"Invalid bundle catalog: version must be an integer.\");\n }\n\n const bundles = Object.fromEntries(\n ZUORA_BUNDLE_NAMES.map((name) => [\n name,\n readBundleCatalogEntry(rawBundles[name], name),\n ]),\n ) as Record<ZuoraBundleName, BundleCatalogEntry>;\n\n return {\n version,\n bundles,\n };\n};\n\nexport const BUNDLE_CATALOG: BundleCatalog = loadBundleCatalog();\n\nexport const ZUORA_BUNDLE_NAME_SET = new Set<ZuoraBundleName>(ZUORA_BUNDLE_NAMES);\n\nexport const hasBundleDefinition = (\n name: string,\n): name is ZuoraBundleName => ZUORA_BUNDLE_NAME_SET.has(name as ZuoraBundleName);\n\nexport const getBundleDefinition = (\n name: ZuoraBundleName,\n tools: ZuoraToolDefinition[] = [],\n): ZuoraBundleDefinition => {\n const metadata = BUNDLE_CATALOG.bundles[name];\n const bundleTools = tools.filter((tool) => tool.meta.bundle === name);\n const description = metadata?.description ?? name;\n const examples = metadata ? [...metadata.examples] : [];\n const commonObjects = metadata ? [...metadata.commonObjects] : [];\n const keywords = metadata ? [...metadata.keywords] : [];\n\n return {\n name,\n description,\n examples,\n commonObjects,\n keywords,\n toolCount: bundleTools.length,\n readToolCount: bundleTools.filter((tool) => tool.meta.access === \"read\")\n .length,\n writeToolCount: bundleTools.filter((tool) => tool.meta.access === \"write\")\n .length,\n tools: bundleTools,\n };\n};\n","export const nonEmptyString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport const normalizeIdList = (value: unknown): string[] | undefined => {\n const values = Array.isArray(value)\n ? value\n : typeof value === \"string\"\n ? value.split(\",\")\n : [];\n const normalized = values.flatMap((entry) => {\n const normalizedEntry = nonEmptyString(entry);\n return normalizedEntry ? [normalizedEntry] : [];\n });\n\n return normalized.length > 0 ? normalized : undefined;\n};\n","import { ZuoraAgentToolkitError } from \"../errors.js\";\nimport type { JsonSchema, ZuoraToolDefinition, ZuoraToolOperation } from \"../types.js\";\n\nexport const inferOperationSelector = (\n inputSchema: JsonSchema | undefined,\n operationPermissions: Record<string, ZuoraToolOperation> | undefined,\n): string | undefined => {\n const operationNames = Object.keys(operationPermissions ?? {});\n\n if (operationNames.length <= 1) {\n return undefined;\n }\n\n const properties = inputSchema?.properties;\n\n if (!properties) {\n return undefined;\n }\n\n const candidates = Object.entries(properties).flatMap(\n ([propertyName, propertySchema]) =>\n isOperationSelectorSchema(propertySchema, operationNames)\n ? [propertyName]\n : [],\n );\n\n return candidates.length === 1 ? candidates[0] : undefined;\n};\n\nexport const omitSchemaProperty = (\n schema: JsonSchema,\n propertyName: string,\n): JsonSchema => {\n if (!schema.properties?.[propertyName]) {\n return schema;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { [propertyName]: _removed, ...properties } = schema.properties;\n const nextSchema: JsonSchema = {\n ...schema,\n properties,\n };\n\n if (schema.required) {\n const required = schema.required.filter((name) => name !== propertyName);\n\n if (required.length > 0) {\n nextSchema.required = required;\n } else {\n delete nextSchema.required;\n }\n }\n\n return nextSchema;\n};\n\nexport const enforceOperationSelector = (\n tool: ZuoraToolDefinition,\n input: Record<string, unknown>,\n): void => {\n const selector = tool.meta.operationSelector;\n\n // Only enforce on split tools that are bound to a single operation.\n // Merged tools have operationSelector set for runtime async lookup but are\n // not bound to one operation — the LLM's input value passes through as-is.\n if (!selector || !tool.meta.operationName) {\n return;\n }\n\n if (!Object.prototype.hasOwnProperty.call(input, selector)) {\n return;\n }\n\n const providedOperation = input[selector];\n\n const expectedOperation = tool.meta.operationName;\n\n if (providedOperation === expectedOperation) {\n return;\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"OPERATION_SELECTOR_MISMATCH\",\n message: `Tool ${tool.name} is bound to ${selector}=${expectedOperation}.`,\n category: \"validation\",\n recoverable: true,\n details: {\n selector,\n expected: expectedOperation,\n received: providedOperation,\n sourceName: tool.meta.sourceName,\n },\n });\n};\n\nexport const createMcpToolInput = (\n tool: ZuoraToolDefinition,\n input: Record<string, unknown>,\n): Record<string, unknown> => {\n const selector = tool.meta.operationSelector;\n\n // Only inject the operation on split tools bound to a single operation.\n // Merged tools pass through input unchanged — the LLM provides the value.\n if (!selector || !tool.meta.operationName) {\n return input;\n }\n\n return { ...input, [selector]: tool.meta.operationName };\n};\n\nconst isOperationSelectorSchema = (\n schema: JsonSchema,\n operationNames: string[],\n): boolean => {\n const enumValues = stringEnumValues(schema);\n\n if (!enumValues) {\n return false;\n }\n\n return haveSameStringSet(enumValues, operationNames);\n};\n\nconst stringEnumValues = (schema: JsonSchema): string[] | undefined => {\n if (schema.type !== \"string\" || !Array.isArray(schema.enum)) {\n return undefined;\n }\n\n return schema.enum.every((value): value is string => typeof value === \"string\")\n ? schema.enum\n : undefined;\n};\n\nconst haveSameStringSet = (left: string[], right: string[]): boolean => {\n if (left.length !== right.length) {\n return false;\n }\n\n const rightSet = new Set(right);\n return left.every((value) => rightSet.has(value));\n};\n","import { isRecord } from \"./values.js\";\n\nconst REDACTED_EVENT_VALUE = \"[REDACTED]\";\nconst TRUNCATED_EVENT_VALUE = \"[TRUNCATED]\";\n\nconst DEFAULT_EVENT_SANITIZER_LIMITS = {\n maxDepth: 4,\n maxArrayLength: 20,\n maxObjectKeys: 50,\n maxStringLength: 512,\n} as const;\n\nexport type EventSanitizerLimits = {\n maxDepth: number;\n maxArrayLength: number;\n maxObjectKeys: number;\n maxStringLength: number;\n};\n\nexport const resolveEventSanitizerLimits = (\n env: Record<string, string | undefined>,\n): EventSanitizerLimits => ({\n maxDepth: readPositiveIntegerEnv(\n env,\n \"MAX_EVENT_METADATA_DEPTH\",\n DEFAULT_EVENT_SANITIZER_LIMITS.maxDepth,\n ),\n maxArrayLength: readPositiveIntegerEnv(\n env,\n \"MAX_EVENT_METADATA_ARRAY_LENGTH\",\n DEFAULT_EVENT_SANITIZER_LIMITS.maxArrayLength,\n ),\n maxObjectKeys: readPositiveIntegerEnv(\n env,\n \"MAX_EVENT_METADATA_OBJECT_KEYS\",\n DEFAULT_EVENT_SANITIZER_LIMITS.maxObjectKeys,\n ),\n maxStringLength: readPositiveIntegerEnv(\n env,\n \"MAX_EVENT_METADATA_STRING_LENGTH\",\n DEFAULT_EVENT_SANITIZER_LIMITS.maxStringLength,\n ),\n});\n\nexport const sanitizeEventRecord = (\n value: Record<string, unknown>,\n limits: EventSanitizerLimits = DEFAULT_EVENT_SANITIZER_LIMITS,\n): Record<string, unknown> => {\n const sanitized = sanitizeEventValue(value, \"\", 0, limits);\n\n return isRecord(sanitized) ? sanitized : { value: sanitized };\n};\n\nconst sanitizeEventValue = (\n value: unknown,\n key: string,\n depth: number,\n limits: EventSanitizerLimits,\n): unknown => {\n if (isSensitiveEventKey(key)) {\n return REDACTED_EVENT_VALUE;\n }\n\n if (value === null) {\n return null;\n }\n\n if (typeof value === \"string\") {\n if (looksSensitiveString(value)) {\n return REDACTED_EVENT_VALUE;\n }\n\n return value.length > limits.maxStringLength\n ? `${value.slice(0, limits.maxStringLength)}...`\n : value;\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n if (value === undefined || typeof value === \"function\" || typeof value === \"symbol\") {\n return undefined;\n }\n\n if (depth >= limits.maxDepth) {\n return TRUNCATED_EVENT_VALUE;\n }\n\n if (Array.isArray(value)) {\n const entries = value\n .slice(0, limits.maxArrayLength)\n .map((entry) => sanitizeEventValue(entry, \"\", depth + 1, limits));\n\n return value.length > limits.maxArrayLength\n ? [...entries, TRUNCATED_EVENT_VALUE]\n : entries;\n }\n\n if (!isRecord(value)) {\n return String(value);\n }\n\n return Object.fromEntries(\n Object.entries(value)\n .slice(0, limits.maxObjectKeys)\n .flatMap(([entryKey, entryValue]) => {\n const sanitizedEntry = sanitizeEventValue(\n entryValue,\n entryKey,\n depth + 1,\n limits,\n );\n\n return sanitizedEntry === undefined ? [] : [[entryKey, sanitizedEntry]];\n }),\n );\n};\n\nconst readPositiveIntegerEnv = (\n env: Record<string, string | undefined>,\n name: string,\n fallback: number,\n): number => {\n const value = env[name];\n\n if (!value?.trim()) {\n return fallback;\n }\n\n const parsed = Number.parseInt(value, 10);\n\n if (!Number.isInteger(parsed) || parsed < 1) {\n return fallback;\n }\n\n return parsed;\n};\n\nconst isSensitiveEventKey = (key: string): boolean =>\n /authorization|client[_-]?secret|access[_-]?token|refresh[_-]?token|api[_-]?key|private[_-]?key|password|secret|token|signed[_-]?url|card[_-]?number|cvv|cvc|iban|bank[_-]?account|routing[_-]?number/i.test(\n key,\n );\n\nconst looksSensitiveString = (value: string): boolean =>\n /^(Bearer|Basic)\\s+\\S+/i.test(value) ||\n looksSignedUrl(value) ||\n /(?:access_token|refresh_token|client_secret|signature|x-amz-signature)=/i.test(\n value,\n ) ||\n /^sk-[A-Za-z0-9_-]{12,}/.test(value) ||\n /^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/.test(value);\n\nconst looksSignedUrl = (value: string): boolean => {\n let parsed: URL;\n\n try {\n parsed = new URL(value);\n } catch {\n return false;\n }\n\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return false;\n }\n\n for (const key of parsed.searchParams.keys()) {\n if (\n /^(sig|signature|token|access_token|security-token|x-amz-.+|x-goog-.+|expires|expires_in)$/i.test(\n key,\n )\n ) {\n return true;\n }\n }\n\n return false;\n};\n","import { ZuoraAgentToolkitError } from \"../errors.js\";\nimport type {\n EventSanitizerLimits,\n ToolkitBundleName,\n ZuoraToolDefinition,\n ZuoraToolkitEvent,\n ZuoraToolkitLogger,\n} from \"../types.js\";\nimport { sanitizeEventRecord } from \"../utils/event-sanitizer.js\";\n\nexport type InternalToolkitEvent = Omit<\n ZuoraToolkitEvent,\n \"type\" | \"timestamp\"\n> &\n Partial<Pick<ZuoraToolkitEvent, \"type\" | \"timestamp\">>;\n\nexport type EventRequestMetadata = Pick<\n ZuoraToolkitEvent,\n | \"requestId\"\n | \"zuoraRequestId\"\n | \"environment\"\n | \"tenantId\"\n | \"entityIds\"\n | \"orgIds\"\n>;\n\nexport const reportObservabilitySinkError = (\n logger: ZuoraToolkitLogger | undefined,\n error: unknown,\n): void => {\n try {\n logger?.error?.(\"[zuora-agent-toolkit] observability sink failed\", {\n name: \"observability.sink_failed\",\n type: \"observability.sink_failed\",\n timestamp: new Date().toISOString(),\n error: {\n code: \"OBSERVABILITY_SINK_ERROR\",\n category: \"configuration\",\n recoverable: true,\n },\n metadata: sanitizeEventRecord({\n message: error instanceof Error ? error.message : String(error),\n }),\n });\n } catch {\n // Ignore logger failures.\n }\n};\n\nexport const normalizeToolkitEvent = (\n event: InternalToolkitEvent,\n sanitizerLimits?: EventSanitizerLimits,\n): ZuoraToolkitEvent => {\n const { metadata, timestamp, type, ...rest } = event;\n\n return {\n ...rest,\n type: type ?? toolkitEventTypeForName(event.name),\n timestamp: timestamp ?? new Date().toISOString(),\n ...(metadata\n ? { metadata: sanitizeEventRecord(metadata, sanitizerLimits) }\n : {}),\n } as ZuoraToolkitEvent;\n};\n\nexport const compactToolkitError = (\n error: ZuoraAgentToolkitError,\n): NonNullable<ZuoraToolkitEvent[\"error\"]> => ({\n code: error.code,\n category: error.category,\n recoverable: error.recoverable,\n retryable: error.retryable,\n message: error.message,\n ...(error.requestId ? { requestId: error.requestId } : {}),\n});\n\nexport const metadataLoadedEventMetadata = (\n tools: ZuoraToolDefinition[],\n): Record<string, unknown> => {\n const bundleCounts = tools.reduce<Partial<Record<ToolkitBundleName, number>>>(\n (counts, tool) => {\n counts[tool.meta.bundle] = (counts[tool.meta.bundle] ?? 0) + 1;\n return counts;\n },\n {},\n );\n return {\n toolCount: tools.length,\n bundleCounts,\n };\n};\n\nconst toolkitEventTypeForName = (\n name: ZuoraToolkitEvent[\"name\"],\n): ZuoraToolkitEvent[\"type\"] =>\n name === \"approval.resolved\" ? \"approval.decided\" : name;\n","import type { ZuoraToolkitEvent, ZuoraToolkitLogger } from \"../types.js\";\nimport { sanitizeEventRecord } from \"../utils/event-sanitizer.js\";\n\nexport type AsyncPollTerminationDecision =\n | \"success\"\n | \"failure\"\n | \"canceled\"\n | \"continue\"\n | \"no_status\";\n\nexport type AsyncPollCheckedDetails = {\n jobId: string;\n attempt: number;\n maxAttempts: number;\n pollingToolName: string;\n statusPath: string;\n statusSource: \"asyncJob.status\" | \"statusPath\" | \"fallback.status\" | \"none\";\n resolvedValue: unknown;\n resolvedStatus?: string;\n terminalStatuses: {\n success: string[];\n failure: string[];\n canceled?: string[];\n };\n matchedSuccess: boolean;\n matchedFailure: boolean;\n matchedCanceled: boolean;\n decision: AsyncPollTerminationDecision;\n};\n\n/**\n * Logs an `async.poll.checked` debug event directly to the toolkit logger.\n *\n * This function intentionally bypasses the central `ToolkitCore.emit()` path\n * (and therefore skips `onEvent`/`emit` sink hooks) because async-poll checks\n * are high-frequency, debug-only telemetry. Routing them through the full\n * sink chain would require threading the `ToolkitCore` instance into the async\n * polling loop, adding complexity with little benefit for production consumers.\n * If you need to capture these events in a sink, subscribe via the `logger`\n * option in the observability config.\n */\nexport const logAsyncPollChecked = (\n logger: ZuoraToolkitLogger | undefined,\n details: AsyncPollCheckedDetails,\n): void => {\n if (!logger?.debug) {\n return;\n }\n\n const message = \"[zuora-agent-toolkit] async.poll.checked\";\n const event: ZuoraToolkitEvent = {\n name: \"async.poll.checked\",\n type: \"async.poll.checked\",\n timestamp: new Date().toISOString(),\n executionPhase: \"async_poll\",\n toolName: details.pollingToolName,\n metadata: sanitizeEventRecord({\n jobId: details.jobId,\n attempt: details.attempt,\n maxAttempts: details.maxAttempts,\n pollingToolName: details.pollingToolName,\n statusPath: details.statusPath,\n statusSource: details.statusSource,\n resolvedValue: details.resolvedValue,\n ...(details.resolvedStatus\n ? { resolvedStatus: details.resolvedStatus }\n : {}),\n terminalStatuses: details.terminalStatuses,\n matchedSuccess: details.matchedSuccess,\n matchedFailure: details.matchedFailure,\n matchedCanceled: details.matchedCanceled,\n decision: details.decision,\n }),\n };\n\n try {\n logger.debug(message, event);\n } catch {\n // Best-effort observability only.\n }\n};\n","import type { ZuoraToolExecutionResult } from \"../types.js\";\nimport { sanitizeEventRecord } from \"../utils/event-sanitizer.js\";\n\nexport const compactToolInputForEvent = (\n input: Record<string, unknown>,\n): Record<string, unknown> => sanitizeEventRecord(input);\n\nexport const compactToolOutputForEvent = (\n result: ZuoraToolExecutionResult,\n): Record<string, unknown> =>\n sanitizeEventRecord({\n toolName: result.toolName,\n ...(result.requestId ? { requestId: result.requestId } : {}),\n ...(result.request ? { request: result.request } : {}),\n riskLevel: result.riskLevel,\n data: result.data,\n ...(result.warnings?.length ? { warnings: result.warnings } : {}),\n });\n","import type { ZuoraEnvironment, ZuoraExecutionRequestMetadata } from \"../types.js\";\nimport {\n nonEmptyString,\n normalizeIdList,\n} from \"../utils/values.js\";\n\n/**\n * Shared normalizer for Zuora request-metadata fields across both the\n * transport layer (`ZuoraExecutionRequestMetadata`) and the observability\n * layer (`EventRequestMetadata`). Both use the same field aliases\n * (camelCase / snake_case), so a single implementation avoids drift.\n *\n * Returns a partial record containing only the fields that were present and\n * non-empty in the source object. Returns `undefined` when the source is not\n * an object or contains no recognisable fields.\n */\nexport const normalizeRequestMetadataFields = (\n value: unknown,\n): ZuoraExecutionRequestMetadata | undefined => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n const requestId = nonEmptyString(record.requestId) ?? nonEmptyString(record.request_id);\n const zuoraRequestId =\n nonEmptyString(record.zuoraRequestId) ??\n nonEmptyString(record.zuora_request_id);\n const tenantId = nonEmptyString(record.tenantId) ?? nonEmptyString(record.tenant_id);\n const entityIds =\n normalizeIdList(record.entityIds) ??\n normalizeIdList(record.entity_ids) ??\n normalizeIdList(record.entityId) ??\n normalizeIdList(record.entity_id);\n const orgIds =\n normalizeIdList(record.orgIds) ??\n normalizeIdList(record.org_ids) ??\n normalizeIdList(record.orgId) ??\n normalizeIdList(record.org_id);\n const environment = normalizeRequestEnvironment(record.environment);\n const metadata = {\n ...(requestId ? { requestId } : {}),\n ...(zuoraRequestId ? { zuoraRequestId } : {}),\n ...(environment ? { environment } : {}),\n ...(tenantId ? { tenantId } : {}),\n ...(entityIds ? { entityIds } : {}),\n ...(orgIds ? { orgIds } : {}),\n };\n\n return Object.keys(metadata).length > 0 ? metadata : undefined;\n};\n\n/** @deprecated Use `normalizeRequestMetadataFields` directly. */\nexport const normalizeExecutionRequestMetadata = normalizeRequestMetadataFields;\n\nconst normalizeRequestEnvironment = (\n value: unknown,\n): ZuoraEnvironment | undefined => {\n const normalized = nonEmptyString(value)?.toLowerCase();\n\n return normalized === \"sandbox\" || normalized === \"production\"\n ? normalized\n : undefined;\n};\n","import type {\n ZuoraToolExecutionResult,\n} from \"../types.js\";\nimport { normalizeRequestMetadataFields } from \"../transport/request-metadata.js\";\nimport type { EventRequestMetadata } from \"./events.js\";\n\nexport const extractExecutionRequestMetadata = (\n result: ZuoraToolExecutionResult,\n): EventRequestMetadata => {\n const explicitRequest = normalizeRequestMetadataFields(result.request) ?? {};\n const nestedRequest = extractNestedRequestMetadata(result.data);\n const fallbackRequestId = result.requestId ?? extractRequestId(result.data);\n const requestId =\n explicitRequest.requestId ??\n nestedRequest.requestId ??\n fallbackRequestId ??\n explicitRequest.zuoraRequestId ??\n nestedRequest.zuoraRequestId;\n const zuoraRequestId =\n explicitRequest.zuoraRequestId ??\n nestedRequest.zuoraRequestId ??\n extractZuoraRequestId(result.data) ??\n requestId;\n const metadata: EventRequestMetadata = {\n ...(requestId ? { requestId } : {}),\n ...(zuoraRequestId ? { zuoraRequestId } : {}),\n ...(explicitRequest.environment ?? nestedRequest.environment\n ? { environment: explicitRequest.environment ?? nestedRequest.environment }\n : {}),\n ...(explicitRequest.tenantId ?? nestedRequest.tenantId\n ? { tenantId: explicitRequest.tenantId ?? nestedRequest.tenantId }\n : {}),\n ...(explicitRequest.entityIds ?? nestedRequest.entityIds\n ? { entityIds: explicitRequest.entityIds ?? nestedRequest.entityIds }\n : {}),\n ...(explicitRequest.orgIds ?? nestedRequest.orgIds\n ? { orgIds: explicitRequest.orgIds ?? nestedRequest.orgIds }\n : {}),\n };\n\n return metadata;\n};\n\nconst extractNestedRequestMetadata = (value: unknown): EventRequestMetadata => {\n if (!value || typeof value !== \"object\") {\n return {};\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n const request = extractNestedRequestMetadata(item);\n\n if (Object.keys(request).length > 0) {\n return request;\n }\n }\n\n return {};\n }\n\n const record = value as Record<string, unknown>;\n const request = normalizeRequestMetadataFields(record.request) ?? {};\n\n if (Object.keys(request).length > 0) {\n return request;\n }\n\n for (const entry of Object.values(record)) {\n const nestedRequest = extractNestedRequestMetadata(entry);\n\n if (Object.keys(nestedRequest).length > 0) {\n return nestedRequest;\n }\n }\n\n return {};\n};\n\n/**\n * Generic recursive search: traverses `value` (object/array) looking for the\n * first string field whose key matches one of `keys`. Returns the first match.\n */\nconst extractFirstMatchingStringField = (\n value: unknown,\n keys: readonly string[],\n): string | undefined => {\n if (!value || typeof value !== \"object\") {\n return undefined;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n const found = extractFirstMatchingStringField(item, keys);\n\n if (found) {\n return found;\n }\n }\n\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n\n for (const key of keys) {\n if (key in record && typeof record[key] === \"string\") {\n return record[key] as string;\n }\n }\n\n for (const entry of Object.values(record)) {\n const found = extractFirstMatchingStringField(entry, keys);\n\n if (found) {\n return found;\n }\n }\n\n return undefined;\n};\n\n/** Extracts any request-correlation ID from a result payload. */\nexport const extractRequestId = (value: unknown): string | undefined =>\n extractFirstMatchingStringField(value, [\n \"zuoraRequestId\",\n \"zuora_request_id\",\n \"requestId\",\n \"request_id\",\n ]);\n\n/** Extracts a Zuora server-assigned trace ID from a result payload. */\nconst extractZuoraRequestId = (value: unknown): string | undefined =>\n extractFirstMatchingStringField(value, [\n \"zuoraRequestId\",\n \"zuora_request_id\",\n ]);\n","import os from \"node:os\";\nimport path from \"node:path\";\n\nimport { ZuoraAgentToolkitError } from \"../../../errors.js\";\nimport type { NativeFileToolsConfig } from \"../../../types.js\";\nimport { nonEmptyString } from \"../../../utils/values.js\";\nimport {\n resolveNativeToolMetadata,\n type ResolvedNativeToolMetadataConfig,\n} from \"../config.js\";\n\nexport type ResolvedNativeFileToolsConfig = {\n enabled: boolean;\n bundleName: \"query\";\n tools: {\n downloadFile: ResolvedNativeToolMetadataConfig;\n readDownloadedFile: ResolvedNativeToolMetadataConfig;\n extractDownloadedArchive: ResolvedNativeToolMetadataConfig;\n readResource: ResolvedNativeToolMetadataConfig;\n };\n rootDir: string;\n rootDirAbsolute: string;\n userHomeDir: string;\n userHomeDirAbsolute: string;\n requireRootUnderUserHome: boolean;\n allowOverwrite: boolean;\n maxDownloadBytes: number;\n maxReadBytes: number;\n maxReadLines: number;\n maxExtractedFiles: number;\n maxExtractedBytes: number;\n downloadTimeoutMs: number;\n allowedProtocols: string[];\n allowedHosts: string[];\n allowedUrlPrefixes: string[];\n zuoraDownloadHosts: string[];\n allowZuoraAuthenticatedDownload: boolean;\n allowS3PresignedDownload: boolean;\n allowArchiveExtraction: boolean;\n};\n\nconst DEFAULT_MAX_DOWNLOAD_BYTES = 10 * 1024 * 1024;\nconst DEFAULT_MAX_READ_BYTES = 64 * 1024;\nconst DEFAULT_MAX_READ_LINES = 200;\nconst DEFAULT_DOWNLOAD_TIMEOUT_MS = 30_000;\n\nexport const resolveNativeFileToolsConfig = (\n input: NativeFileToolsConfig | undefined,\n): ResolvedNativeFileToolsConfig => {\n const enabled = input?.enabled ?? false;\n const bundleName: \"query\" = (input?.bundleName ?? \"query\") as \"query\";\n const userHomeDir = nonEmptyString(input?.userHomeDir) ?? os.homedir();\n const userHomeDirAbsolute = path.resolve(userHomeDir);\n const rootDir = nonEmptyString(input?.rootDir) ?? \"\";\n // When rootDir is empty and enabled=false, rootDirAbsolute is intentionally\n // left as \"\" rather than resolving against process.cwd(). The validation gate\n // in validateEnabledConfig() rejects an empty rootDir whenever enabled=true,\n // so no code path that calls path.resolve(rootDirAbsolute, ...) can reach a\n // live filesystem operation with an empty string.\n const rootDirAbsolute = rootDir ? path.resolve(rootDir) : \"\";\n const requireRootUnderUserHome = input?.requireRootUnderUserHome ?? true;\n const allowedProtocols = normalizeProtocols(input?.allowedProtocols);\n const allowedHosts = normalizeStringList(input?.allowedHosts).map((host) =>\n host.toLowerCase(),\n );\n const allowedUrlPrefixes = normalizeStringList(input?.allowedUrlPrefixes);\n const zuoraDownloadHosts = normalizeStringList(input?.zuoraDownloadHosts).map(\n (host) => host.toLowerCase(),\n );\n const config: ResolvedNativeFileToolsConfig = {\n enabled,\n bundleName,\n tools: {\n downloadFile: resolveNativeToolMetadata(input?.tools?.downloadFile, {\n enabled: false,\n operationAccess: \"read\",\n riskLevel: \"medium\",\n }),\n readDownloadedFile: resolveNativeToolMetadata(input?.tools?.readDownloadedFile, {\n enabled: true,\n operationAccess: \"read\",\n riskLevel: \"low\",\n }),\n extractDownloadedArchive: resolveNativeToolMetadata(\n input?.tools?.extractDownloadedArchive,\n {\n enabled: false,\n operationAccess: \"read\",\n riskLevel: \"medium\",\n },\n ),\n readResource: resolveNativeToolMetadata(input?.tools?.readResource, {\n enabled: true,\n operationAccess: \"read\",\n riskLevel: \"low\",\n }),\n },\n rootDir,\n rootDirAbsolute,\n userHomeDir,\n userHomeDirAbsolute,\n requireRootUnderUserHome,\n allowOverwrite: input?.allowOverwrite ?? false,\n maxDownloadBytes: positiveInteger(\n input?.maxDownloadBytes,\n DEFAULT_MAX_DOWNLOAD_BYTES,\n \"maxDownloadBytes\",\n ),\n maxReadBytes: positiveInteger(\n input?.maxReadBytes,\n DEFAULT_MAX_READ_BYTES,\n \"maxReadBytes\",\n ),\n maxReadLines: positiveInteger(\n input?.maxReadLines,\n DEFAULT_MAX_READ_LINES,\n \"maxReadLines\",\n ),\n maxExtractedFiles: positiveInteger(\n input?.maxExtractedFiles,\n 0,\n \"maxExtractedFiles\",\n true,\n ),\n maxExtractedBytes: positiveInteger(\n input?.maxExtractedBytes,\n 0,\n \"maxExtractedBytes\",\n true,\n ),\n downloadTimeoutMs: positiveInteger(\n input?.downloadTimeoutMs,\n DEFAULT_DOWNLOAD_TIMEOUT_MS,\n \"downloadTimeoutMs\",\n ),\n allowedProtocols,\n allowedHosts,\n allowedUrlPrefixes,\n zuoraDownloadHosts,\n allowZuoraAuthenticatedDownload:\n input?.allowZuoraAuthenticatedDownload ?? false,\n allowS3PresignedDownload: input?.allowS3PresignedDownload ?? true,\n allowArchiveExtraction: input?.allowArchiveExtraction ?? false,\n };\n\n if (!enabled) {\n return config;\n }\n\n validateEnabledConfig(config);\n\n return config;\n};\n\nconst validateEnabledConfig = (config: ResolvedNativeFileToolsConfig): void => {\n if (config.bundleName !== \"query\") {\n throw nativeFileConfigError(\n `Unsupported native file bundle: ${config.bundleName}. Only \"query\" is supported.`,\n );\n }\n\n if (!config.rootDir) {\n throw nativeFileConfigError(\n \"nativeFileTools.rootDir is required when native file tools are enabled.\",\n );\n }\n\n if (\n config.allowedHosts.length === 0 &&\n config.allowedUrlPrefixes.length === 0\n ) {\n throw nativeFileConfigError(\n \"nativeFileTools.allowedHosts or nativeFileTools.allowedUrlPrefixes is required when native file tools are enabled.\",\n );\n }\n\n for (const protocol of config.allowedProtocols) {\n if (protocol !== \"http:\" && protocol !== \"https:\") {\n throw nativeFileConfigError(\n `Unsupported native file download protocol: ${protocol}. This MVP supports HTTP(S) only.`,\n );\n }\n }\n\n if (config.allowedProtocols.length === 0) {\n throw nativeFileConfigError(\n \"nativeFileTools.allowedProtocols must include at least one protocol.\",\n );\n }\n\n if (\n config.requireRootUnderUserHome &&\n !isPathInside(config.rootDirAbsolute, config.userHomeDirAbsolute)\n ) {\n throw nativeFileConfigError(\n \"nativeFileTools.rootDir must be under nativeFileTools.userHomeDir when requireRootUnderUserHome is true.\",\n );\n }\n\n if (config.tools.readDownloadedFile.operationAccess !== \"read\") {\n throw nativeFileConfigError(\n \"read_downloaded_file must be configured with operationAccess \\\"read\\\".\",\n );\n }\n\n if (config.tools.downloadFile.operationAccess !== \"read\") {\n throw nativeFileConfigError(\n \"download_file must be configured with operationAccess \\\"read\\\".\",\n );\n }\n\n if (config.tools.extractDownloadedArchive.operationAccess !== \"read\") {\n throw nativeFileConfigError(\n \"extract_downloaded_archive must be configured with operationAccess \\\"read\\\".\",\n );\n }\n\n for (const prefix of config.allowedUrlPrefixes) {\n validateConfiguredPrefix(prefix);\n }\n\n if (config.allowZuoraAuthenticatedDownload) {\n throw nativeFileConfigError(\n \"Authenticated Zuora file downloads are not supported by the native file tools MVP. Use public or presigned HTTPS links.\",\n );\n }\n\n if (config.allowArchiveExtraction) {\n throw nativeFileConfigError(\n \"Archive extraction is not supported by the native file tools MVP.\",\n );\n }\n};\n\nconst normalizeProtocols = (values: string[] | undefined): string[] => {\n const protocols = normalizeStringList(values ?? [\"https:\"]).map((value) => {\n const normalized = value.toLowerCase();\n return normalized.endsWith(\":\") ? normalized : `${normalized}:`;\n });\n\n return [...new Set(protocols)];\n};\n\nconst normalizeStringList = (values: string[] | undefined): string[] =>\n [...new Set((values ?? []).map((value) => value.trim()).filter(Boolean))];\n\nconst positiveInteger = (\n value: number | undefined,\n fallback: number,\n name: string,\n allowZero = false,\n): number => {\n const candidate = value ?? fallback;\n const minimum = allowZero ? 0 : 1;\n\n if (!Number.isInteger(candidate) || candidate < minimum) {\n throw nativeFileConfigError(\n `nativeFileTools.${name} must be ${allowZero ? \"zero or \" : \"\"}a positive integer.`,\n );\n }\n\n return candidate;\n};\n\nconst validateConfiguredPrefix = (prefix: string): void => {\n let parsed: URL;\n\n try {\n parsed = new URL(prefix);\n } catch {\n throw nativeFileConfigError(\n `Invalid native file allowedUrlPrefixes entry: ${prefix}`,\n );\n }\n\n if (parsed.username || parsed.password) {\n throw nativeFileConfigError(\n \"nativeFileTools.allowedUrlPrefixes entries must not include URL userinfo.\",\n );\n }\n\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw nativeFileConfigError(\n \"nativeFileTools.allowedUrlPrefixes entries must use HTTP(S).\",\n );\n }\n\n if (!parsed.hostname) {\n throw nativeFileConfigError(\n \"nativeFileTools.allowedUrlPrefixes entries must include a host.\",\n );\n }\n\n if (parsed.search || parsed.hash) {\n throw nativeFileConfigError(\n \"nativeFileTools.allowedUrlPrefixes entries must not include query strings or fragments.\",\n );\n }\n};\n\nconst isPathInside = (candidate: string, root: string): boolean => {\n const relative = path.relative(root, candidate);\n\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n};\n\nconst nativeFileConfigError = (message: string): ZuoraAgentToolkitError =>\n new ZuoraAgentToolkitError({\n code: \"NATIVE_FILE_CONFIG_INVALID\",\n message,\n category: \"configuration\",\n recoverable: true,\n });\n","import type {\n NativeToolMetadataConfig,\n ZuoraRiskLevel,\n ZuoraToolOperation,\n} from \"../../types.js\";\nimport { nonEmptyString } from \"../../utils/values.js\";\n\nexport type ResolvedNativeToolMetadataConfig = {\n enabled: boolean;\n operationAccess: ZuoraToolOperation;\n riskLevel: ZuoraRiskLevel;\n description?: string;\n};\n\nexport const resolveNativeToolMetadata = (\n input: NativeToolMetadataConfig | undefined,\n defaults: Omit<ResolvedNativeToolMetadataConfig, \"description\">,\n): ResolvedNativeToolMetadataConfig => {\n const description = nonEmptyString(input?.description);\n\n return {\n enabled: input?.enabled ?? defaults.enabled,\n operationAccess: input?.operationAccess ?? defaults.operationAccess,\n riskLevel: input?.riskLevel ?? defaults.riskLevel,\n ...(description ? { description } : {}),\n };\n};\n","import type { JsonSchema } from \"../../types.js\";\n\nexport const nativeObjectSchema = (\n properties: Record<string, JsonSchema>,\n required: string[] = [],\n): JsonSchema => ({\n type: \"object\",\n properties,\n required,\n additionalProperties: false,\n});\n","import type { ZuoraToolDefinition } from \"../../../types.js\";\nimport { nativeObjectSchema } from \"../metadata.js\";\nimport type { ResolvedNativeFileToolsConfig } from \"./config.js\";\n\nexport const createDownloadFileToolDefinition = (\n config: ResolvedNativeFileToolsConfig,\n): ZuoraToolDefinition => {\n const toolConfig = config.tools.downloadFile;\n\n return {\n name: \"download_file\",\n description:\n toolConfig.description ??\n [\n \"Download a remote file into the configured local artifact folder.\",\n \"Use this when the user asks to download, save, or fetch a file URL from prior tool output.\",\n \"For presigned URLs, pass the exact raw URL including the full query string; do not use redacted, shortened, decoded, or assistant-summarized links.\",\n \"If the URL appears in a field such as dataFile, resultUrl, downloadUrl, fileUrl, or href, use that field value exactly.\",\n \"If the result requires confirmation, ask the user before retrying with overwrite:true.\",\n ].join(\" \"),\n inputSchema: nativeObjectSchema(\n {\n url: {\n type: \"string\",\n description:\n \"Absolute HTTP(S) file URL. For presigned S3 or similar URLs, provide the exact original URL including every query parameter and signature token.\",\n },\n fileName: {\n type: \"string\",\n description:\n \"Optional relative artifact file name under the configured artifact root.\",\n },\n overwrite: {\n type: \"boolean\",\n description:\n \"Replace an existing local artifact at fileName. Set to true only after download_file returned requiresConfirmation:true and the user explicitly confirmed overwrite.\",\n },\n },\n [\"url\"],\n ),\n outputSchema: nativeObjectSchema(\n {\n status: {\n type: \"string\",\n enum: [\n \"downloaded\",\n \"existing\",\n \"requires_confirmation\",\n \"overwritten\",\n ],\n },\n message: { type: \"string\" },\n requiresConfirmation: { type: \"boolean\" },\n artifactId: { type: \"string\" },\n path: { type: \"string\" },\n bytes: { type: \"number\" },\n existingBytes: { type: \"number\" },\n remoteBytes: { type: \"number\" },\n sha256: { type: \"string\" },\n contentType: { type: \"string\" },\n source: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n [\"status\", \"path\", \"source\"],\n ),\n meta: {\n bundle: config.bundleName,\n access: toolConfig.operationAccess,\n riskLevel: toolConfig.riskLevel,\n requiredServicePermissions: [],\n limitations: [],\n sourceName: \"download_file\",\n },\n };\n};\n\nexport const createReadDownloadedFileToolDefinition = (\n config: ResolvedNativeFileToolsConfig,\n): ZuoraToolDefinition => {\n const toolConfig = config.tools.readDownloadedFile;\n\n return {\n name: \"read_downloaded_file\",\n description:\n toolConfig.description ??\n \"Read bounded text content from a registered downloaded file artifact.\",\n inputSchema: nativeObjectSchema({\n artifactId: {\n type: \"string\",\n description:\n \"Artifact id returned by download_query_result or another native download tool.\",\n },\n path: {\n type: \"string\",\n description:\n \"Relative artifact path from a prior download result. Used only when artifactId is omitted.\",\n },\n startLine: {\n type: \"number\",\n description: \"One-based line number to start reading from.\",\n },\n maxLines: {\n type: \"number\",\n description: \"Maximum number of text lines to return.\",\n },\n maxBytes: {\n type: \"number\",\n description: \"Maximum number of bytes to inspect, capped by SDK config.\",\n },\n }),\n outputSchema: nativeObjectSchema(\n {\n artifactId: { type: \"string\" },\n path: { type: \"string\" },\n content: { type: \"string\" },\n startLine: { type: \"number\" },\n endLine: { type: \"number\" },\n linesReturned: { type: \"number\" },\n bytesRead: { type: \"number\" },\n truncated: { type: \"boolean\" },\n },\n [\n \"artifactId\",\n \"path\",\n \"content\",\n \"startLine\",\n \"linesReturned\",\n \"bytesRead\",\n \"truncated\",\n ],\n ),\n meta: {\n bundle: config.bundleName,\n access: toolConfig.operationAccess,\n riskLevel: toolConfig.riskLevel,\n requiredServicePermissions: [],\n limitations: [\n \"Only files registered by this toolkit instance can be read.\",\n \"Reads are bounded by configured byte and line limits.\",\n \"Binary-looking files are rejected.\",\n ],\n sourceName: \"read_downloaded_file\",\n },\n };\n};\n\nexport const createReadResourceToolDefinition = (\n config: ResolvedNativeFileToolsConfig,\n description?: string,\n): ZuoraToolDefinition => {\n return {\n name: \"read_resource\",\n description:\n description ??\n \"Read content from an MCP resource URI returned by Zuora tools. Use this to access files referenced via resourceUri (e.g., zuora://files/{fileId}) in tool results.\",\n inputSchema: nativeObjectSchema({\n uri: {\n type: \"string\",\n description:\n \"The MCP resource URI to read, typically in the format zuora://files/{fileId} or zuora://objects/{type}/{id}.\",\n },\n }),\n outputSchema: nativeObjectSchema(\n {\n uri: { type: \"string\" },\n mimeType: { type: \"string\" },\n content: {\n type: \"string\",\n description: \"Text content if the resource is text-based (JSON, XML, text).\",\n },\n data: {\n type: \"string\",\n description: \"Base64-encoded binary data if the resource is binary (PDF, images, etc.).\",\n },\n },\n [\"uri\", \"mimeType\"],\n ),\n meta: {\n bundle: config.bundleName,\n access: \"read\",\n riskLevel: \"low\",\n requiredServicePermissions: [],\n limitations: [\n \"Resource URIs must be valid MCP resource URIs returned by Zuora tools.\",\n \"Binary content is returned as base64-encoded data.\",\n \"Resource availability depends on the underlying Zuora service.\",\n ],\n sourceName: \"read_resource\",\n },\n };\n};\n","import { createHash, randomBytes } from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { ZuoraAgentToolkitError } from \"../../../errors.js\";\nimport type { ZuoraRiskLevel, ZuoraToolExecutionResult } from \"../../../types.js\";\nimport type { ResolvedNativeFileToolsConfig } from \"./config.js\";\nimport { nativeFileError } from \"./errors.js\";\nimport {\n type FileArtifactRecord,\n FileArtifactManifest,\n} from \"./manifest.js\";\nimport {\n prepareOutputArtifactPath,\n resolveOutputRelativePath,\n} from \"./path-policy.js\";\nimport {\n type NativeFileSafeSource,\n type ValidatedNativeFileUrl,\n validateDownloadUrl,\n validateRedirectUrl,\n} from \"./url-policy.js\";\n\ntype DownloadedResponse = {\n response: Response;\n source: NativeFileSafeSource;\n};\n\nexport type NativeFileDownloadServiceConfig = {\n config: ResolvedNativeFileToolsConfig;\n manifest: FileArtifactManifest;\n};\n\nconst MAX_REDIRECTS = 5;\nconst MAX_GUIDED_DOWNLOAD_FAILURE_ATTEMPTS = 3;\n\nconst PRESIGNED_URL_403_GUIDANCE =\n \"For presigned S3 or similar URLs, provide the exact original URL including every query parameter and signature token. A 403 usually means the URL was stripped, edited, expired, or the signature no longer matches.\";\n\nexport class NativeFileDownloadService {\n /**\n * Per-instance failure counter for guided download retries.\n * Kept as an instance field (not a module-level singleton) so that\n * different toolkit instances and multi-tenant server contexts do not\n * share failure state with each other.\n */\n private readonly guidedDownloadFailureAttempts = new Map<string, number>();\n\n constructor(private readonly serviceConfig: NativeFileDownloadServiceConfig) {}\n\n async downloadFile(\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n const { config } = this.serviceConfig;\n const validatedUrl = validateDownloadUrl(input.url, config);\n const overwrite = readOverwriteInput(input.overwrite);\n const artifactId = createArtifactId();\n const relativePath = resolveOutputRelativePath(\n input.fileName ??\n `${artifactId}-${fallbackFileNameForExecution(validatedUrl.url)}`,\n validatedUrl.url,\n );\n const outputPath = await prepareOutputArtifactPath(config, relativePath, {\n allowExistingFile: true,\n });\n const existingFile = await inspectExistingOutputFile(outputPath);\n const controller = new AbortController();\n const timeout = setTimeout(() => {\n controller.abort();\n }, config.downloadTimeoutMs);\n\n try {\n const { response, source } = await fetchAllowedResponse(\n validatedUrl,\n config,\n controller.signal,\n this.guidedDownloadFailureAttempts,\n );\n const contentType = response.headers.get(\"content-type\") ?? undefined;\n const contentLengthBytes = readContentLengthBytes(response);\n\n if (\n Number.isFinite(contentLengthBytes) &&\n contentLengthBytes > config.maxDownloadBytes\n ) {\n throw createDownloadTooLargeError({\n contentLengthBytes,\n maxDownloadBytes: config.maxDownloadBytes,\n });\n }\n\n if (\n existingFile &&\n !overwrite &&\n Number.isFinite(contentLengthBytes) &&\n existingFile.bytes === contentLengthBytes\n ) {\n await cancelResponseBody(response);\n\n const artifact = await this.registerExistingArtifact({\n artifactId,\n outputPath,\n bytes: existingFile.bytes,\n contentType,\n source,\n });\n\n return {\n toolName: \"download_file\",\n riskLevel: config.tools.downloadFile.riskLevel,\n data: downloadOutput(artifact, {\n status: \"existing\",\n message:\n \"Local file already exists with the same size. The download was skipped and the existing file was registered as an artifact.\",\n }),\n };\n }\n\n if (\n existingFile &&\n !overwrite &&\n Number.isFinite(contentLengthBytes) &&\n existingFile.bytes !== contentLengthBytes\n ) {\n await cancelResponseBody(response);\n\n return {\n toolName: \"download_file\",\n riskLevel: config.tools.downloadFile.riskLevel,\n data: existingFileRequiresConfirmationOutput({\n outputPath,\n source,\n existingBytes: existingFile.bytes,\n remoteBytes: contentLengthBytes,\n }),\n };\n }\n\n // When Content-Length is absent (streaming or chunked responses), we\n // cannot compare sizes before reading. We consume the full body up to\n // maxDownloadBytes here and then decide whether to keep or discard it.\n // This means up to maxDownloadBytes of data is downloaded before the\n // \"requires confirmation\" check fires for the no-Content-Length path.\n // Size-first short-circuiting is not possible without Content-Length.\n const body = await readBoundedResponseBody(response, config);\n const sha256 = createHash(\"sha256\").update(body).digest(\"hex\");\n\n if (existingFile && !overwrite) {\n if (existingFile.bytes === body.byteLength) {\n const artifact = await this.registerExistingArtifact({\n artifactId,\n outputPath,\n bytes: existingFile.bytes,\n contentType,\n source,\n });\n\n return {\n toolName: \"download_file\",\n riskLevel: config.tools.downloadFile.riskLevel,\n data: downloadOutput(artifact, {\n status: \"existing\",\n message:\n \"Local file already exists with the same size. The download was skipped and the existing file was registered as an artifact.\",\n }),\n };\n }\n\n return {\n toolName: \"download_file\",\n riskLevel: config.tools.downloadFile.riskLevel,\n data: existingFileRequiresConfirmationOutput({\n outputPath,\n source,\n existingBytes: existingFile.bytes,\n remoteBytes: body.byteLength,\n }),\n };\n }\n\n try {\n await fs.writeFile(outputPath.absolutePath, body, {\n flag: overwrite ? \"w\" : \"wx\",\n });\n } catch (error) {\n if (isNodeErrorCode(error, \"EEXIST\")) {\n const racedExistingFile = await inspectExistingOutputFile(outputPath);\n\n if (racedExistingFile?.bytes === body.byteLength) {\n const artifact = await this.registerExistingArtifact({\n artifactId,\n outputPath,\n bytes: racedExistingFile.bytes,\n contentType,\n source,\n });\n\n return {\n toolName: \"download_file\",\n riskLevel: config.tools.downloadFile.riskLevel,\n data: downloadOutput(artifact, {\n status: \"existing\",\n message:\n \"Local file already exists with the same size. The download was skipped and the existing file was registered as an artifact.\",\n }),\n };\n }\n\n return {\n toolName: \"download_file\",\n riskLevel: config.tools.downloadFile.riskLevel,\n data: existingFileRequiresConfirmationOutput({\n outputPath,\n source,\n existingBytes: racedExistingFile?.bytes,\n remoteBytes: body.byteLength,\n }),\n };\n }\n\n throw nativeFilesystemError(\n \"FILE_DOWNLOAD_FAILED\",\n \"download_file could not write the local artifact.\",\n error,\n {\n relativePath: outputPath.relativePath,\n },\n );\n }\n\n const artifact = this.serviceConfig.manifest.register({\n artifactId,\n relativePath: outputPath.relativePath,\n bytes: body.byteLength,\n sha256,\n ...(contentType ? { contentType } : {}),\n source,\n createdAt: new Date().toISOString(),\n });\n\n return {\n toolName: \"download_file\",\n riskLevel: config.tools.downloadFile.riskLevel,\n data: downloadOutput(artifact, {\n status: existingFile && overwrite ? \"overwritten\" : \"downloaded\",\n message:\n existingFile && overwrite\n ? \"Existing local file was overwritten after overwrite:true.\"\n : \"Remote file was downloaded into the local artifact root.\",\n }),\n };\n } catch (error) {\n if (isAbortError(error)) {\n throw nativeFileError({\n code: \"FILE_DOWNLOAD_TIMEOUT\",\n message: `download_file exceeded ${config.downloadTimeoutMs}ms.`,\n retryable: true,\n recoverable: true,\n });\n }\n\n throw error;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n async persistBufferedDownload({\n input,\n toolName,\n riskLevel,\n body,\n contentType,\n source,\n defaultFileName,\n }: {\n input: Record<string, unknown>;\n toolName: string;\n riskLevel: ZuoraRiskLevel;\n body: Buffer;\n contentType?: string;\n source: NativeFileSafeSource;\n defaultFileName: string;\n }): Promise<ZuoraToolExecutionResult> {\n const { config } = this.serviceConfig;\n\n if (body.byteLength > config.maxDownloadBytes) {\n throw createDownloadTooLargeError({\n contentLengthBytes: body.byteLength,\n maxDownloadBytes: config.maxDownloadBytes,\n });\n }\n\n const overwrite = readOverwriteInput(input.overwrite);\n const artifactId = createArtifactId();\n const relativePath = resolveOutputRelativePath(\n input.fileName ?? defaultFileName,\n new URL(`https://zuora.local/${encodeURIComponent(defaultFileName)}`),\n );\n const outputPath = await prepareOutputArtifactPath(config, relativePath, {\n allowExistingFile: true,\n });\n const existingFile = await inspectExistingOutputFile(outputPath);\n const remoteBytes = body.byteLength;\n\n if (\n existingFile &&\n !overwrite &&\n existingFile.bytes === remoteBytes\n ) {\n const artifact = await this.registerExistingArtifact({\n artifactId,\n outputPath,\n bytes: existingFile.bytes,\n contentType,\n source,\n });\n\n return {\n toolName,\n riskLevel,\n data: downloadOutput(artifact, {\n status: \"existing\",\n message:\n \"Local file already exists with the same size. The download was skipped and the existing file was registered as an artifact.\",\n }),\n };\n }\n\n if (existingFile && !overwrite && existingFile.bytes !== remoteBytes) {\n return {\n toolName,\n riskLevel,\n data: existingFileRequiresConfirmationOutput({\n outputPath,\n source,\n existingBytes: existingFile.bytes,\n remoteBytes,\n }),\n };\n }\n\n const sha256 = createHash(\"sha256\").update(body).digest(\"hex\");\n\n try {\n await fs.writeFile(outputPath.absolutePath, body, {\n flag: overwrite ? \"w\" : \"wx\",\n });\n } catch (error) {\n if (isNodeErrorCode(error, \"EEXIST\")) {\n const racedExistingFile = await inspectExistingOutputFile(outputPath);\n\n if (racedExistingFile?.bytes === body.byteLength) {\n const artifact = await this.registerExistingArtifact({\n artifactId,\n outputPath,\n bytes: racedExistingFile.bytes,\n contentType,\n source,\n });\n\n return {\n toolName,\n riskLevel,\n data: downloadOutput(artifact, {\n status: \"existing\",\n message:\n \"Local file already exists with the same size. The download was skipped and the existing file was registered as an artifact.\",\n }),\n };\n }\n\n return {\n toolName,\n riskLevel,\n data: existingFileRequiresConfirmationOutput({\n outputPath,\n source,\n existingBytes: racedExistingFile?.bytes,\n remoteBytes: body.byteLength,\n }),\n };\n }\n\n throw nativeFilesystemError(\n \"FILE_DOWNLOAD_FAILED\",\n `${toolName} could not write the local artifact.`,\n error,\n {\n relativePath: outputPath.relativePath,\n },\n );\n }\n\n const artifact = this.serviceConfig.manifest.register({\n artifactId,\n relativePath: outputPath.relativePath,\n bytes: body.byteLength,\n sha256,\n ...(contentType ? { contentType } : {}),\n source,\n createdAt: new Date().toISOString(),\n });\n\n return {\n toolName,\n riskLevel,\n data: downloadOutput(artifact, {\n status: existingFile && overwrite ? \"overwritten\" : \"downloaded\",\n message:\n existingFile && overwrite\n ? \"Existing local file was overwritten after overwrite:true.\"\n : \"Remote file was downloaded into the local artifact root.\",\n }),\n };\n }\n\n private async registerExistingArtifact({\n artifactId,\n outputPath,\n bytes,\n contentType,\n source,\n }: {\n artifactId: string;\n outputPath: { relativePath: string; absolutePath: string };\n bytes: number;\n contentType: string | undefined;\n source: NativeFileSafeSource;\n }): Promise<FileArtifactRecord> {\n const sha256 = await sha256File(outputPath.absolutePath);\n\n return this.serviceConfig.manifest.register({\n artifactId,\n relativePath: outputPath.relativePath,\n bytes,\n sha256,\n ...(contentType ? { contentType } : {}),\n source,\n createdAt: new Date().toISOString(),\n });\n }\n}\n\nconst fetchAllowedResponse = async (\n initialUrl: ValidatedNativeFileUrl,\n config: ResolvedNativeFileToolsConfig,\n signal: AbortSignal,\n failureAttempts: Map<string, number>,\n): Promise<DownloadedResponse> => {\n let currentUrl = initialUrl;\n\n for (let redirectCount = 0; redirectCount <= MAX_REDIRECTS; redirectCount += 1) {\n let response: Response;\n\n try {\n response = await fetch(currentUrl.url, {\n redirect: \"manual\",\n signal,\n });\n } catch (error) {\n if (isAbortError(error)) {\n throw error;\n }\n\n throw nativeFileError({\n code: \"FILE_DOWNLOAD_FAILED\",\n message: \"download_file could not open the remote URL.\",\n retryable: true,\n recoverable: true,\n details: {\n source: currentUrl.source,\n cause: error instanceof Error ? error.message : String(error),\n },\n });\n }\n\n if (isRedirectResponse(response.status)) {\n const location = response.headers.get(\"location\");\n\n if (!location) {\n throw nativeFileError({\n code: \"FILE_DOWNLOAD_FAILED\",\n message: \"Download redirect response did not include a location.\",\n retryable: true,\n recoverable: true,\n details: {\n source: currentUrl.source,\n status: response.status,\n },\n });\n }\n\n currentUrl = validateRedirectUrl(location, currentUrl.url, config);\n continue;\n }\n\n if (!response.ok) {\n const failure = recordGuidedDownloadFailure(currentUrl.source, response.status, failureAttempts);\n const guidance = downloadFailureGuidance(response.status, failure.attempt);\n\n throw nativeFileError({\n code: \"FILE_DOWNLOAD_FAILED\",\n message: guidance\n ? `Download failed with HTTP status ${response.status}. ${guidance}`\n : `Download failed with HTTP status ${response.status}.`,\n retryable: response.status >= 500,\n recoverable: guidance ? failure.shouldRetry : true,\n details: {\n source: currentUrl.source,\n status: response.status,\n downloadAttempt: failure.attempt,\n maxSuggestedAttempts: MAX_GUIDED_DOWNLOAD_FAILURE_ATTEMPTS,\n ...(guidance ? { guidance } : {}),\n },\n });\n }\n\n clearGuidedDownloadFailure(currentUrl.source, failureAttempts);\n\n return {\n response,\n source: currentUrl.source,\n };\n }\n\n throw nativeFileError({\n code: \"FILE_DOWNLOAD_FAILED\",\n message: `Download exceeded ${MAX_REDIRECTS} redirects.`,\n recoverable: true,\n details: {\n source: initialUrl.source,\n },\n });\n};\n\nconst recordGuidedDownloadFailure = (\n source: NativeFileSafeSource,\n status: number,\n failureAttempts: Map<string, number>,\n): {\n attempt: number;\n shouldRetry: boolean;\n} => {\n const key = guidedDownloadFailureKey(source, status);\n const attempt = (failureAttempts.get(key) ?? 0) + 1;\n\n failureAttempts.set(key, attempt);\n\n return {\n attempt,\n shouldRetry: attempt < MAX_GUIDED_DOWNLOAD_FAILURE_ATTEMPTS,\n };\n};\n\nconst clearGuidedDownloadFailure = (\n source: NativeFileSafeSource,\n failureAttempts: Map<string, number>,\n): void => {\n failureAttempts.delete(guidedDownloadFailureKey(source, 403));\n};\n\nconst guidedDownloadFailureKey = (\n source: NativeFileSafeSource,\n status: number,\n): string => `${status}:${source.redactedUrl}`;\n\nconst downloadFailureGuidance = (\n status: number,\n attempt: number,\n): string | undefined => {\n if (status !== 403) {\n return undefined;\n }\n\n if (attempt >= MAX_GUIDED_DOWNLOAD_FAILURE_ATTEMPTS) {\n return `${PRESIGNED_URL_403_GUIDANCE} This is the third failed attempt for this download, so stop retrying this URL and ask the user for a fresh exact dataFile URL or to rerun the query.`;\n }\n\n return `${PRESIGNED_URL_403_GUIDANCE} Retry only with the exact dataFile/download URL from the tool result. Stop retrying after ${MAX_GUIDED_DOWNLOAD_FAILURE_ATTEMPTS} failed attempts.`;\n};\n\nconst readBoundedResponseBody = async (\n response: Response,\n config: ResolvedNativeFileToolsConfig,\n): Promise<Buffer> => {\n const contentLengthBytes = readContentLengthBytes(response);\n\n if (\n Number.isFinite(contentLengthBytes) &&\n contentLengthBytes > config.maxDownloadBytes\n ) {\n throw createDownloadTooLargeError({\n contentLengthBytes,\n maxDownloadBytes: config.maxDownloadBytes,\n });\n }\n\n if (!response.body) {\n return Buffer.alloc(0);\n }\n\n const reader = response.body.getReader();\n const chunks: Buffer[] = [];\n let totalBytes = 0;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n totalBytes += value.byteLength;\n\n if (totalBytes > config.maxDownloadBytes) {\n throw nativeFileError({\n code: \"FILE_DOWNLOAD_TOO_LARGE\",\n message: `Remote file exceeded the configured ${config.maxDownloadBytes} byte download limit.`,\n recoverable: true,\n details: {\n maxDownloadBytes: config.maxDownloadBytes,\n },\n });\n }\n\n chunks.push(Buffer.from(value));\n }\n\n return Buffer.concat(chunks, totalBytes);\n};\n\nconst readContentLengthBytes = (response: Response): number => {\n const contentLength = response.headers.get(\"content-length\");\n\n if (!contentLength) {\n return Number.NaN;\n }\n\n const parsed = Number.parseInt(contentLength, 10);\n\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : Number.NaN;\n};\n\nconst createDownloadTooLargeError = ({\n contentLengthBytes,\n maxDownloadBytes,\n}: {\n contentLengthBytes: number;\n maxDownloadBytes: number;\n}): ZuoraAgentToolkitError =>\n nativeFileError({\n code: \"FILE_DOWNLOAD_TOO_LARGE\",\n message: `Remote file is larger than the configured ${maxDownloadBytes} byte download limit.`,\n recoverable: true,\n details: {\n contentLengthBytes,\n maxDownloadBytes,\n },\n });\n\nconst cancelResponseBody = async (response: Response): Promise<void> => {\n try {\n await response.body?.cancel();\n } catch {\n // Best-effort cleanup after making a decision from response headers.\n }\n};\n\nconst readOverwriteInput = (value: unknown): boolean => {\n if (value === undefined) {\n return false;\n }\n\n if (typeof value !== \"boolean\") {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"download_file overwrite must be a boolean.\",\n recoverable: true,\n });\n }\n\n return value;\n};\n\nconst inspectExistingOutputFile = async (outputPath: {\n absolutePath: string;\n relativePath: string;\n}): Promise<{ bytes: number } | undefined> => {\n try {\n const stat = await fs.stat(outputPath.absolutePath);\n\n if (!stat.isFile()) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"download_file output path already exists and is not a file.\",\n recoverable: true,\n details: {\n relativePath: outputPath.relativePath,\n },\n });\n }\n\n return {\n bytes: stat.size,\n };\n } catch (error) {\n if (isNodeErrorCode(error, \"ENOENT\")) {\n return undefined;\n }\n\n if (error instanceof ZuoraAgentToolkitError) {\n throw error;\n }\n\n throw nativeFilesystemError(\n \"FILE_PATH_NOT_ALLOWED\",\n \"Could not inspect the native file artifact output path.\",\n error,\n {\n relativePath: outputPath.relativePath,\n },\n );\n }\n};\n\nconst sha256File = async (absolutePath: string): Promise<string> => {\n const body = await fs.readFile(absolutePath);\n\n return createHash(\"sha256\").update(body).digest(\"hex\");\n};\n\nconst downloadOutput = (\n artifact: FileArtifactRecord,\n metadata: {\n status: \"downloaded\" | \"existing\" | \"overwritten\";\n message: string;\n },\n): Record<string, unknown> => ({\n status: metadata.status,\n message: metadata.message,\n requiresConfirmation: false,\n artifactId: artifact.artifactId,\n path: artifact.relativePath,\n bytes: artifact.bytes,\n sha256: artifact.sha256,\n ...(artifact.contentType ? { contentType: artifact.contentType } : {}),\n source: artifact.source,\n});\n\nconst existingFileRequiresConfirmationOutput = ({\n outputPath,\n source,\n existingBytes,\n remoteBytes,\n}: {\n outputPath: { relativePath: string };\n source: NativeFileSafeSource;\n existingBytes?: number | undefined;\n remoteBytes: number;\n}): Record<string, unknown> => ({\n status: \"requires_confirmation\",\n message:\n \"Local file already exists with a different size. Ask the user whether to overwrite it, then retry download_file with the same url, same fileName, and overwrite:true only if the user confirms.\",\n requiresConfirmation: true,\n path: outputPath.relativePath,\n ...(typeof existingBytes === \"number\" ? { existingBytes } : {}),\n remoteBytes,\n source,\n});\n\nconst createArtifactId = (): string =>\n `artifact_${Date.now().toString(36)}_${randomBytes(6).toString(\"hex\")}`;\n\nconst fallbackFileNameForExecution = (url: URL): string => {\n const rawBaseName = path.posix.basename(url.pathname) || \"downloaded-file\";\n\n try {\n return decodeURIComponent(rawBaseName);\n } catch {\n return rawBaseName;\n }\n};\n\nconst isRedirectResponse = (status: number): boolean =>\n status >= 300 && status < 400;\n\nconst isAbortError = (error: unknown): boolean =>\n error instanceof Error && error.name === \"AbortError\";\n\nconst isNodeErrorCode = (error: unknown, code: string): boolean =>\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === code;\n\nconst nativeFilesystemError = (\n code: \"FILE_DOWNLOAD_FAILED\" | \"FILE_PATH_NOT_ALLOWED\",\n message: string,\n error: unknown,\n details: Record<string, unknown>,\n): ZuoraAgentToolkitError =>\n nativeFileError({\n code,\n message,\n recoverable: true,\n details: {\n ...details,\n cause: error instanceof Error ? error.message : String(error),\n },\n });\n","import { ZuoraAgentToolkitError } from \"../../../errors.js\";\n\nexport type NativeFileErrorCode =\n | \"NATIVE_FILE_TOOLS_DISABLED\"\n | \"NATIVE_FILE_CONFIG_INVALID\"\n | \"FILE_URL_NOT_ALLOWED\"\n | \"FILE_URL_INVALID\"\n | \"FILE_DOWNLOAD_TOO_LARGE\"\n | \"FILE_DOWNLOAD_TIMEOUT\"\n | \"FILE_DOWNLOAD_FAILED\"\n | \"FILE_PATH_NOT_ALLOWED\"\n | \"FILE_ARTIFACT_NOT_FOUND\"\n | \"FILE_READ_TOO_LARGE\"\n | \"FILE_ARCHIVE_NOT_ALLOWED\"\n | \"FILE_ARCHIVE_UNSAFE_ENTRY\"\n | \"FILE_ARCHIVE_TOO_LARGE\";\n\nexport const nativeFileError = (params: {\n code: NativeFileErrorCode;\n message: string;\n retryable?: boolean;\n recoverable?: boolean;\n details?: unknown;\n}): ZuoraAgentToolkitError =>\n new ZuoraAgentToolkitError({\n code: params.code,\n message: params.message,\n category: \"native_file_tools\",\n ...(params.retryable !== undefined ? { retryable: params.retryable } : {}),\n recoverable: params.recoverable ?? true,\n ...(params.details !== undefined ? { details: params.details } : {}),\n });\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { ZuoraAgentToolkitError } from \"../../../errors.js\";\nimport type { ResolvedNativeFileToolsConfig } from \"./config.js\";\nimport { nativeFileError } from \"./errors.js\";\nimport { normalizeManifestPath } from \"./manifest.js\";\n\nexport type ResolvedArtifactPath = {\n rootRealPath: string;\n absolutePath: string;\n relativePath: string;\n};\n\nexport type PrepareOutputArtifactPathOptions = {\n allowExistingFile?: boolean;\n};\n\nexport const resolveOutputRelativePath = (\n inputFileName: unknown,\n sourceUrl: URL,\n): string => {\n const requested =\n typeof inputFileName === \"string\" && inputFileName.trim()\n ? inputFileName.trim()\n : fallbackFileNameFromUrl(sourceUrl);\n\n return normalizeSafeRelativePath(requested);\n};\n\nexport const resolveInputRelativePath = (inputPath: unknown): string => {\n if (typeof inputPath !== \"string\" || !inputPath.trim()) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"A non-empty artifact path is required.\",\n });\n }\n\n return normalizeSafeRelativePath(inputPath.trim());\n};\n\nexport const prepareOutputArtifactPath = async (\n config: ResolvedNativeFileToolsConfig,\n relativePath: string,\n options: PrepareOutputArtifactPathOptions = {},\n): Promise<ResolvedArtifactPath> => {\n const rootRealPath = await prepareRoot(config);\n const resolved = resolveUnderRoot(rootRealPath, relativePath);\n\n await assertNoSymlinkComponents(rootRealPath, relativePath, {\n includeLeaf: true,\n missingLeafOk: true,\n });\n\n try {\n await fs.mkdir(path.dirname(resolved.absolutePath), { recursive: true });\n } catch (error) {\n throw nativePathFilesystemError(\n \"Could not create the native file artifact output directory.\",\n error,\n {\n relativePath,\n },\n );\n }\n\n await assertNoSymlinkComponents(rootRealPath, relativePath, {\n includeLeaf: true,\n missingLeafOk: true,\n });\n\n if (!config.allowOverwrite && !options.allowExistingFile) {\n try {\n await fs.lstat(resolved.absolutePath);\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message:\n \"download_file would overwrite an existing artifact and allowOverwrite is false.\",\n details: {\n relativePath,\n },\n });\n } catch (error) {\n if (isNodeErrorCode(error, \"ENOENT\")) {\n return resolved;\n }\n\n if (error instanceof ZuoraAgentToolkitError) {\n throw error;\n }\n\n throw nativePathFilesystemError(\n \"Could not inspect the native file artifact output path.\",\n error,\n {\n relativePath,\n },\n );\n }\n }\n\n return resolved;\n};\n\nexport const resolveRegisteredArtifactPath = async (\n config: ResolvedNativeFileToolsConfig,\n relativePath: string,\n): Promise<ResolvedArtifactPath> => {\n const rootRealPath = await prepareRoot(config);\n const resolved = resolveUnderRoot(rootRealPath, relativePath);\n\n await assertNoSymlinkComponents(rootRealPath, relativePath, {\n includeLeaf: true,\n missingLeafOk: false,\n });\n\n let realPath: string;\n\n try {\n realPath = await fs.realpath(resolved.absolutePath);\n } catch (error) {\n if (isNodeErrorCode(error, \"ENOENT\")) {\n throw error;\n }\n\n throw nativePathFilesystemError(\n \"Could not resolve the registered native file artifact path.\",\n error,\n {\n relativePath,\n },\n );\n }\n\n if (!isPathInside(realPath, rootRealPath)) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"Artifact path resolves outside the configured file artifact root.\",\n details: {\n relativePath,\n },\n });\n }\n\n return {\n ...resolved,\n absolutePath: realPath,\n };\n};\n\nexport const assertRootPolicy = async (\n config: ResolvedNativeFileToolsConfig,\n): Promise<string> => prepareRoot(config);\n\nconst prepareRoot = async (\n config: ResolvedNativeFileToolsConfig,\n): Promise<string> => {\n const userHomeRealPath = await resolveRealPathIfPossible(\n config.userHomeDirAbsolute,\n );\n const userHomeAbsolutePath = path.resolve(config.userHomeDirAbsolute);\n\n if (\n config.requireRootUnderUserHome &&\n !isPathInside(config.rootDirAbsolute, userHomeAbsolutePath)\n ) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message:\n \"Configured native file artifact root resolves outside the configured user home directory.\",\n details: {\n rootDir: config.rootDirAbsolute,\n userHomeDir: config.userHomeDirAbsolute,\n },\n });\n }\n\n if (config.requireRootUnderUserHome) {\n await assertNoExistingSymlinkComponents(\n userHomeAbsolutePath,\n config.rootDirAbsolute,\n );\n }\n\n try {\n await fs.mkdir(config.rootDirAbsolute, { recursive: true });\n } catch (error) {\n throw nativePathFilesystemError(\n \"Could not create the native file artifact root directory.\",\n error,\n {\n rootDir: config.rootDirAbsolute,\n },\n );\n }\n\n let rootRealPath: string;\n\n try {\n rootRealPath = await fs.realpath(config.rootDirAbsolute);\n } catch (error) {\n throw nativePathFilesystemError(\n \"Could not resolve the native file artifact root directory.\",\n error,\n {\n rootDir: config.rootDirAbsolute,\n },\n );\n }\n\n if (\n config.requireRootUnderUserHome &&\n !isPathInside(rootRealPath, userHomeRealPath)\n ) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message:\n \"Configured native file artifact root resolves outside the configured user home directory.\",\n details: {\n rootDir: config.rootDirAbsolute,\n userHomeDir: config.userHomeDirAbsolute,\n },\n });\n }\n\n return rootRealPath;\n};\n\nconst resolveRealPathIfPossible = async (targetPath: string): Promise<string> => {\n try {\n return await fs.realpath(targetPath);\n } catch {\n return path.resolve(targetPath);\n }\n};\n\nconst resolveUnderRoot = (\n rootRealPath: string,\n relativePath: string,\n): ResolvedArtifactPath => {\n const normalizedRelativePath = normalizeSafeRelativePath(relativePath);\n const absolutePath = path.resolve(rootRealPath, normalizedRelativePath);\n\n if (!isPathInside(absolutePath, rootRealPath)) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"Artifact path must stay under the configured file artifact root.\",\n details: {\n relativePath: normalizedRelativePath,\n },\n });\n }\n\n return {\n rootRealPath,\n absolutePath,\n relativePath: normalizedRelativePath,\n };\n};\n\nconst assertNoSymlinkComponents = async (\n rootRealPath: string,\n relativePath: string,\n options: {\n includeLeaf: boolean;\n missingLeafOk: boolean;\n },\n): Promise<void> => {\n const components = normalizeManifestPath(relativePath).split(\"/\").filter(Boolean);\n const componentsToCheck = options.includeLeaf\n ? components\n : components.slice(0, -1);\n let current = rootRealPath;\n\n for (let index = 0; index < componentsToCheck.length; index += 1) {\n current = path.join(current, componentsToCheck[index]!);\n\n try {\n const stat = await fs.lstat(current);\n\n if (stat.isSymbolicLink()) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"File artifact paths must not traverse symlinks.\",\n details: {\n relativePath,\n },\n });\n }\n } catch (error) {\n if (\n isNodeErrorCode(error, \"ENOENT\") &&\n (options.missingLeafOk || index < componentsToCheck.length - 1)\n ) {\n // A missing component means the path (or a sub-path of it) does not yet\n // exist on disk, so there is nothing to resolve as a symlink right now.\n // Returning early here is safe because:\n // 1. A non-existent directory cannot be a symlink, and future components\n // under it cannot exist either.\n // 2. `prepareOutputArtifactPath` calls this function a second time after\n // `fs.mkdir()` has created any necessary parent directories, catching\n // any symlink introduced between the two checks (TOCTOU mitigation).\n return;\n }\n\n if (error instanceof ZuoraAgentToolkitError) {\n throw error;\n }\n\n throw nativePathFilesystemError(\n \"Could not inspect native file artifact path components.\",\n error,\n {\n relativePath,\n },\n );\n }\n }\n};\n\nconst assertNoExistingSymlinkComponents = async (\n rootRealPath: string,\n candidatePath: string,\n): Promise<void> => {\n const relative = path.relative(rootRealPath, candidatePath);\n\n if (relative === \"\") {\n return;\n }\n\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"Configured native file artifact root must stay under user home.\",\n details: {\n rootDir: candidatePath,\n userHomeDir: rootRealPath,\n },\n });\n }\n\n await assertNoSymlinkComponents(rootRealPath, relative, {\n includeLeaf: true,\n missingLeafOk: true,\n });\n};\n\nconst normalizeSafeRelativePath = (rawPath: string): string => {\n if (rawPath.includes(\"\\0\")) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"Artifact paths must not contain null bytes.\",\n });\n }\n\n const slashPath = rawPath.replace(/\\\\/g, \"/\");\n\n if (path.isAbsolute(slashPath) || slashPath.startsWith(\"/\")) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"Artifact paths must be relative.\",\n details: {\n relativePath: rawPath,\n },\n });\n }\n\n const normalized = normalizeManifestPath(path.posix.normalize(slashPath));\n\n if (!normalized || normalized === \".\") {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"Artifact paths must not be empty.\",\n });\n }\n\n if (\n normalized === \"..\" ||\n normalized.startsWith(\"../\") ||\n normalized.split(\"/\").includes(\"..\")\n ) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"Artifact paths must not traverse outside the artifact root.\",\n details: {\n relativePath: rawPath,\n },\n });\n }\n\n return normalized;\n};\n\nconst fallbackFileNameFromUrl = (url: URL): string => {\n const rawBaseName = path.posix.basename(url.pathname) || \"downloaded-file\";\n const decodedBaseName = safeDecodeURIComponent(rawBaseName);\n const sanitized = decodedBaseName\n .replace(/[^A-Za-z0-9._-]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\n return sanitized || \"downloaded-file\";\n};\n\nconst safeDecodeURIComponent = (value: string): string => {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n};\n\nconst isPathInside = (candidate: string, root: string): boolean => {\n const relative = path.relative(root, candidate);\n\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n};\n\nconst isNodeErrorCode = (error: unknown, code: string): boolean =>\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === code;\n\nconst nativePathFilesystemError = (\n message: string,\n error: unknown,\n details: Record<string, unknown>,\n): ZuoraAgentToolkitError =>\n nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message,\n recoverable: true,\n details: {\n ...details,\n cause: error instanceof Error ? error.message : String(error),\n },\n });\n","import type { NativeFileSafeSource } from \"./url-policy.js\";\n\nexport type FileArtifactRecord = {\n artifactId: string;\n relativePath: string;\n bytes: number;\n sha256: string;\n contentType?: string;\n source: NativeFileSafeSource;\n createdAt: string;\n};\n\nexport class FileArtifactManifest {\n private readonly byId = new Map<string, FileArtifactRecord>();\n\n private readonly byPath = new Map<string, FileArtifactRecord>();\n\n register(record: FileArtifactRecord): FileArtifactRecord {\n this.byId.set(record.artifactId, record);\n this.byPath.set(normalizeManifestPath(record.relativePath), record);\n\n return record;\n }\n\n getById(artifactId: string): FileArtifactRecord | undefined {\n return this.byId.get(artifactId);\n }\n\n getByRelativePath(relativePath: string): FileArtifactRecord | undefined {\n return this.byPath.get(normalizeManifestPath(relativePath));\n }\n}\n\nexport const normalizeManifestPath = (relativePath: string): string =>\n relativePath.replace(/\\\\/g, \"/\").replace(/^\\/+/, \"\");\n","import type { ResolvedNativeFileToolsConfig } from \"./config.js\";\nimport { nativeFileError } from \"./errors.js\";\n\nexport type NativeFileSafeSource = {\n protocol: string;\n host: string;\n path: string;\n redactedUrl: string;\n kind: \"s3-presigned\" | \"zuora-public\" | \"http\";\n};\n\nexport type ValidatedNativeFileUrl = {\n url: URL;\n source: NativeFileSafeSource;\n};\n\nexport const validateDownloadUrl = (\n rawUrl: unknown,\n config: ResolvedNativeFileToolsConfig,\n): ValidatedNativeFileUrl => {\n if (typeof rawUrl !== \"string\" || !rawUrl.trim()) {\n throw nativeFileError({\n code: \"FILE_URL_INVALID\",\n message: \"download_file requires a non-empty absolute URL.\",\n details: {\n expected: \"absolute HTTP(S) URL\",\n },\n });\n }\n\n let url: URL;\n\n try {\n url = new URL(rawUrl.trim());\n } catch {\n throw nativeFileError({\n code: \"FILE_URL_INVALID\",\n message: \"download_file received an invalid URL.\",\n details: {\n expected: \"absolute HTTP(S) URL\",\n },\n });\n }\n\n return validateParsedDownloadUrl(url, config);\n};\n\nexport const validateRedirectUrl = (\n rawUrl: string,\n baseUrl: URL,\n config: ResolvedNativeFileToolsConfig,\n): ValidatedNativeFileUrl => {\n let url: URL;\n\n try {\n url = new URL(rawUrl, baseUrl);\n } catch {\n throw nativeFileError({\n code: \"FILE_URL_INVALID\",\n message: \"Download redirect returned an invalid URL.\",\n details: {\n source: safeSourceFromUrl(baseUrl, config),\n },\n });\n }\n\n return validateParsedDownloadUrl(url, config);\n};\n\nexport const redactUrl = (url: URL): string => {\n const redacted = new URL(url.toString());\n redacted.username = \"\";\n redacted.password = \"\";\n redacted.search = \"\";\n redacted.hash = \"\";\n\n return redacted.toString();\n};\n\nconst validateParsedDownloadUrl = (\n url: URL,\n config: ResolvedNativeFileToolsConfig,\n): ValidatedNativeFileUrl => {\n if (!url.protocol || !url.hostname) {\n throw nativeFileError({\n code: \"FILE_URL_INVALID\",\n message: \"download_file requires an absolute URL with a host.\",\n });\n }\n\n if (url.username || url.password) {\n throw nativeFileError({\n code: \"FILE_URL_INVALID\",\n message: \"download_file rejects URLs with embedded credentials.\",\n details: {\n source: safeSourceFromUrl(url, config),\n },\n });\n }\n\n if (!config.allowedProtocols.includes(url.protocol)) {\n throw nativeFileError({\n code: \"FILE_URL_NOT_ALLOWED\",\n message: `URL protocol ${url.protocol} is not allowed for native file downloads.`,\n details: {\n source: safeSourceFromUrl(url, config),\n allowedProtocols: config.allowedProtocols,\n },\n });\n }\n\n // `allowedUrlPrefixes` is an independent allowlist, not a supplement to\n // `allowedHosts`. A URL is accepted if EITHER its host is in `allowedHosts`\n // (including S3 virtual-hosted matching) OR its full URL prefix matches an\n // entry in `allowedUrlPrefixes`. The two lists are evaluated with OR semantics\n // so that callers can configure one, the other, or both.\n if (!hostAllowed(url, config) && !prefixMatches(url, config.allowedUrlPrefixes)) {\n throw nativeFileError({\n code: \"FILE_URL_NOT_ALLOWED\",\n message: \"URL host or prefix is not allowed for native file downloads.\",\n details: {\n source: safeSourceFromUrl(url, config),\n },\n });\n }\n\n return {\n url,\n source: safeSourceFromUrl(url, config),\n };\n};\n\nconst safeSourceFromUrl = (\n url: URL,\n config: ResolvedNativeFileToolsConfig,\n): NativeFileSafeSource => ({\n protocol: url.protocol,\n host: url.host.toLowerCase(),\n path: url.pathname,\n redactedUrl: redactUrl(url),\n kind: classifySource(url, config),\n});\n\nconst classifySource = (\n url: URL,\n config: ResolvedNativeFileToolsConfig,\n): NativeFileSafeSource[\"kind\"] => {\n const host = url.hostname.toLowerCase();\n\n if (config.zuoraDownloadHosts.includes(host)) {\n return \"zuora-public\";\n }\n\n if (\n config.allowS3PresignedDownload &&\n (host.includes(\".s3.\") ||\n host.endsWith(\".s3.amazonaws.com\") ||\n host.endsWith(\".amazonaws.com\")) &&\n hasPresignedUrlQuery(url)\n ) {\n return \"s3-presigned\";\n }\n\n return \"http\";\n};\n\nconst hasPresignedUrlQuery = (url: URL): boolean => {\n for (const key of url.searchParams.keys()) {\n if (/^(x-amz-|x-goog-|signature|sig|expires|token)/i.test(key)) {\n return true;\n }\n }\n\n return false;\n};\n\nconst hostAllowed = (\n url: URL,\n config: ResolvedNativeFileToolsConfig,\n): boolean =>\n hostMatches(url.host, config.allowedHosts) ||\n hostMatches(url.hostname, config.allowedHosts) ||\n s3VirtualHostedEndpointMatches(url, config);\n\nconst hostMatches = (host: string, allowedHosts: string[]): boolean => {\n const normalizedHost = host.toLowerCase();\n\n return allowedHosts.some((allowedHost) => {\n const normalizedAllowedHost = allowedHost.toLowerCase();\n\n if (normalizedAllowedHost.startsWith(\"*.\")) {\n const suffix = normalizedAllowedHost.slice(1);\n\n return (\n normalizedHost.length > suffix.length && normalizedHost.endsWith(suffix)\n );\n }\n\n return normalizedHost === normalizedAllowedHost;\n });\n};\n\nconst s3VirtualHostedEndpointMatches = (\n url: URL,\n config: ResolvedNativeFileToolsConfig,\n): boolean => {\n if (!config.allowS3PresignedDownload || !hasPresignedUrlQuery(url)) {\n return false;\n }\n\n const host = url.hostname.toLowerCase();\n\n return config.allowedHosts.some((allowedHost) => {\n const normalizedAllowedHost = allowedHost.toLowerCase();\n\n return (\n isS3RegionalEndpointHost(normalizedAllowedHost) &&\n host.length > normalizedAllowedHost.length + 1 &&\n host.endsWith(`.${normalizedAllowedHost}`)\n );\n });\n};\n\nconst isS3RegionalEndpointHost = (host: string): boolean =>\n host === \"s3.amazonaws.com\" || /^s3[.-][a-z0-9-]+\\.amazonaws\\.com$/.test(host);\n\nconst prefixMatches = (url: URL, allowedPrefixes: string[]): boolean =>\n allowedPrefixes.some((prefix) => {\n let allowedUrl: URL;\n\n try {\n allowedUrl = new URL(prefix);\n } catch {\n return false;\n }\n\n if (url.protocol !== allowedUrl.protocol) {\n return false;\n }\n\n if (url.host.toLowerCase() !== allowedUrl.host.toLowerCase()) {\n return false;\n }\n\n return pathPrefixMatches(url.pathname, allowedUrl.pathname);\n });\n\nconst pathPrefixMatches = (pathName: string, allowedPathName: string): boolean => {\n if (!allowedPathName || allowedPathName === \"/\") {\n return true;\n }\n\n const normalizedAllowedPath = allowedPathName.endsWith(\"/\")\n ? allowedPathName\n : `${allowedPathName}/`;\n\n return pathName === allowedPathName || pathName.startsWith(normalizedAllowedPath);\n};\n","import fs from \"node:fs/promises\";\n\nimport type { ZuoraAgentToolkitError } from \"../../../errors.js\";\nimport { nativeFileError } from \"./errors.js\";\n\nexport const readFilePrefix = async (\n absolutePath: string,\n maxBytes: number,\n): Promise<{\n buffer: Buffer;\n bytesRead: number;\n truncatedByBytes: boolean;\n}> => {\n const handle = await fs.open(absolutePath, \"r\");\n\n try {\n const buffer = Buffer.alloc(maxBytes + 1);\n const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);\n const boundedBytes = Math.min(bytesRead, maxBytes);\n\n return {\n buffer: buffer.subarray(0, boundedBytes),\n bytesRead: boundedBytes,\n truncatedByBytes: bytesRead > maxBytes,\n };\n } finally {\n await handle.close();\n }\n};\n\nexport const capPositiveInteger = (\n value: unknown,\n fallback: number,\n maximum: number,\n name: string,\n): number => {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 1) {\n throw nativeFileError({\n code: \"FILE_READ_TOO_LARGE\",\n message: `read_downloaded_file ${name} must be a positive integer.`,\n recoverable: true,\n });\n }\n\n return Math.min(value, maximum);\n};\n\nexport const looksBinary = (buffer: Buffer): boolean => buffer.includes(0);\n\nexport const isNodeErrorCode = (error: unknown, code: string): boolean =>\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === code;\n\nexport const nativeFilesystemError = (\n code: \"FILE_DOWNLOAD_FAILED\" | \"FILE_PATH_NOT_ALLOWED\",\n message: string,\n error: unknown,\n details: Record<string, unknown>,\n): ZuoraAgentToolkitError =>\n nativeFileError({\n code,\n message,\n recoverable: true,\n details: {\n ...details,\n cause: error instanceof Error ? error.message : String(error),\n },\n });\n","import type {\n NativeToolApprovalMetadata,\n ZuoraToolDefinition,\n ZuoraToolExecutionResult,\n} from \"../../types.js\";\n\nexport type NativeToolExecutor = (\n input: Record<string, unknown>,\n) => Promise<ZuoraToolExecutionResult>;\n\nexport type NativeToolApprovalMetadataFactory = (\n input: Record<string, unknown>,\n) => NativeToolApprovalMetadata | undefined;\n\nexport type NativeRuntimeTool = {\n definition: ZuoraToolDefinition;\n execute: NativeToolExecutor;\n approvalMetadata: NativeToolApprovalMetadataFactory;\n};\n\nexport type NativeToolSet = {\n listTools: () => NativeRuntimeTool[];\n};\n\nexport const createNativeRuntimeTool = ({\n definition,\n execute,\n approvalMetadata = () => undefined,\n}: {\n definition: ZuoraToolDefinition;\n execute: NativeToolExecutor;\n approvalMetadata?: NativeToolApprovalMetadataFactory;\n}): NativeRuntimeTool => ({\n definition,\n execute,\n approvalMetadata,\n});\n","import type {\n NativeFileApprovalMetadata,\n NativeFileToolsConfig,\n ZuoraMcpClient,\n ZuoraToolExecutionResult,\n} from \"../../../types.js\";\nimport {\n type ResolvedNativeFileToolsConfig,\n resolveNativeFileToolsConfig,\n} from \"./config.js\";\nimport {\n createDownloadFileToolDefinition,\n createReadDownloadedFileToolDefinition,\n createReadResourceToolDefinition,\n} from \"./definitions.js\";\nimport { NativeFileDownloadService } from \"./download-service.js\";\nimport { nativeFileError } from \"./errors.js\";\nimport {\n capPositiveInteger,\n isNodeErrorCode,\n looksBinary,\n nativeFilesystemError,\n readFilePrefix,\n} from \"./helpers.js\";\nimport {\n type FileArtifactRecord,\n FileArtifactManifest,\n} from \"./manifest.js\";\nimport {\n resolveInputRelativePath,\n resolveOutputRelativePath,\n resolveRegisteredArtifactPath,\n} from \"./path-policy.js\";\nimport { validateDownloadUrl } from \"./url-policy.js\";\nimport {\n createNativeRuntimeTool,\n type NativeRuntimeTool,\n type NativeToolSet,\n} from \"../registry-source.js\";\n\nexport type NativeFileArtifactToolsOptions = {\n /**\n * Optional MCP client used by read_resource to resolve MCP resource URIs.\n * When absent, read_resource will throw a runtime error.\n */\n mcpClient?: ZuoraMcpClient;\n};\n\nexport class NativeFileArtifactTools implements NativeToolSet {\n private readonly config: ResolvedNativeFileToolsConfig;\n\n private readonly manifest = new FileArtifactManifest();\n\n private readonly downloadService: NativeFileDownloadService;\n\n private readonly mcpClient: ZuoraMcpClient | undefined;\n\n constructor(\n config: NativeFileToolsConfig | undefined,\n options: NativeFileArtifactToolsOptions = {},\n ) {\n this.config = resolveNativeFileToolsConfig(config);\n this.mcpClient = options.mcpClient;\n this.downloadService = new NativeFileDownloadService({\n config: this.config,\n manifest: this.manifest,\n });\n }\n\n listTools(): NativeRuntimeTool[] {\n if (!this.config.enabled) {\n return [];\n }\n\n return [\n ...(this.config.tools.downloadFile.enabled\n ? [this.createDownloadFileTool()]\n : []),\n ...(this.config.tools.readDownloadedFile.enabled\n ? [this.createReadDownloadedFileTool()]\n : []),\n ...(this.config.tools.readResource.enabled\n ? [this.createReadResourceTool()]\n : []),\n ];\n }\n\n isEnabled(): boolean {\n return this.config.enabled;\n }\n\n private createDownloadFileTool(): NativeRuntimeTool {\n return createNativeRuntimeTool({\n definition: createDownloadFileToolDefinition(this.config),\n execute: (input) => this.downloadFile(input),\n approvalMetadata: (input) => this.createDownloadApprovalMetadata(input),\n });\n }\n\n private createReadDownloadedFileTool(): NativeRuntimeTool {\n return createNativeRuntimeTool({\n definition: createReadDownloadedFileToolDefinition(this.config),\n execute: (input) => this.readDownloadedFile(input),\n approvalMetadata: (input) => this.createReadApprovalMetadata(input),\n });\n }\n\n private createReadResourceTool(): NativeRuntimeTool {\n return createNativeRuntimeTool({\n definition: createReadResourceToolDefinition(this.config),\n execute: (input) => this.readResource(input),\n });\n }\n\n async downloadFile(\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n return this.downloadService.downloadFile(input);\n }\n\n async persistBufferedDownload(\n options: Parameters<NativeFileDownloadService[\"persistBufferedDownload\"]>[0],\n ): Promise<ZuoraToolExecutionResult> {\n return this.downloadService.persistBufferedDownload(options);\n }\n\n private async readDownloadedFile(\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n const artifact = this.resolveArtifact(input);\n const maxBytes = capPositiveInteger(\n input.maxBytes,\n this.config.maxReadBytes,\n this.config.maxReadBytes,\n \"maxBytes\",\n );\n const maxLines = capPositiveInteger(\n input.maxLines,\n this.config.maxReadLines,\n this.config.maxReadLines,\n \"maxLines\",\n );\n const startLine = capPositiveInteger(\n input.startLine,\n 1,\n Number.MAX_SAFE_INTEGER,\n \"startLine\",\n );\n\n let artifactPath;\n\n try {\n artifactPath = await resolveRegisteredArtifactPath(\n this.config,\n artifact.relativePath,\n );\n } catch (error) {\n if (isNodeErrorCode(error, \"ENOENT\")) {\n throw nativeFileError({\n code: \"FILE_ARTIFACT_NOT_FOUND\",\n message: \"The registered artifact file no longer exists.\",\n details: {\n artifactId: artifact.artifactId,\n path: artifact.relativePath,\n },\n });\n }\n\n throw error;\n }\n\n let filePrefix;\n\n try {\n filePrefix = await readFilePrefix(artifactPath.absolutePath, maxBytes);\n } catch (error) {\n if (isNodeErrorCode(error, \"ENOENT\")) {\n throw nativeFileError({\n code: \"FILE_ARTIFACT_NOT_FOUND\",\n message: \"The registered artifact file no longer exists.\",\n details: {\n artifactId: artifact.artifactId,\n path: artifact.relativePath,\n },\n });\n }\n\n throw nativeFilesystemError(\n \"FILE_PATH_NOT_ALLOWED\",\n \"read_downloaded_file could not read the local artifact.\",\n error,\n {\n artifactId: artifact.artifactId,\n path: artifact.relativePath,\n },\n );\n }\n\n const { buffer, bytesRead, truncatedByBytes } = filePrefix;\n\n if (looksBinary(buffer)) {\n throw nativeFileError({\n code: \"FILE_PATH_NOT_ALLOWED\",\n message: \"read_downloaded_file only supports text-like artifacts.\",\n recoverable: true,\n details: {\n artifactId: artifact.artifactId,\n path: artifact.relativePath,\n },\n });\n }\n\n const text = buffer.toString(\"utf8\");\n const lines = text.split(/\\r?\\n/);\n const startIndex = startLine - 1;\n const selectedLines = lines.slice(startIndex, startIndex + maxLines);\n const truncatedByLines = lines.length > startIndex + selectedLines.length;\n\n return {\n toolName: \"read_downloaded_file\",\n riskLevel: this.config.tools.readDownloadedFile.riskLevel,\n data: {\n artifactId: artifact.artifactId,\n path: artifact.relativePath,\n content: selectedLines.join(\"\\n\"),\n startLine,\n ...(selectedLines.length > 0\n ? { endLine: startLine + selectedLines.length - 1 }\n : {}),\n linesReturned: selectedLines.length,\n bytesRead,\n truncated: truncatedByBytes || truncatedByLines,\n },\n };\n }\n\n private async readResource(\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n const uri =\n typeof input.uri === \"string\" && input.uri.trim()\n ? input.uri.trim()\n : undefined;\n\n if (!uri) {\n throw nativeFileError({\n code: \"FILE_DOWNLOAD_FAILED\",\n message: \"read_resource requires a non-empty uri.\",\n recoverable: true,\n });\n }\n\n if (!this.mcpClient?.readResource) {\n throw nativeFileError({\n code: \"NATIVE_FILE_TOOLS_DISABLED\",\n message:\n \"read_resource requires an MCP client that supports resource reading. Configure the toolkit with an MCP client to use this tool.\",\n recoverable: false,\n });\n }\n\n const result = await this.mcpClient.readResource(uri);\n const primaryContent = result.contents[0];\n\n return {\n toolName: \"read_resource\",\n riskLevel: this.config.tools.readResource.riskLevel,\n data: {\n uri,\n mimeType: primaryContent?.mimeType ?? \"application/octet-stream\",\n ...(primaryContent?.text !== undefined ? { content: primaryContent.text } : {}),\n ...(primaryContent?.blob !== undefined ? { data: primaryContent.blob } : {}),\n },\n };\n }\n\n private resolveArtifact(input: Record<string, unknown>): FileArtifactRecord {\n const artifactId =\n typeof input.artifactId === \"string\" && input.artifactId.trim()\n ? input.artifactId.trim()\n : undefined;\n\n if (artifactId) {\n const artifact = this.manifest.getById(artifactId);\n\n if (artifact) {\n return artifact;\n }\n }\n\n const inputPath =\n typeof input.path === \"string\" && input.path.trim()\n ? resolveInputRelativePath(input.path)\n : undefined;\n\n if (inputPath) {\n const artifact = this.manifest.getByRelativePath(inputPath);\n\n if (artifact) {\n return artifact;\n }\n }\n\n throw nativeFileError({\n code: \"FILE_ARTIFACT_NOT_FOUND\",\n message:\n \"read_downloaded_file requires an artifactId or path returned by download_file in this toolkit session.\",\n recoverable: true,\n details: {\n artifactId,\n path: inputPath,\n },\n });\n }\n\n private createDownloadApprovalMetadata(\n input: Record<string, unknown>,\n ): NativeFileApprovalMetadata | undefined {\n try {\n const validatedUrl = validateDownloadUrl(input.url, this.config);\n const outputRelativePath =\n typeof input.fileName === \"string\" && input.fileName.trim()\n ? resolveOutputRelativePath(input.fileName, validatedUrl.url)\n : undefined;\n\n return {\n source: \"native\",\n nativeToolType: \"fileArtifacts\",\n filesystemRoot: this.config.rootDirAbsolute,\n sideEffects: [\"networkRead\", \"localFileWrite\"],\n urlHost: validatedUrl.source.host,\n urlProtocol: validatedUrl.source.protocol,\n urlPath: validatedUrl.source.path,\n urlKind: validatedUrl.source.kind,\n ...(outputRelativePath ? { outputRelativePath } : {}),\n };\n } catch {\n return undefined;\n }\n }\n\n private createReadApprovalMetadata(\n input: Record<string, unknown>,\n ): NativeFileApprovalMetadata {\n const artifactId =\n typeof input.artifactId === \"string\" && input.artifactId.trim()\n ? input.artifactId.trim()\n : undefined;\n const relativePath =\n typeof input.path === \"string\" && input.path.trim()\n ? input.path.trim()\n : undefined;\n\n return {\n source: \"native\",\n nativeToolType: \"fileArtifacts\",\n filesystemRoot: this.config.rootDirAbsolute,\n sideEffects: [\"localFileRead\"],\n ...(artifactId ? { artifactId } : {}),\n ...(relativePath ? { relativePath } : {}),\n };\n }\n}\n","import os from \"node:os\";\nimport path from \"node:path\";\n\nimport type {\n NativeFileToolsConfig,\n NativeToolMetadataConfig,\n} from \"../../types.js\";\nimport { nonEmptyString } from \"../../utils/values.js\";\n\n/** SDK-internal defaults — not exposed to agents. */\nexport const DEFAULT_NATIVE_ARTIFACT_ROOT = path.join(\n os.homedir(),\n \".zuora-agent-artifacts\",\n);\n\nexport const DEFAULT_NATIVE_ALLOWED_HOSTS = [\n \"*.amazonaws.com\",\n \"*.s3.amazonaws.com\",\n \"s3.amazonaws.com\",\n \"s3.us-west-2.amazonaws.com\",\n \"*.s3.us-west-2.amazonaws.com\",\n];\n\nconst AGENT_NATIVE_TOOL_DEFAULTS: NonNullable<\n NativeFileToolsConfig[\"tools\"]\n> = {\n downloadFile: { enabled: false, operationAccess: \"read\" },\n extractDownloadedArchive: { enabled: false, operationAccess: \"read\" },\n downloadQueryResult: { enabled: true, operationAccess: \"read\" },\n readDownloadedFile: { enabled: true, operationAccess: \"read\" },\n downloadZuoraFile: { enabled: true, operationAccess: \"read\" },\n readResource: { enabled: true, operationAccess: \"read\" },\n};\n\nconst readEnvAllowedHosts = (): string[] | undefined => {\n const raw = process.env[\"ZUORA_NATIVE_ALLOWED_HOSTS\"]?.trim();\n\n if (!raw) {\n return undefined;\n }\n\n const hosts = raw\n .split(\",\")\n .map((host) => host.trim())\n .filter(Boolean);\n\n return hosts.length > 0 ? hosts : undefined;\n};\n\n/**\n * Resolves native file tool settings for the SDK runtime.\n *\n * Native tools (download_query_result, read_downloaded_file, …) are always\n * registered in the catalog with safe defaults. Bundle filtering at\n * getTools()/listTools() time controls whether they appear for a given\n * selection — the same as any MCP tool.\n *\n * Only agent-facing tools appear in the catalog; internal helpers such as\n * `download_file` stay hidden.\n */\nexport const resolveNativeFileToolsInput = (\n config: { nativeFileTools?: NativeFileToolsConfig },\n): NativeFileToolsConfig => {\n const explicit = config.nativeFileTools;\n\n if (explicit?.enabled === false) {\n return { enabled: false };\n }\n\n const rootDir =\n nonEmptyString(explicit?.rootDir) ??\n nonEmptyString(process.env[\"ZUORA_NATIVE_FILE_ROOT\"]) ??\n DEFAULT_NATIVE_ARTIFACT_ROOT;\n\n const allowedHosts =\n explicit?.allowedHosts ??\n readEnvAllowedHosts() ??\n DEFAULT_NATIVE_ALLOWED_HOSTS;\n\n return {\n enabled: true,\n bundleName: explicit?.bundleName ?? \"query\",\n rootDir,\n allowedHosts,\n allowS3PresignedDownload:\n explicit?.allowS3PresignedDownload ?? true,\n requireRootUnderUserHome: explicit?.requireRootUnderUserHome ?? true,\n tools: mergeNativeToolOverrides(explicit?.tools, AGENT_NATIVE_TOOL_DEFAULTS),\n ...(explicit?.userHomeDir ? { userHomeDir: explicit.userHomeDir } : {}),\n ...(explicit?.allowOverwrite !== undefined\n ? { allowOverwrite: explicit.allowOverwrite }\n : {}),\n ...(explicit?.maxDownloadBytes !== undefined\n ? { maxDownloadBytes: explicit.maxDownloadBytes }\n : {}),\n ...(explicit?.maxReadBytes !== undefined\n ? { maxReadBytes: explicit.maxReadBytes }\n : {}),\n ...(explicit?.maxReadLines !== undefined\n ? { maxReadLines: explicit.maxReadLines }\n : {}),\n ...(explicit?.downloadTimeoutMs !== undefined\n ? { downloadTimeoutMs: explicit.downloadTimeoutMs }\n : {}),\n ...(explicit?.allowedProtocols\n ? { allowedProtocols: explicit.allowedProtocols }\n : {}),\n ...(explicit?.allowedUrlPrefixes\n ? { allowedUrlPrefixes: explicit.allowedUrlPrefixes }\n : {}),\n };\n};\n\nconst mergeNativeToolOverrides = (\n overrides: NativeFileToolsConfig[\"tools\"] | undefined,\n defaults: NonNullable<NativeFileToolsConfig[\"tools\"]>,\n): NonNullable<NativeFileToolsConfig[\"tools\"]> => ({\n downloadFile: mergeNativeToolMetadata(\n defaults.downloadFile,\n overrides?.downloadFile,\n ),\n extractDownloadedArchive: mergeNativeToolMetadata(\n defaults.extractDownloadedArchive,\n overrides?.extractDownloadedArchive,\n ),\n downloadQueryResult: mergeNativeToolMetadata(\n defaults.downloadQueryResult,\n overrides?.downloadQueryResult,\n ),\n readDownloadedFile: mergeNativeToolMetadata(\n defaults.readDownloadedFile,\n overrides?.readDownloadedFile,\n ),\n downloadZuoraFile: mergeNativeToolMetadata(\n defaults.downloadZuoraFile,\n overrides?.downloadZuoraFile,\n ),\n readResource: mergeNativeToolMetadata(\n defaults.readResource,\n overrides?.readResource,\n ),\n});\n\nconst mergeNativeToolMetadata = (\n defaults: NativeToolMetadataConfig | undefined,\n override: NativeToolMetadataConfig | undefined,\n): NativeToolMetadataConfig => {\n const enabled = override?.enabled ?? defaults?.enabled ?? false;\n const operationAccess =\n override?.operationAccess ?? defaults?.operationAccess ?? \"read\";\n const riskLevel = override?.riskLevel ?? defaults?.riskLevel ?? \"low\";\n const description = override?.description ?? defaults?.description;\n\n return {\n enabled,\n operationAccess,\n riskLevel,\n ...(description ? { description } : {}),\n };\n};\n\n/** Agent-visible native tool names (internal `download_file` excluded). */\nexport const AGENT_NATIVE_TOOL_NAMES = [\n \"download_query_result\",\n \"read_downloaded_file\",\n \"download_zuora_file\",\n \"read_resource\",\n] as const;\n","import { ZuoraAgentToolkitError } from \"../../../errors.js\";\nimport type { NativeFileToolsConfig } from \"../../../types.js\";\nimport {\n resolveNativeToolMetadata,\n type ResolvedNativeToolMetadataConfig,\n} from \"../config.js\";\n\nexport type ResolvedNativeQueryResultDownloadConfig = {\n enabled: boolean;\n tool: ResolvedNativeToolMetadataConfig;\n};\n\nexport const resolveNativeQueryResultDownloadConfig = (\n input: NativeFileToolsConfig | undefined,\n options: {\n fileArtifactsEnabled: boolean;\n },\n): ResolvedNativeQueryResultDownloadConfig => {\n const tool = resolveNativeToolMetadata(input?.tools?.downloadQueryResult, {\n enabled: true,\n operationAccess: \"read\",\n riskLevel: \"medium\",\n });\n\n if (tool.operationAccess !== \"read\") {\n throw new ZuoraAgentToolkitError({\n code: \"NATIVE_FILE_CONFIG_INVALID\",\n message: \"download_query_result must be configured with operationAccess \\\"read\\\".\",\n category: \"configuration\",\n recoverable: true,\n });\n }\n\n const config = {\n enabled: options.fileArtifactsEnabled && tool.enabled,\n tool,\n };\n\n return config;\n};\n\n","import type { JsonSchema, ZuoraToolDefinition } from \"../../../../types.js\";\nimport { isRecord } from \"../../../../utils/values.js\";\n\nexport type QueryResultStatusCall = {\n toolName: string;\n input: Record<string, unknown>;\n};\n\nexport const resolveQueryResultStatusCall = (\n tools: ZuoraToolDefinition[],\n jobId: string,\n): QueryResultStatusCall | undefined => {\n const candidates = tools\n .map((tool) => ({\n tool,\n score: scoreQueryResultStatusTool(tool),\n }))\n .filter(({ score, tool }) => score > 0 && !isSubmitStyleStatusTool(tool))\n .sort((first, second) => second.score - first.score);\n\n const candidate = candidates[0];\n\n if (!candidate) {\n return undefined;\n }\n\n return {\n toolName: candidate.tool.name,\n input: createQueryResultStatusInput(candidate.tool, jobId),\n };\n};\n\nconst scoreQueryResultStatusTool = (tool: ZuoraToolDefinition): number => {\n const haystack = `${tool.name} ${tool.description}`.toLowerCase();\n const operationName = tool.meta.operationName ?? \"\";\n\n if (tool.meta.bundle !== \"query\") {\n return 0;\n }\n\n let score = 0;\n\n if (tool.name === \"manage_dataquery\") {\n score += 200;\n }\n\n if (operationName === \"get_query_job\" || tool.name.endsWith(\"__get_query_job\")) {\n score += 220;\n }\n\n if (/(dataquery|data query|data_query|manage_data_queries)/i.test(haystack)) {\n score += 80;\n }\n\n if (/(query).*(job|status|result)|(job|status|result).*(query)/i.test(haystack)) {\n score += 40;\n }\n\n if (\n operationName &&\n /(get|retrieve|fetch|read|status|poll|download)/i.test(operationName)\n ) {\n score += 50;\n }\n\n return score;\n};\n\nconst isSubmitStyleStatusTool = (tool: ZuoraToolDefinition): boolean => {\n const operationName = tool.meta.operationName ?? tool.name;\n\n if (/^(submit|run|create)_/i.test(operationName)) {\n return true;\n }\n\n return /__(submit|run|create)_/i.test(tool.name);\n};\n\nconst createQueryResultStatusInput = (\n tool: ZuoraToolDefinition,\n jobId: string,\n): Record<string, unknown> => {\n const input: Record<string, unknown> = {};\n\n if (tool.meta.operationSelector) {\n const operationName =\n tool.meta.operationName ??\n resolveStatusOperationName(tool);\n\n if (operationName) {\n input[tool.meta.operationSelector] = operationName;\n }\n }\n\n input[resolveQueryJobIdInputName(tool.inputSchema)] = jobId;\n\n return input;\n};\n\n/**\n * For multi-op merged tools that have no bound operationName, infer the status\n * operation name from meta.asyncOperations — prefer the pollingOperation of any\n * async operation entry (e.g. \"get_query_job\"), falling back to any operation\n * name that looks like a get/status/poll operation.\n */\nconst resolveStatusOperationName = (\n tool: ZuoraToolDefinition,\n): string | undefined => {\n const asyncOperations = tool.meta.asyncOperations;\n\n if (!asyncOperations) {\n return undefined;\n }\n\n // First preference: the pollingOperation value from any async entry.\n for (const meta of Object.values(asyncOperations)) {\n if (meta.pollingOperation) {\n return meta.pollingOperation;\n }\n }\n\n // Second preference: an operation key that looks like a status/get call.\n return Object.keys(asyncOperations).find((name) =>\n /(get|status|poll|retrieve|fetch)/i.test(name),\n );\n};\n\nconst resolveQueryJobIdInputName = (schema: JsonSchema): string => {\n const properties = isRecord(schema.properties) ? schema.properties : {};\n const propertyNames = Object.keys(properties);\n const exactPreferred = [\"jobId\", \"queryJobId\", \"dataQueryJobId\", \"id\"].find(\n (name) => propertyNames.includes(name),\n );\n\n if (exactPreferred) {\n return exactPreferred;\n }\n\n return (\n propertyNames.find((name) => /job.*id|id.*job/i.test(name)) ??\n propertyNames.find((name) => /id$/i.test(name)) ??\n \"jobId\"\n );\n};\n","import type { ZuoraToolDefinition } from \"../../../types.js\";\nimport { nativeObjectSchema } from \"../metadata.js\";\nimport type { ResolvedNativeToolMetadataConfig } from \"../config.js\";\n\nexport const createDownloadQueryResultToolDefinition = (\n toolConfig: ResolvedNativeToolMetadataConfig,\n): ZuoraToolDefinition => ({\n name: \"download_query_result\",\n description:\n toolConfig.description ??\n [\n \"Download a completed Zuora Data Query result by jobId.\",\n \"Use this instead of copying a dataFile URL when the user asks to download a query result and a jobId is available.\",\n \"The SDK fetches the latest query job result, extracts the exact dataFile URL internally, and downloads it to the local artifact folder.\",\n ].join(\" \"),\n inputSchema: nativeObjectSchema(\n {\n jobId: {\n type: \"string\",\n description: \"Zuora Data Query job id.\",\n },\n fileName: {\n type: \"string\",\n description:\n \"Optional relative artifact file name under the configured artifact root.\",\n },\n overwrite: {\n type: \"boolean\",\n description:\n \"Replace an existing local artifact at fileName. Set to true only after the user explicitly confirmed overwrite.\",\n },\n },\n [\"jobId\"],\n ),\n outputSchema: nativeObjectSchema(\n {\n jobId: { type: \"string\" },\n queryStatus: { type: \"string\" },\n download: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n [\"jobId\", \"download\"],\n ),\n meta: {\n bundle: \"query\",\n access: toolConfig.operationAccess,\n riskLevel: toolConfig.riskLevel,\n requiredServicePermissions: [],\n limitations: [],\n sourceName: \"download_query_result\",\n },\n});\n","import { ZuoraAgentToolkitError } from \"../../../../errors.js\";\n\nexport const readJobId = (value: unknown): string => {\n if (typeof value === \"string\" && value.trim()) {\n return value.trim();\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"QUERY_RESULT_JOB_ID_INVALID\",\n message: \"download_query_result requires a non-empty jobId.\",\n category: \"validation\",\n recoverable: true,\n });\n};\n\nexport const findDownloadUrl = (value: unknown): string | undefined =>\n findStringByKey(value, (key, candidate) => {\n if (!DOWNLOAD_URL_KEY_PATTERN.test(key)) {\n return false;\n }\n\n return isHttpUrl(candidate);\n });\n\nexport const findQueryStatus = (value: unknown): string | undefined =>\n findStringByKey(value, (key) => /^(queryStatus|status)$/i.test(key));\n\nconst findStringByKey = (\n value: unknown,\n predicate: (key: string, value: string) => boolean,\n depth = 0,\n): string | undefined => {\n if (depth > 8 || typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n const found = findStringByKey(item, predicate, depth + 1);\n\n if (found) {\n return found;\n }\n }\n\n return undefined;\n }\n\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (typeof item === \"string\" && predicate(key, item)) {\n return item;\n }\n\n const found = findStringByKey(item, predicate, depth + 1);\n\n if (found) {\n return found;\n }\n }\n\n return undefined;\n};\n\nconst isHttpUrl = (value: string): boolean => {\n try {\n const url = new URL(value);\n\n return url.protocol === \"http:\" || url.protocol === \"https:\";\n } catch {\n return false;\n }\n};\n\nconst DOWNLOAD_URL_KEY_PATTERN =\n /^(dataFile|resultFile|downloadFile|fileUrl|downloadUrl|resultUrl|href)$/i;\n","import { ZuoraAgentToolkitError } from \"../../../errors.js\";\nimport type { ZuoraToolExecutionResult } from \"../../../types.js\";\nimport {\n createNativeRuntimeTool,\n type NativeRuntimeTool,\n type NativeToolSet,\n} from \"../registry-source.js\";\nimport type { ResolvedNativeToolMetadataConfig } from \"../config.js\";\nimport { createDownloadQueryResultToolDefinition } from \"./definitions.js\";\nimport {\n findDownloadUrl,\n findQueryStatus,\n readJobId,\n} from \"./helpers/index.js\";\n\nexport type QueryResultFetcher = (\n jobId: string,\n) => Promise<ZuoraToolExecutionResult>;\n\nexport type QueryResultDownloader = (\n input: Record<string, unknown>,\n) => Promise<ZuoraToolExecutionResult>;\n\nexport type NativeQueryResultDownloadToolsConfig = {\n enabled: boolean;\n tool: ResolvedNativeToolMetadataConfig;\n fetchQueryResult: QueryResultFetcher;\n downloadFile: QueryResultDownloader;\n};\n\nexport class NativeQueryResultDownloadTools implements NativeToolSet {\n constructor(private readonly config: NativeQueryResultDownloadToolsConfig) {}\n\n listTools(): NativeRuntimeTool[] {\n if (!this.config.enabled) {\n return [];\n }\n\n return [this.createDownloadQueryResultTool()];\n }\n\n private createDownloadQueryResultTool(): NativeRuntimeTool {\n return createNativeRuntimeTool({\n definition: createDownloadQueryResultToolDefinition(this.config.tool),\n execute: (input) => this.downloadQueryResult(input),\n });\n }\n\n private async downloadQueryResult(\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n const jobId = readJobId(input.jobId);\n const queryResult = await this.config.fetchQueryResult(jobId);\n const dataFile = findDownloadUrl(queryResult.data);\n\n if (!dataFile) {\n throw new ZuoraAgentToolkitError({\n code: \"QUERY_RESULT_DATA_FILE_NOT_FOUND\",\n message:\n \"Query result did not include a dataFile URL. Confirm the job is completed before downloading the result.\",\n category: \"native_file_tools\",\n recoverable: true,\n details: {\n jobId,\n queryStatus: findQueryStatus(queryResult.data),\n },\n });\n }\n\n const download = await this.config.downloadFile({\n url: dataFile,\n ...(typeof input.fileName === \"string\" && input.fileName.trim()\n ? { fileName: input.fileName.trim() }\n : {}),\n ...(typeof input.overwrite === \"boolean\"\n ? { overwrite: input.overwrite }\n : {}),\n });\n\n return {\n toolName: \"download_query_result\",\n riskLevel: this.config.tool.riskLevel,\n data: {\n jobId,\n ...(findQueryStatus(queryResult.data)\n ? { queryStatus: findQueryStatus(queryResult.data) }\n : {}),\n download: download.data,\n },\n warnings: [\n ...(queryResult.warnings ?? []),\n ...(download.warnings ?? []),\n ],\n };\n }\n}\n","import type { NativeFileToolsConfig } from \"../../../types.js\";\nimport {\n resolveNativeToolMetadata,\n type ResolvedNativeToolMetadataConfig,\n} from \"../config.js\";\n\nexport type ResolvedNativeZuoraFileDownloadConfig = {\n enabled: boolean;\n tool: ResolvedNativeToolMetadataConfig;\n};\n\nexport const resolveNativeZuoraFileDownloadConfig = (\n input: NativeFileToolsConfig | undefined,\n options: {\n fileArtifactsEnabled: boolean;\n },\n): ResolvedNativeZuoraFileDownloadConfig => {\n const tool = resolveNativeToolMetadata(input?.tools?.downloadZuoraFile, {\n enabled: true,\n operationAccess: \"read\",\n riskLevel: \"medium\",\n });\n const config = {\n enabled: options.fileArtifactsEnabled && tool.enabled,\n tool,\n };\n\n return config;\n};\n","import type { ZuoraToolDefinition } from \"../../../types.js\";\nimport { nativeObjectSchema } from \"../metadata.js\";\nimport type { ResolvedNativeToolMetadataConfig } from \"../config.js\";\n\nexport const createDownloadZuoraFileToolDefinition = (\n toolConfig: ResolvedNativeToolMetadataConfig,\n): ZuoraToolDefinition => ({\n name: \"download_zuora_file\",\n description:\n toolConfig.description ??\n [\n \"Download a Zuora tenant file by fileId using the Zuora REST Files API.\",\n \"Use this when a prior tool result includes resourceUri zuora://files/{fileId} or an explicit fileId for a generated artifact such as an invoice PDF.\",\n \"The SDK downloads the file with the configured Zuora credentials and saves it to the local artifact folder.\",\n ].join(\" \"),\n inputSchema: nativeObjectSchema(\n {\n fileId: {\n type: \"string\",\n description: \"Zuora file id from a prior tool result.\",\n },\n resourceUri: {\n type: \"string\",\n description:\n \"Optional zuora://files/{fileId} resource URI from a prior tool result.\",\n },\n fileName: {\n type: \"string\",\n description:\n \"Optional relative artifact file name under the configured artifact root.\",\n },\n overwrite: {\n type: \"boolean\",\n description:\n \"Replace an existing local artifact at fileName. Set to true only after the user explicitly confirmed overwrite.\",\n },\n },\n [],\n ),\n outputSchema: nativeObjectSchema(\n {\n fileId: { type: \"string\" },\n download: {\n type: \"object\",\n additionalProperties: true,\n },\n },\n [\"fileId\", \"download\"],\n ),\n meta: {\n bundle: \"query\",\n access: toolConfig.operationAccess,\n riskLevel: toolConfig.riskLevel,\n requiredServicePermissions: [],\n limitations: [],\n sourceName: \"download_zuora_file\",\n },\n});\n","import { ZuoraAgentToolkitError } from \"../../../../errors.js\";\n\nconst ZUORA_FILE_RESOURCE_URI_PATTERN =\n /^zuora:\\/\\/files\\/([A-Za-z0-9]+)$/i;\n\nexport const readZuoraFileId = (\n input: Record<string, unknown>,\n): string => {\n const fileId = typeof input.fileId === \"string\" ? input.fileId.trim() : \"\";\n const resourceUri =\n typeof input.resourceUri === \"string\" ? input.resourceUri.trim() : \"\";\n\n if (fileId) {\n return fileId;\n }\n\n const parsedFileId = parseZuoraFileResourceUri(resourceUri);\n\n if (parsedFileId) {\n return parsedFileId;\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"INVALID_INPUT\",\n message:\n \"download_zuora_file requires fileId or resourceUri zuora://files/{fileId}.\",\n category: \"validation\",\n recoverable: true,\n });\n};\n\nexport const parseZuoraFileResourceUri = (\n resourceUri: string,\n): string | undefined => {\n const match = resourceUri.match(ZUORA_FILE_RESOURCE_URI_PATTERN);\n return match?.[1];\n};\n\nexport const resolveZuoraFileResource = (\n value: unknown,\n keyPath: string[] = [],\n depth = 0,\n): { fileId: string; resourceUri: string } | undefined => {\n if (depth > 6) {\n return undefined;\n }\n\n if (typeof value === \"string\") {\n const fileId = parseZuoraFileResourceUri(value);\n\n if (fileId && keyPath.at(-1) === \"resourceUri\") {\n return { fileId, resourceUri: value };\n }\n\n return undefined;\n }\n\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries()) {\n const resolved = resolveZuoraFileResource(item, [\n ...keyPath,\n String(index),\n ], depth + 1);\n\n if (resolved) {\n return resolved;\n }\n }\n\n return undefined;\n }\n\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n const resourceUri = record.resourceUri;\n\n if (typeof resourceUri === \"string\") {\n const fileId = parseZuoraFileResourceUri(resourceUri);\n\n if (fileId) {\n return { fileId, resourceUri };\n }\n }\n\n const explicitFileId =\n typeof record.fileId === \"string\" ? record.fileId.trim() : \"\";\n\n if (explicitFileId && typeof resourceUri === \"string\") {\n const parsed = parseZuoraFileResourceUri(resourceUri);\n\n if (parsed === explicitFileId) {\n return { fileId: explicitFileId, resourceUri };\n }\n }\n\n for (const [key, item] of Object.entries(record)) {\n const resolved = resolveZuoraFileResource(item, [...keyPath, key], depth + 1);\n\n if (resolved) {\n return resolved;\n }\n }\n\n return undefined;\n};\n\nexport const defaultZuoraFileName = (\n fileId: string,\n contentType?: string,\n): string => {\n if (contentType?.includes(\"pdf\")) {\n return `${fileId}.pdf`;\n }\n\n if (contentType?.includes(\"json\")) {\n return `${fileId}.json`;\n }\n\n return `${fileId}.bin`;\n};\n","import type { ZuoraToolExecutionResult } from \"../../../types.js\";\nimport type { ZuoraRestDownloadFileResult } from \"../../../transport/zuora-rest-client.js\";\nimport type { NativeFileSafeSource } from \"../file-artifacts/url-policy.js\";\nimport {\n createNativeRuntimeTool,\n type NativeRuntimeTool,\n type NativeToolSet,\n} from \"../registry-source.js\";\nimport type { ResolvedNativeToolMetadataConfig } from \"../config.js\";\nimport { createDownloadZuoraFileToolDefinition } from \"./definitions.js\";\nimport {\n defaultZuoraFileName,\n readZuoraFileId,\n} from \"./helpers/index.js\";\n\nexport type ZuoraFileFetcher = (\n fileId: string,\n) => Promise<ZuoraRestDownloadFileResult>;\n\nexport type BufferedDownloadPersister = (options: {\n input: Record<string, unknown>;\n toolName: string;\n riskLevel: ResolvedNativeToolMetadataConfig[\"riskLevel\"];\n body: Buffer;\n contentType?: string;\n source: NativeFileSafeSource;\n defaultFileName: string;\n}) => Promise<ZuoraToolExecutionResult>;\n\nexport type NativeZuoraFileDownloadToolsConfig = {\n enabled: boolean;\n tool: ResolvedNativeToolMetadataConfig;\n fetchZuoraFile: ZuoraFileFetcher;\n persistDownload: BufferedDownloadPersister;\n};\n\nexport class NativeZuoraFileDownloadTools implements NativeToolSet {\n constructor(private readonly config: NativeZuoraFileDownloadToolsConfig) {}\n\n listTools(): NativeRuntimeTool[] {\n if (!this.config.enabled) {\n return [];\n }\n\n return [this.createDownloadZuoraFileTool()];\n }\n\n private createDownloadZuoraFileTool(): NativeRuntimeTool {\n return createNativeRuntimeTool({\n definition: createDownloadZuoraFileToolDefinition(this.config.tool),\n execute: (input) => this.downloadZuoraFile(input),\n });\n }\n\n private async downloadZuoraFile(\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n const fileId = readZuoraFileId(input);\n const fetched = await this.config.fetchZuoraFile(fileId);\n const source: NativeFileSafeSource = {\n protocol: \"zuora:\",\n host: \"files\",\n path: `/${fileId}`,\n redactedUrl: `zuora://files/${fileId}`,\n kind: \"zuora-public\",\n };\n const download = await this.config.persistDownload({\n input,\n toolName: \"download_zuora_file\",\n riskLevel: this.config.tool.riskLevel,\n body: Buffer.from(fetched.bytes),\n ...(fetched.contentType ? { contentType: fetched.contentType } : {}),\n source,\n defaultFileName: defaultZuoraFileName(fileId, fetched.contentType),\n });\n\n return {\n toolName: \"download_zuora_file\",\n riskLevel: this.config.tool.riskLevel,\n data: {\n fileId,\n download: download.data,\n },\n ...(download.warnings ? { warnings: download.warnings } : {}),\n };\n }\n}\n","import type {\n JsonSchema,\n ZuoraAsyncOperationMeta,\n ZuoraRiskLevel,\n ZuoraServicePermission,\n ZuoraToolDefinition,\n ZuoraToolOperation,\n} from \"../types.js\";\nimport { isRecord, nonEmptyString } from \"../utils/values.js\";\n\nexport type McpToolMetadataInput = {\n name: string;\n description?: string;\n inputSchema?: JsonSchema;\n outputSchema?: JsonSchema;\n _meta?: Record<string, unknown>;\n annotations?: {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n };\n};\n\nimport { normalizeMetadataPath } from \"../async-jobs.js\";\nimport { createOperationAdapterToolName } from \"../utils/adapter-name.js\";\nimport {\n inferOperationSelector,\n omitSchemaProperty,\n} from \"./operation-metadata.js\";\n\nconst DEFAULT_ACCESS: ZuoraToolOperation = \"write\";\nconst DEFAULT_RISK_LEVEL: ZuoraRiskLevel = \"high\";\nconst DEFAULT_BUNDLE = \"admin\";\n\nconst RISK_RANK: Record<ZuoraRiskLevel, number> = {\n low: 0,\n medium: 1,\n high: 2,\n};\n\nexport const normalizeMcpTools = (\n tools: McpToolMetadataInput[],\n splitOperations: boolean,\n): ZuoraToolDefinition[] =>\n tools.flatMap((tool) => normalizeSingleTool(tool, splitOperations));\n\nconst normalizeSingleTool = (\n tool: McpToolMetadataInput,\n splitOperations: boolean,\n): ZuoraToolDefinition[] => {\n const extracted = extractToolMetadata(tool);\n const operationPermissions = extracted.operationPermissions;\n const operationNames = operationPermissions\n ? Object.keys(operationPermissions)\n : [];\n\n if (operationNames.length <= 1) {\n const access =\n aggregateOperation(operationPermissions) ?? DEFAULT_ACCESS;\n\n return [\n buildZuoraToolDefinition(tool, extracted, {\n name: tool.name,\n access,\n operationName: operationNames[0],\n isSplit: false,\n }),\n ];\n }\n\n if (splitOperations) {\n return operationNames.map((operationName) =>\n buildZuoraToolDefinition(tool, extracted, {\n name: createOperationAdapterToolName(tool.name, operationName),\n access: operationPermissions![operationName]!,\n operationName,\n isSplit: true,\n }),\n );\n }\n\n const access = aggregateOperation(operationPermissions)!;\n\n return [\n buildZuoraToolDefinition(tool, extracted, {\n name: tool.name,\n access,\n isSplit: false,\n isMultiOpMerged: true,\n }),\n ];\n};\n\ntype ExtractedToolMetadata = {\n bundle: string;\n operationPermissions?: Record<string, ZuoraToolOperation> | undefined;\n operationRiskLevels?: Record<string, ZuoraRiskLevel> | undefined;\n asyncOperations?: Record<string, ZuoraAsyncOperationMeta> | undefined;\n requiredServicePermissions: ZuoraServicePermission[];\n limitations: string[];\n};\n\ntype BuildParams = {\n name: string;\n access: ZuoraToolOperation;\n operationName?: string | undefined;\n isSplit: boolean;\n /** True when the source MCP tool has multiple operations collapsed into one merged tool (splitOperations: false). */\n isMultiOpMerged?: boolean;\n};\n\nconst extractToolMetadata = (tool: McpToolMetadataInput): ExtractedToolMetadata => {\n const meta = isRecord(tool._meta) ? tool._meta : undefined;\n const zuoraMeta = isRecord(meta?.zuora) ? meta.zuora : undefined;\n\n const operationPermissions = normalizeOperationPermissions(\n meta?.[\"operationPermissions\"],\n tool.name,\n );\n const operationRiskLevels = normalizeRiskLevels(\n meta?.[\"riskLevels\"] ?? meta?.[\"operationRiskLevels\"],\n tool.name,\n );\n\n const bundleValue = nonEmptyString(meta?.[\"bundle\"]);\n const bundle: string = bundleValue !== undefined\n ? bundleValue.toLowerCase()\n : DEFAULT_BUNDLE;\n\n const requiredServicePermissions = parseServicePermissions(\n meta?.[\"requiredServicePermissions\"],\n );\n const asyncOperations = parseAsyncOperations(meta?.[\"asyncOperations\"]);\n const limitations =\n normalizeLimitations(\n meta?.[\"knownLimitations\"] ?? zuoraMeta?.[\"limitations\"],\n ) ?? [];\n\n return {\n bundle,\n operationPermissions,\n operationRiskLevels,\n asyncOperations,\n requiredServicePermissions,\n limitations,\n };\n};\n\nconst buildZuoraToolDefinition = (\n tool: McpToolMetadataInput,\n extracted: ExtractedToolMetadata,\n params: BuildParams,\n): ZuoraToolDefinition => {\n const asyncOperation = resolveAsyncOperation(extracted, params);\n const baseInputSchema = tool.inputSchema ?? {\n type: \"object\",\n additionalProperties: true,\n };\n // Infer the operation selector for split tools (to strip from inputSchema)\n // and for multi-op merged tools (to store on meta for runtime async lookup).\n const needsOperationSelector =\n (params.isSplit || params.isMultiOpMerged) &&\n extracted.operationPermissions !== undefined;\n const operationSelector = needsOperationSelector\n ? inferOperationSelector(baseInputSchema, extracted.operationPermissions!)\n : undefined;\n const inputSchema =\n params.isSplit && operationSelector\n ? omitSchemaProperty(baseInputSchema, operationSelector)\n : baseInputSchema;\n\n return {\n name: params.name,\n description: tool.description ?? params.name,\n inputSchema,\n ...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),\n meta: {\n bundle: extracted.bundle,\n access: params.access,\n riskLevel: resolveRiskLevel(extracted, params),\n ...(asyncOperation ? { asyncOperation } : {}),\n // Multi-op merged tool: store per-operation maps so callTool can look up\n // the correct access, risk, and async meta from the runtime input.\n ...(params.isMultiOpMerged && extracted.asyncOperations\n ? { asyncOperations: extracted.asyncOperations }\n : {}),\n ...(params.isMultiOpMerged && extracted.operationPermissions\n ? { operationAccess: extracted.operationPermissions }\n : {}),\n ...(params.isMultiOpMerged && extracted.operationRiskLevels\n ? { operationRiskLevel: extracted.operationRiskLevels }\n : {}),\n requiredServicePermissions: extracted.requiredServicePermissions,\n limitations: extracted.limitations,\n sourceName: tool.name,\n ...(operationSelector ? { operationSelector } : {}),\n ...(params.isSplit && params.operationName\n ? { operationName: params.operationName }\n : {}),\n },\n };\n};\n\nconst resolveRiskLevel = (\n extracted: ExtractedToolMetadata,\n params: BuildParams,\n): ZuoraRiskLevel => {\n const { operationRiskLevels } = extracted;\n\n if (operationRiskLevels) {\n if (params.isSplit && params.operationName) {\n return operationRiskLevels[params.operationName] ?? DEFAULT_RISK_LEVEL;\n }\n\n const highest = highestRiskLevel(Object.values(operationRiskLevels));\n if (highest) {\n return highest;\n }\n }\n\n return DEFAULT_RISK_LEVEL;\n};\n\nconst resolveAsyncOperation = (\n extracted: ExtractedToolMetadata,\n params: BuildParams,\n): ZuoraAsyncOperationMeta | undefined => {\n const { asyncOperations } = extracted;\n\n if (!asyncOperations) {\n return undefined;\n }\n\n if (params.isSplit && params.operationName) {\n return asyncOperations[params.operationName];\n }\n\n // Multi-op merged tool: suppress asyncOperation — the full map is stored\n // in meta.asyncOperations for runtime lookup by callTool.\n if (params.isMultiOpMerged) {\n return undefined;\n }\n\n // Single-op tool (no operationPermissions): unambiguous single async meta.\n return Object.values(asyncOperations)[0];\n};\n\nconst parseServicePermissions = (value: unknown): ZuoraServicePermission[] => {\n if (!Array.isArray(value)) {\n return [];\n }\n\n return value.flatMap((item) => {\n if (!isRecord(item)) {\n return [];\n }\n\n const scope = nonEmptyString(item[\"scope\"]);\n const name = nonEmptyString(item[\"name\"]);\n\n if (!scope || !name) {\n return [];\n }\n\n return [{ scope, name }];\n });\n};\n\nconst parseAsyncOperations = (\n value: unknown,\n): Record<string, ZuoraAsyncOperationMeta> | undefined => {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const result: Record<string, ZuoraAsyncOperationMeta> = {};\n\n for (const [opName, opValue] of Object.entries(value)) {\n const parsed = parseAsyncOperationMeta(opValue);\n if (parsed) {\n result[opName] = parsed;\n }\n }\n\n return Object.keys(result).length > 0 ? result : undefined;\n};\n\nconst parseAsyncOperationMeta = (\n value: unknown,\n): ZuoraAsyncOperationMeta | undefined => {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const pollingOperation = nonEmptyString(value[\"pollingOperation\"]);\n const pollingTool = nonEmptyString(value[\"pollingTool\"]);\n const jobIdPath = nonEmptyString(value[\"jobIdPath\"]);\n const statusPath = nonEmptyString(value[\"statusPath\"]);\n\n if ((!pollingOperation && !pollingTool) || !jobIdPath || !statusPath) {\n return undefined;\n }\n\n const terminalStatuses = parseTerminalStatuses(value[\"terminalStatuses\"]);\n if (!terminalStatuses) {\n return undefined;\n }\n\n const pollingArgs = parsePollingArgs(value[\"pollingArgs\"]);\n\n return {\n ...(pollingOperation ? { pollingOperation } : {}),\n ...(pollingTool ? { pollingTool } : {}),\n jobIdPath: normalizeMetadataPath(jobIdPath),\n statusPath: normalizeMetadataPath(statusPath),\n terminalStatuses,\n ...(pollingArgs ? { pollingArgs } : {}),\n ...(typeof value[\"recommendedPollIntervalMs\"] === \"number\"\n ? { recommendedPollIntervalMs: value[\"recommendedPollIntervalMs\"] }\n : {}),\n ...(typeof value[\"defaultTimeoutMs\"] === \"number\"\n ? { defaultTimeoutMs: value[\"defaultTimeoutMs\"] }\n : {}),\n ...(typeof value[\"maxPollAttempts\"] === \"number\"\n ? { maxPollAttempts: value[\"maxPollAttempts\"] }\n : {}),\n };\n};\n\nconst parsePollingArgs = (\n value: unknown,\n): Record<string, string> | undefined => {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const entries = Object.entries(value).flatMap(([key, entryValue]) =>\n typeof entryValue === \"string\" ? [[key, entryValue] as const] : [],\n );\n\n return entries.length > 0 ? Object.fromEntries(entries) : undefined;\n};\n\nconst parseTerminalStatuses = (\n value: unknown,\n): ZuoraAsyncOperationMeta[\"terminalStatuses\"] | undefined => {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const success = parseStringArray(value[\"success\"]);\n const failure = parseStringArray(value[\"failure\"]);\n\n if (!success || !failure) {\n return undefined;\n }\n\n return {\n success,\n failure,\n ...(Array.isArray(value[\"canceled\"])\n ? { canceled: parseStringArray(value[\"canceled\"]) ?? [] }\n : {}),\n };\n};\n\nconst parseStringArray = (value: unknown): string[] | undefined => {\n if (!Array.isArray(value)) {\n return undefined;\n }\n\n const strings = value.filter((entry): entry is string => typeof entry === \"string\");\n return strings.length > 0 ? strings : undefined;\n};\n\nconst normalizeOperationPermissions = (\n value: unknown,\n toolName: string,\n): Record<string, ZuoraToolOperation> | undefined => {\n const direct = normalizeOperation(value);\n\n if (direct) {\n return { [toolName]: direct };\n }\n\n if (!isRecord(value)) {\n return undefined;\n }\n\n const entries = Object.entries(value).flatMap(([operationName, rawValue]) => {\n const operation = normalizeOperation(rawValue);\n return operation ? [[operationName, operation] as const] : [];\n });\n\n return entries.length > 0 ? Object.fromEntries(entries) : undefined;\n};\n\nconst aggregateOperation = (\n operationPermissions: Record<string, ZuoraToolOperation> | undefined,\n): ZuoraToolOperation | undefined => {\n if (!operationPermissions) {\n return undefined;\n }\n\n return Object.values(operationPermissions).includes(\"write\") ? \"write\" : \"read\";\n};\n\nconst normalizeRiskLevels = (\n value: unknown,\n toolName: string,\n): Record<string, ZuoraRiskLevel> | undefined => {\n const direct = normalizeRiskLevel(value);\n\n if (direct) {\n return { [toolName]: direct };\n }\n\n if (!isRecord(value)) {\n return undefined;\n }\n\n const entries = Object.entries(value).flatMap(([operationName, rawValue]) => {\n const riskLevel = normalizeRiskLevel(rawValue);\n return riskLevel ? [[operationName, riskLevel] as const] : [];\n });\n\n return entries.length > 0 ? Object.fromEntries(entries) : undefined;\n};\n\nconst normalizeRiskLevel = (value: unknown): ZuoraRiskLevel | undefined => {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const normalized = value.trim().toLowerCase();\n\n if (normalized === \"low\" || normalized === \"medium\" || normalized === \"high\") {\n return normalized;\n }\n\n return undefined;\n};\n\nconst highestRiskLevel = (\n riskLevels: ZuoraRiskLevel[],\n): ZuoraRiskLevel | undefined => {\n let highest: ZuoraRiskLevel | undefined;\n\n for (const riskLevel of riskLevels) {\n if (!highest || RISK_RANK[riskLevel] > RISK_RANK[highest]) {\n highest = riskLevel;\n }\n }\n\n return highest;\n};\n\nconst normalizeOperation = (value: unknown): ZuoraToolOperation | undefined => {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const normalized = value.trim().toLowerCase();\n\n if (\n normalized === \"read\" ||\n normalized === \"readonly\" ||\n normalized === \"read_only\"\n ) {\n return \"read\";\n }\n\n if (normalized === \"write\" || normalized === \"mutation\") {\n return \"write\";\n }\n\n return undefined;\n};\n\nconst normalizeStringList = (value: unknown): string[] =>\n uniqueStrings(collectStrings(value));\n\nconst normalizeLimitations = (value: unknown): string[] | undefined => {\n const limitations = normalizeStringList(value);\n return limitations.length > 0 ? limitations : undefined;\n};\n\nconst collectStrings = (value: unknown): string[] => {\n const direct = nonEmptyString(value);\n\n if (direct) {\n return [direct];\n }\n\n if (Array.isArray(value)) {\n return value.flatMap(collectStrings);\n }\n\n if (isRecord(value)) {\n return Object.values(value).flatMap(collectStrings);\n }\n\n return [];\n};\n\nconst uniqueStrings = (values: string[]): string[] => [...new Set(values)];\n","export const redactSensitiveString = (\n value: string,\n sensitiveValues: readonly string[],\n): string =>\n sensitiveValues.reduce(\n (redacted, sensitiveValue) =>\n sensitiveValue ? redacted.split(sensitiveValue).join(\"[REDACTED]\") : redacted,\n value,\n );\n\nexport const redactSensitiveDetails = (\n value: unknown,\n sensitiveValues: readonly string[],\n): unknown => {\n if (typeof value === \"string\") {\n return redactSensitiveString(value, sensitiveValues);\n }\n\n if (value instanceof Error) {\n return {\n name: value.name,\n message: redactSensitiveString(value.message, sensitiveValues),\n };\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => redactSensitiveDetails(item, sensitiveValues));\n }\n\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value).map(([key, entry]) => [\n key,\n redactSensitiveDetails(entry, sensitiveValues),\n ]),\n );\n }\n\n return value;\n};\n","import { ZuoraAgentToolkitError } from \"../errors.js\";\nimport { isStagingZuoraBaseUrl } from \"../utils/zuora-url.js\";\nimport {\n redactSensitiveDetails,\n redactSensitiveString,\n} from \"../utils/redaction.js\";\nimport type {\n OAuthTokenResponse,\n OAuthTokenSuccess,\n ResolvedZuoraConnectionConfig,\n} from \"./connection-types.js\";\n\nconst TOKEN_REFRESH_SKEW_MAX_MS = 60_000;\nconst DEFAULT_TOKEN_EXPIRES_IN_SECONDS = 3600;\n\nexport class OAuthTokenProvider {\n private accessToken: string | undefined;\n\n private tokenIssuedAt = 0;\n\n private tokenExpiresAt = 0;\n\n private tenantId: string | undefined;\n\n private preferredTokenEndpoint: string | undefined;\n\n constructor(\n private readonly config: ResolvedZuoraConnectionConfig,\n private readonly restBaseUrl: string,\n ) {}\n\n async ensureAccessToken(): Promise<string> {\n if (!this.config.auth) {\n throw new ZuoraAgentToolkitError({\n code: \"MISSING_AUTH\",\n message:\n \"Zuora auth configuration is required unless tenant auth is enabled.\",\n category: \"auth\",\n });\n }\n\n const now = Date.now();\n\n if (this.accessToken && this.isAccessTokenFresh(now)) {\n return this.accessToken;\n }\n\n const token = await this.fetchOAuthToken();\n\n this.accessToken = token.access_token;\n this.tokenIssuedAt = now;\n this.tokenExpiresAt =\n now + (token.expires_in ?? DEFAULT_TOKEN_EXPIRES_IN_SECONDS) * 1000;\n this.tenantId = extractTenantId(token.scope);\n\n return this.accessToken;\n }\n\n getTenantId(): string | undefined {\n return this.tenantId;\n }\n\n invalidateAccessToken(): void {\n this.accessToken = undefined;\n this.tokenIssuedAt = 0;\n this.tokenExpiresAt = 0;\n }\n\n sensitiveValues(): string[] {\n const values = [this.accessToken];\n const auth = this.config.auth;\n\n if (auth?.clientSecret) {\n values.push(auth.clientSecret);\n }\n\n return values.filter(\n (value): value is string => typeof value === \"string\" && value.length > 0,\n );\n }\n\n private isAccessTokenFresh(now: number): boolean {\n const tokenLifetimeMs = Math.max(0, this.tokenExpiresAt - this.tokenIssuedAt);\n const refreshSkewMs = Math.min(\n TOKEN_REFRESH_SKEW_MAX_MS,\n Math.floor(tokenLifetimeMs / 10),\n );\n\n return now < this.tokenExpiresAt - refreshSkewMs;\n }\n\n private async fetchOAuthToken(): Promise<OAuthTokenSuccess> {\n const endpoints = await this.resolveTokenEndpoints();\n let lastFailure: ZuoraAgentToolkitError | undefined;\n const attempts: Array<{\n tokenEndpoint: string;\n code: string;\n message: string;\n retryable: boolean;\n details?: unknown;\n }> = [];\n\n for (const endpoint of endpoints) {\n try {\n const token = await this.requestOAuthToken(endpoint);\n this.preferredTokenEndpoint = endpoint;\n return token;\n } catch (error) {\n if (error instanceof ZuoraAgentToolkitError) {\n lastFailure = error;\n attempts.push({\n tokenEndpoint: endpoint,\n code: error.code,\n message: error.message,\n retryable: error.retryable,\n details: error.details,\n });\n } else {\n lastFailure = new ZuoraAgentToolkitError({\n code: \"OAUTH_TOKEN_ERROR\",\n message: this.redactString(\n error instanceof Error ? error.message : String(error),\n ),\n category: \"auth\",\n retryable: true,\n recoverable: true,\n details: this.redactDetails(error),\n });\n attempts.push({\n tokenEndpoint: endpoint,\n code: lastFailure.code,\n message: lastFailure.message,\n retryable: lastFailure.retryable,\n details: lastFailure.details,\n });\n }\n }\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"OAUTH_TOKEN_ERROR\",\n message:\n lastFailure?.message ??\n \"OAuth token request failed against all configured endpoints.\",\n category: \"auth\",\n retryable: attempts.some((attempt) => attempt.retryable),\n recoverable: true,\n details: this.redactDetails({ attempts }),\n });\n }\n\n private async resolveTokenEndpoints(): Promise<string[]> {\n const restEndpoint = `${this.restBaseUrl}/oauth/token`;\n const oneIdEndpoint = isStagingZuoraBaseUrl(this.restBaseUrl)\n ? \"https://one.stg.na.zuora.com/oauth2/token\"\n : \"https://one.zuora.com/oauth2/token\";\n const endpoints = [restEndpoint, oneIdEndpoint];\n const uniqueEndpoints = [...new Set(endpoints)];\n\n if (!this.preferredTokenEndpoint) {\n return uniqueEndpoints;\n }\n\n return [\n this.preferredTokenEndpoint,\n ...uniqueEndpoints.filter(\n (endpoint) => endpoint !== this.preferredTokenEndpoint,\n ),\n ];\n }\n\n private async requestOAuthToken(\n tokenEndpoint: string,\n ): Promise<OAuthTokenSuccess> {\n if (!this.config.auth) {\n throw new ZuoraAgentToolkitError({\n code: \"UNSUPPORTED_AUTH\",\n message: \"Unsupported auth configuration for Zuora HTTP MCP client.\",\n category: \"auth\",\n });\n }\n\n const body = new URLSearchParams({ grant_type: \"client_credentials\" });\n const headers: Record<string, string> = {\n \"content-type\": \"application/x-www-form-urlencoded\",\n accept: \"application/json\",\n };\n const auth = this.config.auth;\n\n // Always use client_secret_post (hardcoded default)\n body.set(\"client_id\", auth.clientId);\n body.set(\"client_secret\", auth.clientSecret);\n\n const response = await fetch(tokenEndpoint, {\n method: \"POST\",\n headers,\n body,\n });\n\n const token = (await response\n .json()\n .catch(() => ({}))) as OAuthTokenResponse;\n\n if (!response.ok || !token.access_token) {\n const oauthError =\n typeof token.error === \"string\" && token.error.trim()\n ? token.error.trim()\n : undefined;\n const oauthDescription =\n typeof token.error_description === \"string\" &&\n token.error_description.trim()\n ? token.error_description.trim()\n : undefined;\n\n const summary = oauthDescription\n ? oauthError && oauthError !== oauthDescription\n ? `${oauthError}: ${oauthDescription}`\n : oauthDescription\n : (oauthError ?? `OAuth token request failed with HTTP ${response.status}.`);\n\n throw new ZuoraAgentToolkitError({\n code: \"OAUTH_TOKEN_ERROR\",\n message: this.redactString(`${summary} (HTTP ${response.status})`),\n category: \"auth\",\n retryable: response.status >= 500,\n recoverable: true,\n details: this.redactDetails({\n tokenEndpoint,\n status: response.status,\n ...(oauthError ? { error: oauthError } : {}),\n ...(oauthDescription ? { errorDescription: oauthDescription } : {}),\n }),\n });\n }\n\n return {\n access_token: token.access_token,\n ...(typeof token.expires_in === \"number\"\n ? { expires_in: token.expires_in }\n : {}),\n ...(token.scope ? { scope: token.scope } : {}),\n };\n }\n\n private redactString(value: string): string {\n return redactSensitiveString(value, this.sensitiveValues());\n }\n\n private redactDetails(value: unknown): unknown {\n return redactSensitiveDetails(value, this.sensitiveValues());\n }\n}\n\nconst extractTenantId = (scope?: string): string | undefined => {\n const tenantMatch = scope?.match(/tenant\\.(\\d+)/);\n return tenantMatch?.[1];\n};\n","import type {\n EnabledTenantAuth,\n ResolvedZuoraConnectionConfig,\n} from \"./connection-types.js\";\n\nconst RESERVED_HEADER_NAMES = new Set([\n \"accept\",\n \"authorization\",\n \"content-type\",\n \"mcp-session-id\",\n \"user-agent\",\n \"zuora-entity-ids\",\n \"zuora-org-ids\",\n \"zuora-tenant-id\",\n \"zuora-token-id\",\n \"zuora-user-id\",\n]);\n\nexport type ZuoraRequestHeaderOptions = {\n accessToken?: string;\n userAgent: string;\n accept: string;\n contentType?: string;\n};\n\nexport const buildZuoraRequestHeaders = (\n config: ResolvedZuoraConnectionConfig,\n options: ZuoraRequestHeaderOptions,\n): Record<string, string> => {\n const tenantAuth = enabledTenantAuth(config);\n\n return {\n ...(options.accessToken\n ? { authorization: `Bearer ${options.accessToken}` }\n : {}),\n ...(options.contentType ? { \"content-type\": options.contentType } : {}),\n accept: options.accept,\n \"user-agent\": options.userAgent,\n ...sanitizeConfiguredHeaders(config),\n ...(config.zuoraVersion ? { \"zuora-version\": config.zuoraVersion } : {}),\n ...(tenantAuth\n ? tenantAuthHeaders(config, tenantAuth)\n : scopeHeaders(config)),\n };\n};\n\nexport const enabledTenantAuth = (\n config: ResolvedZuoraConnectionConfig,\n): EnabledTenantAuth | undefined => {\n const tenantAuth = config.tenantAuth;\n return tenantAuth?.enabled === true ? tenantAuth : undefined;\n};\n\nconst sanitizeConfiguredHeaders = (\n config: ResolvedZuoraConnectionConfig,\n): Record<string, string> =>\n Object.fromEntries(\n Object.entries(config.headers ?? {}).filter(\n (entry): entry is [string, string] =>\n Boolean(entry[1]) && !RESERVED_HEADER_NAMES.has(entry[0].toLowerCase()),\n ),\n );\n\nconst tenantAuthHeaders = (\n config: ResolvedZuoraConnectionConfig,\n tenantAuth: EnabledTenantAuth,\n): Record<string, string> => {\n const entityIds = headerListValue(config.entityIds);\n const orgIds = headerListValue(config.orgIds);\n\n return {\n ...(entityIds ? { \"Zuora-Entity-Ids\": entityIds } : {}),\n ...(orgIds ? { \"Zuora-Org-Ids\": orgIds } : {}),\n \"Zuora-Tenant-Id\": tenantAuth.tenantId,\n \"Zuora-Token-Id\": tenantAuth.tokenId,\n \"Zuora-User-Id\": tenantAuth.userId,\n };\n};\n\nconst scopeHeaders = (\n config: ResolvedZuoraConnectionConfig,\n): Record<string, string> => {\n const entityIds = headerListValue(config.entityIds);\n const orgIds = headerListValue(config.orgIds);\n\n return {\n ...(entityIds ? { \"zuora-entity-ids\": entityIds } : {}),\n ...(orgIds ? { \"zuora-org-ids\": orgIds } : {}),\n };\n};\n\nconst headerListValue = (value?: string | string[]): string | undefined => {\n if (!value) {\n return undefined;\n }\n\n if (Array.isArray(value)) {\n const normalized = value.map((item) => item.trim()).filter(Boolean);\n return normalized.length > 0 ? normalized.join(\",\") : undefined;\n }\n\n const normalized = value.trim();\n return normalized || undefined;\n};\n","import type { ZuoraHttpMcpClientConfig } from \"../types.js\";\nimport type { ResolvedZuoraConnectionConfig } from \"./connection-types.js\";\n\nexport const resolveZuoraConnectionConfig = (\n config: ZuoraHttpMcpClientConfig,\n mcpUrl: string,\n): ResolvedZuoraConnectionConfig => ({\n clientName: config.clientName ?? \"zuora-agent-toolkit\",\n clientVersion: config.clientVersion ?? \"0.1.0\",\n protocolVersion: config.protocolVersion ?? \"2025-03-26\",\n url: mcpUrl,\n ...(config.auth ? { auth: config.auth } : {}),\n ...(config.headers ? { headers: config.headers } : {}),\n ...(config.tenantAuth ? { tenantAuth: config.tenantAuth } : {}),\n ...(config.entityIds ? { entityIds: config.entityIds } : {}),\n ...(config.orgIds ? { orgIds: config.orgIds } : {}),\n ...(config.zuoraVersion ? { zuoraVersion: config.zuoraVersion } : {}),\n});\n","import { ZuoraAgentToolkitError } from \"../errors.js\";\nimport type { ZuoraHttpMcpClientConfig } from \"../types.js\";\nimport { normalizeZuoraMcpUrl } from \"../utils/zuora-url.js\";\nimport type {\n EnabledTenantAuth,\n ResolvedZuoraConnectionConfig,\n} from \"./connection-types.js\";\nimport { OAuthTokenProvider } from \"./oauth-token-provider.js\";\nimport {\n buildZuoraRequestHeaders,\n enabledTenantAuth,\n type ZuoraRequestHeaderOptions,\n} from \"./request-headers.js\";\nimport { resolveZuoraConnectionConfig } from \"./resolve-connection-config.js\";\n\nexport type ZuoraClientSharedState = {\n connection: ResolvedZuoraConnectionConfig;\n tokenProvider: OAuthTokenProvider;\n restBaseUrl: string;\n maxDownloadBytes?: number;\n};\n\nexport type CreateZuoraClientOptions = ZuoraHttpMcpClientConfig & {\n maxDownloadBytes?: number;\n};\n\nexport class ZuoraClient {\n protected constructor(protected readonly shared: ZuoraClientSharedState) {}\n\n static createSharedState(\n config: CreateZuoraClientOptions,\n ): ZuoraClientSharedState {\n const { remoteUrl, restBaseUrl } = normalizeZuoraMcpUrl(config.url);\n const connection = resolveZuoraConnectionConfig(config, remoteUrl);\n const normalizedRestBaseUrl = restBaseUrl.replace(/\\/+$/, \"\");\n\n return {\n connection,\n tokenProvider: new OAuthTokenProvider(\n connection,\n normalizedRestBaseUrl,\n ),\n restBaseUrl: normalizedRestBaseUrl,\n ...(typeof config.maxDownloadBytes === \"number\"\n ? { maxDownloadBytes: config.maxDownloadBytes }\n : {}),\n };\n }\n\n protected get connection(): ResolvedZuoraConnectionConfig {\n return this.shared.connection;\n }\n\n protected get tokenProvider(): OAuthTokenProvider {\n return this.shared.tokenProvider;\n }\n\n protected get restBaseUrl(): string {\n return this.shared.restBaseUrl;\n }\n\n protected get maxDownloadBytes(): number | undefined {\n return this.shared.maxDownloadBytes;\n }\n\n getTenantId(): string | undefined {\n return (\n this.enabledTenantAuth()?.tenantId ?? this.tokenProvider.getTenantId()\n );\n }\n\n protected async restGet(\n path: string,\n options: { signal?: AbortSignal } = {},\n ): Promise<Response> {\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n const url = `${this.restBaseUrl}${normalizedPath}`;\n const retryAttempts = this.enabledTenantAuth() ? [false] : [false, true];\n\n for (const retry of retryAttempts) {\n const response = await fetch(url, {\n method: \"GET\",\n headers: await this.buildHeaders({\n accept: \"*/*\",\n }),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n\n if (\n !retry &&\n (response.status === 401 || response.status === 403) &&\n !this.enabledTenantAuth()\n ) {\n this.tokenProvider.invalidateAccessToken();\n continue;\n }\n\n return response;\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"ZUORA_REST_AUTH_RETRY_FAILED\",\n message: \"Zuora REST request failed after auth retry.\",\n category: \"auth\",\n });\n }\n\n protected async buildHeaders(\n options: Pick<ZuoraRequestHeaderOptions, \"accept\" | \"contentType\">,\n ): Promise<Record<string, string>> {\n const tenantAuth = this.enabledTenantAuth();\n const accessToken = tenantAuth\n ? undefined\n : await this.tokenProvider.ensureAccessToken();\n\n return buildZuoraRequestHeaders(this.connection, {\n ...(accessToken ? { accessToken } : {}),\n userAgent: `${this.connection.clientName}/${this.connection.clientVersion}`,\n accept: options.accept,\n ...(options.contentType ? { contentType: options.contentType } : {}),\n });\n }\n\n protected enabledTenantAuth(): EnabledTenantAuth | undefined {\n return enabledTenantAuth(this.connection);\n }\n}\n","import { ZuoraAgentToolkitError } from \"../errors.js\";\nimport {\n ZuoraClient,\n type ZuoraClientSharedState,\n} from \"./zuora-client.js\";\n\nexport type ZuoraRestDownloadFileResult = {\n bytes: Uint8Array;\n contentType?: string;\n contentDisposition?: string;\n};\n\nexport class ZuoraRestClient extends ZuoraClient {\n constructor(shared: ZuoraClientSharedState) {\n super(shared);\n }\n\n async downloadFile(\n fileId: string,\n options: { signal?: AbortSignal } = {},\n ): Promise<ZuoraRestDownloadFileResult> {\n const normalizedFileId = fileId.trim();\n\n if (!normalizedFileId) {\n throw new ZuoraAgentToolkitError({\n code: \"INVALID_INPUT\",\n message: \"fileId is required for Zuora REST file download.\",\n category: \"validation\",\n recoverable: true,\n });\n }\n\n const response = await this.restGet(\n `/v1/files/${encodeURIComponent(normalizedFileId)}`,\n options,\n );\n\n if (!response.ok) {\n throw new ZuoraAgentToolkitError({\n code: \"ZUORA_REST_FILE_DOWNLOAD_FAILED\",\n message: `Zuora REST file download failed with HTTP ${response.status}.`,\n category: response.status === 404 ? \"validation\" : \"mcp\",\n retryable: response.status >= 500,\n recoverable: response.status === 404,\n details: {\n fileId: normalizedFileId,\n status: response.status,\n },\n });\n }\n\n const bytes = await readResponseBytes(response, this.maxDownloadBytes);\n const contentType = response.headers.get(\"content-type\");\n const contentDisposition = response.headers.get(\"content-disposition\");\n\n return {\n bytes,\n ...(contentType ? { contentType } : {}),\n ...(contentDisposition ? { contentDisposition } : {}),\n };\n }\n}\n\nconst readResponseBytes = async (\n response: Response,\n maxDownloadBytes: number | undefined,\n): Promise<Uint8Array> => {\n if (!response.body) {\n const buffer = new Uint8Array(await response.arrayBuffer());\n\n if (\n typeof maxDownloadBytes === \"number\" &&\n buffer.byteLength > maxDownloadBytes\n ) {\n throw new ZuoraAgentToolkitError({\n code: \"ZUORA_REST_FILE_TOO_LARGE\",\n message: `Zuora REST file download exceeded ${maxDownloadBytes} bytes.`,\n category: \"validation\",\n recoverable: true,\n });\n }\n\n return buffer;\n }\n\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let totalBytes = 0;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (!value) {\n continue;\n }\n\n totalBytes += value.byteLength;\n\n if (typeof maxDownloadBytes === \"number\" && totalBytes > maxDownloadBytes) {\n throw new ZuoraAgentToolkitError({\n code: \"ZUORA_REST_FILE_TOO_LARGE\",\n message: `Zuora REST file download exceeded ${maxDownloadBytes} bytes.`,\n category: \"validation\",\n recoverable: true,\n });\n }\n\n chunks.push(value);\n }\n\n const bytes = new Uint8Array(totalBytes);\n let offset = 0;\n\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return bytes;\n};\n","import { SafetyMode } from \"./types.js\";\nimport type {\n BundleConfiguration,\n ToolkitBundleName,\n ToolSelection,\n ZuoraSafetyMode,\n ZuoraToolkitConfiguration,\n} from \"./types.js\";\n\nexport type ToolSelectionPolicy = {\n mode: ZuoraSafetyMode;\n bundles: Set<ToolkitBundleName>;\n include: Set<string>;\n exclude: Set<string>;\n};\n\nexport const resolveToolSelectionPolicy = (\n configuration: ZuoraToolkitConfiguration | undefined,\n selection?: ToolSelection,\n): ToolSelectionPolicy => ({\n mode: resolveToolMode(configuration, selection),\n bundles: resolveBundles(configuration, selection),\n include: new Set([\n ...resolveIncludedToolNames(configuration),\n ...(selection?.include ?? []),\n ]),\n exclude: new Set([\n ...resolveExcludedToolNames(configuration),\n ...(selection?.exclude ?? []),\n ]),\n});\n\nexport const resolveToolMode = (\n configuration: ZuoraToolkitConfiguration | undefined,\n selection?: ToolSelection,\n): ZuoraSafetyMode => selection?.mode ?? configuration?.mode ?? SafetyMode.ReadOnly;\n\nexport const resolveExcludedToolNames = (\n configuration: ZuoraToolkitConfiguration | undefined,\n): Set<string> =>\n new Set([\n ...resolveConfiguredExcludedToolNames(configuration),\n ...resolveBundleExcludedToolNames(configuration),\n ]);\n\nconst resolveBundles = (\n configuration: ZuoraToolkitConfiguration | undefined,\n selection?: ToolSelection,\n): Set<ToolkitBundleName> => {\n if (selection?.bundles) {\n return new Set(selection.bundles);\n }\n\n const configured = configuration?.bundles;\n\n if (!configured) {\n return new Set();\n }\n\n return new Set(\n Object.entries(configured)\n .filter(([, value]) => Boolean(value))\n .map(([name]) => name as ToolkitBundleName),\n );\n};\n\nconst resolveIncludedToolNames = (\n configuration: ZuoraToolkitConfiguration | undefined,\n): string[] => {\n const tools = configuration?.tools ?? {};\n\n return Object.entries(tools)\n .filter(([, enabled]) => enabled)\n .map(([name]) => name);\n};\n\nconst resolveConfiguredExcludedToolNames = (\n configuration: ZuoraToolkitConfiguration | undefined,\n): string[] => {\n const tools = configuration?.tools ?? {};\n\n return Object.entries(tools)\n .filter(([, enabled]) => !enabled)\n .map(([name]) => name);\n};\n\nconst resolveBundleExcludedToolNames = (\n configuration: ZuoraToolkitConfiguration | undefined,\n): string[] => {\n const bundles = configuration?.bundles ?? {};\n\n return Object.values(bundles).flatMap((value) => {\n if (typeof value === \"object\" && value) {\n const config = value as BundleConfiguration;\n return config.exclude ?? [];\n }\n\n return [];\n });\n};\n","import type { McpToolCallResult } from \"./mcp-types.js\";\n\n/**\n * Extracts a human-readable error message from an MCP tools/call error result.\n */\nexport const extractMcpToolErrorMessage = (\n result: McpToolCallResult,\n): string | undefined => {\n if (Array.isArray(result.content)) {\n for (const item of result.content) {\n if (\n item != null &&\n typeof item === \"object\" &&\n \"text\" in item &&\n typeof (item as { text?: unknown }).text === \"string\"\n ) {\n const text = (item as { text: string }).text.trim();\n if (text) {\n return text;\n }\n }\n }\n }\n\n if (result.structuredContent != null) {\n if (\n typeof result.structuredContent === \"object\" &&\n result.structuredContent !== null &&\n \"message\" in result.structuredContent &&\n typeof (result.structuredContent as { message?: unknown }).message ===\n \"string\"\n ) {\n return (result.structuredContent as { message: string }).message;\n }\n\n // Do not serialize the full structuredContent — it may contain raw MCP\n // response body fields that should not appear in error messages per the\n // security guidance. Use a generic fallback instead.\n return \"MCP tool call returned a structured error response.\";\n }\n\n return undefined;\n};\n","import { ZuoraAgentToolkitError } from \"../errors.js\";\nimport {\n redactSensitiveDetails,\n redactSensitiveString,\n} from \"../utils/redaction.js\";\nimport type { JsonRpcResponse } from \"./mcp-types.js\";\n\nexport const parseJsonRpcResponse = async <T>({\n response,\n sensitiveValues,\n}: {\n response: Response;\n sensitiveValues: readonly string[];\n}): Promise<T> => {\n const text = await response.text();\n\n if (!response.ok) {\n throw new ZuoraAgentToolkitError({\n code: \"MCP_HTTP_ERROR\",\n message: `Zuora MCP request failed with HTTP ${response.status}.`,\n category:\n response.status === 401 || response.status === 403 ? \"auth\" : \"mcp\",\n retryable: response.status >= 500,\n details: redactSensitiveString(text, sensitiveValues),\n });\n }\n\n if (!text.trim()) {\n return {} as T;\n }\n\n const json = parseResponseBody(text, response.headers.get(\"content-type\"));\n\n if (json.error) {\n throw new ZuoraAgentToolkitError({\n code: \"MCP_JSON_RPC_ERROR\",\n message: redactSensitiveString(json.error.message, sensitiveValues),\n category: \"mcp\",\n details: redactSensitiveDetails(json.error, sensitiveValues),\n });\n }\n\n return (json.result ?? {}) as T;\n};\n\nconst parseResponseBody = (\n text: string,\n contentType: string | null,\n): JsonRpcResponse<unknown> => {\n if (contentType?.includes(\"text/event-stream\")) {\n const dataLines = text\n .split(/\\r?\\n/)\n .filter((line) => line.startsWith(\"data:\"))\n .map((line) => line.slice(\"data:\".length).trim())\n .filter((line) => line && line !== \"[DONE]\");\n\n const payload = dataLines.find((line) => line.startsWith(\"{\"));\n\n if (!payload) {\n return {};\n }\n\n return JSON.parse(payload) as JsonRpcResponse<unknown>;\n }\n\n return JSON.parse(text) as JsonRpcResponse<unknown>;\n};\n","import { ZuoraAgentToolkitError } from \"../errors.js\";\nimport type {\n ZuoraHttpMcpClientConfig,\n ZuoraToolExecutionResult,\n} from \"../types.js\";\nimport { extractMcpToolErrorMessage } from \"./mcp-tool-error.js\";\nimport { parseJsonRpcResponse } from \"./json-rpc.js\";\nimport { normalizeExecutionRequestMetadata } from \"./request-metadata.js\";\nimport type {\n McpInitializeResult,\n McpReadResourceResult,\n McpTool,\n McpToolCallResult,\n McpToolsListResult,\n} from \"./mcp-types.js\";\nimport {\n ZuoraClient,\n type ZuoraClientSharedState,\n} from \"./zuora-client.js\";\n\nexport class ZuoraHttpMcpClient extends ZuoraClient {\n private mcpRequestId = 0;\n\n private mcpInitialized = false;\n\n private mcpSessionId: string | undefined;\n\n constructor(config: ZuoraHttpMcpClientConfig) {\n super(ZuoraClient.createSharedState(config));\n }\n\n /** @internal Used by ZuoraRestClient via shared state injection. */\n static fromSharedState(shared: ZuoraClientSharedState): ZuoraHttpMcpClient {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- bypass private constructor\n const instance = Object.create(ZuoraHttpMcpClient.prototype) as ZuoraHttpMcpClient;\n (instance as unknown as { shared: ZuoraClientSharedState }).shared = shared;\n instance.mcpRequestId = 0;\n instance.mcpInitialized = false;\n instance.mcpSessionId = undefined;\n return instance;\n }\n\n async initialize(): Promise<void> {\n if (!this.enabledTenantAuth()) {\n await this.tokenProvider.ensureAccessToken();\n }\n\n if (this.mcpInitialized) {\n return;\n }\n\n await this.postMcpJsonRpc<McpInitializeResult>(\"initialize\", {\n protocolVersion: this.connection.protocolVersion,\n capabilities: {},\n clientInfo: {\n name: this.connection.clientName,\n version: this.connection.clientVersion,\n },\n });\n\n await this.postMcpNotification(\"notifications/initialized\");\n this.mcpInitialized = true;\n }\n\n async listTools(): Promise<McpTool[]> {\n await this.initialize();\n\n const result = await this.postMcpJsonRpc<McpToolsListResult>(\n \"tools/list\",\n {},\n );\n return result.tools ?? [];\n }\n\n async callTool(\n name: string,\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n await this.initialize();\n\n const result = await this.postMcpJsonRpc<McpToolCallResult>(\"tools/call\", {\n name,\n arguments: input,\n });\n\n if (result.isError) {\n const mcpMessage = extractMcpToolErrorMessage(result);\n throw new ZuoraAgentToolkitError({\n code: \"TOOL_EXECUTION_ERROR\",\n message:\n mcpMessage ??\n `Zuora MCP tool \"${name}\" returned an error.`,\n category: \"tool_execution\",\n });\n }\n\n const request = normalizeExecutionRequestMetadata(result.request);\n const requestId = request?.requestId ?? request?.zuoraRequestId;\n\n return {\n toolName: name,\n data: result.structuredContent ?? result.content ?? result,\n ...(requestId ? { requestId } : {}),\n ...(request ? { request } : {}),\n };\n }\n\n async readResource(uri: string): Promise<McpReadResourceResult> {\n await this.initialize();\n\n return this.postMcpJsonRpc<McpReadResourceResult>(\"resources/read\", {\n uri,\n });\n }\n\n getSensitiveValues(): readonly string[] {\n return this.tokenProvider.sensitiveValues();\n }\n\n async close(): Promise<void> {\n this.mcpInitialized = false;\n this.mcpSessionId = undefined;\n }\n\n private async postMcpJsonRpc<T>(\n method: string,\n params: Record<string, unknown>,\n ): Promise<T> {\n const id = ++this.mcpRequestId;\n const retryAttempts = this.enabledTenantAuth() ? [false] : [false, true];\n\n for (const retry of retryAttempts) {\n const response = await fetch(this.connection.url, {\n method: \"POST\",\n headers: await this.buildMcpHeaders(),\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id,\n method,\n params,\n }),\n });\n\n const sessionId = response.headers.get(\"mcp-session-id\");\n if (sessionId) {\n this.mcpSessionId = sessionId;\n }\n\n try {\n return await parseJsonRpcResponse<T>({\n response,\n sensitiveValues: this.tokenProvider.sensitiveValues(),\n });\n } catch (error) {\n if (\n retry ||\n !(error instanceof ZuoraAgentToolkitError) ||\n error.category !== \"auth\"\n ) {\n throw error;\n }\n\n this.tokenProvider.invalidateAccessToken();\n }\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"MCP_AUTH_RETRY_FAILED\",\n message: `MCP request ${method} failed after auth retry.`,\n category: \"auth\",\n });\n }\n\n private async postMcpNotification(method: string): Promise<void> {\n const retryAttempts = this.enabledTenantAuth() ? [false] : [false, true];\n\n for (const retry of retryAttempts) {\n const response = await fetch(this.connection.url, {\n method: \"POST\",\n headers: await this.buildMcpHeaders(),\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n method,\n }),\n });\n\n const sessionId = response.headers.get(\"mcp-session-id\");\n if (sessionId) {\n this.mcpSessionId = sessionId;\n }\n\n if (response.ok) {\n return;\n }\n\n const error = new ZuoraAgentToolkitError({\n code: \"MCP_NOTIFICATION_FAILED\",\n message: `MCP notification ${method} failed with HTTP ${response.status}.`,\n category:\n response.status === 401 || response.status === 403 ? \"auth\" : \"mcp\",\n retryable: response.status >= 500,\n });\n\n if (retry || error.category !== \"auth\") {\n throw error;\n }\n\n this.tokenProvider.invalidateAccessToken();\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"MCP_AUTH_RETRY_FAILED\",\n message: `MCP notification ${method} failed after auth retry.`,\n category: \"auth\",\n });\n }\n\n private async buildMcpHeaders(): Promise<Record<string, string>> {\n const baseHeaders = await this.buildHeaders({\n accept: \"application/json, text/event-stream\",\n contentType: \"application/json\",\n });\n\n return {\n ...baseHeaders,\n ...(this.mcpSessionId ? { \"mcp-session-id\": this.mcpSessionId } : {}),\n };\n }\n}\n","import { enforceApproval } from \"./approval-policy.js\";\nimport {\n buildAsyncJobResult,\n DEFAULT_ASYNC_JOB_TERMINAL_STATUSES,\n resolveAsyncJobStatusDetails,\n type ZuoraAsyncJobResult,\n} from \"./async-jobs.js\";\nimport {\n getBundleDefinition,\n hasBundleDefinition,\n ZUORA_BUNDLE_NAMES,\n} from \"./bundles.js\";\nimport { ZuoraAgentToolkitError } from \"./errors.js\";\nimport {\n createMcpToolInput,\n enforceOperationSelector,\n} from \"./tools/operation-metadata.js\";\nimport {\n compactToolkitError,\n metadataLoadedEventMetadata,\n normalizeToolkitEvent,\n reportObservabilitySinkError,\n type InternalToolkitEvent,\n} from \"./observability/events.js\";\nimport {\n logAsyncPollChecked,\n type AsyncPollTerminationDecision,\n} from \"./observability/async-poll-events.js\";\nimport {\n compactToolInputForEvent,\n compactToolOutputForEvent,\n} from \"./observability/payloads.js\";\nimport { extractExecutionRequestMetadata } from \"./observability/request-metadata.js\";\nimport { NativeFileArtifactTools } from \"./tools/native/file-artifacts/index.js\";\nimport { resolveNativeFileToolsInput } from \"./tools/native/resolve-native-file-tools-input.js\";\nimport { resolveNativeQueryResultDownloadConfig } from \"./tools/native/query-result-download/config.js\";\nimport { resolveQueryResultStatusCall } from \"./tools/native/query-result-download/helpers/status-resolver.js\";\nimport { NativeQueryResultDownloadTools } from \"./tools/native/query-result-download/index.js\";\nimport type { NativeRuntimeTool } from \"./tools/native/registry-source.js\";\nimport { resolveNativeZuoraFileDownloadConfig } from \"./tools/native/zuora-file-download/config.js\";\nimport { NativeZuoraFileDownloadTools } from \"./tools/native/zuora-file-download/index.js\";\nimport { normalizeMcpTools } from \"./tools/mcp-tool-definition.js\";\nimport { ZuoraRestClient } from \"./transport/zuora-rest-client.js\";\nimport { ZuoraClient } from \"./transport/zuora-client.js\";\nimport {\n resolveToolSelectionPolicy,\n type ToolSelectionPolicy,\n} from \"./tool-selection.js\";\nimport { ZuoraHttpMcpClient } from \"./transport/mcp-client.js\";\nimport { isRecord } from \"./utils/values.js\";\nimport { SafetyMode } from \"./types.js\";\nimport type {\n EventSanitizerLimits,\n ZuoraAgentToolkitConfig,\n ZuoraBundleDefinition,\n ZuoraBundleName,\n ZuoraConnectionConfig,\n ZuoraHttpMcpClientConfig,\n ZuoraMcpClient,\n ZuoraToolDefinition,\n ZuoraToolExecutionResult,\n ZuoraToolkitEvent,\n ZuoraWaitForJobOptions,\n ToolSelection,\n} from \"./types.js\";\nimport { normalizeIdList } from \"./utils/values.js\";\nimport { inferZuoraEnvironment } from \"./utils/zuora-url.js\";\n\nconst createHttpMcpClientConfig = (\n config: ZuoraAgentToolkitConfig,\n): ZuoraHttpMcpClientConfig => {\n // Routing IDs from configuration.context take precedence over connection-level values.\n const contextEntityIds = config.configuration?.context?.entityIds;\n const contextOrgIds = config.configuration?.context?.orgIds;\n const contextOverrides = {\n ...(contextEntityIds ? { entityIds: contextEntityIds } : {}),\n ...(contextOrgIds ? { orgIds: contextOrgIds } : {}),\n };\n\n // Narrow to the tenantAuth variant — only that variant carries `connection`.\n const connection = \"connection\" in config ? config.connection : undefined;\n\n if (isTenantAuthConnection(connection)) {\n return {\n url: config.baseUrl,\n ...(config.auth ? { auth: config.auth } : {}),\n ...connection,\n ...contextOverrides,\n };\n }\n\n if (!config.auth) {\n throw new ZuoraAgentToolkitError({\n code: \"MISSING_AUTH\",\n message:\n \"Zuora auth configuration is required unless tenant auth is enabled.\",\n category: \"auth\",\n });\n }\n\n return {\n url: config.baseUrl,\n auth: config.auth,\n ...(connection ?? {}),\n ...contextOverrides,\n };\n};\n\nconst isTenantAuthConnection = (\n connection: ZuoraConnectionConfig | undefined,\n): connection is Extract<\n ZuoraConnectionConfig,\n { tenantAuth: { enabled: true } }\n> => connection?.tenantAuth?.enabled === true;\n\nconst filterCatalogTools = (\n tools: ZuoraToolDefinition[],\n policy: ToolSelectionPolicy,\n): ZuoraToolDefinition[] =>\n tools.filter((tool) => {\n // In readOnly mode, filter tools based on their effective access:\n // - For merged multi-op tools (operationAccess present), allow if any operation is read\n // - For all other tools, filter if access is write\n if (policy.mode === SafetyMode.ReadOnly) {\n if (tool.meta.operationAccess) {\n // Merged multi-op tool: check if any operation is read\n const hasReadOperation = Object.values(tool.meta.operationAccess).some(\n (access) => access === \"read\",\n );\n if (!hasReadOperation) {\n return false;\n }\n } else if (tool.meta.access === \"write\") {\n // Single-op or split tool: filter if write\n return false;\n }\n }\n\n if (policy.bundles.size > 0 && !policy.bundles.has(tool.meta.bundle)) {\n return false;\n }\n\n if (policy.include.size > 0 && !policy.include.has(tool.name)) {\n return false;\n }\n\n if (policy.exclude.has(tool.name)) {\n return false;\n }\n\n return true;\n });\n\n// Generic parameter T is the framework-native tool type each adapter returns.\n// e.g. ToolkitCore<ChatCompletionTool> for OpenAI, ToolkitCore<StructuredTool> for LangChain.\n// Framework adapters extend ToolkitCore and override only convertTools().\n// All other methods are intended to be final — do not override them.\nexport abstract class ToolkitCore<T> {\n protected readonly config: ZuoraAgentToolkitConfig;\n\n protected mcpClient: ZuoraMcpClient;\n\n private catalogTools: ZuoraToolDefinition[] | undefined;\n\n private _initialized = false;\n\n // Resolved once at construction so we never read process.env at runtime.\n private readonly sanitizerLimits: EventSanitizerLimits | undefined;\n\n // SDK-native tool sets (e.g. file-artifacts). Indexed by tool name for O(1) dispatch.\n private readonly nativeFileArtifactTools: NativeFileArtifactTools;\n\n private readonly nativeQueryResultDownloadTools: NativeQueryResultDownloadTools;\n\n private readonly nativeZuoraFileDownloadTools: NativeZuoraFileDownloadTools;\n\n // REST client for Zuora file downloads (used by zuora-file-download sub-module).\n private readonly restClient: ZuoraRestClient;\n\n private nativeToolRegistry: Map<string, NativeRuntimeTool> | undefined;\n\n constructor(config: ZuoraAgentToolkitConfig) {\n this.config = config;\n const nativeFileTools = resolveNativeFileToolsInput(config);\n this.sanitizerLimits = config.observability?.sanitizerLimits;\n this.mcpClient = new ZuoraHttpMcpClient(createHttpMcpClientConfig(config));\n // REST client shares the same connection config as the MCP client.\n const sharedState = ZuoraClient.createSharedState({\n ...createHttpMcpClientConfig(config),\n ...(typeof nativeFileTools?.maxDownloadBytes === \"number\"\n ? { maxDownloadBytes: nativeFileTools.maxDownloadBytes }\n : {}),\n });\n this.restClient = new ZuoraRestClient(sharedState);\n // MCP client is passed so read_resource can forward to the underlying MCP server.\n this.nativeFileArtifactTools = new NativeFileArtifactTools(\n nativeFileTools,\n { mcpClient: this.mcpClient },\n );\n const queryResultDownloadConfig = resolveNativeQueryResultDownloadConfig(\n nativeFileTools,\n { fileArtifactsEnabled: this.nativeFileArtifactTools.isEnabled() },\n );\n this.nativeQueryResultDownloadTools = new NativeQueryResultDownloadTools({\n enabled: queryResultDownloadConfig.enabled,\n tool: queryResultDownloadConfig.tool,\n fetchQueryResult: (jobId) => this.fetchQueryResultForDownload(jobId),\n downloadFile: (input) => this.nativeFileArtifactTools.downloadFile(input),\n });\n const zuoraFileDownloadConfig = resolveNativeZuoraFileDownloadConfig(\n nativeFileTools,\n { fileArtifactsEnabled: this.nativeFileArtifactTools.isEnabled() },\n );\n this.nativeZuoraFileDownloadTools = new NativeZuoraFileDownloadTools({\n enabled: zuoraFileDownloadConfig.enabled,\n tool: zuoraFileDownloadConfig.tool,\n fetchZuoraFile: (fileId) => this.restClient.downloadFile(fileId),\n persistDownload: (options) =>\n this.nativeFileArtifactTools.persistBufferedDownload(options),\n });\n }\n\n async initialize(): Promise<void> {\n if (this._initialized) {\n return;\n }\n\n const startedAt = Date.now();\n await this.mcpClient.initialize?.();\n const rawTools = await this.mcpClient.listTools();\n const mcpCatalogTools = normalizeMcpTools(\n rawTools,\n this.resolveSplitOperations(),\n );\n\n // Build native tool registry and merge definitions into catalog.\n // Collect all native runtime tools from all SDK-native sub-modules.\n const nativeRuntimeTools = [\n ...this.nativeFileArtifactTools.listTools(),\n ...this.nativeQueryResultDownloadTools.listTools(),\n ...this.nativeZuoraFileDownloadTools.listTools(),\n ];\n this.nativeToolRegistry = new Map(\n nativeRuntimeTools.map((runtimeTool) => [\n runtimeTool.definition.name,\n runtimeTool,\n ]),\n );\n const nativeToolDefinitions = nativeRuntimeTools.map(\n (runtimeTool) => runtimeTool.definition,\n );\n\n this.catalogTools = [...mcpCatalogTools, ...nativeToolDefinitions];\n this._initialized = true;\n\n this.emit({\n name: \"metadata.loaded\",\n latencyMs: Date.now() - startedAt,\n ...this.createEventContext(),\n metadata: metadataLoadedEventMetadata(this.catalogTools),\n });\n }\n\n async close(): Promise<void> {\n await this.mcpClient.close?.();\n this._initialized = false;\n this.catalogTools = undefined;\n this.nativeToolRegistry = undefined;\n }\n\n async listTools(selection?: ToolSelection): Promise<ZuoraToolDefinition[]> {\n this.warnIfNotInitialized();\n return filterCatalogTools(\n this.getNormalizedTools(),\n resolveToolSelectionPolicy(this.config.configuration, selection),\n );\n }\n\n /**\n * Returns framework-native tool objects for the given selection.\n *\n * @param selection - Optional filter (bundles, mode) to narrow the catalog.\n * @param maxTools - When provided and greater than zero, limits the result to\n * the first `maxTools` entries after filtering. Values ≤ 0 are treated as\n * no-limit. Does not affect `loadFollowUpTools()`, which always searches\n * the full catalog.\n */\n async getTools(selection?: ToolSelection, maxTools?: number): Promise<T[]> {\n this.warnIfNotInitialized();\n let filtered = filterCatalogTools(\n this.getNormalizedTools(),\n resolveToolSelectionPolicy(this.config.configuration, selection),\n );\n\n if (typeof maxTools === \"number\" && maxTools > 0) {\n filtered = filtered.slice(0, maxTools);\n }\n\n return this.convertTools(filtered);\n }\n\n async listBundles(): Promise<ZuoraBundleDefinition[]> {\n this.warnIfNotInitialized();\n const tools = this.getNormalizedTools();\n\n return ZUORA_BUNDLE_NAMES.map((name) => getBundleDefinition(name, tools));\n }\n\n async describeBundle(name: ZuoraBundleName): Promise<ZuoraBundleDefinition> {\n this.warnIfNotInitialized();\n\n if (!hasBundleDefinition(name)) {\n throw new ZuoraAgentToolkitError({\n code: \"BUNDLE_NOT_FOUND\",\n message: `Unknown Zuora bundle: ${name}`,\n category: \"configuration\",\n });\n }\n\n return getBundleDefinition(name, this.getNormalizedTools());\n }\n\n async describeTool(name: string): Promise<ZuoraToolDefinition | undefined> {\n this.warnIfNotInitialized();\n return this.getNormalizedTools().find((tool) => tool.name === name);\n }\n\n async callTool(\n operationName: string,\n input: Record<string, unknown>,\n ): Promise<ZuoraToolExecutionResult> {\n this.warnIfNotInitialized();\n\n const tool = this.getNormalizedTools().find(\n (candidate) => candidate.name === operationName,\n );\n\n if (!tool) {\n throw new ZuoraAgentToolkitError({\n code: \"TOOL_NOT_FOUND\",\n message: `Unknown Zuora tool: ${operationName}`,\n category: \"configuration\",\n });\n }\n\n const mode = this.config.configuration?.mode ?? SafetyMode.ReadOnly;\n\n // Resolve native runtime tool for approval metadata enrichment and execution routing.\n const nativeRuntimeTool = this.nativeToolRegistry?.get(operationName);\n const nativeApprovalMetadata = nativeRuntimeTool?.approvalMetadata(input);\n\n // For merged tools, derive per-operation access and risk from the invoked\n // operation so approval policy and observability events reflect the actual\n // operation rather than the aggregated worst-case values on the merged tool.\n const invokedOperation =\n tool.meta.operationSelector\n ? String(input[tool.meta.operationSelector] ?? \"\")\n : undefined;\n const effectiveAccess: ZuoraToolDefinition[\"meta\"][\"access\"] =\n (invokedOperation\n ? tool.meta.operationAccess?.[invokedOperation]\n : undefined) ?? tool.meta.access;\n const effectiveRiskLevel: ZuoraToolDefinition[\"meta\"][\"riskLevel\"] =\n (invokedOperation\n ? tool.meta.operationRiskLevel?.[invokedOperation]\n : undefined) ?? tool.meta.riskLevel;\n\n // Execution guard: enforce mode based on effective access\n if (mode === SafetyMode.ReadOnly && effectiveAccess === \"write\") {\n throw new ZuoraAgentToolkitError({\n code: \"TOOL_EXECUTION_ERROR\",\n message: `Write operation \"${invokedOperation ?? operationName}\" is disabled in readOnly mode.`,\n category: \"tool_execution\",\n });\n }\n const effectiveTool: ZuoraToolDefinition =\n effectiveAccess === tool.meta.access &&\n effectiveRiskLevel === tool.meta.riskLevel\n ? tool\n : { ...tool, meta: { ...tool.meta, access: effectiveAccess, riskLevel: effectiveRiskLevel } };\n\n await enforceApproval(effectiveTool, input, this.config, (event) =>\n this.emit(event),\n nativeApprovalMetadata);\n\n const startedAt = Date.now();\n const includePayloads = this.config.observability?.includePayloads === true;\n const toolEventBase = {\n toolName: tool.name,\n access: effectiveAccess,\n bundle: tool.meta.bundle,\n riskLevel: effectiveRiskLevel,\n ...this.createEventContext(),\n };\n\n this.emit({\n name: \"tool.called\",\n ...toolEventBase,\n ...(includePayloads ? { input: compactToolInputForEvent(input) } : {}),\n });\n\n // Captured after the MCP call so tool.failed can include the raw\n // response when post-processing (e.g. async job extraction) throws.\n let rawMcpResult: ZuoraToolExecutionResult | undefined;\n\n try {\n let result: ZuoraToolExecutionResult;\n\n if (nativeRuntimeTool) {\n // SDK-native tool: execute locally, no MCP call.\n result = await nativeRuntimeTool.execute(input);\n } else {\n enforceOperationSelector(tool, input);\n const mcpInput = createMcpToolInput(tool, input);\n const rawResult = await this.mcpClient.callTool(\n tool.meta.sourceName,\n mcpInput,\n );\n rawMcpResult = { ...rawResult, riskLevel: tool.meta.riskLevel };\n // For multi-op merged tools, resolve the async meta from the operation\n // the LLM actually invoked (read from the input's operation field).\n const resolvedAsyncOperation: typeof tool.meta.asyncOperation =\n tool.meta.asyncOperation ??\n (tool.meta.asyncOperations && tool.meta.operationSelector\n ? tool.meta.asyncOperations[\n String(input[tool.meta.operationSelector] ?? \"\")\n ]\n : undefined);\n\n // Skip async job extraction when Zuora signals a business-level failure\n // via success:false. The result is a normal (error) response, not a job.\n const isApiFailure =\n isRecord(rawResult.data) && rawResult.data[\"success\"] === false;\n\n if (resolvedAsyncOperation && !isApiFailure) {\n const asyncJobResult = buildAsyncJobResult(\n rawResult,\n resolvedAsyncOperation,\n {\n sourceToolName: tool.meta.sourceName,\n ...(tool.meta.operationSelector\n ? { operationSelector: tool.meta.operationSelector }\n : {}),\n sourceOperationNames: this.getNormalizedTools()\n .filter(\n (candidate) =>\n candidate.meta.sourceName === tool.meta.sourceName,\n )\n .map(\n (candidate) =>\n candidate.meta.operationName ?? candidate.name,\n ),\n },\n );\n // Warn when asyncMeta provides neither pollingOperation nor pollingTool.\n // In this case resolveAsyncJobPollingToolNameFromMeta falls back to\n // sourceToolName, which may not be the intended polling target.\n if (\n resolvedAsyncOperation.pollingOperation === undefined &&\n resolvedAsyncOperation.pollingTool === undefined\n ) {\n this.config.observability?.logger?.warn?.(\n `[zuora-agent-toolkit] async operation metadata for tool \"${tool.name}\" ` +\n `has neither pollingOperation nor pollingTool. ` +\n `Polling will fall back to the source tool \"${tool.meta.sourceName}\" which may be incorrect. ` +\n `Check server metadata.`,\n );\n }\n\n // When the resolved pollingToolName is a split-style name (e.g.\n // \"manage_bill_runs__get_bill_run\") but only the merged tool exists in\n // the registry (splitOperations: false), fall back to the merged base\n // tool and inject the operation into pollingArgs.\n const resolvedPollingTool = this.getNormalizedTools().find(\n (t) => t.name === asyncJobResult.pollingToolName,\n );\n if (!resolvedPollingTool && resolvedAsyncOperation.pollingTool && resolvedAsyncOperation.pollingOperation) {\n const mergedPollingTool = this.getNormalizedTools().find(\n (t) => t.meta.sourceName === resolvedAsyncOperation.pollingTool && t.meta.operationSelector,\n );\n if (mergedPollingTool) {\n asyncJobResult.pollingToolName = mergedPollingTool.name;\n asyncJobResult.pollingArgs = {\n ...asyncJobResult.pollingArgs,\n [mergedPollingTool.meta.operationSelector!]: resolvedAsyncOperation.pollingOperation,\n };\n }\n }\n\n result = {\n toolName: tool.meta.sourceName,\n data: asyncJobResult,\n riskLevel: tool.meta.riskLevel,\n };\n } else {\n result = { ...rawResult, riskLevel: tool.meta.riskLevel };\n }\n }\n\n const requestMetadata = extractExecutionRequestMetadata(result);\n\n this.emit({\n name: \"tool.completed\",\n ...toolEventBase,\n ...requestMetadata,\n latencyMs: Date.now() - startedAt,\n ...(includePayloads ? { output: compactToolOutputForEvent(result) } : {}),\n });\n\n return result;\n } catch (error) {\n if (error instanceof ZuoraAgentToolkitError) {\n const eventError = compactToolkitError(error);\n // error.requestId is a client-side correlation ID, not a Zuora server\n // request ID. Only set requestId here; zuoraRequestId is reserved for\n // server-assigned trace IDs that would appear in the execution result.\n const requestMetadata = error.requestId\n ? { requestId: error.requestId }\n : {};\n\n const rawOutputForEvent =\n includePayloads && rawMcpResult\n ? { output: compactToolOutputForEvent(rawMcpResult) }\n : {};\n\n this.emit({\n name: \"tool.failed\",\n ...toolEventBase,\n ...requestMetadata,\n ...rawOutputForEvent,\n error: eventError,\n metadata: { error: eventError },\n });\n\n throw error;\n }\n\n const wrappedError = new ZuoraAgentToolkitError({\n code: \"TOOL_EXECUTION_ERROR\",\n message: `Tool \"${operationName}\" execution failed: ${\n error instanceof Error ? error.message : String(error)\n }`,\n category: \"tool_execution\",\n recoverable: true,\n });\n const eventError = compactToolkitError(wrappedError);\n\n const rawOutputForEvent =\n includePayloads && rawMcpResult\n ? { output: compactToolOutputForEvent(rawMcpResult) }\n : {};\n\n this.emit({\n name: \"tool.failed\",\n ...toolEventBase,\n ...rawOutputForEvent,\n error: eventError,\n metadata: { error: eventError },\n });\n\n throw wrappedError;\n }\n }\n\n /**\n * Polls an async job to completion using the polling operation specified in\n * the async job result. Returns the final polling tool execution result when\n * the job reaches a terminal state.\n *\n * Polling stops when:\n * - A terminal status is matched (success, failure, or canceled)\n * - The maximum number of poll attempts is exhausted\n * - The absolute timeout is exceeded\n *\n * @param toolName - The name of the tool that started the async job. Used for\n * observability context only.\n * @param asyncResult - The pending async job result from an initial tool call.\n * @param options - Optional overrides for polling behavior.\n * @throws ZuoraAgentToolkitError with ASYNC_JOB_TIMEOUT if the job does not\n * reach a terminal state within the configured limits.\n */\n async waitForJob(\n toolName: string,\n asyncResult: ZuoraAsyncJobResult,\n options?: ZuoraWaitForJobOptions,\n ): Promise<ZuoraToolExecutionResult> {\n this.warnIfNotInitialized();\n\n // Resolve terminal statuses: options override > asyncResult (from originating tool's asyncMeta) > defaults\n const terminalStatuses =\n options?.terminalStatuses ??\n asyncResult.terminalStatuses ??\n DEFAULT_ASYNC_JOB_TERMINAL_STATUSES;\n\n // Resolve statusPath from asyncResult (populated at job-start from the originating tool's asyncMeta),\n // falling back to a common \"status\" path on result.data\n const statusPath = asyncResult.statusPath ?? \"status\";\n\n // Resolve timing from options > asyncResult (from original async meta) > defaults\n const maxPollAttempts =\n options?.maxPollAttempts ??\n asyncResult.maxPollAttempts ??\n 50;\n\n const pollIntervalMs =\n options?.pollIntervalMs ??\n asyncResult.recommendedPollIntervalMs ??\n 2000;\n\n const timeoutMs =\n options?.timeoutMs ??\n asyncResult.defaultTimeoutMs ??\n 300_000; // 5 minutes\n\n const logger = this.config.observability?.logger;\n const startedAt = Date.now();\n\n for (let attempt = 1; attempt <= maxPollAttempts; attempt++) {\n // Check absolute timeout before polling\n if (Date.now() - startedAt >= timeoutMs) {\n throw new ZuoraAgentToolkitError({\n code: \"ASYNC_JOB_TIMEOUT\",\n message: `Async job \"${toolName}\" (id: ${asyncResult.jobId}) timed out after ${timeoutMs}ms.`,\n category: \"tool_execution\",\n recoverable: false,\n details: {\n jobId: asyncResult.jobId,\n toolName,\n pollingOperation: asyncResult.pollingOperation,\n attempt,\n timeoutMs,\n },\n });\n }\n\n // Build polling input: merge pollingArgs substituting jobId where referenced\n const pollingInput = resolvePollingInput(asyncResult);\n\n // Call the polling tool. pollingToolName is always set on ZuoraAsyncJobResult\n // (resolved at job-start time by resolveAsyncJobPollingToolNameFromMeta), so\n // no fallback to pollingOperation is needed here.\n const pollResult = await this.callTool(\n asyncResult.pollingToolName,\n pollingInput,\n );\n\n // Resolve status details\n const statusDetails = resolveAsyncJobStatusDetails(\n pollResult,\n statusPath,\n terminalStatuses,\n );\n\n // Determine decision for observability\n let decision: AsyncPollTerminationDecision;\n if (statusDetails.status == null) {\n decision = \"no_status\";\n } else if (statusDetails.terminalState === \"success\") {\n decision = \"success\";\n } else if (statusDetails.terminalState === \"failure\") {\n decision = \"failure\";\n } else if (statusDetails.terminalState === \"canceled\") {\n decision = \"canceled\";\n } else {\n decision = \"continue\";\n }\n\n logAsyncPollChecked(logger, {\n jobId: asyncResult.jobId,\n attempt,\n maxAttempts: maxPollAttempts,\n // pollingToolName is always set on ZuoraAsyncJobResult\n pollingToolName: asyncResult.pollingToolName,\n statusPath,\n statusSource: statusDetails.status != null ? \"statusPath\" : \"none\",\n resolvedValue: statusDetails.status,\n ...(statusDetails.status != null\n ? { resolvedStatus: statusDetails.status }\n : {}),\n terminalStatuses,\n matchedSuccess: statusDetails.terminalState === \"success\",\n matchedFailure: statusDetails.terminalState === \"failure\",\n matchedCanceled: statusDetails.terminalState === \"canceled\",\n decision,\n });\n\n if (statusDetails.isTerminal) {\n return pollResult;\n }\n\n // Not terminal yet — wait before next attempt (unless this is the last)\n if (attempt < maxPollAttempts) {\n await sleep(pollIntervalMs);\n }\n }\n\n throw new ZuoraAgentToolkitError({\n code: \"ASYNC_JOB_TIMEOUT\",\n message: `Async job \"${toolName}\" (id: ${asyncResult.jobId}) did not reach a terminal state after ${maxPollAttempts} poll attempts.`,\n category: \"tool_execution\",\n recoverable: false,\n details: {\n jobId: asyncResult.jobId,\n toolName,\n pollingOperation: asyncResult.pollingOperation,\n maxPollAttempts,\n },\n });\n }\n\n protected abstract convertTools(tools: ZuoraToolDefinition[]): T[];\n\n /**\n * Returns the full normalized tool catalog after initialization.\n *\n * @internal For use by adapter subclasses only (e.g. to implement\n * follow-up tool resolution against the full catalog). Do not call\n * from outside the class hierarchy.\n */\n protected getNormalizedTools(): ZuoraToolDefinition[] {\n return this.catalogTools ?? [];\n }\n\n private resolveSplitOperations(): boolean {\n return this.config.configuration?.splitOperations ?? false;\n }\n\n private warnIfNotInitialized(): void {\n if (!this._initialized) {\n console.warn(\n \"Zuora Agent Toolkit accessed before initialize(). Call await toolkit.initialize() first.\",\n );\n }\n }\n\n protected emit(event: InternalToolkitEvent): void {\n const normalizedEvent = normalizeToolkitEvent(event, this.sanitizerLimits);\n const logger = this.config.observability?.logger;\n\n try {\n this.config.observability?.onEvent?.(normalizedEvent);\n } catch (error) {\n reportObservabilitySinkError(logger, error);\n }\n\n try {\n const emitResult = this.config.observability?.emit?.(normalizedEvent);\n if (emitResult) {\n void Promise.resolve(emitResult).catch((error) => {\n reportObservabilitySinkError(logger, error);\n });\n }\n } catch (error) {\n reportObservabilitySinkError(logger, error);\n }\n\n const message = `[zuora-agent-toolkit] ${normalizedEvent.name}`;\n\n try {\n if (normalizedEvent.name === \"tool.failed\") {\n logger?.error?.(message, normalizedEvent);\n return;\n }\n if (normalizedEvent.name === \"approval.requested\") {\n logger?.warn?.(message, normalizedEvent);\n return;\n }\n if (\n normalizedEvent.executionPhase === \"async_poll\" &&\n (normalizedEvent.name === \"tool.called\" ||\n normalizedEvent.name === \"tool.completed\" ||\n normalizedEvent.name === \"async.poll.checked\")\n ) {\n logger?.debug?.(message, normalizedEvent);\n return;\n }\n logger?.info?.(message, normalizedEvent);\n } catch {\n // Observability sinks are best-effort.\n }\n }\n\n /**\n * Fetches a Data Query job result to extract the dataFile download URL.\n * Called by NativeQueryResultDownloadTools to resolve the presigned S3 URL\n * for a completed query job before handing off to downloadFile.\n */\n private async fetchQueryResultForDownload(\n jobId: string,\n ): Promise<ZuoraToolExecutionResult> {\n const tools = this.getNormalizedTools();\n const statusCall = resolveQueryResultStatusCall(tools, jobId);\n\n if (!statusCall) {\n throw new ZuoraAgentToolkitError({\n code: \"QUERY_RESULT_STATUS_TOOL_NOT_FOUND\",\n message:\n \"Could not find a Data Query job status tool to resolve the query result dataFile URL.\",\n category: \"native_file_tools\",\n recoverable: true,\n details: {\n jobId,\n expectedTool: \"manage_data_queries__get_query_job\",\n },\n });\n }\n\n return this.callTool(statusCall.toolName, statusCall.input);\n }\n\n private createEventContext(): Pick<\n ZuoraToolkitEvent,\n \"environment\" | \"tenantId\" | \"entityIds\" | \"orgIds\"\n > {\n const configurationContext = this.config.configuration?.context ?? {};\n const entityIds =\n normalizeIdList(configurationContext.entityIds) ??\n normalizeIdList(configurationContext.entityId);\n const orgIds =\n normalizeIdList(configurationContext.orgIds) ??\n normalizeIdList(configurationContext.orgId);\n const environment = inferZuoraEnvironment(this.config.baseUrl) ?? \"sandbox\";\n\n return {\n environment,\n ...(entityIds ? { entityIds } : {}),\n ...(orgIds ? { orgIds } : {}),\n };\n }\n}\n\n/**\n * Builds the input arguments for the polling tool call.\n *\n * When pollingArgs is present, values that reference a path (e.g. \"{{jobId}}\")\n * are substituted with the actual jobId. The bare `jobId` field is always\n * included so that polling tools that accept a plain `jobId` field work out\n * of the box regardless of whether pollingArgs is provided.\n */\nconst JOB_ID_PLACEHOLDERS = new Set([\"{{jobId}}\", \"${jobId}\"]);\n\nconst resolvePollingInput = (\n asyncResult: ZuoraAsyncJobResult,\n): Record<string, unknown> => {\n const base: Record<string, unknown> = { jobId: asyncResult.jobId };\n\n if (!asyncResult.pollingArgs) {\n return base;\n }\n\n const resolved: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(asyncResult.pollingArgs)) {\n // Substitute known job-id placeholders — never replace a static string that\n // happens to equal the current job ID, as that would corrupt literal values.\n if (JOB_ID_PLACEHOLDERS.has(value)) {\n resolved[key] = asyncResult.jobId;\n } else {\n resolved[key] = value;\n }\n }\n\n // Always merge base so jobId is present regardless of pollingArgs mapping\n return { ...resolved, ...base };\n};\n\n/** Returns a promise that resolves after the given number of milliseconds. */\nconst sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n","import { SafetyMode } from \"./types.js\";\nimport type {\n ZuoraAgentToolkitConfig,\n ZuoraAgentToolkitConfigInput,\n ZuoraAgentToolkitEnvConfig,\n ZuoraConnectionConfig,\n ZuoraSafetyMode,\n} from \"./types.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport type ZuoraEnvRecord = Record<string, string | undefined>;\n\nexport const ZUORA_TOOLKIT_ENDPOINT_ENV = \"ZUORA_BASE_URL or ZUORA_MCP_URL\";\n\n// ─── resolve-config ───────────────────────────────────────────────────────────\n\nconst isEnvSourcedConfig = (\n config: ZuoraAgentToolkitConfigInput,\n): config is ZuoraAgentToolkitEnvConfig => \"env\" in config;\n\nconst mergeConfiguration = (\n base: ZuoraAgentToolkitConfig[\"configuration\"],\n overrides: ZuoraAgentToolkitConfig[\"configuration\"],\n): ZuoraAgentToolkitConfig[\"configuration\"] => {\n if (!base && !overrides) {\n return undefined;\n }\n\n return {\n ...(base ?? {}),\n ...(overrides ?? {}),\n ...(overrides?.context || base?.context\n ? {\n context: {\n ...base?.context,\n ...overrides?.context,\n },\n }\n : {}),\n };\n};\n\nconst mergeZuoraAgentToolkitConfig = (\n base: ZuoraAgentToolkitConfig,\n overrides: Omit<ZuoraAgentToolkitEnvConfig, \"env\">,\n): ZuoraAgentToolkitConfig => {\n const { configuration: overrideConfiguration, ...restOverrides } = overrides;\n const configuration = mergeConfiguration(\n base.configuration,\n overrideConfiguration,\n );\n\n return {\n ...base,\n ...restOverrides,\n ...(configuration ? { configuration } : {}),\n };\n};\n\nexport const resolveZuoraAgentToolkitConfig = (\n config: ZuoraAgentToolkitConfigInput,\n): ZuoraAgentToolkitConfig => {\n if (!isEnvSourcedConfig(config)) {\n return config;\n }\n\n const { env: envSource, ...overrides } = config;\n const env =\n envSource === true ? process.env : (envSource.env ?? process.env);\n\n return mergeZuoraAgentToolkitConfig(\n zuoraAgentToolkitConfigFromEnv(env),\n overrides,\n );\n};\n\n// ─── from-env ─────────────────────────────────────────────────────────────────\n\nconst readTrimmedEnv = (\n env: ZuoraEnvRecord,\n name: string,\n): string | undefined => {\n const value = env[name]?.trim();\n return value ? value : undefined;\n};\n\nconst requiredEnv = (env: ZuoraEnvRecord, name: string): string => {\n const value = readTrimmedEnv(env, name);\n\n if (!value) {\n throw new Error(`Missing required environment variable: ${name}`);\n }\n\n return value;\n};\n\nconst readBooleanEnvValue = (\n name: string,\n rawValue: string | undefined,\n): boolean => {\n const value = rawValue?.trim().toLowerCase();\n\n if (!value) {\n return false;\n }\n\n if ([\"true\", \"1\", \"yes\"].includes(value)) {\n return true;\n }\n\n if ([\"false\", \"0\", \"no\"].includes(value)) {\n return false;\n }\n\n throw new Error(`Invalid ${name}: expected true or false.`);\n};\n\nconst readBooleanEnv = (env: ZuoraEnvRecord, name: string): boolean =>\n readBooleanEnvValue(name, env[name]);\n\nconst readZuoraEndpoint = (\n env: ZuoraEnvRecord,\n): string | undefined =>\n readTrimmedEnv(env, \"ZUORA_BASE_URL\") ?? readTrimmedEnv(env, \"ZUORA_MCP_URL\");\n\nconst readToolkitMode = (env: ZuoraEnvRecord): ZuoraSafetyMode => {\n const mode = env.ZUORA_TOOLKIT_MODE?.trim() ?? SafetyMode.ReadOnly;\n\n if (mode === SafetyMode.ReadOnly || mode === SafetyMode.WriteEnabled) {\n return mode;\n }\n\n throw new Error(\n `Invalid ZUORA_TOOLKIT_MODE: ${mode}. Expected ${SafetyMode.ReadOnly} or ${SafetyMode.WriteEnabled}.`,\n );\n};\n\nconst readConnectionOptions = (\n env: ZuoraEnvRecord,\n): ZuoraConnectionConfig => {\n const entityIds = readTrimmedEnv(env, \"ZUORA_ENTITY_IDS\");\n const orgIds = readTrimmedEnv(env, \"ZUORA_ORG_IDS\");\n const zuoraVersion = readTrimmedEnv(env, \"ZUORA_VERSION\");\n\n return {\n ...(entityIds ? { entityIds } : {}),\n ...(orgIds ? { orgIds } : {}),\n ...(zuoraVersion ? { zuoraVersion } : {}),\n };\n};\n\nexport const zuoraAgentToolkitConfigFromEnv = (\n env: ZuoraEnvRecord = process.env,\n): ZuoraAgentToolkitConfig => {\n const baseUrl = readZuoraEndpoint(env);\n\n if (!baseUrl) {\n throw new Error(`Set ${ZUORA_TOOLKIT_ENDPOINT_ENV}.`);\n }\n\n const mode = readToolkitMode(env);\n const connection = readConnectionOptions(env);\n\n if (readBooleanEnv(env, \"ZUORA_TENANT_AUTH\")) {\n const tenantId = requiredEnv(env, \"ZUORA_TENANT_ID\");\n\n return {\n baseUrl,\n connection: {\n ...connection,\n tenantAuth: {\n enabled: true,\n tenantId,\n tokenId: requiredEnv(env, \"ZUORA_TOKEN_ID\"),\n userId: requiredEnv(env, \"ZUORA_USER_ID\"),\n },\n },\n configuration: {\n mode,\n },\n };\n }\n\n return {\n baseUrl,\n auth: {\n clientId: requiredEnv(env, \"ZUORA_CLIENT_ID\"),\n clientSecret: requiredEnv(env, \"ZUORA_CLIENT_SECRET\"),\n },\n ...(Object.keys(connection).length > 0 ? { connection } : {}),\n configuration: {\n mode,\n },\n };\n};\n","import { findDownloadUrl } from \"./tools/native/query-result-download/helpers/index.js\";\nimport { resolveZuoraFileResource } from \"./tools/native/zuora-file-download/helpers/index.js\";\nimport type { ZuoraToolExecutionResult } from \"./types.js\";\n\nexport const QUERY_RESULT_DOWNLOAD_TOOL = \"download_query_result\";\nexport const ZUORA_FILE_DOWNLOAD_TOOL = \"download_zuora_file\";\nexport const READ_DOWNLOADED_FILE_TOOL = \"read_downloaded_file\";\n\nexport type AgentToolFollowUpContext = {\n /** Job id from a pending async job, when the caller already resolved it. */\n asyncJobId?: string;\n};\n\nexport type AgentToolFollowUpResolution = {\n followUpToolNames: string[];\n requireToolOnNextStep: boolean;\n recommendedNextTool?: string;\n recommendedNextArgs?: Record<string, unknown>;\n hasDownloadableOutput: boolean;\n};\n\nexport const resolveAgentToolFollowUps = (\n result: ZuoraToolExecutionResult,\n context: AgentToolFollowUpContext = {},\n): AgentToolFollowUpResolution => {\n const followUpToolNames: string[] = [];\n const data = result.data;\n const jobId = context.asyncJobId ?? findQueryJobId(data);\n const zuoraFile = resolveZuoraFileResource(data);\n const hasDownloadUrl = findDownloadUrl(data) !== undefined;\n const artifactId = findDownloadArtifactId(data);\n\n let recommendedNextTool: string | undefined;\n let recommendedNextArgs: Record<string, unknown> | undefined;\n\n if (zuoraFile) {\n followUpToolNames.push(ZUORA_FILE_DOWNLOAD_TOOL);\n recommendedNextTool = ZUORA_FILE_DOWNLOAD_TOOL;\n recommendedNextArgs = { fileId: zuoraFile.fileId };\n } else if (hasDownloadUrl && jobId) {\n // A download URL is present in the result, and we have a jobId to pass to\n // the download tool. Note: the download URL itself is not included in\n // recommendedNextArgs — the download_query_result tool resolves the URL\n // internally from the jobId via a status-check call. If a download URL is\n // present but no jobId can be resolved (no jobId/queryJobId field in the\n // payload), this branch is skipped and no follow-up is emitted; the caller\n // is expected to supply asyncJobId via context in that case.\n followUpToolNames.push(QUERY_RESULT_DOWNLOAD_TOOL, READ_DOWNLOADED_FILE_TOOL);\n recommendedNextTool = QUERY_RESULT_DOWNLOAD_TOOL;\n recommendedNextArgs = { jobId };\n } else if (\n artifactId &&\n (result.toolName === QUERY_RESULT_DOWNLOAD_TOOL ||\n result.toolName === \"download_file\" ||\n result.toolName === ZUORA_FILE_DOWNLOAD_TOOL)\n ) {\n followUpToolNames.push(READ_DOWNLOADED_FILE_TOOL);\n recommendedNextTool = READ_DOWNLOADED_FILE_TOOL;\n recommendedNextArgs = { artifactId };\n }\n\n const uniqueFollowUps = [...new Set(followUpToolNames)];\n\n return {\n followUpToolNames: uniqueFollowUps,\n requireToolOnNextStep: uniqueFollowUps.length > 0,\n ...(recommendedNextTool ? { recommendedNextTool } : {}),\n ...(recommendedNextArgs ? { recommendedNextArgs } : {}),\n hasDownloadableOutput: hasDownloadUrl || zuoraFile !== undefined,\n };\n};\n\nexport const buildToolMessagePayload = (\n result: ZuoraToolExecutionResult,\n followUp: AgentToolFollowUpResolution,\n): Record<string, unknown> => {\n const baseData =\n typeof result.data === \"object\" && result.data !== null\n ? (result.data as Record<string, unknown>)\n : { value: result.data };\n\n if (!followUp.recommendedNextTool) {\n return baseData;\n }\n\n return {\n ...baseData,\n hasDownloadableOutput: followUp.hasDownloadableOutput,\n recommendedNextTool: followUp.recommendedNextTool,\n ...(followUp.recommendedNextArgs\n ? { recommendedNextArgs: followUp.recommendedNextArgs }\n : {}),\n };\n};\n\nconst findQueryJobId = (value: unknown): string | undefined => {\n const direct = readNonEmptyString(value);\n\n if (direct) {\n return direct;\n }\n\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n const found = findQueryJobId(item);\n\n if (found) {\n return found;\n }\n }\n\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n\n // Check specific job-ID field names. \"id\" is intentionally checked last and\n // only at the top level of the direct object (not recursed into nested\n // objects), because it is too generic and would produce false positives on\n // large MCP responses that contain unrelated \"id\" fields deeper in the tree.\n for (const key of [\"jobId\", \"queryJobId\"]) {\n const candidate = readNonEmptyString(record[key]);\n\n if (candidate) {\n return candidate;\n }\n }\n\n // Recurse into nested objects to find jobId / queryJobId, but do NOT carry\n // the generic \"id\" key through recursion to avoid matching unrelated fields.\n for (const item of Object.values(record)) {\n const found = findQueryJobId(item);\n\n if (found) {\n return found;\n }\n }\n\n // Check \"id\" only at this level (after recursion), as a last resort for\n // responses that use a bare \"id\" field at the top of the data structure.\n const idCandidate = readNonEmptyString(record[\"id\"]);\n\n if (idCandidate) {\n return idCandidate;\n }\n\n return undefined;\n};\n\nconst findDownloadArtifactId = (value: unknown): string | undefined => {\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n const direct = readNonEmptyString(record[\"artifactId\"]);\n\n if (direct) {\n return direct;\n }\n\n const download = record[\"download\"];\n\n if (typeof download === \"object\" && download !== null) {\n const nested = readNonEmptyString(\n (download as Record<string, unknown>)[\"artifactId\"],\n );\n\n if (nested) {\n return nested;\n }\n }\n\n for (const item of Object.values(record)) {\n if (item === record[\"download\"]) {\n continue;\n }\n\n const found = findDownloadArtifactId(item);\n\n if (found) {\n return found;\n }\n }\n\n return undefined;\n};\n\nconst readNonEmptyString = (value: unknown): string | undefined => {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n};\n","/**\n * JSON Schema strictification for the OpenAI Responses API.\n *\n * The Responses API (used by the OpenAI Agents SDK) enforces strict schema\n * mode for all function definitions:\n * - Every object schema must have `additionalProperties: false`\n * - All property keys must appear in `required[]`\n * - Optional properties must be expressed as nullable (`anyOf: [type, null]`)\n * rather than by omission from `required[]`\n *\n * Zuora's raw `inputSchema` objects follow the permissive JSON Schema draft\n * and don't satisfy these constraints. `strictifySchema` transforms a schema\n * tree recursively so it is accepted by the Responses API without any loss of\n * field description information visible to the LLM.\n *\n * @internal Used by the openai-agents adapter. Not part of the public API.\n */\n\nexport type JsonSchemaObject = Record<string, unknown>;\n\n/**\n * Wraps a schema as nullable: `{ anyOf: [schema, { type: \"null\" }] }`.\n * If the schema already has an `anyOf`, the null variant is appended instead\n * of creating a double-wrapped anyOf.\n */\nconst makeNullable = (schema: JsonSchemaObject): JsonSchemaObject => {\n if (Array.isArray(schema[\"anyOf\"])) {\n const anyOf = schema[\"anyOf\"] as JsonSchemaObject[];\n const hasNull = anyOf.some((s) => s[\"type\"] === \"null\");\n return hasNull ? schema : { ...schema, anyOf: [...anyOf, { type: \"null\" }] };\n }\n return { anyOf: [schema, { type: \"null\" }] };\n};\n\n/**\n * Recursively transforms a JSON Schema object to satisfy the OpenAI Responses\n * API strict schema requirements:\n *\n * 1. `additionalProperties: false` is added to every object schema.\n * 2. All property keys are moved into `required[]`.\n * 3. Properties that were NOT originally required are wrapped as nullable\n * (`anyOf: [originalType, { type: \"null\" }]`) so the LLM can omit them\n * by passing `null` rather than omitting the key entirely.\n * 4. `anyOf`, `oneOf`, `allOf`, and `items` are recursed into.\n */\nexport const strictifySchema = (schema: JsonSchemaObject): JsonSchemaObject => {\n if (typeof schema !== \"object\" || schema === null) return schema;\n\n const result: JsonSchemaObject = { ...schema };\n\n // Recurse into combiner keywords\n for (const key of [\"anyOf\", \"oneOf\", \"allOf\"] as const) {\n if (Array.isArray(result[key])) {\n result[key] = (result[key] as JsonSchemaObject[]).map(strictifySchema);\n }\n }\n\n // Recurse into array item schema\n if (typeof result[\"items\"] === \"object\" && result[\"items\"] !== null) {\n result[\"items\"] = strictifySchema(result[\"items\"] as JsonSchemaObject);\n }\n\n // Recurse into schema-form additionalProperties\n if (\n typeof result[\"additionalProperties\"] === \"object\" &&\n result[\"additionalProperties\"] !== null\n ) {\n result[\"additionalProperties\"] = strictifySchema(\n result[\"additionalProperties\"] as JsonSchemaObject,\n );\n }\n\n // Enforce strict rules on object schemas\n if (typeof result[\"properties\"] === \"object\" && result[\"properties\"] !== null) {\n const props = result[\"properties\"] as Record<string, JsonSchemaObject>;\n const required: string[] = Array.isArray(result[\"required\"])\n ? (result[\"required\"] as string[])\n : [];\n const optional = Object.keys(props).filter((k) => !required.includes(k));\n\n const processedProps: Record<string, JsonSchemaObject> = {};\n for (const [key, propSchema] of Object.entries(props)) {\n const strictProp = strictifySchema(propSchema);\n // Optional properties become nullable so the LLM can omit them via null.\n processedProps[key] = optional.includes(key)\n ? makeNullable(strictProp)\n : strictProp;\n }\n\n result[\"properties\"] = processedProps;\n result[\"additionalProperties\"] = false;\n result[\"required\"] = Object.keys(processedProps);\n }\n\n return result;\n};\n","/**\n * Bridge: Zuora toolkit → OpenAI Agents SDK tool() objects.\n *\n * Each Zuora tool becomes a native `tool()` with:\n * - Its full `inputSchema` strictified for the Responses API (invisible to callers)\n * - `strict: false` as an API-level safeguard against residual schema 400 errors\n * - `needsApproval: true` for write tools (SDK-native HITL)\n * - An `execute()` that calls `toolkit.callTool()`, inline `waitForJob()` for\n * async results, and embeds `recommendedNextTool` hints for the download chain\n *\n * @module openai-agents\n */\n\nimport type { ZuoraAsyncJobResult } from \"../shared/async-jobs.js\";\nimport {\n buildToolMessagePayload,\n resolveAgentToolFollowUps,\n} from \"../shared/agent-tool-follow-ups.js\";\nimport { strictifySchema } from \"../shared/utils/strict-schema.js\";\nimport type { ToolSelection, ZuoraToolDefinition } from \"../shared/types.js\";\nimport { ZuoraOpenAIAgentToolkit } from \"../openai/toolkit.js\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- @openai/agents is an optional peer dependency\ntype AgentsTool = any;\n\n/**\n * The minimal interface of `tool()` from `@openai/agents` that we need.\n * Typed as `unknown` so this module compiles without `@openai/agents` installed.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- @openai/agents tool() accepts any options shape\ntype AgentsToolFactory = (options: any) => AgentsTool;\n\nconst isAsyncJobResult = (data: unknown): data is ZuoraAsyncJobResult =>\n data != null &&\n typeof data === \"object\" &&\n (data as ZuoraAsyncJobResult).status === \"pending\" &&\n typeof (data as ZuoraAsyncJobResult).jobId === \"string\";\n\n/**\n * Converts a single `ZuoraToolDefinition` into an `@openai/agents` `tool()`\n * object with the `execute()` function fully wired to the Zuora toolkit.\n *\n * Schema strictification and async-job handling are applied internally —\n * callers receive a ready-to-use tool without needing to know about them.\n *\n * @param toolFactory - The `tool` function imported from `@openai/agents`\n * @param def - The Zuora tool definition\n * @param toolkit - The Zuora toolkit instance (provides callTool / waitForJob)\n */\nexport const buildAgentsTool = (\n toolFactory: AgentsToolFactory,\n sanitizedName: string,\n def: ZuoraToolDefinition,\n toolkit: ZuoraOpenAIAgentToolkit,\n): AgentsTool =>\n toolFactory({\n name: sanitizedName,\n description: def.description,\n // Strictify the schema for the OpenAI Responses API — adds\n // additionalProperties:false and required[] to all nested objects.\n // strict:false is a belt-and-suspenders safeguard at the API level.\n parameters: strictifySchema(def.inputSchema as Record<string, unknown>),\n strict: false,\n\n // Write tools pause the run for CLI / web HITL via SDK interruptions.\n needsApproval: def.meta.access === \"write\",\n\n execute: async (args: Record<string, unknown>): Promise<string> => {\n // 1. Execute the Zuora MCP tool. approvalPolicy fires here as a\n // governance backstop even if needsApproval already allowed the call.\n let result = await toolkit.callTool(def.name, args);\n\n // 2. If the tool started an async job, block until it completes.\n // Capture the jobId before waitForJob() in case the final result\n // omits it at a recognisable path.\n let asyncJobId: string | undefined;\n if (isAsyncJobResult(result.data)) {\n asyncJobId = result.data.jobId;\n result = await toolkit.waitForJob(def.name, result.data);\n }\n\n // 3. Detect downloadable outputs and embed guidance for the model.\n // recommendedNextTool / recommendedNextArgs tell the model to call\n // download_query_result → read_downloaded_file automatically.\n const followUp = resolveAgentToolFollowUps(\n result,\n asyncJobId ? { asyncJobId } : {},\n );\n const payload = buildToolMessagePayload(result, followUp);\n\n return JSON.stringify(payload);\n },\n });\n\n/**\n * Converts the Zuora toolkit's tool catalog into `@openai/agents` `tool()`\n * objects ready to pass to `new Agent({ tools })`.\n *\n * @param toolFactory - The `tool` function imported from `@openai/agents`\n * @param toolkit - An initialised `ZuoraOpenAIAgentToolkit` instance\n * @param selection - Bundle and mode filter (same as `toolkit.getTools()`)\n * @param maxTools - Optional cap on returned tool count\n */\nexport const buildAgentsTools = async (\n toolFactory: AgentsToolFactory,\n toolkit: ZuoraOpenAIAgentToolkit,\n selection?: ToolSelection,\n maxTools?: number,\n): Promise<AgentsTool[]> => {\n const chatTools = await toolkit.getTools(selection, maxTools);\n\n return chatTools.flatMap((chatTool) => {\n if (chatTool.type !== \"function\") return [];\n const sanitizedName = chatTool.function.name;\n const def = toolkit.resolveToolDefinition(sanitizedName);\n if (!def) return [];\n return [buildAgentsTool(toolFactory, sanitizedName, def, toolkit)];\n });\n};\n"],"mappings":";AAAA,SAAS,YAAY;;;AC4Bd,IAAM,yBAAN,cAAqC,MAAM;AAAA,EACvC;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAET,YAAY,QAQT;AACD,UAAM,OAAO,OAAO;AACpB,SAAK,OAAO;AACZ,SAAK,OAAO,OAAO;AACnB,SAAK,WAAW,OAAO;AACvB,SAAK,cAAc,OAAO,eAAe,OAAO,aAAa;AAC7D,SAAK,YAAY,OAAO,aAAa;AACrC,SAAK,YAAY,OAAO;AACxB,SAAK,UAAU,OAAO;AAAA,EACxB;AACF;;;ACnDO,IAAM,aAAa;AAAA,EACxB,UAAU;AAAA,EACV,cAAc;AAChB;AAyRO,IAAM,uBAAuB;AAAA,EAClC,KAAK;AAAA,EACL,WAAW;AAAA,EACX,UAAU;AAAA,EACV,kBAAkB;AAAA,EAClB,oBAAoB;AACtB;;;ACnSO,IAAM,uBAAuB,CAAC,QA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ifact","fs","isNodeErrorCode","path","fs","fs","isNodeErrorCode","nativeFilesystemError","isNodeErrorCode","nativeFilesystemError","os","path","path","os","tool","tool","tool","tool","access","normalizeStringList","normalized","path","tool","eventError","rawOutputForEvent","payload","isAsyncJobResult"]}
|