n8n
Version:
n8n Workflow Automation Tool
262 lines (261 loc) • 13.6 kB
TypeScript
import { type InstanceAiAttachment, type InstanceAiHandoffContext, type InstanceAiConfirmRequest, type InstanceAiConfirmResponse, type InstanceAiThreadStatusResponse } from '@n8n/api-types';
import { Logger } from '@n8n/backend-common';
import { SsrfProtectionService } from '@n8n/backend-network';
import { GlobalConfig, SsrfProtectionConfig } from '@n8n/config';
import { UserRepository, type User } from '@n8n/db';
import { type ModelConfig, type RunDebugRecord } from '@n8n/instance-ai';
import { ErrorReporter, InstanceSettings } from 'n8n-core';
import { UserError } from 'n8n-workflow';
import { EventService } from '../../events/event.service';
import { SourceControlPreferencesService } from '../../modules/source-control.ee/source-control-preferences.service.ee';
import { Publisher } from '../../scaling/pubsub/publisher.service';
import type { PubSubCommandMap } from '../../scaling/pubsub/pubsub.event-map';
import { AiService } from '../../services/ai.service';
import { UrlService } from '../../services/url.service';
import { Telemetry } from '../../telemetry';
import { InstanceAiBrowserSessionService } from './browser/instance-ai-browser-session.service';
import { EvalThreadCredentialAllowlistService } from './eval/thread-credential-allowlist.service';
import { DurableEventLog } from './event-bus/durable-event-log';
import { InProcessEventBus } from './event-bus/in-process-event-bus';
import { InterruptedRunSweeper } from './event-bus/interrupted-run-sweeper';
import { InstanceAiCreditService } from './instance-ai-credit.service';
import { InstanceAiErrorReporterService } from './instance-ai-error-reporter.service';
import { InstanceAiGatewayService } from './instance-ai-gateway.service';
import { InstanceAiMemoryService } from './instance-ai-memory.service';
import { InstanceAiModelService } from './instance-ai-model.service';
import { InstanceAiRunProbe } from './instance-ai-run-probe';
import { InstanceAiSettingsService } from './instance-ai-settings.service';
import { InstanceAiTemporaryWorkflowService } from './instance-ai-temporary-workflow.service';
import { InstanceAiAdapterService } from './instance-ai.adapter.service';
import { InstanceAiMcpRegistryService } from './mcp';
import { InstanceAiPendingConfirmationRepository } from './repositories/instance-ai-pending-confirmation.repository';
import { InstanceAiThreadGrantRepository } from './repositories/instance-ai-thread-grant.repository';
import { DbIterationLogStorage } from './storage/db-iteration-log-storage';
import { DbSnapshotStorage } from './storage/db-snapshot-storage';
import { TypeORMAgentCheckpointStore } from './storage/typeorm-agent-checkpoint-store';
import { TypeORMAgentMemory } from './storage/typeorm-agent-memory';
export declare const QUOTA_EXHAUSTED_USER_MESSAGE = "You've run out of AI credits. Upgrade your plan to continue using the AI assistant.";
export declare function getUserFacingErrorMessage(error: unknown): string;
export declare function isMaskedStreamFailure(error: unknown): error is Error;
export declare class QuotaExhaustedStreamError extends UserError {
readonly errorCode = "quota_exhausted";
constructor(maskedError: Error);
}
export declare class InstanceAiService {
private readonly instanceSettings;
private readonly adapterService;
private readonly eventBus;
private readonly eventLog;
private readonly interruptedRunSweeper;
private readonly settingsService;
private readonly gatewayService;
private readonly browserSessionService;
private readonly memoryService;
private readonly agentMemory;
private readonly checkpointStore;
private readonly aiService;
private readonly threadGrantRepo;
private readonly pendingConfirmationRepo;
private readonly urlService;
private readonly dbSnapshotStorage;
private readonly dbIterationLogStorage;
private readonly sourceControlPreferencesService;
private readonly telemetry;
private readonly mcpRegistryService;
private readonly userRepository;
private readonly temporaryWorkflowService;
private readonly errorReporter;
private readonly eventService;
private readonly evalCredentialAllowlists;
private readonly modelService;
private readonly creditService;
private readonly publisher;
private readonly instanceAiErrorReporter;
private _mcpClientManager?;
private readonly _ssrfProtectionConfig;
private readonly _ssrfProtectionService;
private get mcpClientManager();
private readonly instanceAiConfig;
private readonly oauth2CallbackUrl;
private readonly webhookBaseUrl;
private readonly formBaseUrl;
private readonly runState;
private readonly backgroundTasks;
private readonly memoryTaskRegistry;
private readonly tracing;
private readonly sandboxService;
private readonly domainAccessTrackersByThread;
private readonly threadPushRef;
private readonly planRequestsByThread;
private readonly schedulerLocks;
private readonly failedInternalFollowUpStreaks;
private readonly pendingCheckpointReentries;
private readonly terminalOutcome;
private readonly liveness;
private readonly suspendedThreads;
private readonly suspendedRunRestorer;
private readonly runDebugBuffer;
private readonly defaultTimeZone;
private readonly logger;
private readonly workflowObligations;
private readonly taskProjector;
private checkpointPruneTimer;
private checkpointPruningStopped;
private readonly inFlightExecutions;
private readonly preserveHitlOnShutdown;
constructor(logger: Logger, globalConfig: GlobalConfig, instanceSettings: InstanceSettings, adapterService: InstanceAiAdapterService, eventBus: InProcessEventBus, eventLog: DurableEventLog, interruptedRunSweeper: InterruptedRunSweeper, settingsService: InstanceAiSettingsService, gatewayService: InstanceAiGatewayService, browserSessionService: InstanceAiBrowserSessionService, memoryService: InstanceAiMemoryService, agentMemory: TypeORMAgentMemory, checkpointStore: TypeORMAgentCheckpointStore, aiService: AiService, threadGrantRepo: InstanceAiThreadGrantRepository, pendingConfirmationRepo: InstanceAiPendingConfirmationRepository, urlService: UrlService, dbSnapshotStorage: DbSnapshotStorage, dbIterationLogStorage: DbIterationLogStorage, sourceControlPreferencesService: SourceControlPreferencesService, telemetry: Telemetry, mcpRegistryService: InstanceAiMcpRegistryService, userRepository: UserRepository, temporaryWorkflowService: InstanceAiTemporaryWorkflowService, errorReporter: ErrorReporter, ssrfProtectionConfig: SsrfProtectionConfig, ssrfProtectionService: SsrfProtectionService, eventService: EventService, evalCredentialAllowlists: EvalThreadCredentialAllowlistService, runProbe: InstanceAiRunProbe, modelService: InstanceAiModelService, creditService: InstanceAiCreditService, publisher: Publisher, instanceAiErrorReporter: InstanceAiErrorReporterService);
private createProxyRunConfig;
resolveAgentModelConfig(user: User): Promise<ModelConfig>;
private loadThreadSessionGrants;
private persistThreadSessionGrant;
isProxyEnabled(): boolean;
getCredits(user: User): Promise<{
creditsQuota: number;
creditsClaimed: number;
}>;
private reclassifyMaskedStreamFailure;
isEnabled(): boolean;
hasActiveRun(threadId: string): boolean;
isRunLive(threadId: string, runId: string): boolean;
getThreadStatus(threadId: string): InstanceAiThreadStatusResponse;
private memoryTaskObserverFor;
private subscribeToAgentErrors;
isRunDebugEnabled(): boolean;
private buildOrchestratorAgentStreamOptions;
private buildOrchestratorResumeAgentOptions;
getRunDebug(runId: string): RunDebugRecord | undefined;
listThreadDebugRuns(threadId: string): {
runId: string;
threadId: string;
startedAt: number;
stepCount: number;
workflowCodeCount: number;
label: string | undefined;
}[];
clearTraceContextsForTest(): void;
submitLangsmithFeedback(user: User, threadId: string, responseId: string, payload: {
rating: 'up' | 'down';
comment?: string;
}): Promise<void>;
startRun(user: User, threadId: string, message: string, attachments?: InstanceAiAttachment[], context?: InstanceAiHandoffContext, timeZone?: string, pushRef?: string): string;
getMessageGroupId(threadId: string): string | undefined;
getLiveMessageGroupId(threadId: string): string | undefined;
getRunIdsForMessageGroup(messageGroupId: string): string[];
getActiveRunId(threadId: string): string | undefined;
cancelRun(threadId: string, reason?: string): void;
sendCorrectionToTask(threadId: string, taskId: string, correction: string): 'queued' | 'task-completed' | 'task-not-found';
cancelBackgroundTask(threadId: string, taskId: string): void;
private broadcastTaskControl;
private applyTaskControlLocally;
private routeTaskControl;
routeCorrectionToTask(threadId: string, taskId: string, correction: string): Promise<void>;
routeCancelBackgroundTask(threadId: string, taskId: string): Promise<void>;
routeCancelRun(threadId: string): Promise<void>;
routeClearThreadState(threadId: string): Promise<void>;
handleRelayTaskControl(payload: PubSubCommandMap['relay-instance-ai-task-control']): Promise<void>;
cancelAllBackgroundTasks(): number;
startStuckBackgroundTaskForTest(user: User, threadId: string): Promise<{
threadId: string;
runId: string;
messageGroupId: string;
taskId: string;
agentId: string;
timeoutAt: number;
}>;
runLivenessSweepForTest(now?: number): Promise<void>;
loadTraceEvents(slug: string, events: unknown[]): void;
getTraceEvents(slug: string): unknown[];
hasRunningWorkForTest(): boolean;
activateTraceSlug(slug: string): void;
clearTraceEvents(slug: string): void;
clearThreadState(threadId: string): Promise<void>;
private deleteAgentBuilderSessions;
shutdown(): Promise<void>;
startCheckpointPruning(): void;
stopCheckpointPruning(): void;
private scheduleCheckpointPrune;
private trackInFlightExecution;
private startExecuteRun;
private startProcessResumedStream;
private shouldPreserveHitlOnShutdown;
private drainInFlightExecutions;
private runScheduledPrune;
private hardDeleteExpiredCheckpoints;
private pruneExpiredThreads;
private persistShutdownSnapshot;
private createAgentMemoryOptions;
private createWorkflowTaskServiceWithUiSync;
private trackWorkflowVerificationObligation;
private buildPlannedTaskFollowUpMessage;
private buildWorkflowVerificationFollowUpMessage;
private createPlannedTaskState;
replayUndeliveredTerminalOutcomes(threadId: string, options?: {
delivery?: 'snapshot' | 'event';
}): Promise<void>;
private syncPlannedTasksToUi;
private cancelAwaitingApprovalPlan;
private createExecutionEnvironment;
private getAgentExecutionService;
private bindAgentPreviewSession;
private dispatchPlannedTask;
private collectWorkflowIds;
private getBuildTaskWorkflowName;
private checkpointRequiresRunApproval;
private getCheckpointRunPolicy;
private handlePlannedTaskSettlement;
private maybeStartWorkflowVerificationFollowUp;
private buildWorkflowSetupFollowUpMessage;
private getWorkflowSetupSuspensionWorkflowId;
private markWorkflowSetupHandled;
private maybeStartWorkflowSetupFollowUp;
private listWorkflowLoopRecords;
private createWorkflowSetupRoutingClaim;
private claimWorkItemSetupRouting;
private markWorkItemSetupRouted;
private releaseWorkItemSetupRoutingClaim;
private updateInternalFollowUpFailureStreak;
private startInternalFollowUpRun;
private schedulePlannedTasks;
private createPlannedTaskActionRunner;
private createPlannedTaskView;
private createPlannedTaskRunGate;
private createPlannedTaskDispatcher;
private createPlannedTaskFollowUps;
private createPlannedWorkflowVerificationGate;
private toWorkflowVerificationSourceTask;
private createPlannedWorkflowVerificationTracker;
private createPlannedTaskDispatchContext;
private doSchedulePlannedTasks;
private persistInterruptedUserMessage;
private executeRun;
private queuePendingCheckpointReentry;
private drainPendingCheckpointReentries;
private reenterCheckpointById;
private maybeReenterParentCheckpoint;
private finalizeCheckpointFollowUp;
private finalizePlannedBuildFollowUp;
resolveConfirmation(requestingUserId: string, requestId: string, request: InstanceAiConfirmRequest): Promise<InstanceAiConfirmResponse | null>;
private buildMcpServers;
private createAgentFromEnvironment;
private buildFreshInstanceAgent;
private rebuildSuspendedRunFromCheckpoint;
private revalidateActiveUser;
private canAccessAgentPreviewHandoff;
private assertAgentPreviewHandoffScopes;
private rebuildAgentForAutoSetupResume;
private resumeSuspendedRun;
private processResumedStream;
private spawnBackgroundTask;
private buildMessageWithRunningTasks;
private trackConfirmationRequest;
private finalizeCancelledSuspendedRun;
private publishRunFinish;
private finalizeRun;
private emitRunMetrics;
private refineTitleIfNeeded;
private extractStoredMessageText;
private readDurableEventsForRuns;
private saveAgentTreeSnapshot;
private parseMcpServers;
private trackMcpToolCall;
}