Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
/**
* Whether this host offers worktree configuration and strips host-owned
* worktree keys before delegating configuration to providers. The null
* implementation is the only implementation that returns `false`.
*/
readonly
:
boolean
;
notePending
(
:
string
)
:
void
;
clearPending
(
:
string
)
:
void
;
getResolvedWorktree
(
:
string
)
:
URI
|
undefined
;
resolveOnFirstSend
(
:
)
:
Promise
<
URI
|
undefined
>
;
resolveIsolationConfig
(
:
)
:
Promise
<
|
undefined
>
;
branchCompletions
(
:
URI
|
undefined
,
?
:
string
)
:
Promise
<
{
:
{
:
string
;
:
string
}
[
]
}
>
;
takePendingAnnouncement
(
:
string
)
:
string
|
undefined
;
persistCreationFailure
(
:
URI
,
:
string
,
:
string
|
undefined
)
:
Promise
<
void
>
;
applyRestoreAnnouncement
(
:
URI
,
:
readonly
[
]
)
:
Promise
<
readonly
[
]
>
;
prepareSessionDeletion
(
:
URI
,
:
string
)
:
Promise
<
|
undefined
>
;
removeSessionWorktree
(
:
string
,
:
|
undefined
)
:
Promise
<
void
>
;
cleanupWorktreeOnArchive
(
:
URI
,
:
string
)
:
Promise
<
void
>
;
recreateWorktreeOnUnarchive
(
:
URI
,
:
string
)
:
Promise
<
void
>
;
readWorktreeMetadata
(
:
URI
)
:
Promise
<
|
undefined
>
;
adoptExistingWorktreeMetadata
(
:
URI
,
:
URI
)
:
Promise
<
boolean
>
;
recordAdoptedWorktreeMetadata
(
:
URI
,
:
{
readonly
:
string
;
readonly
:
string
|
undefined
;
readonly
:
URI
;
readonly
:
URI
}
)
:
Promise
<
void
>
;
recordExternalWorktreeProject
(
:
URI
,
:
URI
)
:
Promise
<
|
undefined
>
;
resolveWorktreeProject
(
:
URI
)
:
Promise
<
|
undefined
>
;
sessionWorktreeProject
(
:
string
)
:
|
undefined
;
}
/**
* Per-session-database metadata keys under which the worktree an agent
* created for an isolated session is recorded. The string values keep the
* historical `copilot.worktree.*` prefix so sessions materialized by earlier
* Copilot builds keep resolving their worktree on archive / unarchive /
* restore after this logic was unified across agents. All agents (Copilot,
* Codex, Claude) now write and read these same keys; the per-session database
* is already scoped by session, so there is no cross-agent collision.
*/
const
WORKTREE_META_BRANCH
=
'copilot.worktree.branchName'
;
const
WORKTREE_META_PATH
=
'copilot.worktree.path'
;
export
const
WORKTREE_META_REPOSITORY_ROOT
=
'copilot.worktree.repositoryRoot'
;
const
WORKTREE_META_CREATION_FAILURE
=
'copilot.worktree.creationFailure'
;
// TODO@roblourens: Remove after ~November 2026, when pre-July 2026 sessions no longer need their worktree path/root reconstructed from this legacy key.
const
LEGACY_WORKTREE_META_WORKING_DIRECTORY
=
'copilot.workingDirectory'
;
const
MAX_WORKTREE_FAILURE_DIAGNOSTIC_LENGTH
=
200
;
/** Thrown when a persisted session working directory is missing and cannot be repaired. */
export
class
SessionWorkingDirectoryMissingError
extends
Error
{
constructor
(
readonly
:
URI
,
readonly
?
:
string
)
{
super
(
?
localize
(
'sessionWorkingDirectoryMissingWithReason'
,
"This session couldn't be loaded because its worktree is missing and could not be recreated: {0}"
,
)
:
localize
(
'sessionWorkingDirectoryMissing'
,
"This session couldn't be loaded because its working directory no longer exists: {0}"
,
.
)
)
;
this
.
=
'SessionWorkingDirectoryMissingError'
;
}
}
/** Default upper bound on branch names returned for the branch picker. */
const
BRANCH_COMPLETION_LIMIT
=
25
;
const
WORKTREE_PROGRESS_DEBOUNCE_MS
=
40
;
export
interface
ISessionWorktree
{
readonly
:
URI
;
readonly
:
URI
;
}
export
interface
IWorktreeMetadata
{
readonly
:
string
;
readonly
?
:
URI
;
readonly
?
:
URI
;
}
/**
* The `<repo>.worktrees` sibling directory where per-session isolated
* worktrees are created, e.g. `/src/vscode` → `/src/vscode.worktrees`.
* Defined in {@link ../../common/worktreePaths.js} so browser-layer trust gates
* can share the same implementation; re-exported here for existing importers.
*/
export
{
}
;
/**
* Derives the on-disk worktree directory name from a branch name: strips the
* caller-supplied prefix (e.g. the user's `git.branchPrefix`) and the built-in
* `agents/` prefix so the directory stays concise, then flattens any remaining
* path separators.
*/
export
function
getWorktreeName
(
:
string
,
:
string
=
''
)
:
string
{
let
=
;
if
(
&&
.
startsWith
(
)
)
{
=
.
substring
(
.
)
;
}
if
(
.
startsWith
(
AGENT_BRANCH_PREFIX
)
)
{
=
.
substring
(
AGENT_BRANCH_PREFIX
.
)
;
}
return
.
replace
(
/\//g
,
'-'
)
;
}
/**
* Builds the localized "Created isolated worktree for branch X" markdown shown
* at the top of the first response in worktree-isolated sessions. The branch
* name is wrapped as inline code so the localized template doesn't have to
* embed markdown punctuation. The trailing blank line keeps the announcement
* visually separated when it gets merged into the same markdown part as the
* model's reply.
*/
export
function
buildWorktreeAnnouncementText
(
:
string
)
:
string
{
return
localize
(
'agentHost.worktreeCreated'
,
"Created isolated worktree for branch {0}"
,
appendEscapedMarkdownInlineCode
(
)
)
+
'\n\n'
;
}
/** Builds the warning shown when worktree isolation falls back to the original folder. */
export
function
buildWorktreeFailureNotification
(
?
:
string
)
:
<
,
{
:
.
}
>
{
const
=
normalizeWorktreeFailureDiagnostic
(
)
;
const
=
?
localize
(
'agentHost.worktreeCreationFailedWithDiagnostic'
,
"Couldn't create the isolated worktree. This session is continuing in the original folder.\n\n{0}"
,
appendEscapedMarkdownInlineCode
(
)
)
:
localize
(
'agentHost.worktreeCreationFailed'
,
"Couldn't create the isolated worktree. This session is continuing in the original folder."
)
;
return
{
:
.
,
,
:
toAgentSystemNotificationMeta
(
{
:
.
,
:
.
,
}
)
,
}
;
}
/** Normalizes an arbitrary worktree failure into a bounded single-line diagnostic. */
/**
* The steps of worktree creation that are slow enough to be worth naming while
* a session materializes. Ordered as they run.
*/
export
const
enum
{
/** Queued behind another worktree being created in the same repository. */
,
/** Asking the model for a branch name, then probing candidates for collisions. */
,
/** `git worktree add` — the phase that reports file-level progress. */
,
/** Copying the git-ignored files the client asked to carry over. */
,
}
/**
* Builds the localized activity label for a worktree-creation phase. `percent`
* only applies to the phases that report file-level progress
* ({@link WorktreeCreationPhase.CheckingOut} and
* {@link WorktreeCreationPhase.CopyingIncludeFiles}), where it is absent until
* the first sample arrives.
*/
export
function
buildWorktreeProgressText
(
:
,
?
:
number
)
:
string
{
switch
(
)
{
case
.
:
return
localize
(
'agentHost.worktreeNamingBranch'
,
"Creating isolated worktree (naming branch)"
)
;
case
.
:
return
===
undefined
?
localize
(
'agentHost.worktreeCheckingOut'
,
"Creating isolated worktree (checking out files)"
)
:
localize
(
'agentHost.worktreeCheckingOutPercent'
,
"Creating isolated worktree (checking out files, {0}%)"
/**
* Adapts the raw file counts the git service reports into progress labels for
* a phase. Rounds down to whole percentages, drops non-advancing samples, and
* debounces updates to avoid overwhelming consumers, flushing the latest
* percentage when the operation completes.
*/
async
function
withPercentProgress<T>
(
:
,
:
(
(
:
string
)
=>
void
)
|
undefined
,
:
(
:
(
(
:
)
=>
void
)
|
undefined
)
=>
Promise
<
T
>
,
)
:
Promise
<
T
>
{
if
(
!
)
{
return
operation
(
undefined
)
;
}
let
=
-
1
;
const
=
new
RunOnceScheduler
(
(
)
=>
onProgress
(
buildWorktreeProgressText
(
,
)
)
,
WORKTREE_PROGRESS_DEBOUNCE_MS
)
;
try
{
return
await
operation
(
(
{
,
}
)
=>
{
const
=
.
min
(
100
,
.
floor
(
*
100
/
)
)
;
if
(
<=
)
{
return
;
}
=
;
.
schedule
(
)
;
}
)
;
}
finally
{
const
=
.
isScheduled
(
)
;
.
dispose
(
)
;
if
(
)
{
onProgress
(
buildWorktreeProgressText
(
,
)
)
;
}
}
}
/**
* Returns a copy of `turns` where `announcement` has been prepended to the
* first top-level assistant turn's first markdown response part. Used on
* session restore so the worktree announcement remains visible after the
* session is reopened. If no assistant content exists yet, a fresh markdown
* part is inserted at the top of the first turn.
*/
export
function
prependAnnouncementToFirstTurn
(
:
readonly
[
]
,
:
string
)
:
readonly
[
]
{
if
(
.
===
0
)
{
return
;
}
const
=
.
slice
(
)
;
const
=
[
0
]
;
const
=
.
[
0
]
;
if
(
?.
===
.
)
{
const
=
.
.
slice
(
)
;
[
0
]
=
{
...
,
:
+
.
}
;
[
0
]
=
{
...
,
}
;
}
else
{
const
:
[
]
=
[
{
:
.
,
:
generateUuid
(
)
,
:
}
,
...
.
,
]
;
[
0
]
=
{
...
,
}
;
}
return
;
}
function
prependWorktreeFailureToFirstTurn
(
:
readonly
[
]
,
:
string
|
undefined
)
:
readonly
[
]
{
if
(
.
===
0
)
{
return
;
}
const
=
.
slice
(
)
;
const
=
[
0
]
;
[
0
]
=
{
...
,
:
[
buildWorktreeFailureNotification
(
)
,
...
.
]
,
}
;
return
;
}
/** Parameters for {@link WorktreeIsolation.resolveIsolationConfig}. */
export
interface
IResolveIsolationConfigRequest
{
readonly
:
URI
|
undefined
;
readonly
:
<
string
,
unknown
>
|
undefined
;
}
/**
* The isolation + branch schema contribution for an agent's
* `resolveSessionConfig`. Callers merge {@link isolationProperty} (and
* {@link branchProperty} / {@link worktreeBranchPrefixProperty} when present)
* into their own schema and merge the default values ({@link isolationValue} /
* {@link branchDefault}) into the defaults bag they pass to `validateOrDefault`.
*/
export
interface
IIsolationConfigContribution
{
readonly
:
<
'folder'
|
'worktree'
>
;
readonly
:
<
string
>
|
undefined
;
/**
* Read-only carrier for the client's `git.branchPrefix`. Declared for both
* isolations (like `branch`) so the value rides `_config.values` and
* survives isolation toggles; the host only consumes it for worktree
* isolation (see {@link WorktreeIsolation.resolveWorkingDirectory}).
*/
readonly
:
<
string
>
|
undefined
;
/** Read-only carrier for the client's `git.worktreeIncludeFiles`. */
readonly
:
<
readonly
string
[
]
>
|
undefined
;
/** Read-only carrier for the programmatic worktree branch tracking preference. */
readonly
:
<
boolean
>
|
undefined
;
/** Read-only carrier for checking out the selected branch directly. */
readonly
:
<
boolean
>
|
undefined
;
readonly
:
'folder'
|
'worktree'
;
readonly
:
string
|
undefined
;
readonly
:
string
|
undefined
;
}
/** Parameters for {@link WorktreeIsolation.resolveWorkingDirectory}. */
export
interface
IResolveWorkingDirectoryRequest
{
readonly
:
URI
;
readonly
:
string
;
readonly
:
URI
|
undefined
;
readonly
:
<
string
,
unknown
>
|
undefined
;
readonly
?
:
string
;
readonly
?
:
string
;
/**
* Receives localized activity labels while the worktree is being created,
* so callers can surface live progress. Only called for sessions that
* selected worktree isolation — though such a session can still fall back
* to its folder after the first label (e.g. the directory turns out not to
* be a git repository) — and the caller is responsible for clearing the
* activity once resolution settles.
*/
readonly
?
:
(
:
string
)
=>
void
;
}
/**
* Shared, per-agent controller for git-worktree session isolation. Owns the
* full machinery Copilot pioneered so Codex and Claude get identical behavior:
*
* - advertising the `isolation` (`folder` / `worktree`) and `branch` session
* config properties from `resolveSessionConfig` ({@link resolveIsolationConfig});
* - completing branch names for the branch picker ({@link branchCompletions});
* - creating the worktree on materialization and persisting its metadata
* ({@link resolveWorkingDirectory});
* - surfacing worktree creation success/failure notices live and on restore;
* - cleaning up / recreating the worktree on session deletion, archive, and unarchive.
*
* A single host-owned instance serves every agent: the orchestrator
* ({@link AgentService}) creates it and drives the lifecycle so individual
* agents stay unaware of the folder-vs-worktree distinction. Session state
* (`_materializedWorktrees`, pending markers, pending announcements) is keyed by the
* globally-unique sessionId, so sharing one instance across agents is safe.
*/
export
class
WorktreeIsolation
extends
Disposable
implements
IAgentHostWorktreeIsolation
{
declare
readonly
:
undefined
;
readonly
:
boolean
=
true
;
/** Worktrees materialized during this host process, keyed by sessionId. */
private
readonly
=
new
Map<string, ISessionWorktree>
(
)
;
private
readonly
=
new
Map<string, ISessionWorktree>
(
)
;
/**
* Per-session announcement (markdown) emitted as a synthetic streaming
* markdown part the first time the session sends a message. Surfaces the
* "Created isolated worktree for branch X" message live during the first
* turn; the same announcement is re-injected on restore via
* {@link applyRestoreAnnouncement}.
*/
private
readonly
=
new
Map<string,string>
(
)
;
/**
* SessionIds of freshly-created worktree-isolation sessions whose worktree
* has not yet been created (creation is deferred to the first send so the
* user's prompt can drive branch naming). While a session is in this set the
* host reports its working directory as "pending" ({@link isWorkingDirectoryPending})
* so agents defer prewarming / materializing until {@link resolveOnFirstSend}
* runs. Never populated for restored sessions — their worktree already exists
* on disk and their persisted working directory already points at it.
*/
private
readonly
=
new
Set<string>
(
)
;
private
readonly
=
this
.
_register
(
new
Emitter<string>
(
)
)
;
readonly
:
<
string
>
=
this
.
.
;
/** Fixed log label; one host-owned instance serves every agent. */
private
readonly
=
'AgentHost'
;
/**
* Serializes the worktree lifecycle per session so a first-send creation
* ({@link resolveOnFirstSend}) never interleaves with archive/unarchive
* cleanup ({@link cleanupWorktreeOnArchive} / {@link recreateWorktreeOnUnarchive})
* or deletion ({@link removeSessionWorktree}) for the same session — the
* guarantee each agent previously enforced with its own sequencer.
*/
private
readonly
=
new
SequencerByKey<string>
(
)
;
private
readonly
=
new
SequencerByKey<string>
(
)
;
constructor
(
@IAgentBranchNameGenerator
private
readonly
:
,
@IAgentHostGitService
private
readonly
:
,
@ISessionDataService
private
readonly
:
,
@ILogService
private
readonly
:
,
)
{
super
(
)
;
}
/**
* Marks a fresh worktree-isolation session as pending — its worktree is
* deferred to the first send. Called by the host while a creating session's
* resolved config selects `worktree` isolation.
*/
notePending
(
:
string
)
:
void
{
if
(
!
this
.
.
has
(
)
)
{
this
.
.
add
(
)
;
this
.
.
fire
(
)
;
}
}
/** Clears a pending marker when a session will not materialize a worktree. */
clearPending
(
:
string
)
:
void
{
if
(
this
.
.
delete
(
)
)
{
this
.
.
fire
(
)
;
}
}
/**
* Whether a session's worktree is still pending creation. Consumers inject
* the worktree service and defer materialization until the host resolves it.
*/
isWorkingDirectoryPending
(
:
string
)
:
boolean
{
return
this
.
.
has
(
)
;
}
/** The worktree created for a session in this process, if any. */
getResolvedWorktree
(
:
string
)
:
URI
|
undefined
{
return
this
.
.
get
(
)
?.
;
}
/**
* First-send worktree resolution: creates the worktree (when the session
* selected `worktree` isolation on a git repo) and clears the pending marker
* regardless of outcome, so a failed creation falls back to folder isolation
* instead of leaving the session permanently "pending". Delegates to
* {@link resolveWorkingDirectory}, which is idempotent per session.
*/
async
resolveOnFirstSend
(
:
)
:
Promise
<
URI
|
undefined
>
{
return
this
.
.
queue
(
.
,
async
(
)
=>
{
try
{
return
await
this
.
resolveWorkingDirectory
(
)
;
}
finally
{
this
.
clearPending
(
.
)
;
}
}
)
;
}
/**
* Builds the `isolation` / `branch` schema contribution for
* `resolveSessionConfig`. When {@link IResolveIsolationConfigRequest.workingDirectory}
* is not a git repository (or has no commits yet) isolation is forced to
* `folder` and no branch property is offered.
*/
/**
* Branch-name completions for the branch picker. Callers forward this from
* their `sessionConfigCompletions` when the requested property is
* {@link SessionConfigKey.Branch}.
*/
async
branchCompletions
(
:
URI
|
undefined
,
?
:
string
)
:
Promise
<
{
:
{
:
string
;
:
string
}
[
]
}
>
{
if
(
!
)
{
return
{
:
[
]
}
;
}
const
[
,
,
]
=
await
Promise
.
all
(
[
this
.
.
getBranches
(
,
{
:
[
'refs/heads'
]
,
:
'committerdate'
}
)
,
this
.
.
getCurrentBranch
(
)
,
this
.
.
getDefaultBranch
(
)
,
]
)
;
const
=
getBranchCompletions
(
.
map
(
=>
.
)
,
{
,
:
?.
,
,
:
BRANCH_COMPLETION_LIMIT
,
}
)
;
return
{
:
.
map
(
=>
(
{
:
,
:
}
)
)
}
;
}
/**
* Resolves the effective working directory for a session that is about to
* be materialized. When the session config selects `worktree` isolation on
* a git repository, creates or checks out a branch in a worktree, records it for
* cleanup, queues the first-turn announcement, persists the worktree
* metadata, and returns the worktree URI. Otherwise returns the requested
* working directory unchanged.
*/
async
resolveWorkingDirectory
(
:
)
:
Promise
<
URI
|
undefined
>
{
const
{
,
,
,
,
,
,
}
=
;
if
(
?.
[
.
]
!==
'worktree'
||
!
||
typeof
[
.
]
!==
'string'
)
{
return
;
}
// Idempotent: if a worktree was already created for this session in this
// process (e.g. the caller re-enters materialization after a thread
// restart or a post-creation failure) reuse it rather than creating a
// second branch + worktree.
const
=
this
.
.
get
(
)
;
if
(
)
{
return
.
;
}
?.
(
buildWorktreeProgressText
(
.
)
)
;
const
=
await
this
.
.
getRepositoryRoot
(
)
;
if
(
!
)
{
return
;
}
const
=
await
this
.
_resolvePrimaryWorktreeRoot
(
,
)
;
const
=
[
.
]
as
string
;
const
=
[
.
]
===
true
;
const
=
[
.
]
!==
false
;
// Prefix (e.g. the user's `git.branchPrefix`) the client forwards for
// worktree-isolated sessions. Prepended ahead of the built-in `agents/`
// prefix when naming the branch and stripped from the worktree dir name.
const
=
&&
typeof
[
.
]
===
'string'
?
[
.
]
as
string
:
undefined
;
const
{
,
,
}
=
await
this
.
.
queue
(
.
toString
(
)
,
async
(
)
=>
{
const
=
getWorktreesRoot
(
)
;
if
(
)
{
?.
(
buildWorktreeProgressText
(
.
)
)
;
}
const
=
?
await
this
.
.
generateBranchName
(
{
,
:
,
,
:
,
branchNameCollides
:
async
=>
{
if
(
await
this
.
.
branchExists
(
,
)
.
catch
(
(
)
=>
true
)
)
{
return
true
;
}
const
=
URI
.
joinPath
(
,
getWorktreeName
(
,
)
)
;
return
fileExists
(
.
)
;
}
,
}
)
:
undefined
;
const
=
await
this
.
_resolveBranchStartPoint
(
,
)
;
const
=
?
:
(
await
this
.
.
getDefaultBranch
(
)
)
?.
;
// Git suppresses progress for the first couple of seconds, so name
// the phase up front rather than leaving the label stale until the
// first percentage arrives.
?.
(
buildWorktreeProgressText
(
.
)
)
;
await
.
mkdir
(
.
,
{
:
true
}
)
;
const
=
URI
.
joinPath
(
,
getWorktreeName
(
??
,
)
)
;
await
withPercentProgress
(
.
,
,
=>
this
.
.
addWorktree
(
,
{
:
,
:
?
:
,
,
:
,
:
,
:
,
}
)
)
;
return
{
:
??
,
,
}
;
}
)
;
const
=
Array
.
isArray
(
[
.
]
)
&&
[
.
]
.
every
(
=>
typeof
===
'string'
)
?
[
.
]
as
readonly
string
[
]
:
undefined
;
if
(
?.
)
{
try
{
?.
(
buildWorktreeProgressText
(
.
)
)
;
await
withPercentProgress
(
.
,
,
=>
this
.
.
copyWorktreeIncludeFiles
(
,
,
,
)
)
;
}
catch
(
)
{
this
.
.
warn
(
`[${this._logLabel}:${sessionId}] Failed to copy worktree include files: ${errorMessage(error)}`
)
;
}
}
this
.
.
set
(
,
{
,
:
}
)
;
// Queue the worktree announcement so the first turn (live) and any
// subsequent restore (history) both surface the message in the chat.
this
.
.
set
(
,
buildWorktreeAnnouncementText
(
)
)
;
try
{
await
this
.
_writeWorktreeMetadata
(
,
{
,
,
,
}
)
;
}
catch
(
)
{
this
.
.
warn
(
`[${this._logLabel}:${sessionId}] Failed to persist worktree branch metadata: ${errorMessage(error)}`
)
;
}
return
;
}
/** Resolves a persisted working directory, repairing a removed worktree when possible. */
async
resolveWorkingDirectoryForResume
(
:
URI
,
:
string
,
:
URI
)
:
Promise
<
URI
>
{
return
this
.
.
queue
(
,
(
)
=>
this
.
_resolveWorkingDirectoryForResume
(
,
,
)
)
;
}
private
async
_resolveWorkingDirectoryForResume
(
:
URI
,
:
string
,
:
URI
)
:
Promise
<
URI
>
{
if
(
.
!==
.
)
{
return
;
}
try
{
await
.
access
(
.
)
;
return
;
}
catch
{
// Repair or fall back below.
}
const
=
await
this
.
_readWorktreeMetadata
(
)
.
catch
(
(
)
=>
undefined
)
;
const
=
await
this
.
_isSessionArchived
(
)
;
if
(
)
{
if
(
?.
)
{
try
{
await
.
access
(
.
.
)
;
this
.
.
info
(
`[${this._logLabel}:${sessionId}] Archived session working directory '${workingDirectory.fsPath}' is missing; resuming against repository root '${meta.repositoryRoot.fsPath}' for history`
)
;
return
.
;
}
catch
{
// Fall through when the repository root is also gone.
}
}
this
.
.
warn
(
`[${this._logLabel}:${sessionId}] Cannot resume archived session: working directory '${workingDirectory.fsPath}' is missing and no usable repository-root fallback was found`
)
;
throw
new
SessionWorkingDirectoryMissingError
(
)
;
}
let
:
string
|
undefined
;
if
(
?.
&&
.
)
{
const
{
,
,
}
=
;
const
=
await
this
.
_recreateWorktree
(
,
{
,
,
}
)
;
if
(
.
)
{
this
.
.
info
(
`[${this._logLabel}:${sessionId}] Recreated missing worktree '${worktreePath.fsPath}' for a live session on resume`
)
;
return
;
}
=
.
;
}
this
.
.
warn
(
`[${this._logLabel}:${sessionId}] Cannot resume: working directory '${workingDirectory.fsPath}' is missing and its worktree could not be recreated${recreateFailureReason ?`: ${recreateFailureReason}`:''}`
)
;
throw
new
SessionWorkingDirectoryMissingError
(
,
)
;
}
/**
* Takes (and clears) the pending "worktree created" announcement for a
* session so callers can emit it live as the first response part on the
* first turn. Returns `undefined` when the session has no pending
* announcement.
*/
takePendingAnnouncement
(
:
string
)
:
string
|
undefined
{
const
=
this
.
.
get
(
)
;
if
(
!==
undefined
)
{
this
.
.
delete
(
)
;
}
return
;
}
async
persistCreationFailure
(
:
URI
,
:
string
,
:
string
|
undefined
)
:
Promise
<
void
>
{
const
=
this
.
.
openDatabase
(
)
;
try
{
await
.
.
setMetadata
(
WORKTREE_META_CREATION_FAILURE
,
JSON
.
stringify
(
{
,
:
normalizeWorktreeFailureDiagnostic
(
)
,
}
)
)
;
}
finally
{
.
dispose
(
)
;
}
}
/**
* Re-injects the applicable worktree notice into the first restored turn.
*
* The live path ({@link takePendingAnnouncement}) handles the very first
* turn while the session is fresh; this path takes over on subsequent loads
* (where the synthetic announcement is not part of the agent transcript).
*/
async
applyRestoreAnnouncement
(
:
URI
,
:
readonly
[
]
)
:
Promise
<
readonly
[
]
>
{
const
=
await
this
.
_readWorktreeNotice
(
)
.
catch
(
(
)
=>
undefined
)
;
if
(
?.
===
'failure'
)
{
return
prependWorktreeFailureToFirstTurn
(
,
.
)
;
}
if
(
?.
!==
'success'
)
{
return
;
}
return
prependAnnouncementToFirstTurn
(
,
buildWorktreeAnnouncementText
(
.
)
)
;
}
/** Resolves the worktree to remove before the session database is deleted. */
async
prepareSessionDeletion
(
:
URI
,
:
string
)
:
Promise
<
|
undefined
>
{
return
this
.
.
queue
(
,
async
(
)
=>
{
const
=
this
.
.
get
(
)
;
if
(
)
{
return
;
}
const
=
this
.
.
get
(
)
;
if
(
)
{
return
;
}
try
{
const
=
await
this
.
_readWorktreeMetadata
(
)
;
return
?.
&&
.
?
{
:
.
,
:
.
}
:
undefined
;
}
catch
(
)
{
this
.
.
warn
(
`[${this._logLabel}:${sessionId}] Failed to read worktree metadata before session deletion: ${errorMessage(error)}`
)
;
throw
;
}
}
)
;
}
/** Force-removes the resolved worktree after the user confirms session deletion. */
async
removeSessionWorktree
(
:
string
,
:
|
undefined
)
:
Promise
<
void
>
{
return
this
.
.
queue
(
,
(
)
=>
this
.
_removeSessionWorktree
(
,
)
)
;
}
private
async
_removeSessionWorktree
(
:
string
,
:
|
undefined
)
:
Promise
<
void
>
{
this
.
clearPending
(
)
;
if
(
!
)
{
return
;
}
try
{
await
this
.
.
removeWorktree
(
.
,
.
,
{
:
true
}
)
;
this
.
.
delete
(
)
;
this
.
.
delete
(
)
;
}
catch
(
)
{
this
.
.
set
(
,
)
;
this
.
.
warn
(
`[${this._logLabel}:${sessionId}] Failed to remove worktree '${worktree.worktree.fsPath}': ${errorMessage(error)}`
)
;
throw
;
}
}
/**
* On archive, removes the worktree directory when its branch is preserved
* and the working tree is clean, so the worktree can be recreated on
* unarchive without losing work. Skips the removal when the branch is
* missing or the tree is dirty.
*/
async
cleanupWorktreeOnArchive
(
:
URI
,
:
string
)
:
Promise
<
void
>
{
return
this
.
.
queue
(
,
(
)
=>
this
.
_cleanupWorktreeOnArchive
(
,
)
)
;
}
private
async
_cleanupWorktreeOnArchive
(
:
URI
,
:
string
)
:
Promise
<
void
>
{
const
=
await
this
.
_readWorktreeMetadata
(
)
.
catch
(
(
)
=>
undefined
)
;
if
(
!
?.
||
!
.
)
{
return
;
}
const
{
,
,
}
=
;
// Skip if the worktree directory is already gone — nothing to clean.
try
{
await
.
access
(
.
)
;
}
catch
{
this
.
.
delete
(
)
;
return
;
}
// Skip if the branch is missing — without it we can't safely recreate
// the worktree on unarchive, so leave the working tree intact.
const
=
await
this
.
.
branchExists
(
,
)
.
catch
(
(
)
=>
false
)
;
if
(
!
)
{
this
.
.
info
(
`[${this._logLabel}:${sessionId}] Skipping worktree cleanup: branch '${branchName}' is missing`
)
;
return
;
}
// Commit any uncommitted changes before archiving the session
const
=
await
this
.
.
hasUncommittedChanges
(
)
.
catch
(
(
)
=>
true
)
;
if
(
)
{
try
{
await
this
.
.
commitAll
(
,
localize
(
'worktreeIsolation.commitMessage'
,
'Saving uncommitted changes before archiving session'
)
)
;
}
catch
(
)
{
this
.
.
warn
(
`[${this._logLabel}:${sessionId}] Failed to commit uncommitted changes in '${worktreePath.fsPath}': ${errorMessage(error)}`
)
;
return
;
}
}
try
{
await
this
.
.
removeWorktree
(
,
,
{
:
true
}
)
;
this
.
.
info
(
`[${this._logLabel}:${sessionId}] Removed worktree '${worktreePath.fsPath}' on archive`
)
;
this
.
.
delete
(
)
;
}
catch
(
)
{
this
.
.
warn
(
`[${this._logLabel}:${sessionId}] Failed to remove worktree '${worktreePath.fsPath}' on archive: ${errorMessage(error)}`
)
;
}
}
/**
* On unarchive, recreates a previously cleaned-up worktree against its
* preserved branch. No-op when the directory still exists or the branch is
* missing.
*/
async
recreateWorktreeOnUnarchive
(
:
URI
,
:
string
)
:
Promise
<
void
>
{
return
this
.
.
queue
(
,
(
)
=>
this
.
_recreateWorktreeOnUnarchive
(
,
)
)
;
}
private
async
_recreateWorktreeOnUnarchive
(
:
URI
,
:
string
)
:
Promise
<
void
>
{
const
=
await
this
.
_readWorktreeMetadata
(
)
.
catch
(
(
)
=>
undefined
)
;
if
(
!
?.
||
!
.
)
{
return
;
}
// Skip if the worktree directory already exists — nothing to do.
try
{
await
.
access
(
.
.
)
;
return
;
}
catch
{
// expected when the worktree was cleaned up on archive
}
const
{
,
,
}
=
;
await
this
.
_recreateWorktree
(
,
{
,
,
}
)
;
}
private
async
_recreateWorktree
(
:
string
,
:
{
readonly
:
string
;
readonly
:
URI
;
readonly
:
URI
}
)
:
Promise
<
{
readonly
:
true
}
|
{
readonly
:
false
;
readonly
:
string
}
>
{
const
{
,
,
}
=
;
const
=
await
this
.
.
branchExists
(
,
)
.
catch
(
(
)
=>
false
)
;
if
(
!
)
{
const
=
localize
(
'worktreeRecreateBranchMissing'
,
"the branch '{0}' no longer exists"
,
)
;
this
.
.
info
(
`[${this._logLabel}:${sessionId}] Cannot recreate worktree: branch '${branchName}' is missing`
`[${this._logLabel}:${sessionId}] Failed to recreate worktree '${worktreePath.fsPath}': ${reason}`
)
;
return
{
:
false
,
}
;
}
}
/** Reads the persisted worktree metadata for a session, if any. */
async
readWorktreeMetadata
(
:
URI
)
:
Promise
<
|
undefined
>
{
return
this
.
_readWorktreeMetadata
(
)
;
}
/**
* Bridges worktree metadata for a legacy session adopted in place, whose
* working directory is a pre-existing git worktree the agent host did not
* create. When `workingDirectory` is a linked worktree (its checkout root
* differs from the repository's primary worktree root), persists the worktree
* branch / path / repository-root (and diff base branch) so the adopted
* session groups under its repository and computes diffs against the right
* base — parity with natively worktree-isolated sessions. Deliberately does
* NOT register the worktree as host-created, so disposing the session never
* deletes the user-owned worktree. Returns `true` when metadata was recorded.
*/
async
adoptExistingWorktreeMetadata
(
:
URI
,
:
URI
)
:
Promise
<
boolean
>
{
const
=
await
this
.
_resolveLinkedWorktree
(
)
;
if
(
!
)
{
return
false
;
}
const
{
,
,
}
=
;
const
=
await
this
.
.
getCurrentBranch
(
)
.
catch
(
(
)
=>
undefined
)
??
'HEAD'
;
await
this
.
_writeWorktreeMetadata
(
,
{
,
,
:
,
:
}
)
;
return
true
;
}
/**
* Records worktree identity supplied by a predecessor for an adopted session whose
* checkout is gone, so resume recreates it exactly like a native worktree session.
* Values come from the predecessor's own record rather than probing the (missing)
* directory, which is what {@link adoptExistingWorktreeMetadata} requires.
*/
async
recordAdoptedWorktreeMetadata
(
:
URI
,
:
{
readonly
:
string
;
readonly
:
string
|
undefined
;
readonly
:
URI
;
readonly
:
URI
}
)
:
Promise
<
void
>
{
this
.
.
info
(
`[${this._logLabel}:${AgentSession.id(sessionUri)}] Recorded adopted worktree metadata: worktree='${metadata.worktreePath.fsPath}' branch='${metadata.branchName}' base='${metadata.baseBranch ??'(none)'}' repo='${metadata.repositoryRoot.fsPath}'`
)
;
await
this
.
_writeWorktreeMetadata
(
,
)
;
}
/**
* Records repository identity for an externally-owned linked worktree without taking ownership of its lifecycle.
*/
async
recordExternalWorktreeProject
(
:
URI
,
:
URI
)
:
Promise
<
|
undefined
>
{
const
=
await
this
.
_resolveLinkedWorktree
(
)
;
if
(
!
)
{
return
undefined
;
}
const
{
,
}
=
;
const
=
this
.
.
openDatabase
(
)
;
try
{
const
:
Promise
<
void
>
[
]
=
[
.
.
setMetadata
(
WORKTREE_META_REPOSITORY_ROOT
,
.
toString
(
)
)
,
]
;
if
(
)
{
.
push
(
.
.
setMetadata
(
META_DIFF_BASE_BRANCH
,
)
)
;
}
await
Promise
.
all
(
)
;
}
finally
{
.
dispose
(
)
;
}
return
projectFromRepositoryRoot
(
)
;
}
private
async
_resolveLinkedWorktree
(
:
URI
)
:
Promise
<
{
:
URI
;
:
URI
;
:
string
|
undefined
}
|
undefined
>
{
const
=
await
this
.
.
getRepositoryRoot
(
)
.
catch
(
(
)
=>
undefined
)
;
if
(
!
)
{
return
undefined
;
}
const
=
await
tryResolvePrimaryWorktreeRoot
(
this
.
,
)
.
catch
(
(
)
=>
undefined
)
;
if
(
!
||
isEqual
(
,
)
)
{
return
undefined
;
}
const
=
(
await
this
.
.
getDefaultBranch
(
)
.
catch
(
(
)
=>
undefined
)
)
?.
;
return
{
,
,
}
;
}
/**
* Resolves the repository "project" for a worktree-isolated session from its
* persisted worktree metadata. Worktree sessions run out of a
* `<repo>.worktrees/<name>` directory, but in the sessions UI they must group
* under the *repository* (e.g. `vscode`) — not the worktree folder — exactly
* like Copilot. Returns the repository root as the project so agents can merge
* it into the `project` field of the `IAgentSessionMetadata` reported from
* `listSessions` / `getSessionMetadata`; without it a list refresh clears the
* transient project set by the materialize event and the workspace reverts to
* the worktree directory name. Returns `undefined` for sessions that were never
* worktree-isolated, leaving the caller's own folder-based project untouched.
*/
async
resolveWorktreeProject
(
:
URI
)
:
Promise
<
|
undefined
>
{
const
=
await
this
.
_readWorktreeMetadata
(
)
.
catch
(
(
)
=>
undefined
)
;
return
?.
?
projectFromRepositoryRoot
(
.
)
:
undefined
;
}
private
async
_resolvePrimaryWorktreeRoot
(
:
URI
,
:
URI
)
:
Promise
<
URI
>
{
try
{
return
await
tryResolvePrimaryWorktreeRoot
(
this
.
,
)
??
;
}
catch
(
)
{
this
.
.
warn
(
`[${this._logLabel}] Failed to resolve primary worktree for '${checkoutRoot.fsPath}': ${errorMessage(error)}`
)
;
return
;
}
}
/**
* Synchronous companion to {@link resolveWorktreeProject} for the
* materialize-event path: the repository project for a worktree this agent
* created in the current process, or `undefined` when the session has none.
* Lets an agent supply the materialize event's `project` without an async
* metadata read so a fresh worktree groups under the repository the moment it
* materializes.
*/
sessionWorktreeProject
(
:
string
)
:
|
undefined
{
const
=
this
.
.
get
(
)
;
return
?
projectFromRepositoryRoot
(
.
)
:
undefined
;
}
private
async
_getGitInfo
(
:
URI
)
:
Promise
<
{
:
string
;
:
}
|
undefined
>
{
const
=
await
this
.
.
getRepositoryRoot
(
)
;
if
(
!
)
{
return
undefined
;
}
// Skip worktree isolation for a repo with no commits yet (unborn HEAD); `git worktree add` would fail.
const
=
await
this
.
.
revParse
(
,
'HEAD'
)
.
catch
(
(
)
=>
undefined
)
;
if
(
!
)
{
return
undefined
;
}
const
=
await
this
.
.
getCurrentBranch
(
)
??
'HEAD'
;
const
=
await
this
.
.
getDefaultBranch
(
)
??
{
:
,
:
}
;
return
{
,
}
;
}
private
async
_resolveBranchStartPoint
(
:
URI
,
:
string
)
:
Promise
<
string
>
{
const
=
await
this
.
.
getDefaultBranch
(
)
;
return
?.
===
?
.
:
;
}
private
async
_writeWorktreeMetadata
(
:
URI
,
:
{
:
string
;
:
string
|
undefined
;
:
URI
;
:
URI
}
)
:
Promise
<
void
>
{
const
=
this
.
.
openDatabase
(
)
;
try
{
const
:
Promise
<
void
>
[
]
=
[
.
.
setMetadata
(
WORKTREE_META_BRANCH
,
.
)
,
.
.
setMetadata
(
WORKTREE_META_PATH
,
.
.
toString
(
)
)
,
.
.
setMetadata
(
WORKTREE_META_REPOSITORY_ROOT
,
.
.
toString
(
)
)
,
]
;
if
(
.
)
{
.
push
(
.
.
setMetadata
(
META_DIFF_BASE_BRANCH
,
.
)
)
;
}
await
Promise
.
all
(
)
;
}
finally
{
.
dispose
(
)
;
}
}
/**
* Reads persisted worktree metadata, canonicalizing, repairing, and persisting the repository root when needed.
* It probes an existing worktree when available and otherwise falls back to the persisted root for archived sessions.
* The repair is only reachable when {@link WORKTREE_META_BRANCH} is present, so a root
* persisted without its branch will never heal.
*/
private
async
_readWorktreeMetadata
(
:
URI
)
:
Promise
<
|
undefined
>
{
const
=
await
this
.
.
tryOpenDatabase
(
)
;
if
(
!
)
{
return
undefined
;
}
try
{
const
[
,
,
,
]
=
await
Promise
.
all
(
[
.
.
getMetadata
(
WORKTREE_META_BRANCH
)
,
.
.
getMetadata
(
WORKTREE_META_PATH
)
,
.
.
getMetadata
(
WORKTREE_META_REPOSITORY_ROOT
)
,
.
.
getMetadata
(
LEGACY_WORKTREE_META_WORKING_DIRECTORY
)
,
]
)
;
if
(
!
)
{
return
undefined
;
}
const
=
?
URI
.
parse
(
)
:
?
URI
.
parse
(
)
:
undefined
;
let
=
?
URI
.
parse
(
)
:
?
deriveRepositoryRootFromWorktree
(
)
:
undefined
;
if
(
)
{
const
=
&&
await
fileExists
(
.
)
?
:
;
const
=
await
this
.
_resolvePrimaryWorktreeRoot
(
,
)
;
if
(
.
toString
(
)
!==
.
toString
(
)
)
{
=
;
try
{
await
.
.
setMetadata
(
WORKTREE_META_REPOSITORY_ROOT
,
.
toString
(
)
)
;
}
catch
(
)
{
this
.
.
warn
(
`[${this._logLabel}] Failed to normalize worktree repository metadata for '${sessionUri.toString()}': ${errorMessage(error)}`
)
;
}
}
}
return
{
,
,
}
;
}
finally
{
.
dispose
(
)
;
}
}
private
async
_readWorktreeNotice
(
:
URI
)
:
Promise
<
{
:
'success'
;
:
string
}
|
{
:
'failure'
;
?
:
string
}
|
undefined
>
{
const
=
await
this
.
.
tryOpenDatabase
(
)
;
if
(
!
)
{
return
undefined
;
}
try
{
const
[
,
]
=
await
Promise
.
all
(
[
.
.
getMetadata
(
WORKTREE_META_BRANCH
)
,
.
.
getMetadata
(
WORKTREE_META_CREATION_FAILURE
)
,
]
)
;
if
(
)
{
return
{
:
'success'
,
}
;
}
if
(
!
)
{
return
undefined
;
}
const
=
JSON
.
parse
(
)
;
if
(
!
||
typeof
!==
'object'
||
Array
.
isArray
(
)
)
{
return
undefined
;
}
const
=
as
<
string
,
unknown
>
;
if
(
[
'sessionId'
]
!==
.
id
(
)
)
{
return
undefined
;
}
return
{
:
'failure'
,
:
typeof
[
'diagnostic'
]
===
'string'
?
normalizeWorktreeFailureDiagnostic
(
[
'diagnostic'
]
)
:
undefined
,
}
;
}
finally
{
.
dispose
(
)
;
}
}
private
async
_isSessionArchived
(
:
URI
)
:
Promise
<
boolean
>
{
const
=
await
this
.
.
tryOpenDatabase
(
)
;
if
(
!
)
{
return
false
;
}
try
{
const
[
,
]
=
await
Promise
.
all
(
[
.
.
getMetadata
(
AH_META_IS_ARCHIVED_DB_KEY
)
,
.
.
getMetadata
(
AH_META_IS_DONE_DB_KEY
)
,
]
)
;
return
!==
undefined
?
===
'true'
:
===
'true'
;
}
finally
{
.
dispose
(
)
;
}
}
}
export
class
NullAgentHostWorktreeIsolation
implements
IAgentHostWorktreeIsolation
{
declare
readonly
:
undefined
;
readonly
:
boolean
=
false
;
readonly
=
.
;
isWorkingDirectoryPending
(
:
string
)
:
boolean
{
return
false
;
}
notePending
(
:
string
)
:
void
{
}
clearPending
(
:
string
)
:
void
{
}
getResolvedWorktree
(
:
string
)
:
URI
|
undefined
{
return
undefined
;
}
async
resolveOnFirstSend
(
:
)
:
Promise
<
URI
|
undefined
>
{
return
undefined
;
}
async
resolveIsolationConfig
(
:
)
:
Promise
<
|
undefined
>
{
return
undefined
;
}
async
branchCompletions
(
:
URI
|
undefined
,
?
:
string
)
:
Promise
<
{
:
{
:
string
;
:
string
}
[
]
}
>
{
return
{
:
[
]
}
;
}
async
resolveWorkingDirectoryForResume
(
:
URI
,
:
string
,
:
URI
)
:
Promise
<
URI
>
{
return
;
}
takePendingAnnouncement
(
:
string
)
:
string
|
undefined
{
return
undefined
;
}
async
persistCreationFailure
(
:
URI
,
:
string
,
:
string
|
undefined
)
:
Promise
<
void
>
{
}
async
applyRestoreAnnouncement
(
:
URI
,
:
readonly
[
]
)
:
Promise
<
readonly
[
]
>
{
return
;
}
async
prepareSessionDeletion
(
:
URI
,
:
string
)
:
Promise
<
|
undefined
>
{
return
undefined
;
}
async
removeSessionWorktree
(
:
string
,
:
|
undefined
)
:
Promise
<
void
>
{
}
async
cleanupWorktreeOnArchive
(
:
URI
,
:
string
)
:
Promise
<
void
>
{
}
async
recreateWorktreeOnUnarchive
(
:
URI
,
:
string
)
:
Promise
<
void
>
{
}
async
readWorktreeMetadata
(
:
URI
)
:
Promise
<
|
undefined
>
{
return
undefined
;
}
async
adoptExistingWorktreeMetadata
(
:
URI
,
:
URI
)
:
Promise
<
boolean
>
{
return
false
;
}
async
recordAdoptedWorktreeMetadata
(
:
URI
,
:
{
readonly
:
string
;
readonly
:
string
|
undefined
;
readonly
:
URI
;
readonly
:
URI
}
)
:
Promise
<
void
>
{
}
async
recordExternalWorktreeProject
(
:
URI
,
:
URI
)
:
Promise
<
|
undefined
>
{
return
undefined
;
}
async
resolveWorktreeProject
(
:
URI
)
:
Promise
<
|
undefined
>
{
return
undefined
;
}
sessionWorktreeProject
(
:
string
)
:
|
undefined
{
return
undefined
;
}
}
/**
* Derives the repository {@link IAgentSessionProjectInfo} from a repository
* root URI. The display name is the repo directory's basename (falling back to
* the URI string for pathological roots), matching how Copilot names the
* project via `resolveGitProject`.
*/
function
projectFromRepositoryRoot
(
:
URI
)
:
{
return
{
:
,
:
basename
(
.
)
||
.
toString
(
)
}
;
}
function
deriveRepositoryRootFromWorktree
(
:
URI
)
:
URI
|
undefined
{
if
(
.
!==
.
)
{
return
undefined
;
}
const
=
URI
.
joinPath
(
,
'..'
)
;
const
=
basename
(
.
)
;
const
=
'.worktrees'
;
if
(
!
.
endsWith
(
)
)
{
return
undefined
;
}
const
=
.
slice
(
0
,
-
.
)
;
return
?
URI
.
joinPath
(
,
'..'
,
)
:
undefined
;
}
/**
* Builds the repository {@link IAgentSessionProjectInfo} from a persisted
* {@link WORKTREE_META_REPOSITORY_ROOT} value (a URI string), or `undefined`
* when absent. Lets the host merge the repository project into a session's
* catalog entry directly from a metadata batch it already read, without a
* second database open.
*/