Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
/** The agent-environment endpoints Mission Control exposes. */
type
CloudSandboxEnvironmentAction
=
'get'
|
'connect'
|
'reconnect'
;
/** The subset of a Mission Control task the sandbox discovery path reads. */
interface
ITaskSummary
{
readonly
:
string
;
readonly
?
:
string
;
readonly
?
:
string
|
null
;
readonly
?
:
string
;
readonly
?
:
readonly
{
readonly
?
:
string
}
[
]
;
readonly
?
:
{
readonly
?
:
string
}
;
/**
* The owning repository, identified by numeric id only — the payload carries no name. See
* {@link CloudSandboxApiService._resolveRepositoryName}.
*/
readonly
?
:
{
readonly
?
:
number
}
;
}
/** A full task, which additionally carries the sessions bound to sandbox environments. */
interface
ITaskDetail
extends
ITaskSummary
{
readonly
?
:
readonly
{
readonly
:
string
;
readonly
?
:
string
}
[
]
;
}
const
LOG_PREFIX
=
'[CloudSandboxApi]'
;
/**
* The github.com REST API base, used for the repository-name lookup discovery needs. The CORS
* caveat on {@link CloudSandboxApiService._tasksBaseUrl} is specific to `api.github.com/agents/*`;
* the general REST API is CORS-enabled and already called from the renderer elsewhere.
*/
const
GITHUB_DOT_COM_API_BASE_URI
=
deriveGitHubEndpoints
(
undefined
)
.
;
/** Per-request timeout (ms) for credential and environment calls. */
const
REQUEST_TIMEOUT_MS
=
10_000
;
/** Per-request timeout (ms) for discovery, whose task list is far larger than a credential mint. */
const
DISCOVERY_TIMEOUT_MS
=
30_000
;
/**
* Per-request timeout (ms) for task creation, which waits on a sandbox VM being allocated rather
* than on a record being written.
*/
const
CREATE_TIMEOUT_MS
=
60_000
;
/** Default Retry-After (seconds) when a 202 "waking" response omits the header. */
const
DEFAULT_WAKING_RETRY_AFTER_SECONDS
=
5
;
/**
* Response headers worth logging when a request fails, lowercased to match the response map.
* `x-github-request-id` is what a support escalation is keyed on.
*/
const
DIAGNOSTIC_RESPONSE_HEADERS
=
[
'x-github-request-id'
,
'x-request-id'
,
'x-sweagentd-retry'
,
'retry-after'
]
as
const
;
/** How many recent tasks to scan for sandbox sessions during discovery, per page. */
const
DISCOVERY_TASK_SCAN_LIMIT
=
100
;
/** Bounds sequential page fetches. Hitting it leaves tasks unscanned, so the result is `partial`. */
const
DISCOVERY_TASK_PAGE_LIMIT
=
10
;
/**
* Max concurrent task-detail fetches during discovery.
*
* Discovery used to resolve every sandbox task at once, which meant a user with a few dozen
* sandbox tasks issued that many simultaneous requests and tripped GitHub's rate limit. Each
* rejected fetch drops its session from the pass, and the burst also starves the `listTasks` call
* of whichever pass runs next — including the one a freshly reloaded window depends on.
*/
const
DISCOVERY_TASK_FETCH_CONCURRENCY
=
5
;
/** HTTP status GitHub answers a rate-limited request with. */
const
HTTP_TOO_MANY_REQUESTS
=
429
;
/** How many times a rate-limited discovery read is re-issued before it is given up on. */
const
RATE_LIMIT_MAX_RETRIES
=
3
;
/** First backoff step (ms) for a rate-limited read whose response names no `Retry-After`. */
const
RATE_LIMIT_BASE_DELAY_MS
=
1_000
;
/**
* Cap (ms) on a backoff this client computes for itself. It deliberately does not apply to a
* server-supplied `Retry-After`: shortening that would re-issue the request inside the window the
* server just asked us to stay out of, earning another 429 and adding to the very traffic that
* caused it.
*/
const
RATE_LIMIT_MAX_BACKOFF_MS
=
8_000
;
/**
* Total time (ms) a single read may spend waiting out rate limits before it gives up.
*
* Bounds the pass without ever shortening a wait: a `Retry-After` longer than what is left is not
* trimmed to fit, it ends the retries. The read then reports its 429 and leaves the scan `partial`,
* so the caller keeps the sessions it could not resolve and a later pass picks them up.
*/
const
RATE_LIMIT_WAIT_BUDGET_MS
=
15_000
;
/** Fallback scopes when the product does not configure `defaultChatAgent.providerScopes`. */
const
FALLBACK_SCOPES
=
[
'read:user'
,
'user:email'
,
'repo'
,
'workflow'
]
;
/**
* Mission Control client for cloud sandbox sessions: mints (`connect`) and refreshes (`reconnect`)
* Web PubSub credentials, reads environment and task records, discovers sandbox-backed sessions,
* and replays a task's persisted AHP history.
*
* Runs in the renderer so the sandbox path works in VS Code Web, where no Copilot extension host is
* available.
*/
/**
* Enumerate sandbox-backed cloud sessions by scanning recent tasks and resolving each one's
* Mission Control environment binding.
*
* Only a `complete` result may be reconciled against: a partial or truncated scan is missing
* entries that still exist.
*/
`${LOG_PREFIX} Discovery found ${sessions.length} sandbox session(s) from ${sandboxTasks.length} sandbox task(s) out of ${tasks.length} scanned${truncated ?' (scan truncated)':''}${unresolved >0?`; ${unresolved} unresolved`:''}${unnamed >0?`; ${unnamed} without a repository name (they group under "Unknown")`:''}.`
)
;
return
{
:
>
0
||
?
'partial'
:
'complete'
,
}
;
}
/**
* Provision a sandbox task bound to an on-demand environment. Mission Control provisions a VM
* and binds a session but starts no run, so the caller sends the first turn over the relay.
* The environment on the returned session is the real VM, not the sentinel.
*/
async
createSession
(
:
,
:
)
:
Promise
<
>
{
const
=
parseNwo
(
.
)
;
const
=
await
this
.
_request
(
`${this._tasksBaseUrl()}/tasks`
,
'mc.taskClient.create'
,
'createTask'
,
{
'Accept'
:
'application/json'
,
'Copilot-Integration-Id'
:
COPILOT_INTEGRATION_ID
,
}
,
,
CREATE_TIMEOUT_MS
,
{
:
CLOUD_SANDBOX_ON_DEMAND_ENVIRONMENT_ID
,
// Persisted for display, so replayed history shows the prompt no run was started for.
:
.
,
...
(
&&
{
:
[
]
}
)
,
}
)
;
if
(
!
isSuccess
(
)
)
{
// Read once: the body carries both the id to clean up and the failure message.
const
=
await
asText
(
)
.
catch
(
(
)
=>
''
)
??
''
;
// The generic failure message masks its cause; the request id is the only handle.
`${LOG_PREFIX} Task create failed (HTTP ${context.res.statusCode ??'unknown'}) without reporting a task id. Mission Control may have recorded a task before failing; such a task is orphaned and can only be removed server-side.`
)
;
}
await
this
.
_throwForStatus
(
'task create'
,
,
)
;
}
const
=
await
this
.
_readJson<ITaskDetail>
(
)
;
const
=
?.
;
if
(
!
)
{
throw
new
CloudSandboxRequestError
(
.
.
,
'Mission Control task create returned no task id'
)
;
}
const
=
&&
getTaskEnvironmentBinding
(
)
;
if
(
!
)
{
// A task with no bound session is unusable — the relay has nothing to address — but it
// still shows up in the user's task list, so drop it rather than leaving litter behind.
await
this
.
_deleteTaskBestEffort
(
)
;
throw
new
CloudSandboxRequestError
(
.
.
,
`Mission Control bound no sandbox session to task ${taskId}`
)
;
}
this
.
.
info
(
`${LOG_PREFIX} Provisioned sandbox task ${taskId} (session ${binding.sessionId}) on environment ${binding.environmentId}.`
)
;
return
{
,
:
.
,
:
.
}
;
}
/**
* Delete a task we created but cannot use. Best-effort: the caller is already failing, and a
* failed cleanup must not replace the error that explains why.
*
* Only covers tasks whose id we learned. Mission Control writes the task record before it
* provisions compute, so any failure after that point (an authorization rejection, or a
* provisioning error such as HTTP 500 `failed to create agent compute`) leaves a task behind.
* When the failure response omits the id, that orphan can only be cleaned up server-side.
*/
// A rejected delete resolves rather than throwing, so the status decides.
if
(
!
isSuccess
(
)
)
{
this
.
.
warn
(
`${LOG_PREFIX} Could not clean up sandbox task ${taskId}: HTTP ${context.res.statusCode ??'none'}. It remains and can only be removed server-side.`
)
;
return
;
}
this
.
.
info
(
`${LOG_PREFIX} Cleaned up unusable sandbox task ${taskId}: HTTP ${context.res.statusCode ??'none'}`
)
;
}
catch
(
)
{
this
.
.
warn
(
`${LOG_PREFIX} Could not clean up sandbox task ${taskId}: ${toErrorMessage(error)}`
)
;
}
}
/**
* Read a task's persisted AHP history and fold it into session/chat state.
*
* The only history path that survives the sandbox: `/events` is served by Mission Control's
* mirror, not the environment. The `vnd.github.ahp+json` media type selects the raw relayed
* frames rather than the cloud-task event summaries the endpoint serves by default.
*/
'Task AHP history response was empty or not JSON.'
)
;
}
return
replayTaskAhpEvents
(
parseTaskEventsResponse
(
)
)
;
}
/**
* Resolve a numeric repository id to its `owner/name`, memoized for the life of the service.
* A task names its repository nowhere — `repository` carries an id, and the session's
* `event_url` / `base_ref` are empty for tasks created through the tasks API.
*
* The cached promise must never reject: every task in a pass shares it, and a rejection would
* count each one as unresolved (forcing the scan `partial`) and drop those sessions from the
* listing entirely. A miss is evicted so the next pass retries.
*/
/** Shared handler for the `connect`/`reconnect` endpoints (200 token or 202 waking). */
private
async
_connectRequest
(
:
,
:
string
,
:
,
:
<
string
,
string
>
,
)
:
Promise
<
>
{
const
=
await
this
.
_sendEnvironment
(
,
,
,
)
;
if
(
.
.
===
202
)
{
const
=
parseRetryAfter
(
.
.
?.
[
'retry-after'
]
)
;
this
.
.
debug
(
`${LOG_PREFIX}${action}: environment waking, retry after ${retryAfterSeconds}s`
)
;
return
{
:
'waking'
,
:
{
}
}
;
}
if
(
!
isSuccess
(
)
)
{
await
this
.
_throwForStatus
(
,
)
;
}
const
=
await
this
.
_readJson<ICloudSandboxClientToken>
(
)
;
if
(
!
?.
||
!
?.
||
!
?.
||
!
?.
)
{
throw
new
Error
(
`Mission Control ${action} returned an incomplete token response`
)
;
}
return
{
:
'token'
,
:
}
;
}
/**
* Issue an agent-environment request and return the raw response. The caller owns status
* handling, since the meaning of a status is endpoint-specific (notably HTTP 202 = "waking",
* which is neither an error nor a result).
*/
/** Issue a task API request, throwing on a non-success status. */
private
async
_sendTask
(
:
string
,
:
'list'
|
'get'
,
:
)
:
Promise
<
>
{
const
=
await
this
.
_retryWhileRateLimited
(
`task ${action}`
,
,
(
)
=>
this
.
_request
(
,
`mc.taskClient.${action}`
,
===
'list'
?
'listTasks'
:
'getTask'
,
{
'Accept'
:
'application/json'
,
'Copilot-Integration-Id'
:
COPILOT_INTEGRATION_ID
,
}
,
,
DISCOVERY_TIMEOUT_MS
)
)
;
if
(
!
isSuccess
(
)
)
{
await
this
.
_throwForStatus
(
`task ${action}`
,
)
;
}
return
;
}
/**
* Re-issue a discovery read that came back rate-limited, waiting for `Retry-After` when the
* response names one and backing off exponentially when it does not.
*
* Discovery reads the API far harder than any other sandbox call, so it is the one path that
* routinely trips the limit. Reporting a 429 rather than retrying it loses the session being
* resolved for the rest of the window, because nothing re-runs a pass that otherwise succeeded.
*/
private
async
_retryWhileRateLimited
(
:
string
,
:
,
send
:
(
)
=>
Promise
<
>
)
:
Promise
<
>
{
let
=
0
;
for
(
let
=
0
;
;
++
)
{
const
=
await
send
(
)
;
if
(
.
.
!==
HTTP_TOO_MANY_REQUESTS
||
>=
RATE_LIMIT_MAX_RETRIES
||
.
)
{
return
;
}
const
=
rateLimitDelay
(
.
.
?.
[
'retry-after'
]
,
)
;
// Waiting less than asked would re-issue inside the server's window, so a delay that
// does not fit ends the retries rather than being trimmed to fit.
if
(
+
>
RATE_LIMIT_WAIT_BUDGET_MS
)
{
this
.
.
warn
(
`${LOG_PREFIX}${action} was rate limited and asks for another ${delay}ms, beyond what is left of its ${RATE_LIMIT_WAIT_BUDGET_MS}ms budget; giving up so the pass stays bounded. A later pass retries it.`
)
;
return
;
}
// Nothing reads the body on this path, and an unconsumed stream holds its connection.
await
asText
(
)
.
catch
(
(
)
=>
undefined
)
;
this
.
.
warn
(
`${LOG_PREFIX}${action} was rate limited; retrying in ${delay}ms (attempt ${attempt +1} of ${RATE_LIMIT_MAX_RETRIES}).`
)
;
await
timeout
(
,
)
;
+=
;
}
}
private
async
_request
(
:
string
,
:
string
,
:
,
:
<
string
,
string
>
,
:
,
:
number
=
REQUEST_TIMEOUT_MS
,
?
:
unknown
,
?
:
'GET'
|
'POST'
|
'DELETE'
)
:
Promise
<
>
{
const
=
await
this
.
_resolveGitHubToken
(
)
;
if
(
!
)
{
// No request is issued, so there is no request outcome to count.
throw
new
CloudSandboxAuthenticationRequiredError
(
)
;
}
const
=
.
now
(
)
;
const
=
??
(
===
undefined
?
'GET'
:
'POST'
)
;
try
{
const
=
await
this
.
.
request
(
{
:
,
,
:
{
...
,
// `fetch` labels a string body `text/plain` unless told otherwise.
...
(
===
undefined
?
undefined
:
{
[
'Content-Type'
]
:
'application/json'
}
)
,
[
'Authorization'
]
:
`Bearer ${accessToken}`
}
,
...
(
===
undefined
?
undefined
:
{
:
JSON
.
stringify
(
)
}
)
,
:
,
,
}
,
)
;
this
.
.
reportRequest
(
,
requestOutcomeForStatus
(
.
.
)
)
;
// Latency against its budget: `/connect` blocks on a compute resume, so how close a reply
// came to being cut off separates "Mission Control is silent" from "we stopped listening".
/**
* Mission Control task API base. Uses the Copilot API host: `api.github.com/agents/*` omits
* CORS headers on authenticated responses, so a renderer `fetch` receives the reply and discards it.
*/
private
_tasksBaseUrl
(
)
:
string
{
return
`${GITHUB_DOT_COM_COPILOT_API_BASE_URI}/agents`
;
}
private
async
_readJson<T>
(
:
)
:
Promise
<
T
|
undefined
>
{
const
=
await
asText
(
)
;
if
(
!
)
{
return
undefined
;
}
try
{
return
JSON
.
parse
(
)
as
T
;
}
catch
{
return
undefined
;
}
}
/**
* Throw a diagnosable error for a non-success response. Pass `prereadBody` when the caller has
* already consumed the stream, since reading it twice yields nothing.
*/
private
async
_throwForStatus
(
:
string
,
:
,
?
:
string
)
:
Promise
<
never
>
{
const
=
??
await
asText
(
)
.
catch
(
(
)
=>
''
)
;
const
=
.
.
;
throw
new
CloudSandboxRequestError
(
,
`Mission Control ${action} failed: HTTP ${status ??'unknown'} - ${(body ??'').slice(0,200)}`
,
)
;
}
/**
* Describe a response verbatim for a support escalation: status, the server-side request id,
* and the body as received.
*/
// Fall back to the narrowest session whose scopes are a superset of what we need.
const
=
await
this
.
.
getSessions
(
,
undefined
,
undefined
,
true
)
;
const
=
new
Set
(
)
;
let
:
{
:
string
;
:
number
}
|
undefined
;
for
(
const
of
)
{
const
=
new
Set
(
.
)
;
if
(
[
...
]
.
every
(
=>
.
has
(
)
)
)
{
const
=
.
-
.
;
if
(
!
||
<
.
)
{
=
{
:
.
,
}
;
}
}
}
if
(
!
)
{
this
.
.
warn
(
`${LOG_PREFIX} No '${providerId}' session with scopes [${scopes.join(', ')}]`
)
;
}
return
?.
;
}
}
function
isSuccess
(
:
)
:
boolean
{
const
=
.
.
??
0
;
return
>=
200
&&
<
300
;
}
function
toQuery
(
:
<
string
,
string
>
|
undefined
)
:
string
{
if
(
!
)
{
return
''
;
}
const
=
new
URLSearchParams
(
)
.
toString
(
)
;
return
?
`?${search}`
:
''
;
}
/** Parse a `Retry-After` header (delta-seconds), or `undefined` when absent or unusable. */
function
retryAfterSeconds
(
:
string
|
string
[
]
|
undefined
)
:
number
|
undefined
{
const
=
Array
.
isArray
(
)
?
[
0
]
:
;
if
(
)
{
const
=
.
parseInt
(
,
10
)
;
if
(
.
isFinite
(
)
&&
>
0
)
{
return
;
}
}
return
undefined
;
}
/** Parse a `Retry-After` header (delta-seconds); fall back to a small default. */
function
parseRetryAfter
(
:
string
|
string
[
]
|
undefined
)
:
number
{
return
retryAfterSeconds
(
)
??
DEFAULT_WAKING_RETRY_AFTER_SECONDS
;
}
/**
* How long to wait before re-issuing a rate-limited request: the server's `Retry-After` verbatim
* when it names one, otherwise an exponential backoff of our own, capped. A server delay is never
* shortened — the caller decides whether it still fits its budget, since retrying early only earns
* another 429.
*/
function
rateLimitDelay
(
:
string
|
string
[
]
|
undefined
,
:
number
)
:
number
{
const
=
retryAfterSeconds
(
)
;
return
!==
undefined
?
*
1000
:
.
min
(
RATE_LIMIT_BASE_DELAY_MS
*
.
pow
(
2
,
)
,
RATE_LIMIT_MAX_BACKOFF_MS
)
;
}
/**
* Whether a task is a cloud sandbox task: owned by {@link CLOUD_SANDBOX_AGENT_SLUG} and running on
* the `sandboxes` compute provider. Reads list-level fields only.
*
* The slug half must be settled before `chat.agentHost.cloudSandbox.enabled` is turned on: sandbox
* tasks are expected to move to a different slug, which would silently make discovery return
* nothing. `compute.provider` is the durable test.
*/
function
isCloudSandboxTask
(
:
)
:
boolean
{
const
=
.
?.
some
(
=>
.
===
CLOUD_SANDBOX_AGENT_SLUG
)
??
false
;
return
&&
.
?.
===
'sandboxes'
;
}
/** Whether a `Link` header advertises another page (`rel="next"`). */
function
hasNextLink
(
:
string
|
string
[
]
|
undefined
)
:
boolean
{
const
=
Array
.
isArray
(
)
?
.
join
(
','
)
:
;
return
?
/rel="?next"?/
.
test
(
)
:
false
;
}
/** Split an `owner/name` into the pair Mission Control expects, or `undefined` when unusable. */
function
parseNwo
(
:
string
|
undefined
)
:
{
:
string
;
:
string
}
|
undefined
{
const
=
?.
indexOf
(
'/'
)
??
-
1
;
if
(
!
||
<=
0
||
===
.
-
1
)
{
return
undefined
;
}
return
{
:
.
slice
(
0
,
)
,
:
.
slice
(
+
1
)
}
;
}
/**
* The Mission Control environment a sandbox task runs in, read from the full task's nested
* `sessions[]`. Undefined when no session is bound to an environment yet.
*/