Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
// AHP 0.9 changed the automation catalog wire shape, so VS Code cannot safely negotiate 0.8.
const
CLIENT_SUPPORTED_PROTOCOL_VERSIONS
=
SUPPORTED_PROTOCOL_VERSIONS
.
filter
(
=>
!==
'0.8.0'
)
;
/**
* After this much inbound silence, send an application-level `ping` to
* the remote so we have something to time out on. Reset on every received
* message — busy connections don't generate ping traffic.
*
* Mirrors {@link ProtocolConstants.KeepAliveSendTime} from the regular
* remote extension host stack.
*/
const
PING_INTERVAL_MS
=
5_000
;
/**
* Total inbound silence (ping interval + this) before a non-local connection
* is declared dead and force-closed so the renderer's reconnect logic kicks
* in. Reset on every received message; the only way to reach this is for the
* ping to itself go unanswered.
*
* Matches {@link ProtocolConstants.TimeoutTime} from the regular remote
* extension host stack.
*/
const
LIVENESS_TIMEOUT_MS
=
20_000
;
function
connectionTimeoutError
(
:
string
,
:
number
)
:
{
return
new
ProtocolError
(
AHP_CLIENT_CONNECTION_CLOSED
,
`Connection appears dead: ${address}; no message received for ${silenceMs}ms.`
,
)
;
}
function
connectionClosedError
(
:
string
)
:
{
return
new
ProtocolError
(
AHP_CLIENT_CONNECTION_CLOSED
,
`Connection closed: ${address}`
)
;
}
function
connectionDisposedError
(
:
string
)
:
{
return
new
ProtocolError
(
AHP_CLIENT_CONNECTION_CLOSED
,
`Connection disposed: ${address}`
)
;
}
function
transportLostError
(
:
string
)
:
{
return
new
ProtocolError
(
AHP_CLIENT_CONNECTION_CLOSED
,
`Transport lost (reconnecting): ${address}`
)
;
}
interface
IRemoteAgentHostExtensionNotificationMap
{
'setClientManagedSettingsPermissions'
:
{
:
{
:
}
}
;
}
interface
IPendingRequest
{
readonly
:
<
unknown
>
;
readonly
:
boolean
;
readonly
:
number
;
}
/**
* High-level connection state of an {@link AgentHostProtocolClient}.
* Exposed via {@link AgentHostProtocolClient.onDidChangeConnectionState}
* so consumers can surface transient reconnect activity in the UI.
*/
export
const
enum
{
/** Initial handshake in progress. */
=
'connecting'
,
/** The host rejected the initial protocol version; upgrade remains available. */
=
'incompatible'
,
/** Transport is open and handshake/reconnect has completed. */
=
'connected'
,
/** Transport closed unexpectedly; an automatic reconnect is in flight or scheduled. */
=
'reconnecting'
,
/** Client has been disposed or has given up reconnecting. Terminal state. */
=
'closed'
,
}
/**
* Reconnect-only bookkeeping. Lives exclusively inside the `Reconnecting`
* variant of {@link ClientState} so the fields can't be read or mutated when
* they're not meaningful.
*/
interface
IReconnectState
{
/**
* Resolves when the current attempt's handshake succeeds; rejected and
* replaced (via {@link _newReconnectGate}) on a failed attempt so awaiting
* callers see the failure while new callers gate on the next attempt.
*/
:
<
void
>
;
/**
* Wire messages buffered while the gate is engaged. Drained onto the new
* transport by {@link _drainAfterReconnect} once the handshake completes;
* survives across failed attempts so messages ride through retry cycles.
*/
readonly
:
[
]
;
/** Number of reconnect attempts performed in this reconnect cycle. */
:
number
;
/** Timer for the next scheduled attempt, if any. */
:
<
typeof
>
|
undefined
;
}
/**
* Internal connection state, discriminated by {@link AgentHostClientState}.
* Mutually-exclusive fields (close error, reconnect bookkeeping) live inside
* the variant where they're meaningful so callers can't accidentally read or
* write them in the wrong state.
*/
type
ClientState
=
|
{
readonly
:
.
;
readonly
:
[
]
}
|
{
readonly
:
.
;
readonly
:
}
|
{
readonly
:
.
}
|
{
readonly
:
.
;
readonly
:
}
|
{
readonly
:
.
;
readonly
:
}
;
/** Optional configuration for an {@link AgentHostProtocolClient}. */
export
interface
IAgentHostProtocolClientOptions
{
/** Estimator used to suppress watchdog closes while the local event loop is saturated. Defaults to the shared instance. */
readonly
?
:
;
/** Stable client identity. Generated when omitted. */
readonly
?
:
string
;
/** Client implementation metadata advertised during the handshake. */
readonly
?
:
;
/** How a dropped transport is restored. Defaults to {@link DEFAULT_RECONNECT_POLICY}. */
readonly
?
:
;
}
/**
* A protocol-level client for a single agent host connection.
* Manages the transport, handshake, subscriptions, action dispatch,
* and command/response correlation.
*
* Implements {@link IAgentConnection} so consumers can program against
* a single interface regardless of whether the agent host is local or remote.
*/
export
class
AgentHostProtocolClient
extends
Disposable
implements
IAgentConnection
,
{
declare
readonly
:
undefined
;
private
readonly
:
string
;
private
readonly
:
string
;
private
readonly
:
;
private
readonly
:
(
(
)
=>
)
|
undefined
;
private
!
:
;
/** Disposable holding the listeners attached to the current transport. */
private
readonly
=
this
.
_register
(
new
MutableDisposable<DisposableStore>
(
)
)
;
private
readonly
:
string
;
readonly
:
;
private
=
0
;
private
=
1
;
private
:
string
|
undefined
;
/**
* Latest `initialize` response from the host. Captured at the end of
* {@link connect} and re-captured after a soft-reconnect that pulled
* a fresh snapshot. `undefined` before the handshake completes.
*/
/**
* Fires for every `otlp/exportLogs` notification the host sends on a
* channel this client has subscribed to. Each payload is an
* OTLP/JSON `ExportLogsServiceRequest` value verbatim; consumers
* decode it (see `iterateOtlpLogRecords`) and route the records to a
* registered logger or sink.
*
* Channel URIs are kept opaque on the wire so the same event covers
* every {@link TelemetryCapabilities.logs} URI the host advertises —
* subscribers should filter by `channel` if they care.
*/
private
readonly
=
this
.
_register
(
new
Emitter<OtlpExportLogsParams>
(
)
)
;
readonly
=
this
.
.
;
private
readonly
=
this
.
_register
(
new
Emitter<void>
(
)
)
;
readonly
=
this
.
.
;
private
readonly
=
this
.
_register
(
new
Emitter<ProtocolError>
(
)
)
;
readonly
=
this
.
.
;
private
readonly
=
this
.
_register
(
new
Emitter<AgentHostClientState>
(
)
)
;
readonly
=
this
.
.
;
/**
* Discriminated state union. Read via narrowing (`_state.kind === ...`);
* reconnect-only fields like the gate/outbox/attempt counter are only
* accessible while {@link _state.kind} is {@link AgentHostClientState.Reconnecting},
* and protocol errors are only accessible while the state is
* {@link AgentHostClientState.Incompatible} or {@link AgentHostClientState.Closed}.
*/
private
:
=
{
:
.
,
:
[
]
}
;
/** Pending JSON-RPC requests keyed by request id. */
private
readonly
=
new
Map<number, IPendingRequest>
(
)
;
private
readonly
=
new
Map<string, AuthenticateParams>
(
)
;
private
=
1
;
/**
* Timestamp of the most recent message of any kind received from the
* server. Used only for diagnostic logging when the close timer fires.
*/
private
=
.
now
(
)
;
/**
* Liveness watchdog — see {@link _resetLivenessTimers}.
*
* {@link _pingTimer} fires after {@link PING_INTERVAL_MS} of inbound
* silence and sends an application-level `ping` so we have something
* to time out on. {@link _closeTimer} fires after another
* {@link LIVENESS_TIMEOUT_MS} of continued silence and force-closes
* the transport so the renderer's reconnect logic kicks in. Both are
* reset on every received message, so busy connections generate no
* ping traffic at all.
*
* Detects silently-dead transports (e.g. SSH/tunnel after laptop
* sleep + network change) that don't produce a socket close event of
* their own.
*/
private
readonly
=
this
.
_register
(
new
TimeoutTimer
(
)
)
;
private
readonly
=
this
.
_register
(
new
TimeoutTimer
(
)
)
;
/**
* Used to suppress watchdog-triggered closes when our own JS event loop
* has been pegged — in that case the silence is on our side, not the
* remote's, and tearing down the transport would just generate a useless
* reconnect cycle that aborts in-flight requests.
*/
private
readonly
:
;
private
readonly
:
|
undefined
;
private
readonly
:
;
/**
* URIs we have already granted implicit read access for on this connection.
* Uses URI-aware comparison to dedupe repeat sends and is cleared with the connection.
*/
private
readonly
=
new
ResourceSet
(
)
;
private
readonly
=
this
.
_register
(
new
DisposableStore
(
)
)
;
get
clientId
(
)
:
string
{
return
this
.
;
}
get
address
(
)
:
string
{
return
this
.
;
}
get
defaultDirectory
(
)
:
string
|
undefined
{
return
this
.
;
}
get
connectionState
(
)
:
{
return
this
.
.
;
}
/**
* The latest `initialize` response from the host, or `undefined` if
* the handshake has not completed yet. Exposed observably so callers can
* react as advertised capabilities (telemetry, `completionTriggerCharacters`,
* `terminalCommandPrefix`, ...) arrive.
*/
get
initializeResult
(
)
:
<
|
undefined
>
{
return
this
.
;
}
constructor
(
:
,
:
|
(
(
)
=>
)
,
:
|
undefined
,
@ILogService
private
readonly
:
,
@IAgentHostResourceService
private
readonly
:
,
@IConfigurationService
private
readonly
:
,
@ITelemetryService
private
readonly
:
,
)
{
super
(
)
;
this
.
=
;
this
.
=
===
LOCAL_AGENT_HOST_RESOURCE_IDENTITY
?
AMBIENT_AGENT_HOST_AUTHORITY
:
;
this
.
=
?.
??
generateUuid
(
)
;
this
.
=
===
LOCAL_AGENT_HOST_RESOURCE_IDENTITY
?
AMBIENT_AGENT_HOST_AUTHORITY
:
agentHostAuthority
(
)
;
this
.
=
===
LOCAL_AGENT_HOST_RESOURCE_IDENTITY
?
:
createAgentHostResourceUriMapper
(
this
.
)
;
this
.
=
?.
??
.
getInstance
(
)
;
this
.
=
?.
;
this
.
=
?.
??
DEFAULT_RECONNECT_POLICY
;
if
(
typeof
===
'function'
)
{
this
.
=
;
this
.
_installTransport
(
transportOrFactory
(
)
)
;
}
else
{
this
.
=
undefined
;
this
.
_installTransport
(
)
;
}
this
.
=
this
.
_register
(
new
AgentSubscriptionManager
(
this
.
,
(
)
=>
this
.
nextClientSeq
(
)
,
=>
this
.
.
warn
(
`[AgentHostProtocolClient] ${msg}`
)
,
=>
this
.
subscribe
(
)
,
=>
this
.
unsubscribe
(
)
,
)
)
;
// Forward action envelopes from the transport to the subscription manager
this
.
_register
(
this
.
onDidAction
(
=>
{
this
.
.
receiveEnvelope
(
)
;
}
)
)
;
this
.
_register
(
this
.
.
onDidChangeConfiguration
(
=>
{
if
(
this
.
.
!==
.
)
{
return
;
}
const
:
<
string
,
unknown
>
=
{
}
;
// These keys are host-level and last-writer-wins across windows.
const
:
string
[
]
=
[
]
;
// Mirrored values exclude workspace, folder, and memory layers, so changes from those layers cannot affect them.
// Passive transports are already connected when constructed.
this
.
_resetLivenessTimers
(
)
;
}
}
/**
* Install a transport and wire listeners. Used both for the initial
* transport and for replacements created by the factory during a
* transport-level reconnect.
*/
private
_installTransport
(
:
)
:
void
{
const
=
new
DisposableStore
(
)
;
.
add
(
)
;
.
add
(
.
onMessage
(
=>
this
.
_handleMessage
(
)
)
)
;
.
add
(
.
onClose
(
(
)
=>
this
.
_handleTransportClose
(
)
)
)
;
this
.
=
;
this
.
.
=
;
}
/**
* Transition to a new {@link ClientState}. Fires {@link onDidChangeConnectionState}
* only when the variant kind actually changes; in-place mutation of
* reconnect-state fields (e.g. swapping the gate on a failed retry) does
* NOT count as a transition and produces no event.
*/
private
_transitionTo
(
:
)
:
void
{
if
(
this
.
.
===
.
)
{
return
;
}
this
.
=
;
this
.
.
fire
(
.
)
;
}
private
_newReconnectGate
(
)
:
<
void
>
{
const
=
new
DeferredPromise<void>
(
)
;
// Always-attached handler so a rejection without an awaiter (e.g. a
// retry-fail during the reconnect RPC bypass window) doesn't get
// flagged as unhandled. Actual consumers attach their own `.then`/`await`.
.
.
then
(
undefined
,
(
)
=>
{
/* swallow — each real consumer handles its own await */
}
)
;
return
;
}
private
_newReconnectState
(
)
:
{
return
{
:
this
.
_newReconnectGate
(
)
,
:
[
]
,
:
0
,
:
undefined
}
;
}
dispose
(
)
:
void
{
this
.
_handleClose
(
connectionDisposedError
(
this
.
)
)
;
super
.
dispose
(
)
;
}
/**
* Connect to the remote agent host and perform the protocol handshake.
*/
// Advertise every compatible version, most-preferred first, so an
// older host (a cloud sandbox running a 0.5.x `copilotd`) can negotiate down
// instead of rejecting the connection. A current host still picks the newest.
:
[
...
CLIENT_SUPPORTED_PROTOCOL_VERSIONS
]
,
:
this
.
,
:
this
.
,
:
this
.
_clientMeta
(
)
,
:
[
ROOT_STATE_URI
]
,
}
,
{
:
true
}
)
;
this
.
_applyInitializeResult
(
)
;
// Hydrate root state from the initial snapshot
for
(
const
of
.
??
[
]
)
{
if
(
isAhpRootChannel
(
.
)
)
{
this
.
.
handleRootSnapshot
(
.
as
,
.
)
;
}
}
if
(
isClientTransport
(
this
.
)
&&
this
.
.
===
.
)
{
for
(
const
of
this
.
.
)
{
this
.
.
send
(
)
;
}
this
.
.
.
=
0
;
}
this
.
_transitionTo
(
{
:
.
}
)
;
this
.
_resetLivenessTimers
(
)
;
}
catch
(
)
{
const
=
instanceof
ProtocolError
?
:
new
ProtocolError
(
AHP_CLIENT_CONNECTION_CLOSED
,
instanceof
Error
?
.
:
String
(
)
)
;
if
(
.
===
.
)
{
this
.
_cancelLivenessTimers
(
)
;
if
(
this
.
.
===
.
)
{
this
.
.
.
=
0
;
}
this
.
_rejectPendingRequests
(
)
;
this
.
_transitionTo
(
{
:
.
,
:
}
)
;
throw
;
}
if
(
instanceof
NonReconnectableTransportError
)
{
this
.
_handleFatalClose
(
)
;
throw
;
}
if
(
this
.
.
===
.
)
{
throw
;
}
if
(
.
===
AHP_CLIENT_CONNECTION_CLOSED
&&
this
.
_beginReconnectFromConnecting
(
)
)
{
throw
;
}
this
.
_handleClose
(
)
;
throw
;
}
}
/**
* Externally signal that the transport has closed. Used by services
* managing a passive transport (SSH / dev-tunnels) when they observe
* a connection-loss IPC event independent of the transport's own
* onClose — without this, a single dropped IPC delivery on the
* transport's close channel leaves the client stranded in
* `Connected` until its watchdog fires (which can take hours when
* the renderer is backgrounded and `setTimeout` is throttled).
*
* Idempotent — no-op if already closed or mid-reconnect.
*/
notifyTransportClosed
(
)
:
void
{
this
.
_handleTransportClose
(
)
;
}
/**
* Called from the transport's `onClose` event. When a {@link _transportFactory}
* is configured we attempt to soft-reconnect rather than fire `onDidClose` —
* the protocol-level `reconnect` request lets the server replay missed
* actions and preserves the `clientId` so pending tool calls etc. are not
* cancelled by the host-side disconnect timeout. Without a factory
* (passive-transport SSH/relay path) we fall back to "close means closed"
* and let the service decide whether to spin up a fresh client.
*/
private
_handleTransportClose
(
)
:
void
{
switch
(
this
.
.
)
{
case
.
:
return
;
case
.
:
if
(
!
this
.
_beginReconnectFromConnecting
(
connectionClosedError
(
this
.
)
)
)
{
this
.
_handleClose
(
connectionClosedError
(
this
.
)
)
;
}
return
;
case
.
:
this
.
_handleClose
(
connectionClosedError
(
this
.
)
)
;
return
;
case
.
:
{
if
(
!
this
.
)
{
// Passive-transport path (SSH/tunnel): the transport
// can't be reconstructed from here, so we surface the
// close and let the service decide whether to spin up
// a fresh client.
this
.
_handleClose
(
connectionClosedError
(
this
.
)
)
;
return
;
}
if
(
!
this
.
.
)
{
const
=
connectionClosedError
(
this
.
)
;
this
.
.
info
(
`[RemoteAgentHostProtocol] Transport lost for ${this._address}; automatic reconnect is disabled.`
)
;
this
.
_handleFatalClose
(
)
;
return
;
}
this
.
.
info
(
`[RemoteAgentHostProtocol] Transport lost for ${this._address}; scheduling reconnect.`
)
;
this
.
_transitionTo
(
{
:
.
,
:
this
.
_newReconnectState
(
)
}
)
;
this
.
_cancelLivenessTimers
(
)
;
// In-flight requests can't be answered — the new transport has a
// separate request-id space. Reject them so callers can retry.
this
.
_rejectPendingRequests
(
transportLostError
(
this
.
)
)
;
this
.
_scheduleReconnect
(
)
;
return
;
}
case
.
:
// A second transport drop while a reconnect was already in flight.
// Reject the in-flight `reconnect` RPC so `_attemptReconnect`'s
// catch path runs and schedules the next attempt — returning early
// would leave the await pending forever (#agent-host-deadlock).
// Scheduling lives in the catch so we don't end up with two
// concurrent setTimeouts racing to install new transports.
this
.
.
info
(
`[RemoteAgentHostProtocol] Transport lost for ${this._address} mid-reconnect; aborting the current attempt.`
)
;
this
.
_cancelLivenessTimers
(
)
;
this
.
_rejectPendingRequests
(
transportLostError
(
this
.
)
)
;
return
;
}
}
private
_beginReconnectFromConnecting
(
:
)
:
boolean
{
if
(
this
.
.
!==
.
||
!
this
.
)
{
return
false
;
}
if
(
!
this
.
.
)
{
this
.
.
info
(
`[RemoteAgentHostProtocol] Transport lost while connecting to ${this._address}; automatic reconnect is disabled.`
)
;
this
.
_handleFatalClose
(
)
;
return
true
;
}
this
.
.
info
(
`[RemoteAgentHostProtocol] Transport lost while connecting to ${this._address}; scheduling a fresh initialize.`
)
;
// Carry the pre-handshake outbox into the reconnect state so queued
// messages are replayed once the fresh initialize succeeds.
const
=
this
.
.
;
this
.
_rejectPendingRequests
(
)
;
this
.
.
clear
(
)
;
this
.
.
clear
(
)
;
this
.
_transitionTo
(
{
:
.
,
:
{
...
this
.
_newReconnectState
(
)
,
}
,
}
)
;
this
.
_cancelLivenessTimers
(
)
;
this
.
_scheduleReconnect
(
)
;
return
true
;
}
/**
* Reopens a terminal connection after its host has been explicitly restarted.
*/
reconnectFromClosed
(
)
:
boolean
{
if
(
this
.
.
!==
.
||
!
this
.
||
this
.
.
)
{
return
false
;
}
this
.
_transitionTo
(
{
:
.
,
:
this
.
_newReconnectState
(
)
}
)
;
this
.
_scheduleReconnect
(
true
)
;
return
true
;
}
private
_scheduleReconnect
(
=
false
)
:
void
{
if
(
this
.
.
!==
.
||
!
this
.
)
{
return
;
}
const
=
this
.
.
;
if
(
.
!==
undefined
)
{
return
;
}
if
(
!
&&
!
this
.
.
)
{
const
=
connectionClosedError
(
this
.
)
;
this
.
.
info
(
`[RemoteAgentHostProtocol] Automatic reconnect to ${this._address} is disabled.`
)
;
this
.
_handleFatalClose
(
)
;
return
;
}
if
(
!
&&
hasExhaustedReconnectAttempts
(
this
.
,
.
)
)
{
const
=
new
ProtocolError
(
AHP_CLIENT_CONNECTION_CLOSED
,
`Automatic reconnect gave up after ${reconnect.attempt} attempts.`
)
;
this
.
.
warn
(
`[RemoteAgentHostProtocol] Automatic reconnect to ${this._address} gave up after ${reconnect.attempt} attempts.`
)
;
this
.
_handleFatalClose
(
)
;
return
;
}
const
=
.
+
1
;
const
=
computeReconnectDelay
(
this
.
,
)
;
this
.
.
info
(
`[RemoteAgentHostProtocol] Reconnecting to ${this._address} in ${delay}ms (attempt ${attempt}).`
)
;
.
=
setTimeout
(
(
)
=>
{
if
(
this
.
.
===
.
)
{
this
.
.
.
=
undefined
;
}
void
this
.
_attemptReconnect
(
)
;
}
,
)
;
}
private
async
_attemptReconnect
(
)
:
Promise
<
void
>
{
if
(
this
.
.
!==
.
||
!
this
.
)
{
return
;
}
const
=
this
.
.
;
.
++
;
let
:
|
undefined
;
try
{
=
this
.
_transportFactory
(
)
;
this
.
_installTransport
(
)
;
if
(
isClientTransport
(
)
)
{
await
.
connect
(
)
;
}
if
(
this
.
.
!==
.
)
{
return
;
}
const
=
this
.
.
currentSubscriptionUris
(
)
.
map
(
=>
.
toString
(
)
)
;
// Always include the always-live root state alongside getSubscription-managed entries.
if
(
!
.
includes
(
ROOT_STATE_URI
)
)
{
.
unshift
(
ROOT_STATE_URI
)
;
}
const
=
this
.
;
const
{
,
}
=
await
this
.
_reconnectOrInitialize
(
,
)
;
if
(
this
.
.
!==
.
)
{
return
;
}
this
.
_applyReconnectResult
(
,
)
;
this
.
_updateManagedSettingsPermissions
(
true
)
;
if
(
&&
.
===
.
)
{
await
this
.
_restoreAuthenticationAfterFreshInitialize
(
)
;
await
this
.
_restoreSubscriptionsAfterFreshInitialize
(
.
)
;
}
if
(
this
.
.
!==
.
)
{
return
;
}
// Re-push renderer-owned config on reconnect too: a reconnected host may
// be a freshly restarted process that never received these values (the
// reconnect result itself carries none), which would otherwise leave
// early-read config like the migrate flag at its host-side default.
this
.
_forwardClientConfig
(
false
)
;
// Drain the outbox BEFORE the transition so listeners reacting to
// {@link onDidChangeConnectionState} that synchronously dispatch see
// state=Connected and go direct, landing after the drained outbox
// in wire order.
const
{
}
=
;
this
.
_drainAfterReconnect
(
.
)
;
this
.
=
.
now
(
)
;
this
.
_resetLivenessTimers
(
)
;
this
.
_transitionTo
(
{
:
.
}
)
;
.
complete
(
)
;
this
.
.
info
(
`[RemoteAgentHostProtocol] Reconnected to ${this._address}.`
)
;
}
catch
(
)
{
this
.
.
warn
(
`[RemoteAgentHostProtocol] Reconnect attempt failed for ${this._address}: ${err instanceofError? err.message :String(err)}`
)
;
?.
dispose
(
)
;
if
(
this
.
.
!==
.
)
{
return
;
}
if
(
instanceof
NonReconnectableTransportError
)
{
const
=
new
ProtocolError
(
AHP_CLIENT_CONNECTION_CLOSED
,
.
)
;
this
.
_handleFatalClose
(
)
;
return
;
}
// Replace the gate so awaiting callers see the failure but new
// callers gate on the next attempt instead of slipping through onto
// the dead transport. Outbox carries forward to the next attempt.
/**
* Push the renderer-owned config values the host mirrors (telemetry level,
* proxy discovery, migrate flag, …) as `RootConfigChanged` actions. Called on
* initial connect AND on reconnect: a reconnected host may be a freshly
* restarted process (or one that lost these values), and re-pushing is a cheap
* no-op when nothing changed. Without this, a value read early — like the
* migrate flag in `listSessions` — can be missing after a window reload.
*
* Most settings arrive here declaratively, via `agentHost` on their
* configuration schema. The explicit calls below cover the cases a single
* key-plus-transform can't express: values derived from several settings, and
* settings contributed by an extension rather than by core.
*/
private
_forwardClientConfig
(
=
true
)
:
void
{
this
.
_dispatchRootConfig
(
resolveAgentHostConfigurationSyncPatch
(
this
.
,
getAgentHostConfigurationSyncTarget
(
this
.
)
)
)
;
this
.
_updateTelemetryLevel
(
)
;
this
.
_updateTerminalAutoApproveEnabled
(
)
;
this
.
_updateTerminalAutoApproveRules
(
)
;
this
.
_updateAutoApprovePolicyRestriction
(
)
;
this
.
_updateDisableRepoInfoTelemetry
(
)
;
if
(
)
{
void
this
.
_updateManagedSettingsPermissions
(
)
;
}
}
private
_updateAutoApprovePolicyRestriction
(
)
:
void
{
const
=
this
.
.
inspect<boolean>
(
GLOBAL_AUTO_APPROVE_SETTING_ID
)
?.
===
false
;
this
.
_dispatchRootConfig
(
{
[
]
:
}
)
;
}
/**
* Apply a `reconnect` RPC result to the subscription manager. On `replay`
* we feed each missed envelope through the normal action path; on
* `snapshot` we reseat each named subscription with the fresh state and
* advance the server seq cursor accordingly.
*/
private
_applyReconnectResult
(
:
[
'reconnect'
]
[
'result'
]
,
=
false
)
:
void
{
if
(
.
===
.
)
{
let
=
this
.
;
for
(
const
of
.
)
{
// For own non-rejected actions, drop the matching pending entry up
// front so we don't resend it via {@link _replayPendingActions}.
// For rejected actions we MUST leave the entry in place so the
// subscription's reconcile path sees `idx !== -1` and discards
// the action instead of applying it to confirmed state.
if
(
.
?.
===
this
.
&&
.
.
!==
undefined
&&
!
.
)
{
this
.
.
dropPendingAction
(
.
,
.
.
)
;
}
if
(
.
>
)
{
=
.
;
}
this
.
.
fire
(
normalizeLegacyActionEnvelope
(
)
)
;
}
this
.
=
;
if
(
.
.
>
0
)
{
this
.
.
info
(
`[RemoteAgentHostProtocol] Server cannot resume ${result.missing.length} subscription(s) after reconnect.`
)
;
this
.
.
markSubscriptionsMissing
(
.
.
map
(
=>
URI
.
parse
(
)
)
)
;
}
}
else
{
let
=
this
.
;
for
(
const
of
.
)
{
this
.
.
applyReconnectSnapshot
(
.
,
.
,
.
,
)
;
if
(
.
>
)
{
=
.
;
}
}
this
.
=
;
}
}
/**
* Drain queued outgoing wire traffic after a successful soft reconnect:
*
* 1. Resend pending optimistic session actions that the server did NOT
* echo back in the replay buffer (i.e. anything still on
* {@link AgentSubscriptionManager.getPendingActions}).
* 2. Flush every message that {@link _sendNotification} queued onto the
* outbox while the gate was engaged.
*
* Replays are deduped against the outbox by `clientSeq` so a session
* action that was both optimistic-tracked AND queued during the
* reconnect window only goes out once.
*/
private
_drainAfterReconnect
(
:
readonly
[
]
)
:
void
{
// Build the set of clientSeqs already represented in the outbox so we
// don't replay a duplicate. Only `dispatchAction` notifications carry
// a clientSeq; nothing else is independently re-emitted by the replay
// path, so other queued message kinds need no dedup.
const
=
new
Set<number>
(
)
;
for
(
const
of
)
{
if
(
hasKey
(
,
{
:
true
}
)
&&
.
===
'dispatchAction'
)
{
.
add
(
.
.
)
;
}
}
const
:
[
]
=
[
]
;
for
(
const
of
this
.
.
getPendingActions
(
)
)
{
if
(
.
has
(
.
)
)
{
continue
;
}
this
.
_grantImplicitReadsForOutgoingAction
(
.
)
;
.
push
(
{
:
'2.0'
,
:
'dispatchAction'
,
:
{
:
.
,
:
.
,
:
.
}
,
}
)
;
}
if
(
.
>
0
)
{
this
.
.
info
(
`[RemoteAgentHostProtocol] Replaying ${replays.length} pending action(s) after reconnect to ${this._address}.`
)
;
}
// Replays first (dispatched before the reconnect window), then the
// outbox (dispatched during it) so wire order roughly tracks
// dispatch order.
for
(
const
of
)
{
this
.
.
send
(
)
;
}
for
(
const
of
)
{
this
.
.
send
(
)
;
}
}
// ---- IAgentConnection subscription API ----------------------------------
get
rootState
(
)
:
<
>
{
return
this
.
.
;
}
getSubscription<T>
(
:
,
:
URI
,
:
string
)
:
<
<
T
>>
{
return
this
.
.
getSubscription<T>
(
,
,
)
;
}
getSubscriptionUnmanaged<T>
(
:
,
:
URI
)
:
<
T
>
|
undefined
{
return
this
.
.
getSubscriptionUnmanaged<T>
(
)
;
}
getInflightSessionCreate
(
:
URI
)
:
Promise
<
unknown
>
|
undefined
{
return
this
.
.
getInflightSessionCreate
(
)
;
}
trackSessionCreate
(
:
URI
,
:
Promise
<
unknown
>
)
:
void
{
this
.
.
trackSessionCreate
(
,
)
;
}
getActiveSubscriptions
(
)
:
readonly
[
]
{
return
this
.
.
getActiveSubscriptions
(
)
;
}
dispatch
(
:
string
,
:
|
|
|
|
|
|
|
)
:
void
{
const
=
this
.
.
dispatchOptimistic
(
,
)
;
this
.
dispatchAction
(
,
,
this
.
,
)
;
}
/**
* Subscribe to state at a URI. Returns the current state snapshot.
*
* For stateless channels (e.g. `ahp-otlp:` telemetry channels) use
* {@link subscribeStateless} — calling this method on a stateless
* channel rejects because the server omits `snapshot` on the
* response.
*/
/**
* Subscribe to a stateless channel — one for which the server does
* not maintain replayable state and therefore omits `snapshot` from
* the `subscribe` response. Used today for the host's OTLP telemetry
* channels (`ahp-otlp:`).
*
* Returns once the subscription is confirmed by the server.
* Subsequent notifications on the channel arrive via the relevant
* dispatch event (e.g. {@link onDidReceiveOtlpLogs} for log records).
*/
async
subscribeStateless
(
:
URI
)
:
Promise
<
void
>
{
await
this
.
_sendRequest
(
'subscribe'
,
{
:
.
toString
(
)
}
)
;
}
/**
* Unsubscribe from state at a URI.
*/
unsubscribe
(
:
URI
)
:
void
{
this
.
_sendNotification
(
'unsubscribe'
,
{
:
.
toString
(
)
}
)
;
}
/**
* Dispatch a client action to the server. Returns the clientSeq used.
*/
private
dispatchAction
(
:
string
,
:
|
|
|
|
|
|
|
,
:
string
,
:
number
)
:
void
{
this
.
_grantImplicitReadsForOutgoingAction
(
)
;
this
.
_sendNotification
(
'dispatchAction'
,
{
,
,
}
)
;
}
/**
* Create a new session on the remote agent host.
*/
createSession
(
?
:
)
:
Promise
<
URI
>
{
const
=
?.
;
if
(
!
)
{
throw
new
Error
(
'Cannot create remote agent host session without a provider.'
)
;
}
const
=
?.
??
.
uri
(
,
generateUuid
(
)
)
;
if
(
?.
?.
)
{
this
.
_grantImplicitReadsForCustomizations
(
.
.
)
;
}
// Use `.then` (not `async`) so the tracked promise and the returned promise are the same object — callers
// awaiting via `getInflightSessionCreate` resume on the same microtask queue as direct `createSession()` awaiters.
const
=
this
.
_sendRequest
(
'createSession'
,
{
:
.
toString
(
)
,
:
?.
,
,
:
?.
?.
map
(
=>
fromAgentHostUri
(
)
.
toString
(
)
)
,
:
?.
,
:
?.
,
:
?.
,
}
)
.
then
(
(
)
=>
)
;
this
.
.
trackSessionCreate
(
,
)
;
return
;
}
async
resolveSessionConfig
(
:
)
:
Promise
<
>
{
return
this
.
_sendRequest
(
'resolveSessionConfig'
,
{
:
ROOT_STATE_URI
,
:
.
,
:
.
?
fromAgentHostUri
(
.
)
.
toString
(
)
:
undefined
,
:
.
,
}
)
;
}
async
sessionConfigCompletions
(
:
)
:
Promise
<
>
{
return
this
.
_sendRequest
(
'sessionConfigCompletions'
,
{
:
ROOT_STATE_URI
,
:
.
,
:
.
?
fromAgentHostUri
(
.
)
.
toString
(
)
:
undefined
,
:
.
,
:
.
,
:
.
,
}
)
;
}
async
completions
(
:
)
:
Promise
<
>
{
return
this
.
_sendRequest
(
'completions'
,
)
;
}
async
listAutomationTriggerDefinitions
(
:
)
:
Promise
<
>
{
return
this
.
_sendRequest
(
'listAutomationTriggerDefinitions'
,
)
;
}
async
runAutomation
(
:
)
:
Promise
<
>
{
return
this
.
_sendRequest
(
'runAutomation'
,
)
;
}
async
fetchAutomationRuns
(
:
)
:
Promise
<
>
{
return
this
.
_sendRequest
(
'fetchAutomationRuns'
,
)
;
}
/**
* Send an application-level ping and wait for the server's response.
* Used by {@link _watchdogTick} to keep idle connections under
* watchdog supervision; safe to call from external code as well.
*
* The returned promise rejects with a {@link ProtocolError} if the
* connection closes before a response arrives.
*/
async
ping
(
)
:
Promise
<
void
>
{
await
this
.
_sendRequest
(
'ping'
,
{
:
ROOT_STATE_URI
}
)
;
}
/**
* Returns the trigger characters captured from the `initialize` handshake.
* Empty when the remote host did not announce any.
*/
async
getCompletionTriggerCharacters
(
)
:
Promise
<
readonly
string
[
]
>
{
while
(
this
.
.
===
.
)
{
await
.
toPromise
(
this
.
)
;
}
switch
(
this
.
.
)
{
case
.
:
case
.
:
throw
this
.
.
;
case
.
:
case
.
:
return
this
.
.
get
(
)
?.
??
[
]
;
}
}
/**
* Authenticate with the remote agent host using a specific scheme.
*/
/**
* Gracefully shut down all sessions on the remote host.
*/
async
shutdown
(
)
:
Promise
<
void
>
{
await
this
.
_sendExtensionRequest
(
'shutdown'
)
;
}
/**
* List the endpoints the remote agent host suggests probing for connectivity.
*/
async
getNetworkDiagnosticsInfo
(
)
:
Promise
<
>
{
return
this
.
_sendExtensionRequest
(
'getNetworkDiagnosticsInfo'
)
;
}
async
getManagedSettingsDiagnostics
(
)
:
Promise
<
readonly
[
]
>
{
return
this
.
_sendExtensionRequest
(
'getManagedSettingsDiagnostics'
)
;
}
async
getSessionStateFile
(
:
URI
,
?
:
URI
)
:
Promise
<
URI
|
undefined
>
{
const
=
&&
!
isDefaultChatUri
(
)
?
:
undefined
;
if
(
&&
!
supportsAgentHostChatStateFile
(
this
.
.
get
(
)
)
)
{
return
undefined
;
}
const
=
await
this
.
_sendExtensionRequest
(
,
{
:
.
toString
(
)
,
:
?.
toString
(
)
,
}
)
;
if
(
!
.
)
{
return
undefined
;
}
const
=
URI
.
parse
(
.
,
true
)
;
if
(
.
!==
.
)
{
throw
new
ProtocolError
(
.
,
`Agent Host returned a non-file session state resource: ${resource.toString()}`
)
;
}
return
toAgentHostUri
(
,
this
.
)
;
}
async
collectDebugLogs
(
:
URI
|
undefined
,
:
,
?
:
URI
)
:
Promise
<
>
{
const
=
await
this
.
_sendExtensionRequest
(
,
{
:
?.
toString
(
)
,
:
?.
toString
(
)
,
,
}
)
;
if
(
.
!==
)
{
throw
new
ProtocolError
(
.
,
`Agent Host returned ${result.kind} debug logs for a ${kind} request`
)
;
}
const
=
URI
.
parse
(
.
,
true
)
;
if
(
.
!==
.
)
{
throw
new
ProtocolError
(
.
,
`Agent Host returned a non-file debug log resource: ${resource.toString()}`
)
;
}
if
(
!
.
isSafeInteger
(
.
)
||
.
<
0
||
!
.
isSafeInteger
(
.
)
||
.
<
0
)
{
throw
new
ProtocolError
(
.
,
'Agent Host returned invalid debug log artifact sizes'
)
;
}
if
(
!
Array
.
isArray
(
.
)
||
.
.
>
AGENT_HOST_DEBUG_LOGS_MAX_ENTRIES
)
{
throw
new
ProtocolError
(
.
,
'Agent Host returned an invalid debug log artifact manifest'
)
;
}
const
=
new
Set<string>
(
)
;
let
=
0
;
for
(
const
of
.
)
{
const
=
.
.
split
(
'/'
)
;
if
(
!
.
||
.
.
includes
(
'\\'
)
||
.
some
(
(
:
string
)
=>
!
||
===
'.'
||
===
'..'
)
||
!
.
isSafeInteger
(
.
)
||
.
<
0
||
.
has
(
.
)
)
{
throw
new
ProtocolError
(
.
,
'Agent Host returned an invalid debug log artifact manifest entry'
)
;
}
.
add
(
.
)
;
+=
.
;
}
if
(
!
.
isSafeInteger
(
)
||
!==
.
)
{
throw
new
ProtocolError
(
.
,
'Agent Host debug log artifact manifest size does not match its declared size'
)
;
}
return
{
:
.
,
:
toAgentHostUri
(
,
this
.
)
,
:
.
,
:
.
,
:
.
,
:
.
,
}
;
}
/**
* Read one bounded slice of a debug-log artifact previously returned by
* {@link collectDebugLogs}. `resource` is the agent-host URI handed out by
* that call; it is unwrapped back to the host-local path here.
*/
async
readDebugLogsChunk
(
:
URI
,
:
number
)
:
Promise
<
>
{
const
=
await
this
.
_sendExtensionRequest
(
,
{
:
fromAgentHostUri
(
)
.
toString
(
)
,
,
}
)
;
const
=
decodeBase64
(
.
)
;
if
(
.
>
AGENT_HOST_DEBUG_LOGS_CHUNK_BYTES
)
{
throw
new
ProtocolError
(
.
,
'Agent Host returned an oversized debug log chunk'
)
;
}
return
{
,
:
.
===
true
}
;
}
/**
* Probe connectivity from the remote agent host to a single `url`.
*/
async
diagnosticsFetch
(
:
string
)
:
Promise
<
>
{
return
this
.
_sendExtensionRequest
(
'diagnosticsFetch'
,
{
}
)
;
}
/**
* Dispose a session on the remote agent host.
*/
async
disposeSession
(
:
URI
)
:
Promise
<
void
>
{
await
this
.
_sendRequest
(
'disposeSession'
,
{
:
.
toString
(
)
}
)
;
}
async
createChat
(
:
URI
,
:
URI
,
?
:
)
:
Promise
<
void
>
{
await
this
.
_sendRequest
(
'createChat'
,
{
:
.
toString
(
)
,
:
.
toString
(
)
,
...
(
?.
?
{
:
{
:
.
,
:
.
.
.
toString
(
)
,
:
.
.
}
}
:
{
}
)
,
...
(
?.
?
{
:
{
:
.
,
:
.
.
.
toString
(
)
,
:
.
.
,
...
(
.
.
?
{
:
.
.
}
:
{
}
)
,
}
}
:
{
}
)
,
}
)
;
}
async
disposeChat
(
:
URI
)
:
Promise
<
void
>
{
await
this
.
_sendRequest
(
'disposeChat'
,
{
:
.
toString
(
)
}
)
;
}
/**
* Create a new terminal on the remote agent host.
*/
async
createTerminal
(
:
)
:
Promise
<
void
>
{
await
this
.
_sendRequest
(
'createTerminal'
,
)
;
}
/**
* Dispose a terminal on the remote agent host.
*/
async
disposeTerminal
(
:
URI
)
:
Promise
<
void
>
{
await
this
.
_sendRequest
(
'disposeTerminal'
,
{
:
.
toString
(
)
}
)
;
}
async
invokeChangesetOperation
(
:
)
:
Promise
<
>
{
return
await
this
.
_sendRequest
(
'invokeChangesetOperation'
,
)
;
}
/**
* Send a request on an `mcp://` AHP side channel. The agent-host
* routes by `params.channel` so we inject it automatically.
*/
async
handleMcpRequest
(
:
string
,
:
string
,
:
<
string
,
unknown
>
|
undefined
)
:
Promise
<
unknown
>
{
return
await
this
.
_dispatchRequest<unknown>
(
,
{
...
(
??
{
}
)
,
}
)
;
}
/**
* List all sessions from the remote agent host.
*/
async
listSessions
(
)
:
Promise
<
(
&
{
readonly
?
:
URI
}
)
[
]
>
{
const
=
await
this
.
_sendRequest
(
'listSessions'
,
{
:
ROOT_STATE_URI
}
)
;
return
.
.
map
(
(
:
)
=>
(
{
:
URI
.
parse
(
.
)
,
:
.
parse
(
.
)
,
:
.
parse
(
.
)
,
...
(
.
?
{
:
{
:
this
.
_toLocalProjectUri
(
URI
.
parse
(
.
.
)
)
,
:
.
.
,
}
}
:
{
}
)
,
:
.
,
:
.
,
:
.
,
:
typeof
.
?.
[
0
]
===
'string'
?
toAgentHostUri
(
URI
.
parse
(
.
?.
[
0
]
)
,
this
.
)
:
undefined
,
:
.
?.
map
(
=>
toAgentHostUri
(
URI
.
parse
(
)
,
this
.
)
)
,
:
.
,
// Carry durable host provenance for sessions first materialized from a listing.
...
(
.
!==
undefined
?
{
:
.
}
:
{
}
)
,
}
)
)
;
}
private
_toLocalProjectUri
(
:
URI
)
:
URI
{
return
.
===
.
?
toAgentHostUri
(
,
this
.
)
:
;
}
/**
* Inspect an outgoing client-dispatched action and grant implicit reads for
* resources that the host will need to read after receiving the action.
*/
private
_grantImplicitReadsForOutgoingAction
(
:
|
|
|
|
|
|
|
)
:
void
{
switch
(
.
)
{
case
.
:
if
(
.
.
)
{
this
.
_grantImplicitReadsForCustomizations
(
.
.
)
;
}
break
;
case
.
:
case
.
:
this
.
_grantImplicitReadsForMessage
(
.
)
;
break
;
}
}
private
_grantImplicitReadsForMessage
(
:
)
:
void
{
for
(
const
of
.
??
[
]
)
{
if
(
.
!==
.
)
{
continue
;
}
try
{
this
.
_grantImplicitRead
(
URI
.
parse
(
.
)
)
;
}
catch
{
continue
;
}
}
}
/**
* Register implicit read grants for each customization URI that we are
* about to send to the host. The host needs to read these to materialize
* the customization, but should not need to write them. Grants are
* deduped per connection and revoked when the connection closes.
*/
private
_grantImplicitReadsForCustomizations
(
:
readonly
[
]
)
:
void
{
for
(
const
of
)
{
let
:
URI
;
try
{
=
URI
.
parse
(
.
)
;
}
catch
{
continue
;
}
this
.
_grantImplicitRead
(
)
;
}
}
private
_grantImplicitRead
(
:
URI
)
:
void
{
if
(
this
.
.
has
(
)
)
{
return
;
}
this
.
.
add
(
)
;
this
.
.
add
(
this
.
.
grantImplicitRead
(
this
.
,
)
)
;
}
/**
* List the contents of a directory on the remote host's filesystem.
*/
async
resourceList
(
:
URI
)
:
Promise
<
[
'resourceList'
]
[
'result'
]
>
{
return
await
this
.
_sendRequest
(
'resourceList'
,
{
:
ROOT_STATE_URI
,
:
.
toString
(
)
}
)
;
}
/**
* Read the content of a resource on the remote host.
*/
async
resourceRead
(
:
URI
,
?
:
)
:
Promise
<
[
'resourceRead'
]
[
'result'
]
>
{
return
this
.
_sendRequest
(
'resourceRead'
,
{
:
ROOT_STATE_URI
,
:
.
toString
(
)
,
}
)
;
}
async
resourceWrite
(
:
[
'resourceWrite'
]
[
'params'
]
)
:
Promise
<
[
'resourceWrite'
]
[
'result'
]
>
{
return
this
.
_sendRequest
(
'resourceWrite'
,
)
;
}
async
resourceCopy
(
:
[
'resourceCopy'
]
[
'params'
]
)
:
Promise
<
[
'resourceCopy'
]
[
'result'
]
>
{
return
this
.
_sendRequest
(
'resourceCopy'
,
)
;
}
async
resourceDelete
(
:
[
'resourceDelete'
]
[
'params'
]
)
:
Promise
<
[
'resourceDelete'
]
[
'result'
]
>
{
return
this
.
_sendRequest
(
'resourceDelete'
,
)
;
}
async
resourceMove
(
:
[
'resourceMove'
]
[
'params'
]
)
:
Promise
<
[
'resourceMove'
]
[
'result'
]
>
{
return
this
.
_sendRequest
(
'resourceMove'
,
)
;
}
async
resourceResolve
(
:
[
'resourceResolve'
]
[
'params'
]
)
:
Promise
<
[
'resourceResolve'
]
[
'result'
]
>
{
return
this
.
_sendRequest
(
'resourceResolve'
,
)
;
}
async
resourceMkdir
(
:
[
'resourceMkdir'
]
[
'params'
]
)
:
Promise
<
[
'resourceMkdir'
]
[
'result'
]
>
{
return
this
.
_sendRequest
(
'resourceMkdir'
,
)
;
}
async
createResourceWatch
(
:
[
'createResourceWatch'
]
[
'params'
]
)
:
Promise
<
[
'createResourceWatch'
]
[
'result'
]
>
{
return
this
.
_sendRequest
(
'createResourceWatch'
,
)
;
}
/**
* Convenience wrapper used by {@link AHPFileSystemProvider.watch}:
* runs `createResourceWatch` + `subscribe` and returns a handle that
* surfaces `resourceWatch/changed` envelopes as
* {@link IFileChange}[] events. Disposing the handle unsubscribes
* the watch channel.
*/
watchResource
(
:
[
'createResourceWatch'
]
[
'params'
]
)
:
Promise
<
>
{
return
createRemoteWatchHandle
(
{
createResourceWatch
:
=>
this
.
createResourceWatch
(
)
,
subscribe
:
=>
this
.
subscribe
(
)
,
unsubscribe
:
=>
this
.
unsubscribe
(
)
,
:
this
.
,
}
,
)
;
}
/**
* Trigger the CLI-managed upgrade flow for this agent host using the
* method name advertised by the server (typically
* {@link VSCODE_UPGRADE_METHOD}). Callable before {@link connect} has
* completed — typically used when the host has just rejected our
* `initialize` with an `UnsupportedProtocolVersion` error. The
* transport stays open after the rejection, so the extension request
* rides over it without a special out-of-band path.
*
* The result mirrors the CLI's HTTP response: ok flag, whether the
* upgrade is needed / started, running/latest commits.
*/
triggerVscodeUpgrade
(
:
string
)
:
Promise
<
>
{
return
this
.
_dispatchRequest<IVscodeUpgradeResult>
(
,
{
}
,
{
:
true
}
)
;
}
private
_handleMessage
(
:
)
:
void
{
if
(
this
.
.
===
.
)
{
// After close, the transport may still emit late messages (e.g.
// because the same shared event source is also feeding a newer
// transport for the same connectionId). Drop them so they can't
// trigger any side effects.
return
;
}
// Any inbound traffic — including this message — is evidence the
// transport is still alive. Reset the liveness timers before
// dispatch so they're consistent even if a handler synchronously
// Stop the liveness timers so they don't keep ticking on a dead
// connection (the client may outlive the close, waiting to be replaced).
this
.
_cancelLivenessTimers
(
)
;
if
(
this
.
.
===
.
)
{
const
=
this
.
.
;
if
(
.
!==
undefined
)
{
clearTimeout
(
.
)
;
}
if
(
!
.
.
)
{
.
.
error
(
)
;
}
// Outbox is dropped when the reconnect state is discarded by the
// transition below.
}
if
(
this
.
.
===
.
)
{
this
.
.
.
=
0
;
}
this
.
_rejectPendingRequests
(
)
;
this
.
.
clear
(
)
;
this
.
.
clear
(
)
;
this
.
.
connectionClosed
(
this
.
)
;
this
.
_transitionTo
(
{
:
.
,
}
)
;
this
.
.
fire
(
)
;
}
private
async
_raceClose<T>
(
:
Promise
<
T
>
)
:
Promise
<
T
>
{
if
(
this
.
.
===
.
)
{
return
Promise
.
reject
(
this
.
.
)
;
}
let
=
.
;
const
=
new
Promise<never>
(
(
,
)
=>
{
=
this
.
onDidClose
(
(
)
=>
reject
(
this
.
.
===
.
?
this
.
.
:
connectionClosedError
(
this
.
)
)
)
;
}
)
;
try
{
return
await
Promise
.
race
(
[
,
]
)
;
}
finally
{
.
dispose
(
)
;
}
}
/**
* Handles reverse RPC requests from the server (e.g. resourceList,
* resourceRead). Thin wire adapter — dispatches each frame to
* {@link IAgentHostResourceService} (which owns gating, virtual reads,
* and the user-prompt flow) and translates results / errors back into
* JSON-RPC frames.
*/
private
_handleReverseRequest
(
:
number
,
:
string
,
:
unknown
)
:
void
{
// Capture the transport at request-entry so async handlers (permission
// checks, file ops) reply on the same transport the request arrived on.
// Without this, a soft reconnect mid-handler would route the response
// onto a new transport with a stale id — stray response at best, id
// collision with a new server-issued reverse RPC at worst.
/** Merge a patch into the agent host's root configuration. */
private
_dispatchRootConfig
(
:
<
string
,
unknown
>
)
:
void
{
this
.
dispatchAction
(
ROOT_STATE_URI
,
{
:
.
,
,
}
,
this
.
,
0
)
;
}
private
_updateDisableRepoInfoTelemetry
(
)
:
void
{
const
=
this
.
.
getValue<boolean>
(
DISABLE_REPO_INFO_TELEMETRY_SETTING_ID
)
===
true
;
this
.
_dispatchRootConfig
(
{
[
]
:
}
)
;
}
private
_updateTerminalAutoApproveEnabled
(
)
:
void
{
// Deliberately on the manual, workspace-aware path rather than declaring
// `agentHost` on its schema: the setting is `restricted` and settable per
// workspace, and its companion rule set (`terminalAutoApproveRules`) is
// workspace-aware too. Resolving only the global value here would let a
// workspace that turned auto-approval off still have it applied.
const
=
this
.
.
getValue<boolean>
(
TERMINAL_AUTO_APPROVE_ENABLED_SETTING_ID
)
!==
false
;
this
.
_dispatchRootConfig
(
{
[
]
:
}
)
;
}
private
_updateTerminalAutoApproveRules
(
)
:
void
{
this
.
_dispatchRootConfig
(
{
[
]
:
getAgentHostTerminalAutoApproveRulesConfig
(
this
.
)
}
)
;
}
private
_updateManagedSettingsPermissions
(
=
false
)
:
void
{
const
=
this
.
===
LOCAL_AGENT_HOST_RESOURCE_IDENTITY
?
resolveManagedSettingsPermissions
(
this
.
)
:
{
}
;
this
.
_sendExtensionNotification
(
'setClientManagedSettingsPermissions'
,
{
}
,
)
;
}
/**
* Common path for outgoing JSON-RPC requests: queue pre-initialize traffic,
* gate on any in-flight reconnect (unless explicitly bypassed for the
* `reconnect` RPC itself), assign an id, register the pending deferred, and
* write to the wire.
*
* The reconnect-gate bypass exists because the `reconnect` request is sent
* from inside `_attemptReconnect` while the gate is engaged, so it can't
* wait on its own resolution.
*/
private
async
_dispatchRequest<TResult>
(
:
string
,
:
unknown
,
:
{
readonly
?
:
boolean
;
readonly
?
:
boolean
;
readonly
?
:
boolean
}
=
{
}
,
)
:
Promise
<
>
{
if
(
this
.
.
===
.
)
{
throw
this
.
.
;
}
if
(
this
.
.
===
.
)
{
if
(
!
.
)
{
throw
this
.
.
;
}
const
{
,
}
=
this
.
_createRequest<TResult>
(
,
)
;
this
.
.
send
(
)
;
return
;
}
if
(
!
.
&&
isClientTransport
(
this
.
)
&&
this
.
.
===
.
)
{
const
{
,
}
=
this
.
_createRequest<TResult>
(
,
)
;
this
.
.
.
push
(
as
)
;
return
;
}
// Ride through any number of reconnect cycles until the client is
// either Connected (proceed) or Closed (throw). A transient failed
// attempt does NOT surface to the caller — the request stays gated
// until the connection eventually resumes, matching how the
// notification outbox rides across retries. A subsequent transport
// drop that bounces us back into Reconnecting after the gate already
// resolved is also handled here: the loop re-checks state on each
// iteration so we never send on a dead/reconnecting transport.
while
(
!
.
&&
this
.
.
===
.
)
{
const
=
this
.
as
;
if
(
.
!==
.
)
{
break
;
}
try
{
await
.
.
.
;
}
catch
{
// Transient attempt failure — swallow and re-check state on the
// next loop iteration. If we transitioned to Closed the check
// after the loop surfaces the error; if we're still Reconnecting
// with a fresh gate we'll await that one.
}
}
const
=
this
.
as
;
if
(
.
===
.
||
.
===
.
)
{
throw
.
;
}
const
{
,
}
=
this
.
_createRequest<TResult>
(
,
)
;
this
.
.
send
(
)
;
return
;
}
private
_createRequest<TResult>
(
:
string
,
:
unknown
)
:
{
:
;
:
Promise
<
>
}
{
const
=
this
.
++
;
const
=
new
DeferredPromise<unknown>
(
)
;
this
.
.
set
(
,
{
,
:
isFileResourceRead
(
,
)
,
:
.
now
(
)
}
)
;
return
{
:
{
:
'2.0'
,
,
,
}
,
:
.
as
Promise
<
>
,
}
;
}
private
_shouldLogFailedRequest
(
:
,
:
[
'error'
]
)
:
boolean
{
if
(
.
===
.
&&
.
)
{
return
false
;
}
return
true
;
}
private
_toProtocolError
(
:
[
'error'
]
)
:
{
return
new
ProtocolError
(
.
,
.
,
.
)
;
}
private
_rejectPendingRequests
(
:
)
:
void
{
for
(
const
of
this
.
.
values
(
)
)
{
.
.
error
(
)
;
}
this
.
.
clear
(
)
;
}
/**
* Reset the liveness timers. Called at construction for an already-open
* passive transport, after a successful client-transport initialization,
* once on every received message (which is itself proof the remote is
* alive), and once after a successful soft reconnect.
*
* Two timers cooperate:
*
* 1. {@link _pingTimer} fires after {@link PING_INTERVAL_MS} of silence
* and sends an application-level `ping` so the close timer has
* something to time out on. Tolerates servers that don't implement
* `ping` — the error response still resets both timers.
*
* 2. {@link _closeTimer} fires after {@link PING_INTERVAL_MS}+
* {@link LIVENESS_TIMEOUT_MS} of continued silence and force-closes
* the transport so the renderer's reconnect logic kicks in. Catches
* silently-dead transports (e.g. SSH/tunnel after laptop sleep +
* network change) that don't emit a socket close event of their own.
*
* After laptop sleep + wake the JS event loop is paused, so a timer
* armed before sleep fires immediately after wake. That's fine —
* any inbound message processed during the wake catch-up resets it
* before the close handler runs.
*
* No-op while {@link _state.kind} is {@link AgentHostClientState.Incompatible},
* {@link AgentHostClientState.Reconnecting}, or {@link AgentHostClientState.Closed}:
* the transport is not available for normal liveness traffic in those states.
*/
private
_resetLivenessTimers
(
)
:
void
{
this
.
_cancelLivenessTimers
(
)
;
if
(
this
.
.
===
.
||
this
.
.
===
.
||
this
.
.
===
.
)
{
return
;
}
this
.
.
cancelAndSet
(
(
)
=>
this
.
_onPingTimer
(
)
,
PING_INTERVAL_MS
)
;
this
.
.
cancelAndSet
(
(
)
=>
this
.
_onCloseTimer
(
)
,
PING_INTERVAL_MS
+
LIVENESS_TIMEOUT_MS
)
;
}
private
_cancelLivenessTimers
(
)
:
void
{
this
.
.
cancel
(
)
;
this
.
.
cancel
(
)
;
}
private
_onPingTimer
(
)
:
void
{
if
(
this
.
.
===
.
||
this
.
.
===
.
||
this
.
.
===
.
)
{
return
;
}
// Fire-and-forget. The reply (or any other inbound message that
// happens to arrive first) will reset both timers; if nothing
// arrives, {@link _onCloseTimer} fires.
void
this
.
ping
(
)
.
catch
(
(
)
=>
undefined
)
;
}
private
_onCloseTimer
(
)
:
void
{
if
(
this
.
.
===
.
||
this
.
.
===
.
||
this
.
.
===
.
)
{
return
;
}
if
(
this
.
.
===
.
)
{
// The main process reports actual child-process exits explicitly.
return
;
}
// {@link ILoadEstimator} guards against the *local* side of the
// confusion: if our own JS event loop has been pegged we suppress
// the close — the silence is on our end, not the remote's, and
// tearing down the transport would just abort in-flight requests.
// Re-arm only the close timer at {@link PING_INTERVAL_MS} so we
// re-evaluate promptly once load normalizes (rather than waiting a
// full PING_INTERVAL + LIVENESS_TIMEOUT window).
if
(
this
.
.
hasHighLoad
(
)
)
{
this
.
.
cancelAndSet
(
(
)
=>
this
.
_onCloseTimer
(
)
,
PING_INTERVAL_MS
)
;
return
;
}
const
=
.
now
(
)
-
this
.
;
this
.
.
info
(
`[RemoteAgentHostProtocol] Liveness: no message from ${this._address} for ${silence}ms; forcing close to trigger reconnect.`
,
)
;
// Tear down the dead transport so it can't keep delivering messages
// to a Reconnecting/Closed client (and, on the non-factory path,
// so we don't leak a half-open socket waiting for client disposal).
// WebSocketClientTransport.dispose() disposes its emitters
// synchronously before the native close event arrives, so this
// won't re-enter {@link _handleTransportClose}.
this
.
.
clear
(
)
;
if
(
this
.
)
{
// In factory mode, route directly through the soft-reconnect path.
this
.
_rejectPendingRequests
(
connectionTimeoutError
(
this
.
,
)
)
;
this
.
_handleTransportClose
(
)
;
return
;
}
this
.
_handleClose
(
connectionTimeoutError
(
this
.
,
)
)
;
}
/**
* Get the next client sequence number for optimistic dispatch.
*/