import { Disposable } from "../../../../../base/common/lifecycle.js"; import { URI } from "../../../../../base/common/uri.js"; import { IFileService } from "../../../../../platform/files/common/files.service.js"; import { ILogService } from "../../../../../platform/log/common/log.service.js"; import { IAgentHostService } from "../../../../../platform/agentHost/common/agentService.service.js"; import { IRemoteAgentHostService } from "../../../../../platform/agentHost/common/remoteAgentHostService.service.js"; import { type ActionEnvelope } from "../../../../../platform/agentHost/common/state/sessionActions.js"; import { type Customization } from "../../../../../platform/agentHost/common/state/sessionState.js"; import { type IAgentModelCallDiagnostics } from "../../../../../platform/agentHost/common/meta/agentModelCallMeta.js"; import { type AgentHostChatOwnerSource } from "../agentSessions/agentHost/agentHostChatOwner.js"; /** * One captured Copilot `ChatUsage` action, i.e. the usage report for a single * model call. Persisted as a line in the session's sidecar so per-turn/per-round * token metrics survive a VS Code restart (the reduced chat state keeps only the * last request's input/cache per turn, and `events.jsonl` only records * `outputTokens` until `session.shutdown`). */ export interface IAgentHostUsageRecord extends Partial> { readonly schemaVersion?: 2; readonly kind?: "modelCall"; readonly correlation?: "exact" | "unresolved"; /** Turn the model call belongs to. */ readonly turnId?: string; /** Model that served the call, if reported. */ readonly model?: string; /** Input tokens for this single call. */ readonly inputTokens?: number; /** Output tokens for this single call. */ readonly outputTokens?: number; /** Cache-read tokens for this single call. */ readonly cacheReadTokens?: number; /** Per-turn cumulative Copilot AIU (nano) at the time of this call. */ readonly totalNanoAiu?: number; /** ISO timestamp when the client captured the action. */ readonly ts: string; } /** Builds the sidecar URI for a session's usage records under `baseDir`. */ export declare function buildAgentHostUsageUri(baseDir: URI, rawSessionId: string): URI; /** * Reads a session's usage sidecar. Returns the records in capture order, * skipping blank or malformed lines. Returns an empty array when the file does * not exist (e.g. a session that ran before capture shipped). */ export declare function readAgentHostUsageRecords(fileService: IFileService, uri: URI): Promise; /** * The minimal agent-host surface the recorders observe: a stream of protocol * actions plus the notifications that drive sidecar lifetime. Satisfied by * {@link IAgentHostService} in production and by bare emitters in tests, so the * recorders don't depend on the full service. */ type IAgentHostActionSource = Pick & AgentHostChatOwnerSource; /** The host that emitted an action, used to read its session state and records. */ type IAgentHostSessionCatalog = AgentHostChatOwnerSource; /** * Shared client-side plumbing for recorders that observe agent-host protocol * actions across the ambient (local) connection and every live remote * connection, and persist derived data to a client-local sidecar. Enable * gating, local/remote fan-out, and sidecar lifetime live here; subclasses * implement {@link _onAction} for the action(s) they care about and * {@link _sidecarUri} for the file to delete when a session goes away. * * Running on the client (where wire logs are captured) means every session's * actions arrive through the same subscription reducers regardless of * transport, so subclasses work uniformly for local and remote hosts. * * ## Why these sidecars are client-side * * The data they capture (`ChatUsage` / `SessionCustomizationsChanged`) is * produced by the agent host, and the host persists its own copy of the parts * it needs for correctness (see `turns.usage` in the session database, which * restores the context-usage gauge and session cost). These sidecars are NOT * that store and should not be confused with it — they exist because the * renderer has no way to read host-side session storage: the AHP protocol is * generated outside this repo, so no "read session data" RPC can be added here, * and the session data directory's path is never published to clients. Until * such a contract exists, a client-side capture is the only mechanism that * works uniformly for local *and* remote hosts. * * The two stores therefore differ deliberately: * - host store: per turn, always on, all providers, correctness-critical; * - these sidecars: per model call, debug-gated, best-effort diagnostics. * * What IS unified: lifetime (both are deleted with their session — see * {@link _sidecarUri}) and collection (both are included in the exported debug * log bundle, so an export can explain a usage discrepancy). */ declare abstract class AgentHostActionRecorder extends Disposable { protected readonly _baseDir: URI; protected readonly _isEnabled: () => boolean; protected readonly _fileService: IFileService; protected readonly _logService: ILogService; private readonly _remoteAgentHostService; /** Live per-remote-connection listeners (actions + notifications), keyed by agent-host authority. */ private readonly _remoteListeners; /** * Per-session serialized file-operation queue shared by writes and cleanup, * so a delete can never be overtaken by an in-flight write for the same * session. Owned by the base class because deletion is driven from here. */ private readonly _queues; /** * The connection object currently subscribed for each authority. Tracked so * a reconnect (which replaces the connection object under the same * authority) is detected and the listener re-subscribed to the live object. */ private readonly _remoteConnections; constructor(_baseDir: URI, _isEnabled: () => boolean, _fileService: IFileService, _logService: ILogService, agentHostService: IAgentHostActionSource, _remoteAgentHostService: IRemoteAgentHostService); /** Gate on the enable predicate before handing the action to the subclass. */ private _dispatch; /** * Deletes a session's sidecar when the host reports the session removed, so * these files don't accumulate indefinitely for sessions the user deleted * (the host's own per-session storage cascades away with the session * directory; without this the client-side copies would outlive it). * * Deliberately NOT gated on {@link _isEnabled}: toggling debug logging off * must not strand the files already written while it was on. */ private _onNotification; /** * Runs `operation` after any previously queued work for `rawSessionId`, * keeping per-session file operations in submission order. Failures are * swallowed (and traced) so one failed operation cannot break the chain. */ protected queued(rawSessionId: string, operation: () => Promise): Promise; /** Handle a single action from any (local or remote) connection. */ protected abstract _onAction(envelope: ActionEnvelope, catalog: IAgentHostSessionCatalog): void; /** The sidecar file owned by this recorder for the given raw session id. */ protected abstract _sidecarUri(rawSessionId: string): URI; /** Subscribes to each current remote connection's streams; drops stale ones. */ private _syncRemoteListeners; } /** * Captures Copilot `ChatUsage` actions on the client and appends them to a * stable, client-local per-session sidecar so token metrics survive a VS Code * restart and feed accurate per-round Cache Explorer numbers. * * Dedup: a single model call can surface multiple `ChatUsage` actions — * 1. a parent-scope emit on the session's DEFAULT chat channel, and * 2. for sub-agent calls, a sub-agent-scope emit on a sub-agent chat channel * (`parseChatUri` maps both to the same session), and * 3. an async re-emit carrying the same tokens plus `_meta.contextAttribution`. * Capturing only actions on the default chat channel (1) that lack * `contextAttribution` yields exactly one record per model call — and the * parent aggregate already includes sub-agent token usage. */ export declare class AgentHostUsageRecorder extends AgentHostActionRecorder { private readonly _seenCalls; private readonly _retention; /** Default chat -> owning session, cached only for chats a host has listed. */ private readonly _defaultChatOwners; /** Chats a held or listed session names as one of its non-default chats, so their usage is not recorded. */ private readonly _nonDefaultChats; /** Per-host queue keeping that host's records in arrival order while owners resolve. */ private readonly _recordingByHost; protected _sidecarUri(rawSessionId: string): URI; protected _onAction(envelope: ActionEnvelope, catalog: IAgentHostSessionCatalog): void; /** Settles once every received action has been handed to its sidecar queue. */ protected whenRecorded(): Promise; /** * Finds the session whose default chat this is: held session state first, * then the host's session records. Remembers a chat that a session names as * a non-default chat. A chat no session names yet, or a lookup that fails, * is not remembered, so a later action looks it up again. */ private _resolveDefaultChatOwner; /** * Appends a record to the session's sidecar. Uses the file system's append * capability so each record is a single small write (no read-modify-write of * the whole file, and no in-memory copy of the growing file) — writes are * still serialized per session to keep records ordered. Records written * before a restart are preserved because we append to the existing file. */ private _append; } /** Builds the sidecar URI for a session's customization snapshot under `baseDir`. */ export declare function buildAgentHostCustomizationsUri(baseDir: URI, rawSessionId: string): URI; /** * Reads a session's persisted customization snapshot — the last * full-replacement `SessionCustomizationsChanged` payload captured live. * Returns `undefined` when the file is absent (e.g. a session that ran before * capture shipped) or malformed, so callers fall back to the live session * state rather than showing nothing. */ export declare function readAgentHostCustomizationsSnapshot(fileService: IFileService, uri: URI): Promise; /** * Captures each session's loaded customizations (skills/hooks/agents/MCP) to a * stable client-local snapshot so the debug view can surface them even for * historical/closed sessions. This is necessary because the live * {@link IAgentHostCustomizationService} only knows the customizations of * sessions with an active state subscription, and the SDK's `session.*_loaded` * events are ephemeral (never written to `events.jsonl`). * * Listens for the full-replacement `SessionCustomizationsChanged` action — the * canonical way a host publishes its effective customization set — on the * `:/` session channel, and overwrites the session's snapshot. * The raw id derived from the channel matches the one the reader derives from * the client session resource (both are the URI path), so the snapshot lines up * with the session it belongs to. */ export declare class AgentHostCustomizationRecorder extends AgentHostActionRecorder { protected _sidecarUri(rawSessionId: string): URI; protected _onAction(envelope: ActionEnvelope): void; /** Overwrites the session's snapshot, serializing writes per session. */ private _write; } export {};