@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,193 @@
|
|
|
1
|
+
import { ErrorEvent, OperationEvent } from "./agent-operations.js";
|
|
2
|
+
import { SummaryEvent } from "@inkeep/agents-core";
|
|
3
|
+
|
|
4
|
+
//#region src/domains/run/utils/stream-helpers.d.ts
|
|
5
|
+
interface StreamHelper {
|
|
6
|
+
writeRole(role?: string): Promise<void>;
|
|
7
|
+
writeContent(content: string): Promise<void>;
|
|
8
|
+
streamData(data: any): Promise<void>;
|
|
9
|
+
streamText(text: string, delayMs?: number): Promise<void>;
|
|
10
|
+
writeError(error: string | ErrorEvent): Promise<void>;
|
|
11
|
+
complete(): Promise<void>;
|
|
12
|
+
writeData(type: string, data: any): Promise<void>;
|
|
13
|
+
writeOperation(operation: OperationEvent): Promise<void>;
|
|
14
|
+
writeSummary(summary: SummaryEvent): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
interface HonoSSEStream {
|
|
17
|
+
writeSSE(message: {
|
|
18
|
+
data: string;
|
|
19
|
+
event?: string;
|
|
20
|
+
id?: string;
|
|
21
|
+
}): Promise<void>;
|
|
22
|
+
sleep(ms: number): Promise<unknown>;
|
|
23
|
+
}
|
|
24
|
+
interface ChatCompletionChunk {
|
|
25
|
+
id: string;
|
|
26
|
+
object: string;
|
|
27
|
+
created: number;
|
|
28
|
+
model: string;
|
|
29
|
+
choices: Array<{
|
|
30
|
+
index: number;
|
|
31
|
+
delta: {
|
|
32
|
+
role?: string;
|
|
33
|
+
content?: string;
|
|
34
|
+
};
|
|
35
|
+
finish_reason: string | null;
|
|
36
|
+
}>;
|
|
37
|
+
}
|
|
38
|
+
declare class SSEStreamHelper implements StreamHelper {
|
|
39
|
+
private stream;
|
|
40
|
+
private requestId;
|
|
41
|
+
private timestamp;
|
|
42
|
+
private isTextStreaming;
|
|
43
|
+
private queuedEvents;
|
|
44
|
+
constructor(stream: HonoSSEStream, requestId: string, timestamp: number);
|
|
45
|
+
/**
|
|
46
|
+
* Write the initial role message
|
|
47
|
+
*/
|
|
48
|
+
writeRole(role?: string): Promise<void>;
|
|
49
|
+
/**
|
|
50
|
+
* Write content chunk
|
|
51
|
+
*/
|
|
52
|
+
writeContent(content: string): Promise<void>;
|
|
53
|
+
/**
|
|
54
|
+
* Stream text word by word with optional delay
|
|
55
|
+
*/
|
|
56
|
+
streamText(text: string, delayMs?: number): Promise<void>;
|
|
57
|
+
streamData(data: any): Promise<void>;
|
|
58
|
+
/**
|
|
59
|
+
* Write error message or error event
|
|
60
|
+
*/
|
|
61
|
+
writeError(error: string | ErrorEvent): Promise<void>;
|
|
62
|
+
/**
|
|
63
|
+
* Write the final completion message
|
|
64
|
+
*/
|
|
65
|
+
writeCompletion(finishReason?: string): Promise<void>;
|
|
66
|
+
writeData(type: string, data: any): Promise<void>;
|
|
67
|
+
writeSummary(summary: SummaryEvent): Promise<void>;
|
|
68
|
+
writeOperation(operation: OperationEvent): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* Flush all queued operations in order after text streaming completes
|
|
71
|
+
*/
|
|
72
|
+
private flushQueuedOperations;
|
|
73
|
+
/**
|
|
74
|
+
* Write the final [DONE] message
|
|
75
|
+
*/
|
|
76
|
+
writeDone(): Promise<void>;
|
|
77
|
+
/**
|
|
78
|
+
* Complete the stream with finish reason and done message
|
|
79
|
+
*/
|
|
80
|
+
complete(finishReason?: string): Promise<void>;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Factory function to create SSE stream helper
|
|
84
|
+
*/
|
|
85
|
+
declare function createSSEStreamHelper(stream: HonoSSEStream, requestId: string, timestamp: number): SSEStreamHelper;
|
|
86
|
+
interface VercelUIWriter {
|
|
87
|
+
write(chunk: any): void;
|
|
88
|
+
merge(stream: any): void;
|
|
89
|
+
onError?: (error: Error) => void;
|
|
90
|
+
}
|
|
91
|
+
declare class VercelDataStreamHelper implements StreamHelper {
|
|
92
|
+
private writer;
|
|
93
|
+
private textId;
|
|
94
|
+
private jsonBuffer;
|
|
95
|
+
private sentItems;
|
|
96
|
+
private completedItems;
|
|
97
|
+
private static readonly MAX_BUFFER_SIZE;
|
|
98
|
+
private isCompleted;
|
|
99
|
+
private isTextStreaming;
|
|
100
|
+
private queuedEvents;
|
|
101
|
+
private lastTextEndTimestamp;
|
|
102
|
+
private connectionDropTimer?;
|
|
103
|
+
constructor(writer: VercelUIWriter);
|
|
104
|
+
writeRole(_?: string): Promise<void>;
|
|
105
|
+
writeContent(content: string): Promise<void>;
|
|
106
|
+
streamText(text: string, delayMs?: number): Promise<void>;
|
|
107
|
+
writeData(type: string, data: any): Promise<void>;
|
|
108
|
+
writeError(error: string | ErrorEvent): Promise<void>;
|
|
109
|
+
streamData(data: any): Promise<void>;
|
|
110
|
+
mergeStream(stream: any): Promise<void>;
|
|
111
|
+
/**
|
|
112
|
+
* Clean up all memory allocations
|
|
113
|
+
* Should be called when the stream helper is no longer needed
|
|
114
|
+
*/
|
|
115
|
+
cleanup(): void;
|
|
116
|
+
/**
|
|
117
|
+
* JSON-aware buffer truncation that preserves complete JSON structures
|
|
118
|
+
*/
|
|
119
|
+
private truncateJsonBufferSafely;
|
|
120
|
+
/**
|
|
121
|
+
* Reindex sent items after buffer truncation
|
|
122
|
+
*/
|
|
123
|
+
private reindexSentItems;
|
|
124
|
+
/**
|
|
125
|
+
* Force cleanup on connection drop or timeout
|
|
126
|
+
*/
|
|
127
|
+
private forceCleanup;
|
|
128
|
+
/**
|
|
129
|
+
* Check if the stream has been completed and cleaned up
|
|
130
|
+
*/
|
|
131
|
+
isStreamCompleted(): boolean;
|
|
132
|
+
/**
|
|
133
|
+
* Get current memory usage stats (for debugging/monitoring)
|
|
134
|
+
*/
|
|
135
|
+
getMemoryStats(): {
|
|
136
|
+
bufferSize: number;
|
|
137
|
+
sentItemsCount: number;
|
|
138
|
+
completedItemsCount: number;
|
|
139
|
+
isCompleted: boolean;
|
|
140
|
+
};
|
|
141
|
+
writeSummary(summary: SummaryEvent): Promise<void>;
|
|
142
|
+
writeOperation(operation: OperationEvent): Promise<void>;
|
|
143
|
+
/**
|
|
144
|
+
* Flush all queued operations in order after text streaming completes
|
|
145
|
+
*/
|
|
146
|
+
private flushQueuedOperations;
|
|
147
|
+
writeCompletion(_finishReason?: string): Promise<void>;
|
|
148
|
+
writeDone(): Promise<void>;
|
|
149
|
+
/**
|
|
150
|
+
* Complete the stream and clean up all memory
|
|
151
|
+
* This is the primary cleanup point to prevent memory leaks between requests
|
|
152
|
+
*/
|
|
153
|
+
complete(): Promise<void>;
|
|
154
|
+
}
|
|
155
|
+
declare function createVercelStreamHelper(writer: VercelUIWriter): VercelDataStreamHelper;
|
|
156
|
+
/**
|
|
157
|
+
* Buffering Stream Helper that captures content instead of streaming
|
|
158
|
+
* Used for MCP tool responses and non-streaming API responses that require a single complete message
|
|
159
|
+
*/
|
|
160
|
+
declare class BufferingStreamHelper implements StreamHelper {
|
|
161
|
+
private capturedText;
|
|
162
|
+
private capturedData;
|
|
163
|
+
private capturedOperations;
|
|
164
|
+
private capturedSummaries;
|
|
165
|
+
private hasError;
|
|
166
|
+
private errorMessage;
|
|
167
|
+
writeRole(_role?: string): Promise<void>;
|
|
168
|
+
writeContent(content: string): Promise<void>;
|
|
169
|
+
streamText(text: string, _delayMs?: number): Promise<void>;
|
|
170
|
+
streamData(data: any): Promise<void>;
|
|
171
|
+
streamSummary(summary: SummaryEvent): Promise<void>;
|
|
172
|
+
streamOperation(operation: OperationEvent): Promise<void>;
|
|
173
|
+
writeData(_type: string, data: any): Promise<void>;
|
|
174
|
+
writeSummary(summary: SummaryEvent): Promise<void>;
|
|
175
|
+
writeOperation(operation: OperationEvent): Promise<void>;
|
|
176
|
+
writeError(error: string | ErrorEvent): Promise<void>;
|
|
177
|
+
complete(): Promise<void>;
|
|
178
|
+
/**
|
|
179
|
+
* Get the captured response for non-streaming output
|
|
180
|
+
*/
|
|
181
|
+
getCapturedResponse(): {
|
|
182
|
+
text: string;
|
|
183
|
+
data: any[];
|
|
184
|
+
operations: OperationEvent[];
|
|
185
|
+
hasError: boolean;
|
|
186
|
+
errorMessage: string;
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
declare function createBufferingStreamHelper(): BufferingStreamHelper;
|
|
190
|
+
declare const createMCPStreamHelper: typeof createBufferingStreamHelper;
|
|
191
|
+
type MCPStreamHelper = BufferingStreamHelper;
|
|
192
|
+
//#endregion
|
|
193
|
+
export { BufferingStreamHelper, ChatCompletionChunk, HonoSSEStream, MCPStreamHelper, SSEStreamHelper, StreamHelper, VercelDataStreamHelper, VercelUIWriter, createBufferingStreamHelper, createMCPStreamHelper, createSSEStreamHelper, createVercelStreamHelper };
|
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
import { STREAM_BUFFER_MAX_SIZE_BYTES, STREAM_MAX_LIFETIME_MS, STREAM_TEXT_GAP_THRESHOLD_MS } from "../constants/execution-limits/index.js";
|
|
2
|
+
import { parsePartialJson } from "ai";
|
|
3
|
+
|
|
4
|
+
//#region src/domains/run/utils/stream-helpers.ts
|
|
5
|
+
var SSEStreamHelper = class {
|
|
6
|
+
isTextStreaming = false;
|
|
7
|
+
queuedEvents = [];
|
|
8
|
+
constructor(stream, requestId, timestamp) {
|
|
9
|
+
this.stream = stream;
|
|
10
|
+
this.requestId = requestId;
|
|
11
|
+
this.timestamp = timestamp;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Write the initial role message
|
|
15
|
+
*/
|
|
16
|
+
async writeRole(role = "assistant") {
|
|
17
|
+
await this.stream.writeSSE({ data: JSON.stringify({
|
|
18
|
+
id: this.requestId,
|
|
19
|
+
object: "chat.completion.chunk",
|
|
20
|
+
created: this.timestamp,
|
|
21
|
+
choices: [{
|
|
22
|
+
index: 0,
|
|
23
|
+
delta: { role },
|
|
24
|
+
finish_reason: null
|
|
25
|
+
}]
|
|
26
|
+
}) });
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Write content chunk
|
|
30
|
+
*/
|
|
31
|
+
async writeContent(content) {
|
|
32
|
+
await this.stream.writeSSE({ data: JSON.stringify({
|
|
33
|
+
id: this.requestId,
|
|
34
|
+
object: "chat.completion.chunk",
|
|
35
|
+
created: this.timestamp,
|
|
36
|
+
choices: [{
|
|
37
|
+
index: 0,
|
|
38
|
+
delta: { content },
|
|
39
|
+
finish_reason: null
|
|
40
|
+
}]
|
|
41
|
+
}) });
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Stream text word by word with optional delay
|
|
45
|
+
*/
|
|
46
|
+
async streamText(text, delayMs = 100) {
|
|
47
|
+
const words = text.split(" ");
|
|
48
|
+
this.isTextStreaming = true;
|
|
49
|
+
try {
|
|
50
|
+
for (let i = 0; i < words.length; i++) {
|
|
51
|
+
await this.stream.sleep(delayMs);
|
|
52
|
+
const content = i === 0 ? words[i] : ` ${words[i]}`;
|
|
53
|
+
await this.writeContent(content);
|
|
54
|
+
}
|
|
55
|
+
} finally {
|
|
56
|
+
this.isTextStreaming = false;
|
|
57
|
+
await this.flushQueuedOperations();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async streamData(data) {
|
|
61
|
+
await this.writeContent(JSON.stringify(data));
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Write error message or error event
|
|
65
|
+
*/
|
|
66
|
+
async writeError(error) {
|
|
67
|
+
const errorMessage = typeof error === "string" ? error : error.message;
|
|
68
|
+
await this.writeContent(`\n\n${errorMessage}`);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Write the final completion message
|
|
72
|
+
*/
|
|
73
|
+
async writeCompletion(finishReason = "stop") {
|
|
74
|
+
await this.stream.writeSSE({ data: JSON.stringify({
|
|
75
|
+
id: this.requestId,
|
|
76
|
+
object: "chat.completion.chunk",
|
|
77
|
+
created: this.timestamp,
|
|
78
|
+
choices: [{
|
|
79
|
+
index: 0,
|
|
80
|
+
delta: {},
|
|
81
|
+
finish_reason: finishReason
|
|
82
|
+
}]
|
|
83
|
+
}) });
|
|
84
|
+
}
|
|
85
|
+
async writeData(type, data) {
|
|
86
|
+
await this.stream.writeSSE({ data: JSON.stringify({
|
|
87
|
+
id: this.requestId,
|
|
88
|
+
object: "chat.completion.chunk",
|
|
89
|
+
created: this.timestamp,
|
|
90
|
+
choices: [{
|
|
91
|
+
index: 0,
|
|
92
|
+
delta: { content: JSON.stringify({
|
|
93
|
+
type,
|
|
94
|
+
data
|
|
95
|
+
}) },
|
|
96
|
+
finish_reason: null
|
|
97
|
+
}]
|
|
98
|
+
}) });
|
|
99
|
+
}
|
|
100
|
+
async writeSummary(summary) {
|
|
101
|
+
if (this.isTextStreaming) {
|
|
102
|
+
this.queuedEvents.push({
|
|
103
|
+
type: "data-summary",
|
|
104
|
+
event: summary
|
|
105
|
+
});
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
await this.flushQueuedOperations();
|
|
109
|
+
await this.writeData("data-summary", summary);
|
|
110
|
+
}
|
|
111
|
+
async writeOperation(operation) {
|
|
112
|
+
if (this.isTextStreaming) {
|
|
113
|
+
this.queuedEvents.push({
|
|
114
|
+
type: "data-operation",
|
|
115
|
+
event: operation
|
|
116
|
+
});
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
await this.flushQueuedOperations();
|
|
120
|
+
await this.writeData("data-operation", operation);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Flush all queued operations in order after text streaming completes
|
|
124
|
+
*/
|
|
125
|
+
async flushQueuedOperations() {
|
|
126
|
+
if (this.queuedEvents.length === 0) return;
|
|
127
|
+
const eventsToFlush = [...this.queuedEvents];
|
|
128
|
+
this.queuedEvents = [];
|
|
129
|
+
for (const event of eventsToFlush) await this.writeData(event.type, event.event);
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Write the final [DONE] message
|
|
133
|
+
*/
|
|
134
|
+
async writeDone() {
|
|
135
|
+
await this.stream.writeSSE({ data: "[DONE]" });
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Complete the stream with finish reason and done message
|
|
139
|
+
*/
|
|
140
|
+
async complete(finishReason = "stop") {
|
|
141
|
+
await this.flushQueuedOperations();
|
|
142
|
+
await this.writeCompletion(finishReason);
|
|
143
|
+
await this.writeDone();
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
/**
|
|
147
|
+
* Factory function to create SSE stream helper
|
|
148
|
+
*/
|
|
149
|
+
function createSSEStreamHelper(stream, requestId, timestamp) {
|
|
150
|
+
return new SSEStreamHelper(stream, requestId, timestamp);
|
|
151
|
+
}
|
|
152
|
+
var VercelDataStreamHelper = class VercelDataStreamHelper {
|
|
153
|
+
textId = null;
|
|
154
|
+
jsonBuffer = "";
|
|
155
|
+
sentItems = /* @__PURE__ */ new Map();
|
|
156
|
+
completedItems = /* @__PURE__ */ new Set();
|
|
157
|
+
static MAX_BUFFER_SIZE = STREAM_BUFFER_MAX_SIZE_BYTES;
|
|
158
|
+
isCompleted = false;
|
|
159
|
+
isTextStreaming = false;
|
|
160
|
+
queuedEvents = [];
|
|
161
|
+
lastTextEndTimestamp = 0;
|
|
162
|
+
connectionDropTimer;
|
|
163
|
+
constructor(writer) {
|
|
164
|
+
this.writer = writer;
|
|
165
|
+
this.connectionDropTimer = setTimeout(() => {
|
|
166
|
+
this.forceCleanup("Connection lifetime exceeded");
|
|
167
|
+
}, STREAM_MAX_LIFETIME_MS);
|
|
168
|
+
}
|
|
169
|
+
async writeRole(_ = "assistant") {}
|
|
170
|
+
async writeContent(content) {
|
|
171
|
+
if (this.isCompleted) {
|
|
172
|
+
console.warn("Attempted to write content to completed stream");
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
if (!this.textId) this.textId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
176
|
+
if (this.jsonBuffer.length + content.length > VercelDataStreamHelper.MAX_BUFFER_SIZE) {
|
|
177
|
+
const newBuffer = this.truncateJsonBufferSafely(this.jsonBuffer);
|
|
178
|
+
if (newBuffer.length === this.jsonBuffer.length) {
|
|
179
|
+
console.warn("VercelDataStreamHelper: Could not find safe JSON truncation point, clearing buffer");
|
|
180
|
+
this.jsonBuffer = "";
|
|
181
|
+
this.sentItems.clear();
|
|
182
|
+
} else {
|
|
183
|
+
this.jsonBuffer = newBuffer;
|
|
184
|
+
this.reindexSentItems();
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
this.jsonBuffer += content;
|
|
188
|
+
const { value, state } = await parsePartialJson(this.jsonBuffer);
|
|
189
|
+
if (!["repaired-parse", "successful-parse"].includes(state)) return;
|
|
190
|
+
if (!Array.isArray(value)) return;
|
|
191
|
+
for (let i = 0; i < value.length; i++) {
|
|
192
|
+
const { type, ...data } = value[i];
|
|
193
|
+
const currentContent = JSON.stringify(data);
|
|
194
|
+
if (currentContent !== this.sentItems.get(i)) {
|
|
195
|
+
const chunk = {
|
|
196
|
+
type: "data-component",
|
|
197
|
+
id: `${this.textId}-${i}`,
|
|
198
|
+
data: {
|
|
199
|
+
type,
|
|
200
|
+
...data
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
this.writer.write(chunk);
|
|
204
|
+
this.sentItems.set(i, currentContent);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
async streamText(text, delayMs = 100) {
|
|
209
|
+
if (this.isCompleted) {
|
|
210
|
+
console.warn("Attempted to stream text to completed stream");
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
if (!this.textId) this.textId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
214
|
+
const id = this.textId;
|
|
215
|
+
const startTime = Date.now();
|
|
216
|
+
if ((this.lastTextEndTimestamp > 0 ? startTime - this.lastTextEndTimestamp : Number.MAX_SAFE_INTEGER) >= STREAM_TEXT_GAP_THRESHOLD_MS) await this.flushQueuedOperations();
|
|
217
|
+
this.isTextStreaming = true;
|
|
218
|
+
try {
|
|
219
|
+
this.writer.write({
|
|
220
|
+
type: "text-start",
|
|
221
|
+
id
|
|
222
|
+
});
|
|
223
|
+
if (delayMs > 0) await new Promise((r) => setTimeout(r, delayMs));
|
|
224
|
+
this.writer.write({
|
|
225
|
+
type: "text-delta",
|
|
226
|
+
id,
|
|
227
|
+
delta: text
|
|
228
|
+
});
|
|
229
|
+
this.writer.write({
|
|
230
|
+
type: "text-end",
|
|
231
|
+
id
|
|
232
|
+
});
|
|
233
|
+
this.lastTextEndTimestamp = Date.now();
|
|
234
|
+
} finally {
|
|
235
|
+
this.isTextStreaming = false;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
async writeData(type, data) {
|
|
239
|
+
if (this.isCompleted) {
|
|
240
|
+
console.warn("Attempted to write data to completed stream");
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (type === "data-artifact") {
|
|
244
|
+
const now = Date.now();
|
|
245
|
+
const gapFromLastTextEnd = this.lastTextEndTimestamp > 0 ? now - this.lastTextEndTimestamp : Number.MAX_SAFE_INTEGER;
|
|
246
|
+
if (this.isTextStreaming || gapFromLastTextEnd < STREAM_TEXT_GAP_THRESHOLD_MS) {
|
|
247
|
+
this.writer.write({
|
|
248
|
+
type: `${type}`,
|
|
249
|
+
data
|
|
250
|
+
});
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
this.writer.write({
|
|
255
|
+
type: `${type}`,
|
|
256
|
+
data
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
async writeError(error) {
|
|
260
|
+
if (this.isCompleted) {
|
|
261
|
+
console.warn("Attempted to write error to completed stream");
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
if (typeof error === "string") this.writer.write({
|
|
265
|
+
type: "error",
|
|
266
|
+
message: error,
|
|
267
|
+
severity: "error",
|
|
268
|
+
timestamp: Date.now()
|
|
269
|
+
});
|
|
270
|
+
else this.writer.write({
|
|
271
|
+
...error,
|
|
272
|
+
type: "error"
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
async streamData(data) {
|
|
276
|
+
await this.writeContent(JSON.stringify(data));
|
|
277
|
+
}
|
|
278
|
+
async mergeStream(stream) {
|
|
279
|
+
if (this.isCompleted) {
|
|
280
|
+
console.warn("Attempted to merge stream to completed stream");
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
this.writer.merge(stream);
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Clean up all memory allocations
|
|
287
|
+
* Should be called when the stream helper is no longer needed
|
|
288
|
+
*/
|
|
289
|
+
cleanup() {
|
|
290
|
+
if (this.connectionDropTimer) {
|
|
291
|
+
clearTimeout(this.connectionDropTimer);
|
|
292
|
+
this.connectionDropTimer = void 0;
|
|
293
|
+
}
|
|
294
|
+
this.jsonBuffer = "";
|
|
295
|
+
this.sentItems.clear();
|
|
296
|
+
this.completedItems.clear();
|
|
297
|
+
this.textId = null;
|
|
298
|
+
this.queuedEvents = [];
|
|
299
|
+
this.isTextStreaming = false;
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* JSON-aware buffer truncation that preserves complete JSON structures
|
|
303
|
+
*/
|
|
304
|
+
truncateJsonBufferSafely(buffer) {
|
|
305
|
+
const keepSize = Math.floor(VercelDataStreamHelper.MAX_BUFFER_SIZE * .6);
|
|
306
|
+
if (buffer.length <= keepSize) return buffer;
|
|
307
|
+
let depth = 0;
|
|
308
|
+
let inString = false;
|
|
309
|
+
let escaping = false;
|
|
310
|
+
let lastCompleteStructureEnd = -1;
|
|
311
|
+
for (let i = Math.min(keepSize + 1e3, buffer.length - 1); i >= keepSize; i--) {
|
|
312
|
+
const char = buffer[i];
|
|
313
|
+
if (escaping) {
|
|
314
|
+
escaping = false;
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
if (char === "\\") {
|
|
318
|
+
escaping = true;
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
if (char === "\"") {
|
|
322
|
+
inString = !inString;
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
if (inString) continue;
|
|
326
|
+
if (char === "}" || char === "]") depth++;
|
|
327
|
+
else if (char === "{" || char === "[") {
|
|
328
|
+
depth--;
|
|
329
|
+
if (depth === 0) {
|
|
330
|
+
lastCompleteStructureEnd = i - 1;
|
|
331
|
+
break;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
if (lastCompleteStructureEnd > 0) return buffer.slice(lastCompleteStructureEnd + 1);
|
|
336
|
+
for (let i = keepSize; i < Math.min(keepSize + 500, buffer.length); i++) if (buffer[i] === "\n" && buffer[i + 1] && buffer[i + 1].match(/[{[]]/)) return buffer.slice(i + 1);
|
|
337
|
+
return buffer;
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Reindex sent items after buffer truncation
|
|
341
|
+
*/
|
|
342
|
+
reindexSentItems() {
|
|
343
|
+
this.sentItems.clear();
|
|
344
|
+
this.completedItems.clear();
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Force cleanup on connection drop or timeout
|
|
348
|
+
*/
|
|
349
|
+
forceCleanup(reason) {
|
|
350
|
+
console.warn(`VercelDataStreamHelper: Forcing cleanup - ${reason}`);
|
|
351
|
+
this.isCompleted = true;
|
|
352
|
+
this.cleanup();
|
|
353
|
+
try {
|
|
354
|
+
if (this.writer && !this.isCompleted) this.writer.write({
|
|
355
|
+
type: "error",
|
|
356
|
+
message: `Stream terminated: ${reason}`,
|
|
357
|
+
severity: "error",
|
|
358
|
+
timestamp: Date.now()
|
|
359
|
+
});
|
|
360
|
+
} catch (_e) {}
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Check if the stream has been completed and cleaned up
|
|
364
|
+
*/
|
|
365
|
+
isStreamCompleted() {
|
|
366
|
+
return this.isCompleted;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Get current memory usage stats (for debugging/monitoring)
|
|
370
|
+
*/
|
|
371
|
+
getMemoryStats() {
|
|
372
|
+
return {
|
|
373
|
+
bufferSize: this.jsonBuffer.length,
|
|
374
|
+
sentItemsCount: this.sentItems.size,
|
|
375
|
+
completedItemsCount: this.completedItems.size,
|
|
376
|
+
isCompleted: this.isCompleted
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
async writeSummary(summary) {
|
|
380
|
+
if (this.isCompleted) {
|
|
381
|
+
console.warn("Attempted to write summary to completed stream");
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
const now = Date.now();
|
|
385
|
+
const gapFromLastTextEnd = this.lastTextEndTimestamp > 0 ? now - this.lastTextEndTimestamp : Number.MAX_SAFE_INTEGER;
|
|
386
|
+
if (this.isTextStreaming || gapFromLastTextEnd < STREAM_TEXT_GAP_THRESHOLD_MS) {
|
|
387
|
+
this.queuedEvents.push({
|
|
388
|
+
type: "data-summary",
|
|
389
|
+
event: summary
|
|
390
|
+
});
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
await this.flushQueuedOperations();
|
|
394
|
+
await this.writer.write({
|
|
395
|
+
id: "id" in summary ? summary.id : void 0,
|
|
396
|
+
type: "data-summary",
|
|
397
|
+
data: summary
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
async writeOperation(operation) {
|
|
401
|
+
if (this.isCompleted) {
|
|
402
|
+
console.warn("Attempted to write operation to completed stream");
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
const now = Date.now();
|
|
406
|
+
const gapFromLastTextEnd = this.lastTextEndTimestamp > 0 ? now - this.lastTextEndTimestamp : Number.MAX_SAFE_INTEGER;
|
|
407
|
+
if (operation.type !== "tool_call" && operation.type !== "tool_result" && (this.isTextStreaming || gapFromLastTextEnd < STREAM_TEXT_GAP_THRESHOLD_MS)) {
|
|
408
|
+
this.queuedEvents.push({
|
|
409
|
+
type: "data-operation",
|
|
410
|
+
event: operation
|
|
411
|
+
});
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
await this.flushQueuedOperations();
|
|
415
|
+
this.writer.write({
|
|
416
|
+
id: "id" in operation ? operation.id : void 0,
|
|
417
|
+
type: "data-operation",
|
|
418
|
+
data: operation
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Flush all queued operations in order after text streaming completes
|
|
423
|
+
*/
|
|
424
|
+
async flushQueuedOperations() {
|
|
425
|
+
if (this.queuedEvents.length === 0) return;
|
|
426
|
+
const eventsToFlush = [...this.queuedEvents];
|
|
427
|
+
this.queuedEvents = [];
|
|
428
|
+
for (const event of eventsToFlush) this.writer.write({
|
|
429
|
+
id: "id" in event.event ? event.event.id : void 0,
|
|
430
|
+
type: event.type,
|
|
431
|
+
data: event.event
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
async writeCompletion(_finishReason = "stop") {}
|
|
435
|
+
async writeDone() {}
|
|
436
|
+
/**
|
|
437
|
+
* Complete the stream and clean up all memory
|
|
438
|
+
* This is the primary cleanup point to prevent memory leaks between requests
|
|
439
|
+
*/
|
|
440
|
+
async complete() {
|
|
441
|
+
if (this.isCompleted) return;
|
|
442
|
+
await this.flushQueuedOperations();
|
|
443
|
+
this.isCompleted = true;
|
|
444
|
+
this.cleanup();
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
function createVercelStreamHelper(writer) {
|
|
448
|
+
return new VercelDataStreamHelper(writer);
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Buffering Stream Helper that captures content instead of streaming
|
|
452
|
+
* Used for MCP tool responses and non-streaming API responses that require a single complete message
|
|
453
|
+
*/
|
|
454
|
+
var BufferingStreamHelper = class {
|
|
455
|
+
capturedText = "";
|
|
456
|
+
capturedData = [];
|
|
457
|
+
capturedOperations = [];
|
|
458
|
+
capturedSummaries = [];
|
|
459
|
+
hasError = false;
|
|
460
|
+
errorMessage = "";
|
|
461
|
+
async writeRole(_role) {}
|
|
462
|
+
async writeContent(content) {
|
|
463
|
+
this.capturedText += content;
|
|
464
|
+
}
|
|
465
|
+
async streamText(text, _delayMs) {
|
|
466
|
+
this.capturedText += text;
|
|
467
|
+
}
|
|
468
|
+
async streamData(data) {
|
|
469
|
+
this.capturedData.push(data);
|
|
470
|
+
}
|
|
471
|
+
async streamSummary(summary) {
|
|
472
|
+
this.capturedSummaries.push(summary);
|
|
473
|
+
}
|
|
474
|
+
async streamOperation(operation) {
|
|
475
|
+
this.capturedOperations.push(operation);
|
|
476
|
+
}
|
|
477
|
+
async writeData(_type, data) {
|
|
478
|
+
this.capturedData.push(data);
|
|
479
|
+
}
|
|
480
|
+
async writeSummary(summary) {
|
|
481
|
+
this.capturedSummaries.push(summary);
|
|
482
|
+
}
|
|
483
|
+
async writeOperation(operation) {
|
|
484
|
+
this.capturedOperations.push(operation);
|
|
485
|
+
}
|
|
486
|
+
async writeError(error) {
|
|
487
|
+
this.hasError = true;
|
|
488
|
+
this.errorMessage = typeof error === "string" ? error : error.message;
|
|
489
|
+
}
|
|
490
|
+
async complete() {}
|
|
491
|
+
/**
|
|
492
|
+
* Get the captured response for non-streaming output
|
|
493
|
+
*/
|
|
494
|
+
getCapturedResponse() {
|
|
495
|
+
return {
|
|
496
|
+
text: this.capturedText,
|
|
497
|
+
data: this.capturedData,
|
|
498
|
+
operations: this.capturedOperations,
|
|
499
|
+
hasError: this.hasError,
|
|
500
|
+
errorMessage: this.errorMessage
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
};
|
|
504
|
+
function createBufferingStreamHelper() {
|
|
505
|
+
return new BufferingStreamHelper();
|
|
506
|
+
}
|
|
507
|
+
const createMCPStreamHelper = createBufferingStreamHelper;
|
|
508
|
+
|
|
509
|
+
//#endregion
|
|
510
|
+
export { BufferingStreamHelper, SSEStreamHelper, VercelDataStreamHelper, createBufferingStreamHelper, createMCPStreamHelper, createSSEStreamHelper, createVercelStreamHelper };
|