@inkeep/agents-api 0.0.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/LICENSE.md +56 -0
- package/SUPPLEMENTAL_TERMS.md +40 -0
- package/dist/.well-known/workflow/v1/flow.cjs +46446 -0
- package/dist/.well-known/workflow/v1/flow.cjs.debug.json +8 -0
- package/dist/.well-known/workflow/v1/manifest.debug.json +93 -0
- package/dist/.well-known/workflow/v1/step.cjs +219923 -0
- package/dist/.well-known/workflow/v1/step.cjs.debug.json +8 -0
- package/dist/.well-known/workflow/v1/webhook.mjs +29 -0
- package/dist/createApp.d.ts +10 -0
- package/dist/createApp.js +170 -0
- package/dist/data/db/index.d.ts +4 -0
- package/dist/data/db/index.js +5 -0
- package/dist/data/db/manageDbClient.d.ts +6 -0
- package/dist/data/db/manageDbClient.js +9 -0
- package/dist/data/db/manageDbPool.d.ts +6 -0
- package/dist/data/db/manageDbPool.js +9 -0
- package/dist/data/db/runDbClient.d.ts +6 -0
- package/dist/data/db/runDbClient.js +9 -0
- package/dist/domains/evals/index.d.ts +13 -0
- package/dist/domains/evals/index.js +13 -0
- package/dist/domains/evals/routes/datasetTriggers.d.ts +7 -0
- package/dist/domains/evals/routes/datasetTriggers.js +65 -0
- package/dist/domains/evals/routes/evaluationTriggers.d.ts +11 -0
- package/dist/domains/evals/routes/evaluationTriggers.js +311 -0
- package/dist/domains/evals/routes/index.d.ts +7 -0
- package/dist/domains/evals/routes/index.js +12 -0
- package/dist/domains/evals/scripts/build-workflow.d.ts +1 -0
- package/dist/domains/evals/scripts/build-workflow.js +31 -0
- package/dist/domains/evals/services/EvaluationService.d.ts +96 -0
- package/dist/domains/evals/services/EvaluationService.js +863 -0
- package/dist/domains/evals/services/conversationEvaluation.d.ts +15 -0
- package/dist/domains/evals/services/conversationEvaluation.js +102 -0
- package/dist/domains/evals/services/datasetRun.d.ts +16 -0
- package/dist/domains/evals/services/datasetRun.js +43 -0
- package/dist/domains/evals/services/evaluationJob.d.ts +17 -0
- package/dist/domains/evals/services/evaluationJob.js +65 -0
- package/dist/domains/evals/services/startEvaluation.d.ts +19 -0
- package/dist/domains/evals/services/startEvaluation.js +18 -0
- package/dist/domains/evals/workflow/functions/evaluateConversation.d.ts +28 -0
- package/dist/domains/evals/workflow/functions/evaluateConversation.js +134 -0
- package/dist/domains/evals/workflow/functions/runDatasetItem.d.ts +36 -0
- package/dist/domains/evals/workflow/functions/runDatasetItem.js +204 -0
- package/dist/domains/evals/workflow/index.d.ts +4 -0
- package/dist/domains/evals/workflow/index.js +5 -0
- package/dist/domains/evals/workflow/routes.d.ts +7 -0
- package/dist/domains/evals/workflow/routes.js +106 -0
- package/dist/domains/evals/workflow/world.d.ts +4 -0
- package/dist/domains/evals/workflow/world.js +36 -0
- package/dist/domains/index.d.ts +4 -0
- package/dist/domains/index.js +5 -0
- package/dist/domains/manage/index.d.ts +12 -0
- package/dist/domains/manage/index.js +31 -0
- package/dist/domains/manage/routes/agent.d.ts +9 -0
- package/dist/domains/manage/routes/agent.js +264 -0
- package/dist/domains/manage/routes/agentFull.d.ts +9 -0
- package/dist/domains/manage/routes/agentFull.js +207 -0
- package/dist/domains/manage/routes/agentToolRelations.d.ts +9 -0
- package/dist/domains/manage/routes/agentToolRelations.js +289 -0
- package/dist/domains/manage/routes/apiKeys.d.ts +9 -0
- package/dist/domains/manage/routes/apiKeys.js +217 -0
- package/dist/domains/manage/routes/artifactComponents.d.ts +9 -0
- package/dist/domains/manage/routes/artifactComponents.js +210 -0
- package/dist/domains/manage/routes/branches.d.ts +9 -0
- package/dist/domains/manage/routes/branches.js +182 -0
- package/dist/domains/manage/routes/cliAuth.d.ts +9 -0
- package/dist/domains/manage/routes/cliAuth.js +60 -0
- package/dist/domains/manage/routes/contextConfigs.d.ts +9 -0
- package/dist/domains/manage/routes/contextConfigs.js +189 -0
- package/dist/domains/manage/routes/conversations.d.ts +7 -0
- package/dist/domains/manage/routes/conversations.js +59 -0
- package/dist/domains/manage/routes/credentialStores.d.ts +9 -0
- package/dist/domains/manage/routes/credentialStores.js +86 -0
- package/dist/domains/manage/routes/credentials.d.ts +9 -0
- package/dist/domains/manage/routes/credentials.js +207 -0
- package/dist/domains/manage/routes/dataComponents.d.ts +9 -0
- package/dist/domains/manage/routes/dataComponents.js +192 -0
- package/dist/domains/manage/routes/evals/datasetItems.d.ts +9 -0
- package/dist/domains/manage/routes/evals/datasetItems.js +310 -0
- package/dist/domains/manage/routes/evals/datasetRunConfigs.d.ts +9 -0
- package/dist/domains/manage/routes/evals/datasetRunConfigs.js +402 -0
- package/dist/domains/manage/routes/evals/datasetRuns.d.ts +9 -0
- package/dist/domains/manage/routes/evals/datasetRuns.js +256 -0
- package/dist/domains/manage/routes/evals/datasets.d.ts +9 -0
- package/dist/domains/manage/routes/evals/datasets.js +238 -0
- package/dist/domains/manage/routes/evals/evaluationJobConfigEvaluatorRelations.d.ts +9 -0
- package/dist/domains/manage/routes/evals/evaluationJobConfigEvaluatorRelations.js +146 -0
- package/dist/domains/manage/routes/evals/evaluationJobConfigs.d.ts +9 -0
- package/dist/domains/manage/routes/evals/evaluationJobConfigs.js +364 -0
- package/dist/domains/manage/routes/evals/evaluationResults.d.ts +7 -0
- package/dist/domains/manage/routes/evals/evaluationResults.js +192 -0
- package/dist/domains/manage/routes/evals/evaluationRunConfigs.d.ts +9 -0
- package/dist/domains/manage/routes/evals/evaluationRunConfigs.js +403 -0
- package/dist/domains/manage/routes/evals/evaluationSuiteConfigEvaluatorRelations.d.ts +9 -0
- package/dist/domains/manage/routes/evals/evaluationSuiteConfigEvaluatorRelations.js +146 -0
- package/dist/domains/manage/routes/evals/evaluationSuiteConfigs.d.ts +9 -0
- package/dist/domains/manage/routes/evals/evaluationSuiteConfigs.js +246 -0
- package/dist/domains/manage/routes/evals/evaluators.d.ts +9 -0
- package/dist/domains/manage/routes/evals/evaluators.js +281 -0
- package/dist/domains/manage/routes/evals/index.d.ts +9 -0
- package/dist/domains/manage/routes/evals/index.js +26 -0
- package/dist/domains/manage/routes/externalAgents.d.ts +9 -0
- package/dist/domains/manage/routes/externalAgents.js +199 -0
- package/dist/domains/manage/routes/functionTools.d.ts +9 -0
- package/dist/domains/manage/routes/functionTools.js +256 -0
- package/dist/domains/manage/routes/functions.d.ts +9 -0
- package/dist/domains/manage/routes/functions.js +285 -0
- package/dist/domains/manage/routes/index.d.ts +7 -0
- package/dist/domains/manage/routes/index.js +68 -0
- package/dist/domains/manage/routes/invitations.d.ts +9 -0
- package/dist/domains/manage/routes/invitations.js +41 -0
- package/dist/domains/manage/routes/mcp.d.ts +7 -0
- package/dist/domains/manage/routes/mcp.js +45 -0
- package/dist/domains/manage/routes/mcpCatalog.d.ts +9 -0
- package/dist/domains/manage/routes/mcpCatalog.js +454 -0
- package/dist/domains/manage/routes/oauth.d.ts +10 -0
- package/dist/domains/manage/routes/oauth.js +327 -0
- package/dist/domains/manage/routes/playgroundToken.d.ts +9 -0
- package/dist/domains/manage/routes/playgroundToken.js +127 -0
- package/dist/domains/manage/routes/projectFull.d.ts +9 -0
- package/dist/domains/manage/routes/projectFull.js +304 -0
- package/dist/domains/manage/routes/projectMembers.d.ts +9 -0
- package/dist/domains/manage/routes/projectMembers.js +201 -0
- package/dist/domains/manage/routes/projectPermissions.d.ts +9 -0
- package/dist/domains/manage/routes/projectPermissions.js +68 -0
- package/dist/domains/manage/routes/projects.d.ts +9 -0
- package/dist/domains/manage/routes/projects.js +279 -0
- package/dist/domains/manage/routes/ref.d.ts +9 -0
- package/dist/domains/manage/routes/ref.js +33 -0
- package/dist/domains/manage/routes/signoz.d.ts +10 -0
- package/dist/domains/manage/routes/signoz.js +159 -0
- package/dist/domains/manage/routes/subAgentArtifactComponents.d.ts +9 -0
- package/dist/domains/manage/routes/subAgentArtifactComponents.js +202 -0
- package/dist/domains/manage/routes/subAgentDataComponents.d.ts +9 -0
- package/dist/domains/manage/routes/subAgentDataComponents.js +201 -0
- package/dist/domains/manage/routes/subAgentExternalAgentRelations.d.ts +9 -0
- package/dist/domains/manage/routes/subAgentExternalAgentRelations.js +216 -0
- package/dist/domains/manage/routes/subAgentFunctionTools.d.ts +9 -0
- package/dist/domains/manage/routes/subAgentFunctionTools.js +205 -0
- package/dist/domains/manage/routes/subAgentRelations.d.ts +9 -0
- package/dist/domains/manage/routes/subAgentRelations.js +263 -0
- package/dist/domains/manage/routes/subAgentTeamAgentRelations.d.ts +9 -0
- package/dist/domains/manage/routes/subAgentTeamAgentRelations.js +216 -0
- package/dist/domains/manage/routes/subAgentToolRelations.d.ts +9 -0
- package/dist/domains/manage/routes/subAgentToolRelations.js +289 -0
- package/dist/domains/manage/routes/subAgents.d.ts +9 -0
- package/dist/domains/manage/routes/subAgents.js +220 -0
- package/dist/domains/manage/routes/thirdPartyMCPServers.d.ts +9 -0
- package/dist/domains/manage/routes/thirdPartyMCPServers.js +72 -0
- package/dist/domains/manage/routes/tools.d.ts +9 -0
- package/dist/domains/manage/routes/tools.js +261 -0
- package/dist/domains/manage/routes/triggers.d.ts +9 -0
- package/dist/domains/manage/routes/triggers.js +423 -0
- package/dist/domains/manage/routes/userOrganizations.d.ts +9 -0
- package/dist/domains/manage/routes/userOrganizations.js +58 -0
- package/dist/domains/run/a2a/client.d.ts +186 -0
- package/dist/domains/run/a2a/client.js +524 -0
- package/dist/domains/run/a2a/handlers.d.ts +7 -0
- package/dist/domains/run/a2a/handlers.js +582 -0
- package/dist/domains/run/a2a/transfer.d.ts +27 -0
- package/dist/domains/run/a2a/transfer.js +50 -0
- package/dist/domains/run/a2a/types.d.ts +79 -0
- package/dist/domains/run/a2a/types.js +22 -0
- package/dist/domains/run/agents/Agent.d.ts +273 -0
- package/dist/domains/run/agents/Agent.js +2104 -0
- package/dist/domains/run/agents/ModelFactory.d.ts +63 -0
- package/dist/domains/run/agents/ModelFactory.js +194 -0
- package/dist/domains/run/agents/SystemPromptBuilder.d.ts +21 -0
- package/dist/domains/run/agents/SystemPromptBuilder.js +48 -0
- package/dist/domains/run/agents/ToolSessionManager.d.ts +63 -0
- package/dist/domains/run/agents/ToolSessionManager.js +146 -0
- package/dist/domains/run/agents/generateTaskHandler.d.ts +44 -0
- package/dist/domains/run/agents/generateTaskHandler.js +384 -0
- package/dist/domains/run/agents/relationTools.d.ts +64 -0
- package/dist/domains/run/agents/relationTools.js +365 -0
- package/dist/domains/run/agents/types.d.ts +31 -0
- package/dist/domains/run/agents/types.js +1 -0
- package/dist/domains/run/agents/versions/v1/Phase1Config.d.ts +29 -0
- package/dist/domains/run/agents/versions/v1/Phase1Config.js +458 -0
- package/dist/domains/run/agents/versions/v1/Phase2Config.d.ts +33 -0
- package/dist/domains/run/agents/versions/v1/Phase2Config.js +341 -0
- package/dist/domains/run/constants/execution-limits/defaults.d.ts +51 -0
- package/dist/domains/run/constants/execution-limits/defaults.js +52 -0
- package/dist/domains/run/constants/execution-limits/index.d.ts +6 -0
- package/dist/domains/run/constants/execution-limits/index.js +21 -0
- package/dist/domains/run/context/ContextFetcher.d.ts +68 -0
- package/dist/domains/run/context/ContextFetcher.js +276 -0
- package/dist/domains/run/context/ContextResolver.d.ts +56 -0
- package/dist/domains/run/context/ContextResolver.js +273 -0
- package/dist/domains/run/context/context.d.ts +19 -0
- package/dist/domains/run/context/context.js +108 -0
- package/dist/domains/run/context/contextCache.d.ts +56 -0
- package/dist/domains/run/context/contextCache.js +174 -0
- package/dist/domains/run/context/index.d.ts +6 -0
- package/dist/domains/run/context/index.js +7 -0
- package/dist/domains/run/context/validation.d.ts +39 -0
- package/dist/domains/run/context/validation.js +255 -0
- package/dist/domains/run/data/agent.d.ts +7 -0
- package/dist/domains/run/data/agent.js +67 -0
- package/dist/domains/run/data/agents.d.ts +34 -0
- package/dist/domains/run/data/agents.js +131 -0
- package/dist/domains/run/data/conversations.d.ts +129 -0
- package/dist/domains/run/data/conversations.js +517 -0
- package/dist/domains/run/handlers/executionHandler.d.ts +42 -0
- package/dist/domains/run/handlers/executionHandler.js +484 -0
- package/dist/domains/run/index.d.ts +13 -0
- package/dist/domains/run/index.js +21 -0
- package/dist/domains/run/routes/agents.d.ts +13 -0
- package/dist/domains/run/routes/agents.js +141 -0
- package/dist/domains/run/routes/chat.d.ts +14 -0
- package/dist/domains/run/routes/chat.js +300 -0
- package/dist/domains/run/routes/chatDataStream.d.ts +14 -0
- package/dist/domains/run/routes/chatDataStream.js +381 -0
- package/dist/domains/run/routes/mcp.d.ts +14 -0
- package/dist/domains/run/routes/mcp.js +483 -0
- package/dist/domains/run/routes/webhooks.d.ts +15 -0
- package/dist/domains/run/routes/webhooks.js +396 -0
- package/dist/domains/run/services/AgentSession.d.ts +354 -0
- package/dist/domains/run/services/AgentSession.js +1203 -0
- package/dist/domains/run/services/ArtifactParser.d.ts +105 -0
- package/dist/domains/run/services/ArtifactParser.js +338 -0
- package/dist/domains/run/services/ArtifactService.d.ts +122 -0
- package/dist/domains/run/services/ArtifactService.js +629 -0
- package/dist/domains/run/services/BaseCompressor.d.ts +183 -0
- package/dist/domains/run/services/BaseCompressor.js +500 -0
- package/dist/domains/run/services/ConversationCompressor.d.ts +32 -0
- package/dist/domains/run/services/ConversationCompressor.js +91 -0
- package/dist/domains/run/services/IncrementalStreamParser.d.ts +98 -0
- package/dist/domains/run/services/IncrementalStreamParser.js +327 -0
- package/dist/domains/run/services/MidGenerationCompressor.d.ts +63 -0
- package/dist/domains/run/services/MidGenerationCompressor.js +104 -0
- package/dist/domains/run/services/PendingToolApprovalManager.d.ts +62 -0
- package/dist/domains/run/services/PendingToolApprovalManager.js +133 -0
- package/dist/domains/run/services/ResponseFormatter.d.ts +39 -0
- package/dist/domains/run/services/ResponseFormatter.js +152 -0
- package/dist/domains/run/services/evaluationRunConfigMatcher.d.ts +4 -0
- package/dist/domains/run/services/evaluationRunConfigMatcher.js +7 -0
- package/dist/domains/run/tools/NativeSandboxExecutor.d.ts +38 -0
- package/dist/domains/run/tools/NativeSandboxExecutor.js +432 -0
- package/dist/domains/run/tools/SandboxExecutorFactory.d.ts +36 -0
- package/dist/domains/run/tools/SandboxExecutorFactory.js +80 -0
- package/dist/domains/run/tools/VercelSandboxExecutor.d.ts +71 -0
- package/dist/domains/run/tools/VercelSandboxExecutor.js +340 -0
- package/dist/domains/run/tools/distill-conversation-history-tool.d.ts +62 -0
- package/dist/domains/run/tools/distill-conversation-history-tool.js +206 -0
- package/dist/domains/run/tools/distill-conversation-tool.d.ts +41 -0
- package/dist/domains/run/tools/distill-conversation-tool.js +141 -0
- package/dist/domains/run/tools/sandbox-utils.d.ts +18 -0
- package/dist/domains/run/tools/sandbox-utils.js +53 -0
- package/dist/domains/run/types/chat.d.ts +27 -0
- package/dist/domains/run/types/chat.js +1 -0
- package/dist/domains/run/types/executionContext.d.ts +40 -0
- package/dist/domains/run/types/executionContext.js +28 -0
- package/dist/domains/run/types/xml.d.ts +9 -0
- package/dist/domains/run/utils/SchemaProcessor.d.ts +52 -0
- package/dist/domains/run/utils/SchemaProcessor.js +182 -0
- package/dist/domains/run/utils/agent-operations.d.ts +62 -0
- package/dist/domains/run/utils/agent-operations.js +53 -0
- package/dist/domains/run/utils/artifact-component-schema.d.ts +42 -0
- package/dist/domains/run/utils/artifact-component-schema.js +186 -0
- package/dist/domains/run/utils/cleanup.d.ts +21 -0
- package/dist/domains/run/utils/cleanup.js +59 -0
- package/dist/domains/run/utils/data-component-schema.d.ts +2 -0
- package/dist/domains/run/utils/data-component-schema.js +3 -0
- package/dist/domains/run/utils/default-status-schemas.d.ts +20 -0
- package/dist/domains/run/utils/default-status-schemas.js +24 -0
- package/dist/domains/run/utils/json-postprocessor.d.ts +13 -0
- package/dist/domains/run/utils/json-postprocessor.js +19 -0
- package/dist/domains/run/utils/model-context-utils.d.ts +39 -0
- package/dist/domains/run/utils/model-context-utils.js +181 -0
- package/dist/domains/run/utils/model-resolver.d.ts +6 -0
- package/dist/domains/run/utils/model-resolver.js +24 -0
- package/dist/domains/run/utils/project.d.ts +207 -0
- package/dist/domains/run/utils/project.js +315 -0
- package/dist/domains/run/utils/schema-validation.d.ts +44 -0
- package/dist/domains/run/utils/schema-validation.js +97 -0
- package/dist/domains/run/utils/stream-helpers.d.ts +193 -0
- package/dist/domains/run/utils/stream-helpers.js +510 -0
- package/dist/domains/run/utils/stream-registry.d.ts +22 -0
- package/dist/domains/run/utils/stream-registry.js +33 -0
- package/dist/domains/run/utils/token-estimator.d.ts +23 -0
- package/dist/domains/run/utils/token-estimator.js +17 -0
- package/dist/domains/run/utils/tracer.d.ts +7 -0
- package/dist/domains/run/utils/tracer.js +7 -0
- package/dist/env.d.ts +89 -0
- package/dist/env.js +69 -0
- package/dist/factory.d.ts +1535 -0
- package/dist/factory.js +42 -0
- package/dist/index.d.ts +1530 -0
- package/dist/index.js +44 -0
- package/dist/initialization.d.ts +6 -0
- package/dist/initialization.js +65 -0
- package/dist/instrumentation.d.ts +17 -0
- package/dist/instrumentation.js +68 -0
- package/dist/logger.d.ts +2 -0
- package/dist/logger.js +3 -0
- package/dist/middleware/branchScopedDb.d.ts +31 -0
- package/dist/middleware/branchScopedDb.js +137 -0
- package/dist/middleware/cors.d.ts +36 -0
- package/dist/middleware/cors.js +131 -0
- package/dist/middleware/errorHandler.d.ts +12 -0
- package/dist/middleware/errorHandler.js +88 -0
- package/dist/middleware/evalsAuth.d.ts +16 -0
- package/dist/middleware/evalsAuth.js +52 -0
- package/dist/middleware/index.d.ts +8 -0
- package/dist/middleware/index.js +9 -0
- package/dist/middleware/manageAuth.d.ts +25 -0
- package/dist/middleware/manageAuth.js +80 -0
- package/dist/middleware/projectAccess.d.ts +31 -0
- package/dist/middleware/projectAccess.js +118 -0
- package/dist/middleware/projectConfig.d.ts +25 -0
- package/dist/middleware/projectConfig.js +89 -0
- package/dist/middleware/ref.d.ts +61 -0
- package/dist/middleware/ref.js +239 -0
- package/dist/middleware/requirePermission.d.ts +14 -0
- package/dist/middleware/requirePermission.js +80 -0
- package/dist/middleware/runAuth.d.ts +29 -0
- package/dist/middleware/runAuth.js +253 -0
- package/dist/middleware/sessionAuth.d.ts +17 -0
- package/dist/middleware/sessionAuth.js +58 -0
- package/dist/middleware/tenantAccess.d.ts +22 -0
- package/dist/middleware/tenantAccess.js +63 -0
- package/dist/middleware/tracing.d.ts +7 -0
- package/dist/middleware/tracing.js +50 -0
- package/dist/openapi.d.ts +7 -0
- package/dist/openapi.js +156 -0
- package/dist/ssoHelpers.d.ts +20 -0
- package/dist/ssoHelpers.js +51 -0
- package/dist/templates/v1/phase1/system-prompt.js +5 -0
- package/dist/templates/v1/phase1/thinking-preparation.js +5 -0
- package/dist/templates/v1/phase1/tool.js +5 -0
- package/dist/templates/v1/phase2/data-component.js +5 -0
- package/dist/templates/v1/phase2/data-components.js +5 -0
- package/dist/templates/v1/phase2/system-prompt.js +5 -0
- package/dist/templates/v1/shared/artifact-retrieval-guidance.js +5 -0
- package/dist/templates/v1/shared/artifact.js +5 -0
- package/dist/types/app.d.ts +64 -0
- package/dist/types/app.js +1 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.js +1 -0
- package/dist/types/runExecutionContext.d.ts +25 -0
- package/dist/types/runExecutionContext.js +28 -0
- package/dist/utils/oauthService.d.ts +71 -0
- package/dist/utils/oauthService.js +106 -0
- package/dist/utils/signozHelpers.d.ts +9 -0
- package/dist/utils/signozHelpers.js +33 -0
- package/dist/utils/speakeasy.d.ts +93 -0
- package/dist/utils/speakeasy.js +44 -0
- package/dist/utils/tempApiKeys.d.ts +17 -0
- package/dist/utils/tempApiKeys.js +26 -0
- package/dist/utils/workflowApiHelpers.d.ts +1 -0
- package/dist/utils/workflowApiHelpers.js +1 -0
- package/package.json +126 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import runDbClient_default from "../../../data/db/runDbClient.js";
|
|
2
|
+
import { ContextResolver } from "./ContextResolver.js";
|
|
3
|
+
import { getConversation, getLogger, getTracer, setSpanWithError, updateConversation } from "@inkeep/agents-core";
|
|
4
|
+
import { SpanStatusCode } from "@opentelemetry/api";
|
|
5
|
+
|
|
6
|
+
//#region src/domains/run/context/context.ts
|
|
7
|
+
const logger = getLogger("context");
|
|
8
|
+
const tracer = getTracer("context");
|
|
9
|
+
async function determineContextTrigger(tenantId, projectId, conversationId) {
|
|
10
|
+
const conversation = await getConversation(runDbClient_default)({
|
|
11
|
+
scopes: {
|
|
12
|
+
tenantId,
|
|
13
|
+
projectId
|
|
14
|
+
},
|
|
15
|
+
conversationId
|
|
16
|
+
});
|
|
17
|
+
if (!conversation || !conversation.lastContextResolution) return "initialization";
|
|
18
|
+
return "invocation";
|
|
19
|
+
}
|
|
20
|
+
async function handleContextConfigChange(executionContext, conversationId, newContextConfigId, credentialStores) {
|
|
21
|
+
const { tenantId, projectId, agentId } = executionContext;
|
|
22
|
+
const conversation = await getConversation(runDbClient_default)({
|
|
23
|
+
scopes: {
|
|
24
|
+
tenantId,
|
|
25
|
+
projectId
|
|
26
|
+
},
|
|
27
|
+
conversationId
|
|
28
|
+
});
|
|
29
|
+
if (!conversation) return;
|
|
30
|
+
if (conversation.lastContextResolution) {
|
|
31
|
+
await new ContextResolver(executionContext, credentialStores).clearCache(tenantId, projectId, conversationId);
|
|
32
|
+
logger.info({
|
|
33
|
+
conversationId,
|
|
34
|
+
agentId,
|
|
35
|
+
contextConfigId: newContextConfigId
|
|
36
|
+
}, "Potential context config change for existing conversation, cache cleared");
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
async function handleContextResolution({ executionContext, conversationId, headers: headers$1, credentialStores }) {
|
|
40
|
+
return tracer.startActiveSpan("context.handle_context_resolution", { attributes: { "context.headers_keys": Object.keys(headers$1) } }, async (parentSpan) => {
|
|
41
|
+
const { tenantId, projectId, agentId, project } = executionContext;
|
|
42
|
+
const agent = project.agents[agentId];
|
|
43
|
+
let trigger;
|
|
44
|
+
try {
|
|
45
|
+
const contextConfig = agent.contextConfig;
|
|
46
|
+
if (!contextConfig) {
|
|
47
|
+
logger.debug({ agentId }, "No context config found for agent");
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
await handleContextConfigChange(executionContext, conversationId, contextConfig.id, credentialStores);
|
|
51
|
+
trigger = await determineContextTrigger(tenantId, projectId, conversationId);
|
|
52
|
+
const contextResult = await new ContextResolver(executionContext, credentialStores).resolve(contextConfig, {
|
|
53
|
+
triggerEvent: trigger,
|
|
54
|
+
conversationId,
|
|
55
|
+
headers: headers$1,
|
|
56
|
+
tenantId
|
|
57
|
+
});
|
|
58
|
+
logger.info({ contextResult }, "Context result");
|
|
59
|
+
const resolvedContext = {
|
|
60
|
+
...contextResult.resolvedContext,
|
|
61
|
+
$env: process.env
|
|
62
|
+
};
|
|
63
|
+
await updateConversation(runDbClient_default)({
|
|
64
|
+
scopes: {
|
|
65
|
+
tenantId,
|
|
66
|
+
projectId
|
|
67
|
+
},
|
|
68
|
+
conversationId,
|
|
69
|
+
data: { lastContextResolution: (/* @__PURE__ */ new Date()).toISOString() }
|
|
70
|
+
});
|
|
71
|
+
if (contextResult.errors.length > 0) parentSpan.setStatus({
|
|
72
|
+
code: SpanStatusCode.ERROR,
|
|
73
|
+
message: `Context resolution completed with errors`
|
|
74
|
+
});
|
|
75
|
+
else parentSpan.setStatus({ code: SpanStatusCode.OK });
|
|
76
|
+
logger.info({
|
|
77
|
+
conversationId,
|
|
78
|
+
agentId,
|
|
79
|
+
contextConfigId: contextConfig.id,
|
|
80
|
+
trigger,
|
|
81
|
+
resolvedKeys: Object.keys(resolvedContext),
|
|
82
|
+
cacheHits: contextResult.cacheHits.length,
|
|
83
|
+
cacheMisses: contextResult.cacheMisses.length,
|
|
84
|
+
fetchedDefinitions: contextResult.fetchedDefinitions.length,
|
|
85
|
+
errors: contextResult.errors.length
|
|
86
|
+
}, "Context resolution completed (contextConfigId derived from agent)");
|
|
87
|
+
return resolvedContext;
|
|
88
|
+
} catch (error) {
|
|
89
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
90
|
+
parentSpan.setAttributes({
|
|
91
|
+
"context.final_status": "failed",
|
|
92
|
+
"context.error_message": errorMessage
|
|
93
|
+
});
|
|
94
|
+
setSpanWithError(parentSpan, error instanceof Error ? error : new Error(String(error)));
|
|
95
|
+
logger.error({
|
|
96
|
+
error: errorMessage,
|
|
97
|
+
contextConfigId: agent?.contextConfig?.id,
|
|
98
|
+
trigger: await determineContextTrigger(tenantId, projectId, conversationId).catch(() => "unknown")
|
|
99
|
+
}, "Failed to resolve context, proceeding without context resolution");
|
|
100
|
+
return null;
|
|
101
|
+
} finally {
|
|
102
|
+
parentSpan.end();
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
//#endregion
|
|
108
|
+
export { determineContextTrigger, handleContextConfigChange, handleContextResolution };
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { FullExecutionContext } from "@inkeep/agents-core";
|
|
2
|
+
|
|
3
|
+
//#region src/domains/run/context/contextCache.d.ts
|
|
4
|
+
interface CacheEntry {
|
|
5
|
+
contextConfigId: string;
|
|
6
|
+
contextVariableKey: string;
|
|
7
|
+
conversationId: string;
|
|
8
|
+
value: unknown;
|
|
9
|
+
requestHash?: string;
|
|
10
|
+
tenantId: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Context cache with request hash-based invalidation and graceful error handling.
|
|
14
|
+
*
|
|
15
|
+
* Implements conversation-scoped caching with smart cache invalidation based on
|
|
16
|
+
* request hash changes. All cache errors are treated as cache misses to ensure
|
|
17
|
+
* system reliability.
|
|
18
|
+
*/
|
|
19
|
+
declare class ContextCache {
|
|
20
|
+
private executionContext;
|
|
21
|
+
constructor(executionContext: FullExecutionContext);
|
|
22
|
+
/**
|
|
23
|
+
* Get cached context data for a conversation
|
|
24
|
+
*/
|
|
25
|
+
get({
|
|
26
|
+
conversationId,
|
|
27
|
+
contextConfigId,
|
|
28
|
+
contextVariableKey,
|
|
29
|
+
requestHash
|
|
30
|
+
}: {
|
|
31
|
+
conversationId: string;
|
|
32
|
+
contextConfigId: string;
|
|
33
|
+
contextVariableKey: string;
|
|
34
|
+
requestHash?: string;
|
|
35
|
+
}): Promise<CacheEntry | null>;
|
|
36
|
+
/**
|
|
37
|
+
* Set cached context data for a conversation
|
|
38
|
+
*/
|
|
39
|
+
set(entry: CacheEntry): Promise<void>;
|
|
40
|
+
/**
|
|
41
|
+
* Clear cache entries for a specific conversation
|
|
42
|
+
*/
|
|
43
|
+
clearConversation(tenantId: string, projectId: string, conversationId: string): Promise<void>;
|
|
44
|
+
/**
|
|
45
|
+
* Clear all cache entries for a specific context configuration
|
|
46
|
+
*/
|
|
47
|
+
clearContextConfig(tenantId: string, projectId: string, contextConfigId: string): Promise<void>;
|
|
48
|
+
/**
|
|
49
|
+
* Clean up expired or orphaned cache entries
|
|
50
|
+
*/
|
|
51
|
+
cleanup(): Promise<void>;
|
|
52
|
+
invalidateInvocationDefinitions(tenantId: string, projectId: string, conversationId: string, contextConfigId: string, definitionIds: string[]): Promise<void>;
|
|
53
|
+
invalidateHeaders(tenantId: string, projectId: string, conversationId: string, contextConfigId: string): Promise<void>;
|
|
54
|
+
}
|
|
55
|
+
//#endregion
|
|
56
|
+
export { CacheEntry, ContextCache };
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import runDbClient_default from "../../../data/db/runDbClient.js";
|
|
2
|
+
import { cleanupTenantCache, clearContextConfigCache, clearConversationCache, generateId, getCacheEntry, getLogger, invalidateHeadersCache, invalidateInvocationDefinitionsCache, setCacheEntry } from "@inkeep/agents-core";
|
|
3
|
+
|
|
4
|
+
//#region src/domains/run/context/contextCache.ts
|
|
5
|
+
const logger = getLogger("context-cache");
|
|
6
|
+
/**
|
|
7
|
+
* Context cache with request hash-based invalidation and graceful error handling.
|
|
8
|
+
*
|
|
9
|
+
* Implements conversation-scoped caching with smart cache invalidation based on
|
|
10
|
+
* request hash changes. All cache errors are treated as cache misses to ensure
|
|
11
|
+
* system reliability.
|
|
12
|
+
*/
|
|
13
|
+
var ContextCache = class {
|
|
14
|
+
executionContext;
|
|
15
|
+
constructor(executionContext) {
|
|
16
|
+
this.executionContext = executionContext;
|
|
17
|
+
logger.info({ tenantId: this.executionContext.tenantId }, "ContextCache initialized");
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Get cached context data for a conversation
|
|
21
|
+
*/
|
|
22
|
+
async get({ conversationId, contextConfigId, contextVariableKey, requestHash }) {
|
|
23
|
+
try {
|
|
24
|
+
let cacheEntry = null;
|
|
25
|
+
cacheEntry = await getCacheEntry(runDbClient_default)({
|
|
26
|
+
conversationId,
|
|
27
|
+
contextConfigId,
|
|
28
|
+
contextVariableKey,
|
|
29
|
+
requestHash
|
|
30
|
+
});
|
|
31
|
+
if (!cacheEntry) return null;
|
|
32
|
+
return {
|
|
33
|
+
contextConfigId: cacheEntry.contextConfigId,
|
|
34
|
+
contextVariableKey: cacheEntry.contextVariableKey,
|
|
35
|
+
conversationId: cacheEntry.conversationId,
|
|
36
|
+
value: cacheEntry.value,
|
|
37
|
+
requestHash: cacheEntry.requestHash || void 0,
|
|
38
|
+
tenantId: this.executionContext.tenantId
|
|
39
|
+
};
|
|
40
|
+
} catch (error) {
|
|
41
|
+
logger.error({
|
|
42
|
+
conversationId,
|
|
43
|
+
contextConfigId,
|
|
44
|
+
contextVariableKey,
|
|
45
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
46
|
+
}, "Failed to get cache entry");
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Set cached context data for a conversation
|
|
52
|
+
*/
|
|
53
|
+
async set(entry) {
|
|
54
|
+
try {
|
|
55
|
+
const { tenantId, projectId } = this.executionContext;
|
|
56
|
+
const cacheData = {
|
|
57
|
+
id: generateId(),
|
|
58
|
+
tenantId,
|
|
59
|
+
projectId,
|
|
60
|
+
conversationId: entry.conversationId,
|
|
61
|
+
contextConfigId: entry.contextConfigId,
|
|
62
|
+
contextVariableKey: entry.contextVariableKey,
|
|
63
|
+
value: entry.value,
|
|
64
|
+
requestHash: entry.requestHash,
|
|
65
|
+
fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
66
|
+
fetchSource: `${entry.contextConfigId}:${entry.contextVariableKey}`,
|
|
67
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
68
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
69
|
+
ref: this.executionContext.resolvedRef
|
|
70
|
+
};
|
|
71
|
+
await setCacheEntry(runDbClient_default)(cacheData);
|
|
72
|
+
logger.debug({
|
|
73
|
+
conversationId: entry.conversationId,
|
|
74
|
+
contextConfigId: entry.contextConfigId,
|
|
75
|
+
contextVariableKey: entry.contextVariableKey
|
|
76
|
+
}, "Cache entry set successfully");
|
|
77
|
+
} catch (error) {
|
|
78
|
+
logger.error({
|
|
79
|
+
conversationId: entry.conversationId,
|
|
80
|
+
contextConfigId: entry.contextConfigId,
|
|
81
|
+
contextVariableKey: entry.contextVariableKey,
|
|
82
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
83
|
+
}, "Failed to set cache entry");
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Clear cache entries for a specific conversation
|
|
88
|
+
*/
|
|
89
|
+
async clearConversation(tenantId, projectId, conversationId) {
|
|
90
|
+
try {
|
|
91
|
+
const result = await clearConversationCache(runDbClient_default)({
|
|
92
|
+
scopes: {
|
|
93
|
+
tenantId,
|
|
94
|
+
projectId
|
|
95
|
+
},
|
|
96
|
+
conversationId
|
|
97
|
+
});
|
|
98
|
+
logger.info({
|
|
99
|
+
conversationId,
|
|
100
|
+
rowsCleared: result
|
|
101
|
+
}, "Conversation cache cleared successfully");
|
|
102
|
+
} catch (error) {
|
|
103
|
+
logger.error({
|
|
104
|
+
conversationId,
|
|
105
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
106
|
+
}, "Failed to clear conversation cache");
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Clear all cache entries for a specific context configuration
|
|
112
|
+
*/
|
|
113
|
+
async clearContextConfig(tenantId, projectId, contextConfigId) {
|
|
114
|
+
try {
|
|
115
|
+
const result = await clearContextConfigCache(runDbClient_default)({
|
|
116
|
+
scopes: {
|
|
117
|
+
tenantId,
|
|
118
|
+
projectId
|
|
119
|
+
},
|
|
120
|
+
contextConfigId
|
|
121
|
+
});
|
|
122
|
+
logger.info({
|
|
123
|
+
contextConfigId,
|
|
124
|
+
rowsCleared: result
|
|
125
|
+
}, "Context config cache cleared successfully");
|
|
126
|
+
} catch (error) {
|
|
127
|
+
logger.error({
|
|
128
|
+
contextConfigId,
|
|
129
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
130
|
+
}, "Failed to clear context config cache");
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Clean up expired or orphaned cache entries
|
|
136
|
+
*/
|
|
137
|
+
async cleanup() {
|
|
138
|
+
try {
|
|
139
|
+
const { tenantId, projectId } = this.executionContext;
|
|
140
|
+
const result = await cleanupTenantCache(runDbClient_default)({ scopes: {
|
|
141
|
+
tenantId,
|
|
142
|
+
projectId
|
|
143
|
+
} });
|
|
144
|
+
logger.info({ rowsCleared: result }, "Cache cleanup completed");
|
|
145
|
+
} catch (error) {
|
|
146
|
+
logger.error({ error: error instanceof Error ? error.message : "Unknown error" }, "Failed to cleanup cache");
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
async invalidateInvocationDefinitions(tenantId, projectId, conversationId, contextConfigId, definitionIds) {
|
|
151
|
+
await invalidateInvocationDefinitionsCache(runDbClient_default)({
|
|
152
|
+
scopes: {
|
|
153
|
+
tenantId,
|
|
154
|
+
projectId
|
|
155
|
+
},
|
|
156
|
+
conversationId,
|
|
157
|
+
contextConfigId,
|
|
158
|
+
invocationDefinitionIds: definitionIds
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
async invalidateHeaders(tenantId, projectId, conversationId, contextConfigId) {
|
|
162
|
+
await invalidateHeadersCache(runDbClient_default)({
|
|
163
|
+
scopes: {
|
|
164
|
+
tenantId,
|
|
165
|
+
projectId
|
|
166
|
+
},
|
|
167
|
+
conversationId,
|
|
168
|
+
contextConfigId
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
//#endregion
|
|
174
|
+
export { ContextCache };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { ContextFetcher, FetchResult, MissingRequiredVariableError } from "./ContextFetcher.js";
|
|
2
|
+
import { ContextResolutionOptions, ContextResolutionResult, ContextResolver, ResolvedContext } from "./ContextResolver.js";
|
|
3
|
+
import { determineContextTrigger, handleContextConfigChange, handleContextResolution } from "./context.js";
|
|
4
|
+
import { CacheEntry, ContextCache } from "./contextCache.js";
|
|
5
|
+
import { ContextValidationError, ContextValidationResult, HTTP_REQUEST_PARTS, HttpRequestPart, ParsedHttpRequest, contextValidationMiddleware, getCachedValidator, isValidHttpRequest, validateAgainstJsonSchema, validateHeaders, validateHttpRequestHeaders, validationHelper } from "./validation.js";
|
|
6
|
+
export { type CacheEntry, ContextCache, ContextFetcher, type ContextResolutionOptions, type ContextResolutionResult, ContextResolver, type ContextValidationError, type ContextValidationResult, type FetchResult, HTTP_REQUEST_PARTS, type HttpRequestPart, MissingRequiredVariableError, type ParsedHttpRequest, type ResolvedContext, contextValidationMiddleware, determineContextTrigger, getCachedValidator, handleContextConfigChange, handleContextResolution, isValidHttpRequest, validateAgainstJsonSchema, validateHeaders, validateHttpRequestHeaders, validationHelper };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { ContextCache } from "./contextCache.js";
|
|
2
|
+
import { ContextResolver } from "./ContextResolver.js";
|
|
3
|
+
import { HTTP_REQUEST_PARTS, contextValidationMiddleware, getCachedValidator, isValidHttpRequest, validateAgainstJsonSchema, validateHeaders, validateHttpRequestHeaders, validationHelper } from "./validation.js";
|
|
4
|
+
import { ContextFetcher, MissingRequiredVariableError } from "./ContextFetcher.js";
|
|
5
|
+
import { determineContextTrigger, handleContextConfigChange, handleContextResolution } from "./context.js";
|
|
6
|
+
|
|
7
|
+
export { ContextCache, ContextFetcher, ContextResolver, HTTP_REQUEST_PARTS, MissingRequiredVariableError, contextValidationMiddleware, determineContextTrigger, getCachedValidator, handleContextConfigChange, handleContextResolution, isValidHttpRequest, validateAgainstJsonSchema, validateHeaders, validateHttpRequestHeaders, validationHelper };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Context, Next } from "hono";
|
|
2
|
+
import { CredentialStoreRegistry, FullExecutionContext } from "@inkeep/agents-core";
|
|
3
|
+
import { ValidateFunction } from "ajv";
|
|
4
|
+
|
|
5
|
+
//#region src/domains/run/context/validation.d.ts
|
|
6
|
+
declare const HTTP_REQUEST_PARTS: readonly ["headers"];
|
|
7
|
+
type HttpRequestPart = (typeof HTTP_REQUEST_PARTS)[number];
|
|
8
|
+
interface ContextValidationError {
|
|
9
|
+
field: string;
|
|
10
|
+
message: string;
|
|
11
|
+
value?: unknown;
|
|
12
|
+
}
|
|
13
|
+
interface ContextValidationResult {
|
|
14
|
+
valid: boolean;
|
|
15
|
+
errors: ContextValidationError[];
|
|
16
|
+
validatedContext?: Record<string, unknown> | ParsedHttpRequest;
|
|
17
|
+
}
|
|
18
|
+
interface ParsedHttpRequest {
|
|
19
|
+
headers?: Record<string, string>;
|
|
20
|
+
}
|
|
21
|
+
declare function isValidHttpRequest(obj: any): obj is ParsedHttpRequest;
|
|
22
|
+
declare function getCachedValidator(schema: Record<string, unknown>): ValidateFunction;
|
|
23
|
+
declare function validationHelper(jsonSchema: Record<string, unknown>): ValidateFunction<unknown>;
|
|
24
|
+
declare function validateAgainstJsonSchema(jsonSchema: Record<string, unknown>, context: unknown): boolean;
|
|
25
|
+
declare function validateHttpRequestHeaders(headersSchema: any, httpRequest: ParsedHttpRequest): Promise<ContextValidationResult>;
|
|
26
|
+
declare function validateHeaders({
|
|
27
|
+
executionContext,
|
|
28
|
+
conversationId,
|
|
29
|
+
parsedRequest,
|
|
30
|
+
credentialStores
|
|
31
|
+
}: {
|
|
32
|
+
executionContext: FullExecutionContext;
|
|
33
|
+
conversationId: string;
|
|
34
|
+
parsedRequest: ParsedHttpRequest;
|
|
35
|
+
credentialStores?: CredentialStoreRegistry;
|
|
36
|
+
}): Promise<ContextValidationResult>;
|
|
37
|
+
declare function contextValidationMiddleware(c: Context, next: Next): Promise<void>;
|
|
38
|
+
//#endregion
|
|
39
|
+
export { ContextValidationError, ContextValidationResult, HTTP_REQUEST_PARTS, HttpRequestPart, ParsedHttpRequest, contextValidationMiddleware, getCachedValidator, isValidHttpRequest, validateAgainstJsonSchema, validateHeaders, validateHttpRequestHeaders, validationHelper };
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import { ContextResolver } from "./ContextResolver.js";
|
|
2
|
+
import { createApiError, getLogger } from "@inkeep/agents-core";
|
|
3
|
+
import Ajv from "ajv";
|
|
4
|
+
|
|
5
|
+
//#region src/domains/run/context/validation.ts
|
|
6
|
+
const logger = getLogger("context-validation");
|
|
7
|
+
const ajv = new Ajv({
|
|
8
|
+
allErrors: true,
|
|
9
|
+
strict: false
|
|
10
|
+
});
|
|
11
|
+
const HTTP_REQUEST_PARTS = ["headers"];
|
|
12
|
+
const MAX_SCHEMA_CACHE_SIZE = 1e3;
|
|
13
|
+
const schemaCache = /* @__PURE__ */ new Map();
|
|
14
|
+
function isValidHttpRequest(obj) {
|
|
15
|
+
return obj != null && typeof obj === "object" && !Array.isArray(obj) && "headers" in obj;
|
|
16
|
+
}
|
|
17
|
+
function getCachedValidator(schema) {
|
|
18
|
+
const key = JSON.stringify(schema);
|
|
19
|
+
if (schemaCache.has(key)) {
|
|
20
|
+
const validator$1 = schemaCache.get(key);
|
|
21
|
+
if (!validator$1) throw new Error("Unexpected: validator not found in cache after has() check");
|
|
22
|
+
schemaCache.delete(key);
|
|
23
|
+
schemaCache.set(key, validator$1);
|
|
24
|
+
return validator$1;
|
|
25
|
+
}
|
|
26
|
+
if (schemaCache.size >= MAX_SCHEMA_CACHE_SIZE) {
|
|
27
|
+
const firstKey = schemaCache.keys().next().value;
|
|
28
|
+
if (firstKey) schemaCache.delete(firstKey);
|
|
29
|
+
}
|
|
30
|
+
const permissiveSchema = makeSchemaPermissive(schema);
|
|
31
|
+
const validator = ajv.compile(permissiveSchema);
|
|
32
|
+
schemaCache.set(key, validator);
|
|
33
|
+
return validator;
|
|
34
|
+
}
|
|
35
|
+
function makeSchemaPermissive(schema) {
|
|
36
|
+
if (!schema || typeof schema !== "object") return schema;
|
|
37
|
+
const permissiveSchema = { ...schema };
|
|
38
|
+
if (permissiveSchema.type === "object") {
|
|
39
|
+
permissiveSchema.additionalProperties = true;
|
|
40
|
+
if (permissiveSchema.properties && typeof permissiveSchema.properties === "object") {
|
|
41
|
+
const newProperties = {};
|
|
42
|
+
for (const [key, value] of Object.entries(permissiveSchema.properties)) newProperties[key] = makeSchemaPermissive(value);
|
|
43
|
+
permissiveSchema.properties = newProperties;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (permissiveSchema.type === "array" && permissiveSchema.items) permissiveSchema.items = makeSchemaPermissive(permissiveSchema.items);
|
|
47
|
+
if (permissiveSchema.oneOf) permissiveSchema.oneOf = permissiveSchema.oneOf.map(makeSchemaPermissive);
|
|
48
|
+
if (permissiveSchema.anyOf) permissiveSchema.anyOf = permissiveSchema.anyOf.map(makeSchemaPermissive);
|
|
49
|
+
if (permissiveSchema.allOf) permissiveSchema.allOf = permissiveSchema.allOf.map(makeSchemaPermissive);
|
|
50
|
+
return permissiveSchema;
|
|
51
|
+
}
|
|
52
|
+
function validationHelper(jsonSchema) {
|
|
53
|
+
return getCachedValidator(jsonSchema);
|
|
54
|
+
}
|
|
55
|
+
function validateAgainstJsonSchema(jsonSchema, context) {
|
|
56
|
+
return validationHelper(jsonSchema)(context);
|
|
57
|
+
}
|
|
58
|
+
function filterByJsonSchema(data, schema) {
|
|
59
|
+
if (!schema || data === null || data === void 0) return data;
|
|
60
|
+
if (schema.type === "object" && schema.properties && typeof data === "object" && !Array.isArray(data)) {
|
|
61
|
+
const filtered = {};
|
|
62
|
+
for (const [key, propSchema] of Object.entries(schema.properties)) if (key in data) filtered[key] = filterByJsonSchema(data[key], propSchema);
|
|
63
|
+
return filtered;
|
|
64
|
+
}
|
|
65
|
+
if (schema.type === "array" && schema.items && Array.isArray(data)) return data.map((item) => filterByJsonSchema(item, schema.items));
|
|
66
|
+
if (schema.anyOf && Array.isArray(schema.anyOf)) {
|
|
67
|
+
for (const subSchema of schema.anyOf) if (subSchema.type && typeof data === subSchema.type) return filterByJsonSchema(data, subSchema);
|
|
68
|
+
return filterByJsonSchema(data, schema.anyOf[0]);
|
|
69
|
+
}
|
|
70
|
+
return data;
|
|
71
|
+
}
|
|
72
|
+
function filterContextToSchemaKeys(validatedContext, headersSchema) {
|
|
73
|
+
if (!headersSchema || !validatedContext) return validatedContext;
|
|
74
|
+
const filteredHeaders = filterByJsonSchema(validatedContext, headersSchema);
|
|
75
|
+
if (filteredHeaders !== null && filteredHeaders !== void 0) {
|
|
76
|
+
if (typeof filteredHeaders === "object" && Object.keys(filteredHeaders).length > 0) return filteredHeaders;
|
|
77
|
+
if (typeof filteredHeaders !== "object") return filteredHeaders;
|
|
78
|
+
}
|
|
79
|
+
return {};
|
|
80
|
+
}
|
|
81
|
+
async function validateHttpRequestHeaders(headersSchema, httpRequest) {
|
|
82
|
+
const errors = [];
|
|
83
|
+
let validatedContext = {};
|
|
84
|
+
if (!isValidHttpRequest(httpRequest)) return {
|
|
85
|
+
valid: false,
|
|
86
|
+
errors: [{
|
|
87
|
+
field: "httpRequest",
|
|
88
|
+
message: "Invalid HTTP request format - must contain headers"
|
|
89
|
+
}]
|
|
90
|
+
};
|
|
91
|
+
try {
|
|
92
|
+
if (headersSchema && httpRequest.headers !== void 0) try {
|
|
93
|
+
const validate = validationHelper(headersSchema);
|
|
94
|
+
if (validate(httpRequest.headers)) validatedContext = httpRequest.headers;
|
|
95
|
+
else if (validate.errors) for (const error of validate.errors) errors.push({
|
|
96
|
+
field: `headers.${error.instancePath || "root"}`,
|
|
97
|
+
message: `headers ${error.message}`,
|
|
98
|
+
value: error.data
|
|
99
|
+
});
|
|
100
|
+
} catch (validationError) {
|
|
101
|
+
errors.push({
|
|
102
|
+
field: "headers",
|
|
103
|
+
message: `Failed to validate headers: ${validationError instanceof Error ? validationError.message : "Unknown error"}`
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
const filteredContext = errors.length === 0 ? filterContextToSchemaKeys(validatedContext, headersSchema) : void 0;
|
|
107
|
+
return {
|
|
108
|
+
valid: errors.length === 0,
|
|
109
|
+
errors,
|
|
110
|
+
validatedContext: filteredContext
|
|
111
|
+
};
|
|
112
|
+
} catch (error) {
|
|
113
|
+
logger.error({ error: error instanceof Error ? error.message : "Unknown error" }, "Failed to validate headers schema");
|
|
114
|
+
return {
|
|
115
|
+
valid: false,
|
|
116
|
+
errors: [{
|
|
117
|
+
field: "schema",
|
|
118
|
+
message: "Failed to validate headers schema"
|
|
119
|
+
}]
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
async function fetchExistingHeaders({ executionContext, contextConfig, conversationId, credentialStores }) {
|
|
124
|
+
const headers$1 = await new ContextResolver(executionContext, credentialStores).resolveHeaders(conversationId, contextConfig.id);
|
|
125
|
+
if (Object.keys(headers$1).length > 0) return {
|
|
126
|
+
valid: true,
|
|
127
|
+
errors: [],
|
|
128
|
+
validatedContext: headers$1
|
|
129
|
+
};
|
|
130
|
+
throw new Error("No headers found in cache. Please provide headers in request.");
|
|
131
|
+
}
|
|
132
|
+
async function validateHeaders({ executionContext, conversationId, parsedRequest, credentialStores }) {
|
|
133
|
+
try {
|
|
134
|
+
const { tenantId, projectId, agentId, project } = executionContext;
|
|
135
|
+
logger.info({
|
|
136
|
+
tenantId,
|
|
137
|
+
projectId,
|
|
138
|
+
agentId
|
|
139
|
+
}, "Validating headers");
|
|
140
|
+
const contextConfig = project.agents[agentId].contextConfig;
|
|
141
|
+
logger.info({ contextConfig }, "Context config found");
|
|
142
|
+
if (!contextConfig) {
|
|
143
|
+
logger.info({ agentId }, "No context config found for agent, skipping validation");
|
|
144
|
+
return {
|
|
145
|
+
valid: true,
|
|
146
|
+
errors: [],
|
|
147
|
+
validatedContext: parsedRequest
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
if (!contextConfig.headersSchema) {
|
|
151
|
+
logger.debug({ contextConfigId: contextConfig.id }, "No headers schema defined, accepting any context");
|
|
152
|
+
return {
|
|
153
|
+
valid: true,
|
|
154
|
+
errors: [],
|
|
155
|
+
validatedContext: parsedRequest
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
try {
|
|
159
|
+
const schema = contextConfig.headersSchema;
|
|
160
|
+
logger.debug({ contextConfigId: contextConfig.id }, "Using headers schema validation");
|
|
161
|
+
const validationResult = await validateHttpRequestHeaders(schema, parsedRequest);
|
|
162
|
+
if (validationResult.valid) return validationResult;
|
|
163
|
+
try {
|
|
164
|
+
return await fetchExistingHeaders({
|
|
165
|
+
executionContext,
|
|
166
|
+
contextConfig,
|
|
167
|
+
conversationId,
|
|
168
|
+
credentialStores
|
|
169
|
+
});
|
|
170
|
+
} catch (_error) {
|
|
171
|
+
validationResult.errors.push({
|
|
172
|
+
field: "headers",
|
|
173
|
+
message: "Failed to fetch headers from cache"
|
|
174
|
+
});
|
|
175
|
+
return validationResult;
|
|
176
|
+
}
|
|
177
|
+
} catch (error) {
|
|
178
|
+
logger.error({
|
|
179
|
+
contextConfigId: contextConfig.id,
|
|
180
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
181
|
+
}, "Failed to compile or validate schema");
|
|
182
|
+
return {
|
|
183
|
+
valid: false,
|
|
184
|
+
errors: [{
|
|
185
|
+
field: "schema",
|
|
186
|
+
message: "Invalid schema definition or validation error"
|
|
187
|
+
}]
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
} catch (error) {
|
|
191
|
+
logger.error({
|
|
192
|
+
tenantId: executionContext.tenantId,
|
|
193
|
+
agentId: executionContext.agentId,
|
|
194
|
+
error: error instanceof Error ? error.message : "Unknown error"
|
|
195
|
+
}, "Failed to validate headers");
|
|
196
|
+
return {
|
|
197
|
+
valid: false,
|
|
198
|
+
errors: [{
|
|
199
|
+
field: "validation",
|
|
200
|
+
message: "Context validation failed due to internal error"
|
|
201
|
+
}]
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
async function contextValidationMiddleware(c, next) {
|
|
206
|
+
try {
|
|
207
|
+
const executionContext = c.get("executionContext");
|
|
208
|
+
let { tenantId, projectId, agentId } = executionContext;
|
|
209
|
+
if (!tenantId || !projectId || !agentId) {
|
|
210
|
+
tenantId = c.req.param("tenantId");
|
|
211
|
+
projectId = c.req.param("projectId");
|
|
212
|
+
agentId = c.req.param("agentId");
|
|
213
|
+
}
|
|
214
|
+
if (!tenantId || !projectId || !agentId) return next();
|
|
215
|
+
const conversationId = (c.get("requestBody") || {}).conversationId || "";
|
|
216
|
+
const headers$1 = {};
|
|
217
|
+
c.req.raw.headers.forEach((value, key) => {
|
|
218
|
+
headers$1[key.toLowerCase()] = value;
|
|
219
|
+
});
|
|
220
|
+
const credentialStores = c.get("credentialStores");
|
|
221
|
+
const validationResult = await validateHeaders({
|
|
222
|
+
executionContext,
|
|
223
|
+
conversationId,
|
|
224
|
+
parsedRequest: { headers: headers$1 },
|
|
225
|
+
credentialStores
|
|
226
|
+
});
|
|
227
|
+
if (!validationResult.valid) {
|
|
228
|
+
logger.warn({
|
|
229
|
+
tenantId,
|
|
230
|
+
agentId,
|
|
231
|
+
errors: validationResult.errors
|
|
232
|
+
}, "Headers validation failed");
|
|
233
|
+
throw createApiError({
|
|
234
|
+
code: "bad_request",
|
|
235
|
+
message: `Invalid headers: ${validationResult.errors.map((e) => `${e.field}: ${e.message}`).join(", ")}`
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
c.set("validatedContext", validationResult.validatedContext);
|
|
239
|
+
logger.debug({
|
|
240
|
+
tenantId,
|
|
241
|
+
agentId,
|
|
242
|
+
contextKeys: Object.keys(validationResult.validatedContext || {})
|
|
243
|
+
}, "Request context validation successful");
|
|
244
|
+
return next();
|
|
245
|
+
} catch (error) {
|
|
246
|
+
logger.error({ error: error instanceof Error ? error.message : "Unknown error" }, "Context validation middleware error");
|
|
247
|
+
throw createApiError({
|
|
248
|
+
code: "internal_server_error",
|
|
249
|
+
message: "Context validation failed"
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
//#endregion
|
|
255
|
+
export { HTTP_REQUEST_PARTS, contextValidationMiddleware, getCachedValidator, isValidHttpRequest, validateAgainstJsonSchema, validateHeaders, validateHttpRequestHeaders, validationHelper };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { RegisteredAgent } from "../a2a/types.js";
|
|
2
|
+
import { FullExecutionContext } from "@inkeep/agents-core";
|
|
3
|
+
|
|
4
|
+
//#region src/domains/run/data/agent.d.ts
|
|
5
|
+
declare function getRegisteredAgent(executionContext: FullExecutionContext): Promise<RegisteredAgent | null>;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { getRegisteredAgent };
|