import { Disposable, IDisposable } from "../../../../../base/common/lifecycle.js"; import { type CloudSandboxDiscoveryTrigger, type CloudSandboxTaskCreationPath, type ICloudSandboxConnectOptions, type ICloudSandboxCreatedSession, type ICloudSandboxCreateSessionRequest, type ICloudSandboxDiscoveryResult } from "../../../../../platform/agentHost/common/cloudSandboxAgentHost.js"; import { IConnectionDiagnosticEvent, type IConnectionDiagnosticState } from "../../../../../platform/agentHost/common/connectionDiagnostics.js"; import { type ConnectionTelemetryErrorClassification } from "../../../../../platform/agentHost/common/connectionTelemetry.js"; import { RemoteAgentHostConnectionObserver } from "../../../../../platform/agentHost/common/remoteAgentHostService.js"; import { ITelemetryService } from "../../../../../platform/telemetry/common/telemetry.service.js"; import { type ActionEnvelope } from "../../../../../platform/agentHost/common/state/sessionActions.js"; import { CloudSandboxLifecycleTelemetry, type CloudSandboxRefreshStopReason } from "./cloudSandboxLifecycleTelemetry.js"; import { ICloudSandboxTelemetryService } from "./cloudSandboxTelemetry.service.js"; export type { CloudSandboxRefreshStopReason } from "./cloudSandboxLifecycleTelemetry.js"; /** The Mission Control call being reported. A closed set, so it is safe to send verbatim. */ export type CloudSandboxRequestAction = "connect" | "reconnect" | "connectSessionFeed" | "getEnvironment" | "listEnvironments" | "deleteEnvironment" | "listTasks" | "getTask" | "createTask" | "reserveTask" | "deleteTask" | "renameTask" | "archiveTask" | "unarchiveTask" | "getTaskEvents" | "getRepository" | "listModels" | "mintIdentityToken" | "sealToken"; /** * How a Mission Control request ended, bucketed so a count is meaningful without carrying the * response itself. `waking` is the 202 an environment returns while it boots, which is neither a * success nor a failure but is the response most likely to be retried in a loop. `unexpectedStatus` * covers 1xx/3xx, which the client does not treat as success either — see * {@link requestOutcomeForStatus}. */ export type CloudSandboxRequestOutcome = "succeeded" | "waking" | "clientError" | "serverError" | "networkError" | "unexpectedStatus"; /** * What a session feed attempt or established socket did. A closed set, so it is safe to send * verbatim. `unavailable` is the server declining the feed for this account; `negotiationFailed` * and `socketFailed` are retried attempts that leave the window on discovery polling meanwhile. */ export type CloudSandboxSessionFeedOutcome = "connected" | "unavailable" | "negotiationFailed" | "socketFailed" | "disconnected" | "invalidMessage"; export interface ICloudSandboxSessionFeedTelemetryData { readonly outcome: CloudSandboxSessionFeedOutcome; /** Dropped sockets and failed attempts since the last healthy connection, including this failure. */ readonly consecutiveFailures: number; /** Delay before the next automatic attempt; absent when the feed connected or stopped retrying. */ readonly retryDelayMs?: number; /** HTTP status of a rejected negotiation request, when that caused the failure. */ readonly statusCode?: number; } export type CloudSandboxConnectionStage = "credentials" | "connection" | "relay" | "protocol" | "authentication" | "restoration"; export type CloudSandboxConnectionOutcome = "success" | "failure" | "cancelled"; export type CloudSandboxConnectionSurface = "agentsDesktop" | "agentsWeb" | "editorDesktop" | "editorWeb" | "unknown"; export type CloudSandboxConnectionSource = NonNullable; type CloudSandboxEnvironmentClassification = { environmentKind: { classification: "SystemMetaData"; purpose: "FeatureInsight"; comment: "Cloud sandbox or user-local Mission Control host; no environment identity."; }; }; type CloudSandboxTaskCreationClassification = { taskCreationPath: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Bounded task-creation path and confirmed reservation result for the initial startup, not VM readiness. Unknown when no creation context was supplied; later recovery retains this provenance."; }; }; export type CloudSandboxConnectionContext = Pick & Partial>; export declare function getCloudSandboxConnectionSurface(isSessionsWindow: boolean, isWeb: boolean): CloudSandboxConnectionSurface; export declare function getCloudSandboxTaskCreationPath(request: ICloudSandboxCreateSessionRequest, created?: ICloudSandboxCreatedSession): CloudSandboxTaskCreationPath; export interface ICloudSandboxConnectionTelemetry extends IDisposable { setConnectStage(stage: CloudSandboxConnectionStage): void; completeConnect(outcome: CloudSandboxConnectionOutcome): void; onConnectionStateChange(state: Parameters[0]): void; recordReceivedFrame(): void; createRequestObserver(): (event: "issued" | "waking") => void; recordConnectionDiagnostic(event: IConnectionDiagnosticEvent): void; setConnectionId(connectionId: string): void; recordSessionAction(envelope: ActionEnvelope, state?: IConnectionDiagnosticState): void; } /** * The outcome bucket for a response with {@link statusCode}. * * Only 2xx counts as a success, matching the client's own `isSuccess` check — a 1xx or 3xx is * thrown as a request failure, so counting it as a success would understate the failure rate. */ export declare function requestOutcomeForStatus(statusCode: number | undefined): CloudSandboxRequestOutcome; export declare class CloudSandboxTelemetryService extends Disposable implements ICloudSandboxTelemetryService { private readonly _telemetryService; readonly _serviceBrand: undefined; readonly lifecycle: CloudSandboxLifecycleTelemetry; private readonly _counts; private readonly _reportTimer; private readonly _connections; private readonly _connectionReportTimer; /** When the current window began, i.e. when its first request was recorded. */ private _windowStart; constructor(_telemetryService: ITelemetryService); trackConnection(stage: CloudSandboxConnectionStage, surface?: CloudSandboxConnectionSurface, source?: CloudSandboxConnectionSource, context?: CloudSandboxConnectionContext): ICloudSandboxConnectionTelemetry; flushConnectionHealth(): void; private _reportConnectionHealth; reportRequest(action: CloudSandboxRequestAction, outcome: CloudSandboxRequestOutcome): void; reportDiscovery(data: ICloudSandboxDiscoveryTelemetryData): void; reportProvisioningOutcome(outcome: CloudSandboxConnectionOutcome, durationMs: number, taskCreationPath?: CloudSandboxTaskCreationPath): void; reportCredentialRefreshStopped(reason: CloudSandboxRefreshStopReason, consecutiveFailures: number, error?: unknown): void; reportSessionFeed(data: ICloudSandboxSessionFeedTelemetryData): void; /** Report and reset the accumulated request counts. Safe to call when nothing has been recorded. */ flushRequestCounts(): void; } export type CloudSandboxConnectionOutcomeClassification = CloudSandboxEnvironmentClassification & CloudSandboxTaskCreationClassification & { operation: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Logical connect or recovery, including all retries."; }; environmentOperation: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Provision follows task submission, including prepared-environment or reservation reuse; resume opens an existing sandbox; recover follows loss of a ready connection; attach connects a user-local Mission Control host. Client workflow, not confirmed VM lifecycle state."; }; outcome: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Success, failure, or cancellation; cancellations are not failures."; }; stage: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Last observed connection stage: credentials, connection, relay, protocol, authentication, or restoration."; }; durationMs: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Elapsed milliseconds to readiness, terminal failure, or cancellation, including backoff."; }; provisioningMs: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Milliseconds from caller submission startup to connection start, including remaining preparation wait, task creation or claim, and local provider setup, but not background preparation before submission. Zero for resume, recovery and user-local attach; absent when the caller did not supply the start time."; }; reservationWaitMs: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Milliseconds awaiting and validating a draft reservation after submission, included in provisioningMs rather than added to readinessMs. Zero for resume, recovery and attach; absent when unobserved, and bounded by known provisioningMs."; }; readinessMs: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "End-to-end client-observed milliseconds through authenticated AHP readiness, failure or cancellation: provisioningMs plus durationMs. Includes protocol waits even after credentials arrive. Absent when provisioning start is unknown; success samples compare provisioning with resuming at the same readiness boundary."; }; preparationMs: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Exclusive client-observed credential preparation time, including environment wake/resume, token waits and backoff after credential failures until preparation succeeds or connection setup resumes. Includes HTTP and authentication overhead; not pure server startup time. Excludes task provisioning."; }; connectionMs: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Elapsed milliseconds outside credential preparation, including relay, protocol, authentication, restoration and connection retry backoff. Together with preparationMs equals durationMs, without nested phase overlap."; }; surface: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Editor or Agents window, on desktop or web; unknown when not supplied."; }; source: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Created or existing environment from the caller; does not imply warm or cold compute."; }; credentialRequests: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Credential requests handed to the request service during this operation, including failed and cancelled in-flight requests."; }; wakingResponses: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Credential requests answered with a pending response during this operation."; }; transportAttempts: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Relay connection attempts begun during this operation."; }; credentialsMs: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Cumulative credential acquisition and waiting time, including partial spans; may overlap authentication."; }; relayMs: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Cumulative relay connection time, including interrupted attempts."; }; protocolMs: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Cumulative protocol initialization or reconnect time, including interrupted attempts."; }; authenticationMs: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Cumulative authentication time, including credential preparation and interrupted attempts."; }; restorationMs: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Cumulative subscription restoration time, including interrupted attempts."; }; firstFailurePhase: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "First failed diagnostic phase: credentials, transport.connect, transport.reconnect, protocol.initialize, protocol.reconnect, protocol.authentication, or protocol.subscriptions. Absent if no phase failure was observed; preserved across later retries and cancellation. This is the recovery step, not necessarily the failed RPC method."; }; firstFailureCode: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Known JSON-RPC or AHP error code on the first failed phase. Absent for unrecognized or missing codes; no messages or error data are included."; }; firstFailureCategory?: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Allowlisted category for the first failed phase, derived only from structured metadata."; }; firstFailureStatusCode?: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Validated HTTP status for the first failed phase, including a bounded nested cause."; }; credentialFailures: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Failed credential preparation phases, including local cooldown rejections. Nested phase failures may overlap; not a count of HTTP requests."; }; relayFailures: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Failed transport establishment phases in this operation."; }; protocolFailures: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Failed initialization or reconnect phases, including fallback initialization failures; not a count of individual RPC requests."; }; authenticationFailures: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Failed authentication phases. May overlap nested credential preparation failures."; }; restorationFailures: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Failed subscription restoration phases in this operation."; }; owner: "osortega"; comment: "One outcome per logical cloud sandbox or user-local relay connect or recovery, excluding reuse of a ready connection."; }; export type CloudSandboxProvisioningOutcomeClassification = CloudSandboxTaskCreationClassification & { outcome: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Success, failure, or cancellation of sandbox task/VM provisioning; success requires a usable environment/session binding, not connection readiness."; }; durationMs: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Client-observed task creation or reservation claim milliseconds, including account resolution, HTTP, response validation and failure cleanup. Excludes earlier preparation wait, subsequent environment connection and repository preparation; not pure server provisioning time."; }; owner: "osortega"; comment: "One outcome per sandbox task creation, measured separately from connect and recovery."; }; export type CloudSandboxFirstSessionRequestClassification = CloudSandboxEnvironmentClassification & CloudSandboxTaskCreationClassification & ConnectionTelemetryErrorClassification & { surface: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Editor or Agents window, on desktop or web; unknown when not supplied."; }; source: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Created or existing environment from the caller; does not imply warm or cold compute."; }; outcome: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Outcome of the first session create, list, or subscribe request issued while ready; not turn completion."; }; durationMs: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Milliseconds for the first post-readiness session request, excluding user idle time before it."; }; requestKind?: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Allowlisted request category distinguishing session listing, creation, root, session, chat and other subscriptions."; }; connectionOperation?: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Whether the ready connection cycle followed initial connection or recovery."; }; attemptId?: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Client-generated UUID for the protocol connection attempt, shared by first-request and first-session-snapshot observations."; }; owner: "osortega"; comment: "At most one first session request sample per ready connection cycle, without issuing an extra request or recording its content."; }; export type UserLocalRelaySessionOpenClassification = Omit & { comment: "First managed session subscription per ready user-local connection cycle, from subscribe entry through receipt of a snapshot. Excludes root, chat, listing and automatic restoration; not a paint or delivery acknowledgement. At most one outcome per cycle."; }; export type CloudSandboxConnectionHealthClassification = CloudSandboxEnvironmentClassification & { connectedMs: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Sum of authenticated ready connection milliseconds since the previous snapshot, excluding outages."; }; unexpectedDisconnects: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Losses of previously ready connections; excludes initial retries and intentional teardown."; }; receivedFrames: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Inbound relay WebSocket frames, including setup, recovery, control, malformed and chunk frames; not unique protocol messages."; }; owner: "osortega"; comment: "Delta cloud sandbox or user-local relay connection exposure, unexpected losses and receive load, aggregated every five minutes with a final teardown flush."; }; export interface ICloudSandboxDiscoveryTelemetryData { trigger: CloudSandboxDiscoveryTrigger | "unknown"; requestedMode: "full" | "incremental" | "targeted"; mode: "full" | "incremental" | "targeted"; outcome: ICloudSandboxDiscoveryResult["kind"] | "cancelled"; durationMs: number; pageCount: number; listRequestCount: number; taskCount: number; sandboxTaskCount: number; changedSandboxTaskCount: number; checkpointAdvanced: boolean; } export type CloudSandboxDiscoveryClassification = { owner: "osortega"; comment: "Measures the cause, cost and outcome of one cloud sandbox discovery attempt without task content or identifiers."; trigger: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Bounded reason that initiated the discovery attempt."; }; requestedMode: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Mode requested at the discovery API boundary, before falling back when no incremental checkpoint exists."; }; mode: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Actual full, incremental or targeted API read."; }; outcome: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; comment: "Discovery result, including partial results and cancellation; HTTP success alone is not discovery success."; }; durationMs: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Elapsed client time for this discovery attempt."; }; pageCount: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Task-list responses parsed with a tasks array, including empty arrays; not a count of unique backend pages."; }; listRequestCount: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Task-list HTTP attempts issued, including retries and subsequently cancelled requests."; }; taskCount: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Unique task IDs returned by list pages or targeted reads, excluding cached tasks revisited locally."; }; sandboxTaskCount: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Unique returned tasks identified as sandbox tasks."; }; changedSandboxTaskCount: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Returned sandbox task summaries absent from or different from the client cache at scan start; not an authoritative server change count."; }; checkpointAdvanced: { classification: "SystemMetaData"; purpose: "PerformanceAndHealth"; isMeasurement: true; comment: "Whether this attempt initialized or advanced the committed incremental checkpoint."; }; };