Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
/// Internal env var that flips `code agent host` into supervisor mode:
/// the body that actually binds the TCP listener, publishes the
/// supervisor's registry entry, owns the proxy sidecar, and manages the AH
/// backend's lifecycle. Unless `--foreground` is passed, the foreground
/// `code agent host` invocation re-execs itself detached with this
/// variable set so the supervisor outlives the user's terminal.
const
SUPERVISOR_ENV
:
&
str
=
"VSCODE_AGENT_HOST_SUPERVISOR"
;
/// Single-line sentinel the supervisor prints once the listener is bound,
/// its registry entry is published, and the banner has been flushed. The
/// foreground process watches for this on the detached supervisor's stdout
/// and then exits. Not printed when the supervisor runs with
/// `--foreground`, since there is no parent waiting on it.
const
SUPERVISOR_READY_LINE
:
&
str
=
"__VSCODE_AGENT_HOST_READY__"
;
/// Cap on how long the foreground waits for the supervisor to become
/// ready before giving up and surfacing a failure.
const
SUPERVISOR_READY_TIMEOUT
:
Duration
=
Duration
::
from_secs
(
5
*
60
)
;
/// Runs the `code agent host` command. Acts in one of two modes:
///
/// * **Foreground** (the default): consults the shared local agent-host
/// endpoint registry and either prints info about the live supervisor
/// (`Reuse`), or starts a new supervisor (`SpawnFresh`) — daemonized by
/// default, or run inline in this process when `--foreground` is set.
///
/// * **Supervisor** (when [`SUPERVISOR_ENV`] is set): binds the public TCP
/// listener, publishes a registry entry recording this process's PID +
/// port, runs the proxy accept loop, and manages the underlying VS Code
/// server as a regular child process so the supervisor can kill+respawn
/// it on update.
pub
async
fn
agent_host
(
:
CommandContext
,
:
AgentHostArgs
)
->
Result
<
i32
,
AnyError
>
{
if
std::env::
var_os
(
SUPERVISOR_ENV
)
.
is_some
(
)
{
return
run_supervisor
(
,
)
.
await
;
}
run_foreground
(
,
)
.
await
}
/// Pure decision of what `run_foreground` should do next, derived only
/// from `args` and an already-computed [`AgentHostReuseDecision`] — no
/// I/O, process killing, or spawning happens here. Kept separate from
/// `run_foreground` so the flag-priority rules (in particular, that
/// `--new-instance` always wins and never triggers the `--replace` kill
/// path) can be unit tested deterministically without spawning any real
/// process or touching a real registry.
#[derive(Debug, Clone, PartialEq, Eq)]
enum
ForegroundAction
{
/// Start a brand new supervisor unconditionally: either nothing
/// reusable is registered, or `--new-instance` was passed. Never
/// touches any existing registry entry.
SpawnFresh
,
/// `--replace` was passed and a reusable supervisor exists: kill it
/// and remove its exact registry entry first, then start a new one.
ReplaceThenSpawnFresh
{
:
u32
,
:
String
}
,
/// The requested configuration conflicts with the reusable
/// supervisor's; print `message` and exit with status 2.
ConflictError
(
String
)
,
/// Reuse the existing supervisor; print an informational banner and
/// exit with status 0 without spawning anything.
ReuseBanner
{
:
u32
,
:
Option
<
String
>
,
:
u16
,
:
Option
<
String
>
,
:
Option
<
String
>
,
}
,
}
fn
decide_foreground_action
(
:
&
AgentHostArgs
,
:
AgentHostReuseDecision
,
)
->
ForegroundAction
{
// `--new-instance` always wins: it bypasses reuse (and therefore
// `--replace`'s kill path too) so an existing standalone/editor
// entry is guaranteed to survive untouched, and a brand new
// supervisor is always started.
if
.
{
return
ForegroundAction
::
SpawnFresh
;
}
let
AgentHostReuseDecision
::
Reuse
{
,
,
,
,
,
,
}
=
else
{
return
ForegroundAction
::
SpawnFresh
;
}
;
// User asked to replace explicitly: kill + spawn fresh, regardless
// of whether the running config matches.
if
.
{
return
ForegroundAction
::
ReplaceThenSpawnFresh
{
,
}
;
}
// No `--replace`: check whether the requested network config
// matches the running supervisor. If it differs, error out with a
// clear message instead of silently sharing a differently-bound
// supervisor.
if
let
Some
(
)
=
detect_config_conflict
(
,
.
as_deref
(
)
,
,
.
as_deref
(
)
,
.
as_deref
(
)
,
)
{
return
ForegroundAction
::
ConflictError
(
format!
(
"Agent host already running on {host_str}:{port} (PID {pid}), but {conflict}.\n\
Use `{application_name} agent kill` to stop it, or pass `--replace` to take over."
,
=
constants::
APPLICATION_NAME
,
=
.
as_deref
(
)
.
unwrap_or
(
"127.0.0.1"
)
,
)
)
;
}
ForegroundAction
::
ReuseBanner
{
,
,
,
,
,
}
}
/// Foreground entry point: decides whether to reuse an existing supervisor
/// or start a fresh one, either detached (the default) or inline in this
/// process when `--foreground` is set.
async
fn
run_foreground
(
:
CommandContext
,
:
AgentHostArgs
)
->
Result
<
i32
,
AnyError
>
{
let
=
Instant
::
now
(
)
;
let
=
resolve_user_data_path
(
.
.
as_deref
(
)
)
;
// Skip consulting the registry entirely when `--new-instance` is set:
// its outcome can't change the decision (see `decide_foreground_action`)
// and we don't want an unrelated registry read to slow down or race
// with the fresh spawn below.
let
=
if
.
{
AgentHostReuseDecision
::
SpawnFresh
}
else
{
classify_agent_host
(
&
.
,
&
)
.
await
}
;
// Bind the action before matching so the `&args` borrow ends here and
// the arms below are free to move `args` into `start_supervisor`.
let
=
decide_foreground_action
(
&
,
)
;
match
{
ForegroundAction
::
SpawnFresh
=>
start_supervisor
(
,
)
.
await
,
ForegroundAction
::
ReplaceThenSpawnFresh
{
,
}
=>
{
info!
(
.
,
"--replace set; stopping agent host (PID {}) before starting new one"
,
)
;
replace_existing
(
&
.
,
&
,
,
)
.
await
?
;
start_supervisor
(
,
)
.
await
}
ForegroundAction
::
ConflictError
(
)
=>
{
.
.
result
(
)
;
Ok
(
2
)
}
ForegroundAction
::
ReuseBanner
{
,
,
,
,
,
}
=>
{
print_reuse_banner
(
&
.
,
,
,
.
as_deref
(
)
,
,
.
as_deref
(
)
,
.
as_deref
(
)
,
)
;
Ok
(
0
)
}
}
}
/// Starts a brand new supervisor for this invocation: inline in this
/// process when `--foreground` is set (so its logs stay attached to the
/// terminal and Ctrl-C stops it), otherwise detached in the background.
async
fn
start_supervisor
(
:
CommandContext
,
:
AgentHostArgs
)
->
Result
<
i32
,
AnyError
>
{
if
.
{
run_supervisor
(
,
)
.
await
}
else
{
daemonize_supervisor
(
)
.
await
}
}
/// Body of the supervisor process. Starts an [`AgentHostManager`], binds
/// an [`AgentHostSidecar`] on the user's chosen `--host`/`--port`,
/// optionally exposes it over a dev tunnel, prints the readiness banner /
/// sentinel, then services connections until killed.
async
fn
run_supervisor
(
mut
:
CommandContext
,
mut
:
AgentHostArgs
)
->
Result
<
i32
,
AnyError
>
{
let
=
Instant
::
now
(
)
;
let
=
resolve_user_data_path
(
.
.
as_deref
(
)
)
;
let
=
uuid::
Uuid
::
new_v4
(
)
.
to_string
(
)
;
// Attach a file log sink before anything else, so download progress,
// AH child crashes, update-loop errors, and post-handoff diagnostics
// are captured even after we redirect stdio to null. The file always
// records at Trace level — the foreground stdio sink keeps its
// caller-supplied level so the parent doesn't see noise on its
// terminal.
let
=
.
.
agent_host_log_file
(
)
;
if
let
Some
(
)
=
.
parent
(
)
{
let
=
fs::
create_dir_all
(
)
;
}
match
log::
FileLogSink
::
new
(
log::
Level
::
Trace
,
&
)
{
Ok
(
)
=>
{
.
=
.
.
tee
(
)
;
info!
(
.
,
"Agent host supervisor logging to {}"
,
.
display
(
)
)
;
}
Err
(
)
=>
{
warning!
(
.
,
"Failed to open agent host supervisor log file {}: {}"
,
.
display
(
)
,
)
;
}
}
let
:
Platform
=
PreReqChecker
::
new
(
)
.
verify
(
)
.
await
?
;
if
!
.
{
if
let
Some
(
)
=
.
.
as_deref
(
)
{
let
=
fs::
read_to_string
(
PathBuf
::
from
(
)
)
.
map_err
(
CodeError
::
CouldNotReadConnectionTokenFile
)
?
;
.
=
Some
(
.
trim
(
)
.
to_string
(
)
)
;
}
else
{
let
=
.
.
root
(
)
.
join
(
"agent-host-token"
)
;
let
=
mint_connection_token
(
&
,
.
.
clone
(
)
)
.
map_err
(
CodeError
::
CouldNotCreateConnectionTokenFile
)
?
;
.
=
Some
(
)
;
.
=
Some
(
.
to_string_lossy
(
)
.
to_string
(
)
)
;
}
}
let
=
AgentHostManager
::
new
(
.
.
clone
(
)
,
,
.
.
.
clone
(
)
,
Arc
::
new
(
ReqwestSimpleHttp
::
with_client
(
.
.
clone
(
)
)
)
,
AgentHostConfig
{
:
.
.
clone
(
)
,
:
if
.
.
.
{
Some
(
TelemetryLevel
::
Off
)
}
else
{
.
.
.
}
,
// The AH backend runs on an internal-only unix socket / named
// pipe between this supervisor and its child, so we
// deliberately disable the backend's token check; this
// supervisor's loopback accept loop enforces the user-facing
// token at the proxy edge.
:
true
,
:
None
,
:
None
,
}
,
)
;
// Eagerly resolve the latest version so the first connection is fast,
// and kick off the background update loop. Skip when using a dev
// override since updates don't apply.
if
option_env!
(
"VSCODE_CLI_OVERRIDE_SERVER_PATH"
)
.
is_none
(
)
{
match
.
get_latest_release
(
)
.
await
{
Ok
(
)
=>
{
if
let
Err
(
)
=
.
ensure_downloaded
(
&
)
.
await
{
warning!
(
.
,
"Error downloading latest server version: {}"
,
)
;
}
}
Err
(
)
=>
warning!
(
.
,
"Error resolving initial server version: {}"
,
)
,
}
let
=
.
clone
(
)
;
tokio::
spawn
(
async
move
{
.
run_update_loop
(
)
.
await
;
}
)
;
}
let
mut
=
None
;
let
mut
:
Option
<
String
>
=
None
;
if
.
{
let
mut
=
Auth
::
new
(
&
.
,
.
.
clone
(
)
)
;
.
set_provider
(
crate
::auth::
AuthProvider
::
Github
)
;
let
mut
=
DevTunnels
::
new_remote_tunnel
(
&
.
,
,
&
.
)
;
let
mut
=
if
let
Some
(
)
=
fulfill_existing_tunnel_args
(
.
.
clone
(
)
,
&
.
)
{
.
start_existing_tunnel
(
)
.
await
}
else
{
.
start_new_launcher_tunnel
(
.
.
as_deref
(
)
,
.
,
&
[
]
)
.
await
}
?
;
=
Some
(
.
.
clone
(
)
)
;
let
=
.
add_port_direct
(
AGENT_HOST_PORT
)
.
await
?
;
=
Some
(
(
,
)
)
;
}
let
=
resolve_listen_addr
(
&
)
?
;
let
=
match
.
.
as_deref
(
)
{
Some
(
)
=>
LoopbackAuth
::
Token
(
.
to_string
(
)
)
,
None
=>
LoopbackAuth
::
Disabled
,
}
;
// `--idle-timeout` is opt-in: only build the activity-tracking channel
// when requested, so a manually started local host (the default) never
// pays for/depends on this bookkeeping and never self-terminates.
let
=
.
.
map
(
Duration
::
)
;
let
(
,
)
=
match
{
Some
(
)
=>
{
let
(
,
)
=
idle_timeout::
new_activity_channel
(
)
;
(
Some
(
)
,
Some
(
)
)
}
None
=>
(
None
,
None
)
,
}
;
let
=
AgentHostSidecar
::
bind_tcp
(
.
.
clone
(
)
,
.
clone
(
)
,
,
.
.
clone
(
)
,
,
.
clone
(
)
,
.
clone
(
)
,
.
clone
(
)
,
,
)
.
await
?
;
let
=
.
bound_addr
(
)
.
port
(
)
;
let
mut
:
Option
<
crate
::tunnels::dev_tunnels::
ActiveTunnel
>
=
None
;
if
let
Some
(
(
,
mut
)
)
=
{
// Route each tunneled connection through the same protocol-v6
// uses (`serve_agent_host_tunnel_connection`), instead of the
// legacy direct proxy (`AgentHostSidecar::serve_tunnel_connection`)
// this used to call unconditionally. That legacy method never
// looked at the request path, so a renderer's `/agent-host/select`
// WebSocket upgrade -- sent because this tunnel is tagged
// `protocolv6`, see `add_port_direct` above -- fell straight
// through to the AH backend instead of the selection gateway, and
// no inventory was ever sent (the reported timeout).
//
// The root/default (legacy v5) route must still resolve to *this*
// running sidecar -- never `ensure_supervisor_running`, which
// could spawn or reuse an unrelated supervisor -- so we build an
// already-resolved `SharedActiveAgentHost` from the sidecar's own
// published identity.
//
// Each relayed socket carries its own `--idle-timeout` activity
// guard, attached to the transport so it survives the WebSocket
// upgrade (see `idle_timeout::GuardedStream`). The inner dial the
// gateway makes back into our own listener is not enough on its
// own: a client still waiting to send its selection, or one whose
// selection resolves to a *different* endpoint (another live
// registry entry, or a freshly spawned dedicated host), never
// reaches our accept loop at all, so without this guard an
// actively proxied tunnel client could not stop us timing out from
// under it.
let
=
ready_active_agent_host
(
.
active_agent_host
(
)
)
;
let
=
.
.
clone
(
)
;
let
=
.
clone
(
)
;
let
=
.
.
clone
(
)
;
info!
(
.
,
"Routing dev-tunnel-hosted agent-host port through the protocol-v6 selection gateway"
)
;
let
=
.
activity_tracker
(
)
;
tokio::
spawn
(
async
move
{
while
let
Some
(
)
=
.
recv
(
)
.
await
{
let
=
.
clone
(
)
;
let
=
.
clone
(
)
;
let
=
.
clone
(
)
;
let
=
.
clone
(
)
;
let
=
idle_timeout::
GuardedStream
::
new
(
.
into_rw
(
)
,
.
as_ref
(
)
.
map
(
|a|
.
client_connected
(
)
)
,
)
;
tokio::
spawn
(
async
move
{
serve_agent_host_tunnel_connection
(
,
,
,
,
,
false
,
)
.
await
;
}
)
;
}
}
)
;
=
Some
(
)
;
}
let
=
constants::
QUALITYLESS_PRODUCT_NAME
;
let
=
.
.
as_deref
(
)
.
map
(
|t|
format!
(
"?tkn={t}"
)
)
.
unwrap_or_default
(
)
;
output::
print_banner_header
(
&
format!
(
"{product} Agent Host"
)
,
.
elapsed
(
)
)
;
if
let
(
Some
(
)
,
Some
(
)
)
=
(
constants::
EDITOR_WEB_URL
,
&
)
{
output::
print_banner_line
(
"Tunnel"
,
&
format!
(
"{base}/agents/tunnel/{name}"
)
)
;
}
// Resolve the user's `--host` choice into an `IpAddr` so the banner can
// either suggest exposing the agent host or enumerate the bound
// interfaces. Defaults to loopback when `--host` was omitted.
let
=
.
.
as_deref
(
)
.
and_then
(
|h|
.
parse
::
<
std::net::
IpAddr
>
(
)
.
ok
(
)
)
.
unwrap_or
(
std::net::
IpAddr
::
V4
(
std::net::
Ipv4Addr
::
LOCALHOST
)
)
;
output::
print_network_lines
(
,
,
&
)
;
print_manage_banner_line
(
)
;
output::
print_banner_footer
(
)
;
let
=
std::io::
stdout
(
)
.
flush
(
)
;
if
!
.
{
// Signal readiness to the foreground parent and then sever the
// inherited stdio so subsequent writes don't `BrokenPipe` once
// the parent exits. When running with `--foreground` there is no
// parent waiting on us and the user wants to keep seeing logs,
// so both are skipped.
println!
(
"{SUPERVISOR_READY_LINE}"
)
;
let
=
std::io::
stdout
(
)
.
flush
(
)
;
let
=
std::io::
stderr
(
)
.
flush
(
)
;
if
let
Err
(
)
=
redirect_stdio_to_null
(
)
{
warning!
(
.
,
"Failed to redirect stdio after detach: {}"
,
)
;
}
}
let
=
ShutdownRequest
::
create_rx
(
[
ShutdownRequest
::
CtrlC
]
)
;
match
(
,
)
{
(
Some
(
)
,
Some
(
)
)
=>
{
tokio::
select!
{
=
.
serve
(
)
=>
{
?
;
}
=
idle_timeout::
wait_for_idle_timeout
(
,
,
&
TokioIdleSleeper
)
=>
{
info!
(
.
,
"Agent host supervisor idle for {}s with no connected clients; shutting down"
,
.
as_secs
(
)
)
;
}
}
}
=>
{
.
serve
(
)
.
await
?
;
}
}
.
shutdown
(
)
.
await
;
if
let
Some
(
mut
)
=
.
take
(
)
{
.
close
(
)
.
await
.
ok
(
)
;
}
Ok
(
0
)
}
/// Resolve the user's `--host`/`--port` choice into a single
/// [`SocketAddr`]. Defaults to loopback when `--host` is unset.
fn
resolve_listen_addr
(
:
&
AgentHostArgs
)
->
Result
<
SocketAddr
,
AnyError
>
{
let
=
.
.
as_deref
(
)
.
unwrap_or
(
"127.0.0.1"
)
;
let
:
std::net::
IpAddr
=
match
.
parse
(
)
{
Ok
(
)
=>
,
Err
(
)
=>
match
(
,
0
)
.
to_socket_addrs
(
)
{
Ok
(
mut
)
=>
match
.
next
(
)
{
Some
(
)
=>
.
ip
(
)
,
None
=>
{
return
Err
(
CodeError
::
CouldNotListenOnInterface
(
std::io::
Error
::
new
(
std::io::
ErrorKind
::
InvalidInput
,
format!
(
"could not resolve --host '{host}'"
)
,
)
)
.
into
(
)
)
}
}
,
Err
(
)
=>
return
Err
(
wrap
(
,
format!
(
"could not resolve --host '{host}'"
)
)
.
into
(
)
)
,
}
,
}
;
Ok
(
SocketAddr
::
new
(
,
.
)
)
}
fn
print_reuse_banner
(
:
&
log::
Logger
,
:
Instant
,
:
u32
,
:
Option
<
&
str
>
,
:
u16
,
:
Option
<
&
str
>
,
:
Option
<
&
str
>
,
)
{
let
=
constants::
QUALITYLESS_PRODUCT_NAME
;
let
=
.
map
(
|t|
format!
(
"?tkn={t}"
)
)
.
unwrap_or_default
(
)
;
output::
print_banner_header
(
&
format!
(
"{product} Agent Host"
)
,
.
elapsed
(
)
)
;
if
let
(
Some
(
)
,
Some
(
)
)
=
(
constants::
EDITOR_WEB_URL
,
)
{
output::
print_banner_line
(
"Tunnel"
,
&
format!
(
"{base}/agents/tunnel/{name}"
)
)
;
}
// Surface the host the supervisor was actually bound to (falling back
// to loopback if unknown). This lets the network hint correctly say
// "use --host to expose" only when the supervisor really is
// loopback-only.
let
=
.
and_then
(
|h|
.
parse
::
<
std::net::
IpAddr
>
(
)
.
ok
(
)
)
.
unwrap_or
(
std::net::
IpAddr
::
V4
(
std::net::
Ipv4Addr
::
LOCALHOST
)
)
;
output::
print_network_lines
(
,
,
&
)
;
print_manage_banner_line
(
)
;
output::
print_banner_footer
(
)
;
let
=
std::io::
stdout
(
)
.
flush
(
)
;
.
result
(
format!
(
"Agent host supervisor already running (PID {pid}). \
Use `{application_name} agent kill` to stop it, or `{application_name} agent host --replace` to start a fresh one."