import { type ClarificationResponseAction, type ClarificationSubmission, type SecretRequestView, type SecretSubmissionPayload } from '@xopcai/gateway-contract'; import type { TurnOrigin } from '@xopcai/endpoint-tools-protocol'; import type { RealtimeAudience } from '../../realtime/broker.js'; import type { Config } from '../../config/schema.js'; import type { MessageBus } from '../../infra/bus/index.js'; import type { AgentService } from '../../agent/service.js'; import type { ChannelManager } from '../../channels/manager.js'; import type { SessionIndex } from '../../session/index.js'; import { type ClarificationStreamEvent } from '../ephemeral-clarification-waiter.js'; import { SecretRequests } from '../../secrets/index.js'; import type { ClarifyRequestPayload, ClarifyRequestResult } from '../../agent/tools/clarify-tool.js'; import type { RequestSecretPayload, RequestSecretResult } from '../../agent/tools/request-secret-tool.js'; import type { GatewayPrincipal } from '../security/gateway-principal.js'; import { type RunGatewayAgentOptions } from './run-gateway-agent.js'; import { NextTurnSuggestionService } from '../next-turn-suggestions/service.js'; import { type ActiveExecution, type ActiveExecutionKind } from './active-execution.js'; import type { UserTurnAttachment, UserTurnInput } from '../user-turn-input.js'; import type { AgentSourceContext, TurnContextRef } from '../../agent/source-context/types.js'; import { SessionInputCoordinator, type ReplaceLatestTurnInput, type SubmitSessionInput } from './session-input-coordinator.js'; export interface GatewayAgentRunnerOptions { secretRequests?: SecretRequests; canResumeDeviceInteraction?: (conversationId: string, checkpoint: import('@xopcai/gateway-contract').DeviceInteractionCheckpoint) => boolean; issueDeviceGrantForApproval?: (conversationId: string, request: import('@xopcai/gateway-contract').DeviceGrantRequestCheckpoint) => { status: 'issued'; } | { status: 'needs_foreground'; displayName: string; } | { status: 'unavailable'; }; isDeviceForeground?: (endpointId: string) => boolean; afterConnectionResume?: (input: import('../../storage/sqlite/session-input-repository.js').SessionInput, status: string) => Promise; onSessionInputSettled?: (input: { conversationId: string; sessionInputId: string; agentRunId: string; status: string; summary?: string; error?: string; }) => void; bindEmbeddedBrowserGrant?: (params: { conversationId: string; clientMessageId: string; runId: string; }) => void; validateConnectionResume?: (input: import('../../storage/sqlite/session-input-repository.js').SessionInput) => Promise; continueConnection?: (wait: import('@xopcai/gateway-contract').ConnectionWait, idempotencyKey: string) => Promise; cancelConnection?: (wait: import('@xopcai/gateway-contract').ConnectionWait) => void; bus: MessageBus; sessionIndex: SessionIndex; /** Resolved lazily — the runner is constructed before AgentService exists. */ getAgentService: () => AgentService; getChannelManager: () => ChannelManager; getConfig: () => Config; /** Publish low-frequency gateway state changes. */ emit: (type: string, payload: unknown) => void; publishRealtime: (topic: string, event: string, data: unknown, audience?: RealtimeAudience) => void; completeRealtimeTopic: (topic: string) => void; resolveTurnContext: (ref: TurnContextRef, conversationId: string) => Promise; } export declare class GatewayAgentRunner { private readonly opts; /** Per-run abort for webchat (POST /api/agent/abort or client disconnect). */ private readonly runAbortControllers; private readonly runCompletions; private readonly resolveRunCompletions; private readonly ephemeralClarifications; /** Maps webchat session key → active `runId` for `clarify` tool routing. */ private readonly activeWebchatRunBySession; private readonly activeExecutionBySession; private readonly externalStreamBySession; private readonly externalClarificationResponses; readonly inputs: SessionInputCoordinator; readonly nextTurnSuggestions: NextTurnSuggestionService; readonly secretRequests: SecretRequests; private readonly reactions; private readonly unsubscribeConnectionWait; constructor(opts: GatewayAgentRunnerOptions); /** True when a webchat agent run is currently in-flight for `conversationId`. */ hasActiveRun(conversationId: string): boolean; getActiveRunId(conversationId: string): string | undefined; listActiveRuns(): Array<{ conversationId: string; runId: string; }>; listActiveExecutions(): ActiveExecution[]; disposeClarifications(): void; registerExternalWebchatRun(conversationId: string, runId: string, publish: (event: ClarificationStreamEvent) => void, options?: { beforeClarificationResponse?: () => boolean; kind?: ActiveExecutionKind; }): void; unregisterExternalWebchatRun(conversationId: string, runId: string): void; cancelClarificationForRun(runId: string): void; runAgent(message: string, channel: string, chatId: string, origin: TurnOrigin, attachments?: UserTurnAttachment[], thinking?: string, runOptions?: RunGatewayAgentOptions): AsyncGenerator<{ type: string; [key: string]: unknown; }, { status: string; summary: string; }, unknown>; submitSessionInput(input: SubmitSessionInput): Promise<{ ok: true; effectiveDelivery: import("../../storage/sqlite/session-input-repository.js").SessionInputDelivery; state: import("../../storage/sqlite/session-input-repository.js").SessionInputState; } | { ok: false; code: "BAD_REQUEST" | "QUEUE_FULL" | "CONTEXT_UNAVAILABLE" | "SESSION_CHANGED"; }>; replaceLatestSessionTurn(input: ReplaceLatestTurnInput, actor?: GatewayPrincipal): Promise<{ ok: false; code: "BAD_REQUEST" | "TARGET_NOT_FOUND" | "NOT_LATEST" | "SESSION_BUSY" | "CONTEXT_UNAVAILABLE" | "ROLLBACK_FAILED"; message?: string; } | { ok: true; effectiveDelivery: "next"; state: import("../../storage/sqlite/session-input-repository.js").SessionInputState; }>; getSessionInputState(conversationId: string): import("../../storage/sqlite/session-input-repository.js").SessionInputState; updateSessionInput(conversationId: string, id: string, body: { version: number; content?: string; attachments?: UserTurnAttachment[]; contextRefs?: TurnContextRef[]; thinking?: string; position?: number; }): Promise<{ ok: boolean; state: import("../../storage/sqlite/session-input-repository.js").SessionInputState; contextUnavailable?: boolean; }>; removeSessionInput(conversationId: string, id: string, version: number): { ok: boolean; state: import("../../storage/sqlite/session-input-repository.js").SessionInputState; }; recoverSessionInputs(): void; /** Abort an in-flight webchat agent run. */ abortAgentRun(runId: string): Promise<{ aborted: boolean; idle: boolean; }>; answerEphemeralClarification(requestId: string, answer: ClarificationSubmission): boolean; getClarificationState(conversationId: string, actor?: GatewayPrincipal): import("@xopcai/gateway-contract").ClarificationWaitSnapshot | undefined; resolveClarificationResponse(input: ClarificationSubmission & { id: string; expectedVersion: number; idempotencyKey: string; action: ClarificationResponseAction; responseActor?: GatewayPrincipal; }): import("../../storage/sqlite/clarification-wait-repository.js").ResolveClarificationResult; handleEndpointAvailabilityChange(endpointId: string, availability: 'foreground' | 'background'): void; getClarificationById(id: string): import("@xopcai/gateway-contract").ClarificationWait | undefined; answerClarificationChoice(requestId: string, choiceIndex: number, idempotencyKey: string): boolean; answerClarificationDecision(requestId: string, decision: 'approve' | 'deny', idempotencyKey: string): boolean; answerClarificationText(conversationId: string, text: string, idempotencyKey: string): boolean; /** Same execution path as scheduled continuation, but lets callers observe failures. */ runScheduledWebchatTurn(conversationId: string, userTurn: UserTurnInput): Promise; runScheduledWebchatContinuation(conversationId: string, message: string): Promise; /** Background drain for extension-initiated webchat turns (`scheduleWebchatContinuation`). */ drainScheduledWebchatContinuation(conversationId: string, message: string): Promise; publishSecretRequestsUpdated(requests: readonly SecretRequestView[]): void; private publishSecretRequestUpdate; private maskSecretRequestForActor; listSecretRequests(conversationId: string, actor?: GatewayPrincipal): Promise; resolveSecretRequestResponse(input: { requestId: string; submission: SecretSubmissionPayload; actor?: GatewayPrincipal; }): Promise<{ ok: true; request: SecretRequestView; } | { ok: false; code: string; message: string; }>; requestSecret(opts: { conversationId: string; runId: string; toolCallId: string; request: RequestSecretPayload; publishStreamFor: (runId: string) => (event: ClarificationStreamEvent) => void; }): Promise; savePastedSecret(opts: { conversationId: string; toolCallId: string; value: string; }): Promise<{ file: string; }>; /** * Persist normal clarification waits and use the lifecycle-bound waiter only * for caller-owned ephemeral sessions. * Rejects when neither path is available (e.g. CLI without webchat or TG). * * `publishStreamFor(runId)` is the bridge into AgentService's * `turnDispatcher.enqueueWebchatStreamEvent`. We take it as a callback so the * runner does not import AgentService statically. */ requestClarification(opts: { conversationId: string; runId: string; toolCallId: string; request: ClarifyRequestPayload; publishStreamFor: (runId: string) => (event: ClarificationStreamEvent) => void; }): Promise; private deliverTelegramClarify; }