Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/import{ timeout }from'../../../base/common/async.js';import{ CancellationToken }from'../../../base/common/cancellation.js';import{ vArray, vObj, vString, vUnknown }from'../../../base/common/validation.js';import{ TelemetryConfiguration }from'../../telemetry/common/telemetry.js';import{ getAgentHostEndpointIdentityKey, IAgentHostEndpointMetadata, parseAgentHostEndpointRegistry }from'../common/agentHostEndpointRegistry.js';/**
* Validate that a quality string is safe for bare interpolation in shell commands.
* Quality comes from `productService.quality` (not user input) but we validate
* as defense-in-depth since these values end up in unquoted shell paths (the `~`
* prefix requires shell expansion, so we cannot single-quote the entire path).
*/exportfunctionvalidateShellTokenvalue label
value
value
value TelemetryConfiguration
value
TelemetryConfiguration
TelemetryConfiguration
TelemetryConfiguration
TelemetryConfiguration
value
commit
normalized commit
normalized
normalized
quality
q quality
q
serverDataFolderName
d serverDataFolderName
serverDataFolderName
serverDataFolderName quality commit
archive quality
root serverDataFolderName
commit
c commit
s
escaped s
cliBin cliDataDir telemetryLevel TelemetryConfiguration
unameS unameM libc os arch
os unameS
machine unameM
normalizedLibc libc
platformOs
os
platformOs normalizedLibc
os
platformOs
arch
machine machine
arch
machine machine
arch
machine
arch
platformOs arch
os platformOs arch
os arch quality commit
base
artifact
commit
c commit
serverDataFolderName quality
root serverDataFolderName
archive quality
commitGlob
serverDataFolderName quality
root serverDataFolderName
archive quality
commitGlob
q quality
legacyDir q
legacyBin
candidate serverDataFolderName quality
root serverDataFolderName
archive quality
q quality
legacyDir q
legacyBin
candidate legacyBin
pinnedPrefix
candidatepinnedPrefix
suffix candidatepinnedPrefixlength
suffix
text
text
text url host port token
match text
match
url match
host
port match
token match
command opts ignoreExitCode stdout stderr code
bound
bound bound bound bound
bound
cliBin cliDataDir userDataPath
userDataArg userDataPath
cliBin cliDataDir userDataPath telemetryLevel TelemetryConfiguration idleTimeoutSec
NumberidleTimeoutSec idleTimeoutSec
cliBin cliDataDir instanceId userDataPath
userDataPath
endpoints IAgentHostEndpointMetadata
agentEndpointsEnvelopeValidator
userDataPath
endpoints
stdout IAgentEndpointsResult
trimmed stdout
trimmed
candidates trimmed
lastLine trimmed
lastLine lastLine trimmed
candidateslastLine
candidate candidates
result candidate
result
result
value IAgentEndpointsResult
raw
raw value
content error agentEndpointsEnvelopeValidatorraw
error
userDataPath contentuserDataPath
endpoints contentendpoints
exec ISshExec cliBin cliDataDir userDataPath IAgentEndpointsResult
command cliBin cliDataDir userDataPath
stdout stderr code command ignoreExitCode
code
result stdout
result
result
exec ISshExec entries IAgentHostEndpointMetadata IAgentHostEndpointMetadata
pids entriese epid
alive
pids pid
code ignoreExitCode
code
alivepid
entriese aliveepid
before IAgentHostEndpointMetadata after IAgentHostEndpointMetadata IAgentHostEndpointMetadata
beforeKeys beforegetAgentHostEndpointIdentityKey
afterentry entrytype beforeKeysentry
attempts
intervalMs
token CancellationToken
exec ISshExec
cliBin
cliDataDir
userDataPath
before IAgentHostEndpointMetadata
options IWaitForNewEndpointOptions
IAgentHostEndpointMetadata
attempts optionsattempts
intervalMs optionsintervalMs
attempt attempt attempts attempt
endpoints exec cliBin cliDataDir userDataPath
found before endpoints
found
found
attempt attempts
optionstoken
intervalMs optionstoken
intervalMs
`Unsafe ${label} value for shell interpolation: ${JSON.stringify(value)}`
)
;
}
return
;
}
export
function
validateAgentHostTelemetryLevel
(
:
unknown
)
:
{
switch
(
)
{
case
.
OFF
:
case
.
CRASH
:
case
.
ERROR
:
case
.
ON
:
return
;
default
:
throw
new
Error
(
`Unsafe telemetry level for shell interpolation: ${JSON.stringify(value)}`
)
;
}
}
/**
* Validate and normalize a commit SHA. Returns the lowercase form.
*
* The commit-keyed install layout, the cleanup glob (`[0-9a-f]{40}`), and
* the fallback discovery glob all assume an exactly-40-char lowercase hex
* commit. If a caller ever supplies a non-SHA value (or uppercase hex),
* the cleanup pass would silently miss those binaries and the
* commit-pinned download URL could 404. Enforce the shape at the source.
*
* `productService.commit` is already lowercase hex in practice; the
* normalization is defense-in-depth for any future callers.
*/
export
function
validateCommit
(
:
string
)
:
string
{
const
=
.
toLowerCase
(
)
;
if
(
!
/^[0-9a-f]{40}$/
.
test
(
)
)
{
throw
new
Error
(
`Unsafe commit value (expected 40-char hex SHA): ${JSON.stringify(commit)}`
)
;
}
return
;
}
/**
* Name of the CLI binary as it appears inside the downloaded archive,
* derived from product quality. Matches the names used by Remote-SSH's
* exec-server installer so that CLI binaries can be shared between the
* two features.
*/
export
function
getRemoteCLIArchiveName
(
:
string
)
:
string
{
const
=
validateShellToken
(
,
'quality'
)
;
switch
(
)
{
case
'stable'
:
return
'code'
;
case
'exploration'
:
return
'code-exploration'
;
default
:
return
'code-insiders'
;
}
}
/**
* Install root for the VS Code CLI on the remote machine. Shared with
* Remote-SSH's exec-server installer so the two features can reuse each
* other's installations. Also the parent of the agent host lockfile dir.
*/
export
function
getRemoteCLIInstallRoot
(
:
string
)
:
string
{
const
=
validateShellToken
(
,
'server data folder name'
)
;
return
`~/${d}`
;
}
/**
* Per-machine launcher data dir for `code agent host` (and the embedded
* CLI machinery it inherits). Passed as `--cli-data-dir` so the CLI's
* downloads cache, unpacked server installs, supervisor logs, and other
* launcher state land under the same root Remote-SSH's `command-shell`
* uses (e.g. `~/.vscode-server/cli`). Without this flag the CLI would
* default to `~/.vscode-cli{,-<quality>}/` and split state across two
* roots.
*
* The lockfile is unaffected: the Rust CLI anchors it on
* `serverDataFolderName` regardless of `--cli-data-dir` (see
* `cli/src/state.rs::agent_host_root`).
*/
/**
* Full path to the installed CLI binary on the remote.
*
* When `commit` is provided, the path is keyed on commit (e.g.
* `~/.vscode-server/code-insiders-<40hex>`) so we can install the CLI
* matching the current desktop without disturbing other installs. This
* mirrors Remote-SSH's exec-server layout.
*
* When `commit` is undefined (dev/OSS builds with no commit in product
* metadata), the path is just `<root>/<archive>` — a single, non-keyed
* filename. Caller code should keep the loose `--version`-based reuse
* check in that case.
*/
export
function
getRemoteCLIBin
(
:
string
,
:
string
,
?
:
string
)
:
string
{
const
=
getRemoteCLIArchiveName
(
)
;
const
=
getRemoteCLIInstallRoot
(
)
;
if
(
)
{
const
=
validateCommit
(
)
;
return
`${root}/${archive}-${c}`
;
}
return
`${root}/${archive}`
;
}
/** Escape a string for use as a single shell argument (single-quote wrapping). */
export
function
shellEscape
(
:
string
)
:
string
{
// Wrap in single quotes; escape embedded single quotes as: '\''
const
=
.
replace
(
/'/g
,
'\'\\\'\''
)
;
return
`'${escaped}'`
;
}
/**
* Construct the bare command that launches the agent host on the remote.
*
* `--cli-data-dir` is passed up-front so the embedded CLI's launcher
* state (downloads cache, unpacked server installs, supervisor log) lands
* under `<cliDataDir>` — the same root Remote-SSH uses. The supervisor
* propagates this flag to its detached child (see
* `cli/src/commands/agent_host.rs`), so the entire AH process tree
* agrees on one launcher root.
*
* Inputs must already be safe for unquoted shell interpolation; callers
* build them via {@link getRemoteCLIBin} / {@link getRemoteCLIDataDir}
* which validate their components.
*/
/**
* URL of the CLI download artifact.
*
* When `commit` is provided, uses the commit-pinned URL form so we get
* the exact CLI matching the current desktop build (mirrors Remote-SSH).
* When `commit` is undefined (dev/OSS builds), falls back to `latest`.
*/
export
function
buildCLIDownloadUrl
(
:
string
,
:
string
,
:
string
,
?
:
string
)
:
string
{
const
=
'https://update.code.visualstudio.com'
;
const
=
`cli-${os}-${arch}`
;
if
(
)
{
// Defense-in-depth: same validation as getRemoteCLIBin so the URL
// can never be formed with a non-SHA commit (would 404) and stays
// consistent with the commit-keyed install path.
const
=
validateCommit
(
)
;
return
`${base}/commit:${c}/${artifact}/${quality}`
;
}
return
`${base}/latest/${artifact}/${quality}`
;
}
/**
* Shell snippet that prunes older commit-keyed CLI binaries from the
* install root, keeping the 5 most recently modified. Mirrors the
* retention policy in Remote-SSH's exec-server installer.
*
* The glob is tightened to exactly 40 hex chars (`[0-9a-f]`-only) so we
* never accidentally delete (or hand to `xargs`) any filename that
* happens to start with `<archive>-` but isn't actually one of our
* commit-keyed binaries — both for correctness and to avoid passing
* attacker-controlled filenames through `xargs rm` with option/whitespace
* splitting hazards. We also use `rm -f --` and `xargs -I{}` (which
* skips the command entirely on empty input on both GNU and BSD `xargs`).
*/
export
function
buildCleanupOldCLIsCommand
(
:
string
,
:
string
)
:
string
{
const
=
getRemoteCLIInstallRoot
(
)
;
const
=
getRemoteCLIArchiveName
(
)
;
const
=
'[0-9a-f]'
.
repeat
(
40
)
;
// `ls -1t` sorts by mtime newest-first on both Linux (coreutils) and
// macOS (BSD). `awk 'NR>5'` drops the 5 most recent entries we want to
// keep. `xargs -I{} rm -f -- {}` is one-rm-per-line — slow but safe
// against whitespace splitting and option injection, and a no-op when
/**
* Shell snippet that prints candidate CLI binary paths that could be
* used as a fallback when the commit-pinned download fails. Order: any
* commit-keyed binaries in the shared install root (newest mtime first),
* then the legacy single-binary paths from the previous installer
* (`~/.vscode-cli{,-<quality>}/<archive>`).
*
* Each line is a single path. The glob for commit-keyed candidates is
* restricted to exactly 40 hex chars so the output can only contain
* filenames we recognise (callers should still re-validate with
* {@link isValidFallbackCLIPath}). The legacy paths are fixed strings
* derived from validated tokens, so they cannot contain shell
* metacharacters either.
*/
/**
* Validate that a candidate path string returned by the remote shell
* matches one of the two shapes we expect from
* {@link buildFindFallbackCLICommand}:
*
* - `<installRoot>/<archive>-<40 hex chars>` — commit-keyed install
* - `<legacyDir>/<archive>` — legacy single-binary install
*
* Anything else is rejected. This guards against the candidate being
* interpolated into a follow-up shell command (`<candidate> --version`,
* agent host spawn) with attacker-controlled metacharacters in the
* event that something unexpected ends up in the install root.
*/
export
function
isValidFallbackCLIPath
(
:
string
,
:
string
,
:
string
)
:
boolean
{
const
=
getRemoteCLIInstallRoot
(
)
;
const
=
getRemoteCLIArchiveName
(
)
;
const
=
validateShellToken
(
,
'quality'
)
;
const
=
===
'stable'
?
'~/.vscode-cli'
:
`~/.vscode-cli-${q}`
;
const
=
`${legacyDir}/${archive}`
;
if
(
===
)
{
return
true
;
}
const
=
`${root}/${archive}-`
;
if
(
.
startsWith
(
)
)
{
const
=
.
slice
(
.
)
;
return
/^[0-9a-f]{40}$/
.
test
(
)
;
}
return
false
;
}
/** Redact connection tokens from log output. */
export
function
redactToken
(
:
string
)
:
string
{
return
.
replace
(
/\?tkn=[^\s&]+/g
,
'?tkn=***'
)
;
}
/**
* Match the `ws://127.0.0.1:PORT[?tkn=TOKEN]` URL emitted by `code agent host`
* on stdout/stderr. Shared by SSH and WSL agent-host transports — both spawn
* the CLI inside a posix shell and scrape its first line of output to discover
* the WebSocket endpoint.
*/
/**
* Extract the `ws://` URL printed by `code agent host` from a line or buffer
* of mixed output. Returns the full URL plus its parsed components, or
* `undefined` if no match is found.
*/
export
function
extractAgentHostWebSocketURL
(
:
string
)
:
{
:
string
;
:
string
;
:
number
;
:
string
|
undefined
}
|
undefined
{
const
=
.
match
(
AGENT_HOST_WS_URL_RE
)
;
if
(
!
)
{
return
undefined
;
}
return
{
:
[
0
]
,
:
'127.0.0.1'
,
:
parseInt
(
[
1
]
,
10
)
,
:
[
2
]
||
undefined
,
}
;
}
/**
* Abstraction over SSH command execution to enable testing without a real SSH connection.
*/
export
interface
ISshExec
{
(
:
string
,
?
:
{
?
:
boolean
}
)
:
Promise
<
{
:
string
;
:
string
;
:
number
}
>
;
}
/**
* Map a recorded `host` value from the agent host lockfile to a dialable
* loopback address. The supervisor records the literal `--host` value it
* was given (e.g. `0.0.0.0`, `::1`, `localhost`); local callers (SSH
* relay, tunnel reuse-forward, renderer bridge) want a target they can
* actually open a socket to. Wildcards are mapped to their corresponding
* loopback; specific hosts pass through unchanged. Missing `host`
* (lockfile written by an older CLI) falls back to IPv4 loopback to
* preserve the prior behaviour.
*/
export
function
dialAgentHostHost
(
:
string
|
undefined
)
:
string
{
if
(
!
||
===
'0.0.0.0'
||
===
'::'
||
===
'[::]'
)
{
return
'127.0.0.1'
;
}
return
;
}
/**
* Build the `code agent endpoints` command that lists every live agent
* host endpoint (editor + standalone) known to the shared registry on the
* remote. When `userDataPath` is omitted the CLI resolves its own default
* user-data path and reports it back in the envelope's `userDataPath`
* field; once known, callers should pass it back explicitly so every
* subsequent lookup/spawn/relay command targets the exact same registry.
*/
/**
* Build the command that spawns a brand-new dedicated standalone agent
* host on the remote, self-managed via `--idle-timeout`: once no client
* has been connected for `idleTimeoutSec`, the process exits on its own,
* so callers must NOT tie its lifetime to the SSH exec channel used to
* launch it (see {@link waitForNewStandaloneEndpoint}).
*
* Always passes `--new-instance`: plain `agent host` reuses an existing
* live standalone when one is already registered, which would silently
* defeat the "Start New Dedicated Agent Host" choice (no new entry would
* ever appear, and delta-matching in {@link waitForNewStandaloneEndpoint}
* would time out) and could otherwise touch a standalone another
* selection path is still relying on. `--new-instance` guarantees a
* genuinely new process/registry entry every time this command runs,
* leaving all existing standalone/editor entries untouched.
*/
export
function
buildAgentHostSpawnCommand
(
:
string
,
:
string
,
:
string
,
:
,
=
300
)
:
string
{
if
(
!
.
isSafeInteger
(
)
||
<=
0
)
{
throw
new
Error
(
`Unsafe idle timeout value for shell interpolation: ${JSON.stringify(idleTimeoutSec)}`
/**
* Build the command that performs a raw stdin/stdout byte relay to the
* exact endpoint identified by `instanceId`, used to open a duplex channel
* to a `socket`-addressed endpoint (see `AgentHostEndpointAddress`) that
* `forwardOut` cannot reach directly.
*/
/** Parsed, validated result of `code agent endpoints`. */
export
interface
IAgentEndpointsResult
{
/** The remote user-data path the registry was read from/for. */
readonly
:
string
;
/** Every live endpoint currently in the registry, already schema-validated. */
readonly
:
readonly
[
]
;
}
const
=
vObj
(
{
:
vString
(
)
,
:
vArray
(
vUnknown
(
)
)
,
}
)
;
/**
* Parse the JSON envelope printed by `code agent endpoints`
* (`{ userDataPath, endpoints }`). Individual endpoint entries are
* validated via the shared {@link parseAgentHostEndpointRegistry} parser
* (malformed/unsupported-schema entries are dropped, not fatal). Returns
* `undefined` if `stdout` is empty or the top-level envelope itself is
* malformed.
*/
export
function
parseAgentEndpointsOutput
(
:
string
)
:
|
undefined
{
const
=
.
trim
(
)
;
if
(
!
)
{
return
undefined
;
}
const
=
[
]
;
const
=
.
split
(
'\n'
)
.
at
(
-
1
)
?.
trim
(
)
;
if
(
&&
!==
)
{
.
push
(
)
;
}
for
(
const
of
)
{
const
=
parseAgentEndpointsDocument
(
)
;
if
(
)
{
return
;
}
}
return
undefined
;
}
function
parseAgentEndpointsDocument
(
:
string
)
:
|
undefined
{
let
:
unknown
;
try
{
=
JSON
.
parse
(
)
;
}
catch
{
return
undefined
;
}
const
{
,
}
=
.
validate
(
)
;
if
(
)
{
return
undefined
;
}
return
{
:
.
,
:
parseAgentHostEndpointRegistry
(
.
)
,
}
;
}
/**
* Execute `code agent endpoints` over `exec` and return the parsed
* envelope. Throws if the command fails or its output cannot be parsed —
* callers rely on endpoint discovery to make a correct selection decision,
* so a silently empty/garbage result would be worse than a loud failure.
*/
`'agent endpoints' produced unparsable output (${stdout.length} characters)`
)
;
}
return
;
}
/**
* Filter `entries` down to the ones whose PID is still alive, probing each
* distinct PID at most once with `kill -0`. The registry file itself may
* lag reality slightly (e.g. a crashed writer's stale entry before its
* cleanup ran), so liveness must always be re-checked before an entry is
* offered for reuse.
*/
export
async
function
filterLiveAgentHostEndpoints
(
:
,
:
readonly
[
]
)
:
Promise
<
[
]
>
{
const
=
[
...
new
Set
(
.
map
(
=>
.
)
)
]
;
const
=
new
Set<number>
(
)
;
await
Promise
.
all
(
.
map
(
async
=>
{
const
{
}
=
await
exec
(
`kill -0 ${pid} 2>/dev/null`
,
{
:
true
}
)
;
if
(
===
0
)
{
.
add
(
)
;
}
}
)
)
;
return
.
filter
(
=>
.
has
(
.
)
)
;
}
/**
* Diff two endpoint snapshots and return the standalone entry present in
* `after` but not `before`, identified by `(type, pid, instanceId)`. Used
* to match the endpoint published by a just-spawned agent host without
* relying on any output scraped from the spawn command itself.
*/
export
function
findNewAgentHostEndpoint
(
:
readonly
[
]
,
:
readonly
[
]
)
:
|
undefined
{
const
=
new
Set
(
.
map
(
)
)
;
return
.
find
(
=>
.
===
'standalone'
&&
!
.
has
(
getAgentHostEndpointIdentityKey
(
)
)
)
;
}
export
interface
IWaitForNewEndpointOptions
{
/** Maximum number of `agent endpoints` polls before giving up. Defaults to 20. */
readonly
?
:
number
;
/** Delay between polls, in milliseconds. Defaults to 500. */
readonly
?
:
number
;
readonly
?
:
;
}
/**
* Poll `code agent endpoints` until a newly spawned standalone entry shows
* up (see {@link findNewAgentHostEndpoint}), or throw once the attempt
* budget is exhausted. The spawn command itself is fire-and-forget (its
* process is not tied to the SSH exec channel that launched it — see
* {@link buildAgentHostSpawnCommand}), so this is the only way to learn
* the freshly assigned TCP address/token/instanceId.
*/
export
async
function
waitForNewStandaloneEndpoint
(
:
,
:
string
,
:
string
,
:
string
,
:
readonly
[
]
,
?
:
,
)
:
Promise
<
>
{
const
=
?.
??
20
;
const
=
?.
??
500
;
for
(
let
=
0
;
<
;
++
)
{
const
{
}
=
await
runAgentEndpoints
(
,
,
,
)
;
const
=
findNewAgentHostEndpoint
(
,
)
;
if
(
)
{
return
;
}
if
(
<
-
1
)
{
if
(
?.
)
{
await
timeout
(
,
.
)
;
}
else
{
await
timeout
(
)
;
}
}
}
throw
new
Error
(
`Timed out waiting for the newly spawned agent host to register itself (checked ${attempts} times, ~${Math.round(attempts * intervalMs /1000)}s)`