@gitkraken/core-gitlens 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -1
- package/dist/git/cache.d.ts +38 -8
- package/dist/git/cache.d.ts.map +1 -1
- package/dist/git/cache.js +120 -55
- package/dist/git/cache.js.map +1 -1
- package/dist/git/context.d.ts +19 -0
- package/dist/git/context.d.ts.map +1 -1
- package/dist/git/context.js.map +1 -1
- package/dist/git/features.d.ts +1 -1
- package/dist/git/features.d.ts.map +1 -1
- package/dist/git/features.js +1 -0
- package/dist/git/features.js.map +1 -1
- package/dist/git/models/commit.d.ts.map +1 -1
- package/dist/git/models/commit.js.map +1 -1
- package/dist/git/models/graph.d.ts +96 -0
- package/dist/git/models/graph.d.ts.map +1 -1
- package/dist/git/models/graph.js +24 -1
- package/dist/git/models/graph.js.map +1 -1
- package/dist/git/models/reference.d.ts +31 -0
- package/dist/git/models/reference.d.ts.map +1 -1
- package/dist/git/models/remote.d.ts.map +1 -1
- package/dist/git/models/remote.js.map +1 -1
- package/dist/git/models/remoteProvider.d.ts +1 -0
- package/dist/git/models/remoteProvider.d.ts.map +1 -1
- package/dist/git/models/remoteProvider.js.map +1 -1
- package/dist/git/models/repository.d.ts +30 -13
- package/dist/git/models/repository.d.ts.map +1 -1
- package/dist/git/models/repository.js +89 -87
- package/dist/git/models/repository.js.map +1 -1
- package/dist/git/models/search.d.ts +2 -2
- package/dist/git/models/search.d.ts.map +1 -1
- package/dist/git/models/statusFile.d.ts +9 -0
- package/dist/git/models/statusFile.d.ts.map +1 -1
- package/dist/git/models/statusFile.js +11 -0
- package/dist/git/models/statusFile.js.map +1 -1
- package/dist/git/models/worktree.d.ts +4 -1
- package/dist/git/models/worktree.d.ts.map +1 -1
- package/dist/git/models/worktree.js +2 -2
- package/dist/git/models/worktree.js.map +1 -1
- package/dist/git/parsers/diffParser.d.ts.map +1 -1
- package/dist/git/parsers/diffParser.js.map +1 -1
- package/dist/git/providers/branches.d.ts +15 -4
- package/dist/git/providers/branches.d.ts.map +1 -1
- package/dist/git/providers/commits.d.ts +4 -0
- package/dist/git/providers/commits.d.ts.map +1 -1
- package/dist/git/providers/config.d.ts +5 -4
- package/dist/git/providers/config.d.ts.map +1 -1
- package/dist/git/providers/operations.d.ts +61 -12
- package/dist/git/providers/operations.d.ts.map +1 -1
- package/dist/git/providers/pausedOperations.d.ts +3 -1
- package/dist/git/providers/pausedOperations.d.ts.map +1 -1
- package/dist/git/providers/refs.d.ts +23 -2
- package/dist/git/providers/refs.d.ts.map +1 -1
- package/dist/git/providers/staging.d.ts +16 -0
- package/dist/git/providers/staging.d.ts.map +1 -1
- package/dist/git/providers/status.d.ts +4 -1
- package/dist/git/providers/status.d.ts.map +1 -1
- package/dist/git/remotes/azure-devops.d.ts.map +1 -1
- package/dist/git/remotes/azure-devops.js.map +1 -1
- package/dist/git/remotes/custom.d.ts +2 -0
- package/dist/git/remotes/custom.d.ts.map +1 -1
- package/dist/git/remotes/custom.js +20 -0
- package/dist/git/remotes/custom.js.map +1 -1
- package/dist/git/{exec.types.d.ts → run.types.d.ts} +22 -3
- package/dist/git/run.types.d.ts.map +1 -0
- package/dist/git/run.types.js +2 -0
- package/dist/git/run.types.js.map +1 -0
- package/dist/git/service.d.ts.map +1 -1
- package/dist/git/service.js.map +1 -1
- package/dist/git/utils/autolink.utils.d.ts.map +1 -1
- package/dist/git/utils/autolink.utils.js.map +1 -1
- package/dist/git/utils/blame.utils.d.ts.map +1 -1
- package/dist/git/utils/blame.utils.js.map +1 -1
- package/dist/git/utils/conflictResolution.utils.d.ts +6 -0
- package/dist/git/utils/conflictResolution.utils.d.ts.map +1 -0
- package/dist/git/utils/conflictResolution.utils.js +25 -0
- package/dist/git/utils/conflictResolution.utils.js.map +1 -0
- package/dist/git/utils/contributor.utils.d.ts +3 -0
- package/dist/git/utils/contributor.utils.d.ts.map +1 -1
- package/dist/git/utils/contributor.utils.js +22 -0
- package/dist/git/utils/contributor.utils.js.map +1 -1
- package/dist/git/utils/fileStatus.utils.d.ts +2 -1
- package/dist/git/utils/fileStatus.utils.d.ts.map +1 -1
- package/dist/git/utils/fileStatus.utils.js +4 -0
- package/dist/git/utils/fileStatus.utils.js.map +1 -1
- package/dist/git/utils/reachability.utils.d.ts +37 -0
- package/dist/git/utils/reachability.utils.d.ts.map +1 -0
- package/dist/git/utils/reachability.utils.js +96 -0
- package/dist/git/utils/reachability.utils.js.map +1 -0
- package/dist/git/utils/search.utils.d.ts.map +1 -1
- package/dist/git/utils/search.utils.js +3 -0
- package/dist/git/utils/search.utils.js.map +1 -1
- package/dist/git/utils/sorting.d.ts +8 -0
- package/dist/git/utils/sorting.d.ts.map +1 -1
- package/dist/git/utils/sorting.js +15 -0
- package/dist/git/utils/sorting.js.map +1 -1
- package/dist/git/utils/status.utils.d.ts.map +1 -1
- package/dist/git/utils/status.utils.js.map +1 -1
- package/dist/git/watching/classifyChange.d.ts.map +1 -1
- package/dist/git/watching/classifyChange.js +8 -0
- package/dist/git/watching/classifyChange.js.map +1 -1
- package/dist/git/watching/gitIgnoreFilter.js +1 -1
- package/dist/git/watching/gitIgnoreFilter.js.map +1 -1
- package/dist/git/watching/initWatcher.d.ts.map +1 -1
- package/dist/git/watching/initWatcher.js.map +1 -1
- package/dist/git/watching/watchGroup.d.ts.map +1 -1
- package/dist/git/watching/watchGroup.js.map +1 -1
- package/dist/git/watching/watchService.d.ts +4 -2
- package/dist/git/watching/watchService.d.ts.map +1 -1
- package/dist/git/watching/watchService.js +31 -6
- package/dist/git/watching/watchService.js.map +1 -1
- package/dist/git/watching/watchSession.d.ts +14 -12
- package/dist/git/watching/watchSession.d.ts.map +1 -1
- package/dist/git/watching/watchSession.js +56 -55
- package/dist/git/watching/watchSession.js.map +1 -1
- package/dist/git-cli/exec/exec.types.d.ts +1 -1
- package/dist/git-cli/exec/exec.types.d.ts.map +1 -1
- package/dist/git-cli/exec/git.d.ts +3 -3
- package/dist/git-cli/exec/git.d.ts.map +1 -1
- package/dist/git-cli/exec/git.js.map +1 -1
- package/dist/git-cli/exec/gitQueue.d.ts +10 -2
- package/dist/git-cli/exec/gitQueue.d.ts.map +1 -1
- package/dist/git-cli/exec/gitQueue.js +39 -12
- package/dist/git-cli/exec/gitQueue.js.map +1 -1
- package/dist/git-cli/parsers/blameParser.d.ts.map +1 -1
- package/dist/git-cli/parsers/blameParser.js.map +1 -1
- package/dist/git-cli/parsers/logParser.js.map +1 -1
- package/dist/git-cli/parsers/refParser.d.ts +3 -30
- package/dist/git-cli/parsers/refParser.d.ts.map +1 -1
- package/dist/git-cli/parsers/refParser.js +30 -30
- package/dist/git-cli/parsers/refParser.js.map +1 -1
- package/dist/git-cli/providers/blame.d.ts.map +1 -1
- package/dist/git-cli/providers/blame.js.map +1 -1
- package/dist/git-cli/providers/branches.d.ts +15 -5
- package/dist/git-cli/providers/branches.d.ts.map +1 -1
- package/dist/git-cli/providers/branches.js +99 -68
- package/dist/git-cli/providers/branches.js.map +1 -1
- package/dist/git-cli/providers/commits.d.ts +1 -0
- package/dist/git-cli/providers/commits.d.ts.map +1 -1
- package/dist/git-cli/providers/commits.js +86 -30
- package/dist/git-cli/providers/commits.js.map +1 -1
- package/dist/git-cli/providers/config.d.ts +19 -6
- package/dist/git-cli/providers/config.d.ts.map +1 -1
- package/dist/git-cli/providers/config.js +86 -38
- package/dist/git-cli/providers/config.js.map +1 -1
- package/dist/git-cli/providers/diff.d.ts.map +1 -1
- package/dist/git-cli/providers/diff.js +5 -3
- package/dist/git-cli/providers/diff.js.map +1 -1
- package/dist/git-cli/providers/graph.d.ts.map +1 -1
- package/dist/git-cli/providers/graph.js +139 -16
- package/dist/git-cli/providers/graph.js.map +1 -1
- package/dist/git-cli/providers/operations.d.ts +17 -14
- package/dist/git-cli/providers/operations.d.ts.map +1 -1
- package/dist/git-cli/providers/operations.js +135 -63
- package/dist/git-cli/providers/operations.js.map +1 -1
- package/dist/git-cli/providers/patch.d.ts.map +1 -1
- package/dist/git-cli/providers/patch.js.map +1 -1
- package/dist/git-cli/providers/pausedOperations.d.ts +3 -1
- package/dist/git-cli/providers/pausedOperations.d.ts.map +1 -1
- package/dist/git-cli/providers/pausedOperations.js +7 -1
- package/dist/git-cli/providers/pausedOperations.js.map +1 -1
- package/dist/git-cli/providers/refs.d.ts +19 -2
- package/dist/git-cli/providers/refs.d.ts.map +1 -1
- package/dist/git-cli/providers/refs.js +286 -2
- package/dist/git-cli/providers/refs.js.map +1 -1
- package/dist/git-cli/providers/revision.js.map +1 -1
- package/dist/git-cli/providers/staging.d.ts +6 -0
- package/dist/git-cli/providers/staging.d.ts.map +1 -1
- package/dist/git-cli/providers/staging.js +32 -0
- package/dist/git-cli/providers/staging.js.map +1 -1
- package/dist/git-cli/providers/stash.d.ts.map +1 -1
- package/dist/git-cli/providers/stash.js +20 -2
- package/dist/git-cli/providers/stash.js.map +1 -1
- package/dist/git-cli/providers/status.d.ts +4 -1
- package/dist/git-cli/providers/status.d.ts.map +1 -1
- package/dist/git-cli/providers/status.js +8 -4
- package/dist/git-cli/providers/status.js.map +1 -1
- package/dist/git-cli/providers/tags.d.ts.map +1 -1
- package/dist/git-cli/providers/tags.js +10 -6
- package/dist/git-cli/providers/tags.js.map +1 -1
- package/dist/ipc/discovery.d.ts +49 -0
- package/dist/ipc/discovery.d.ts.map +1 -0
- package/dist/ipc/discovery.js +147 -0
- package/dist/ipc/discovery.js.map +1 -0
- package/dist/ipc/ipcServer.d.ts +20 -0
- package/dist/ipc/ipcServer.d.ts.map +1 -0
- package/dist/ipc/ipcServer.js +162 -0
- package/dist/ipc/ipcServer.js.map +1 -0
- package/dist/plus/agents/providers/claudeCodeProvider.d.ts +167 -0
- package/dist/plus/agents/providers/claudeCodeProvider.d.ts.map +1 -0
- package/dist/plus/agents/providers/claudeCodeProvider.js +1786 -0
- package/dist/plus/agents/providers/claudeCodeProvider.js.map +1 -0
- package/dist/plus/agents/providers/claudeCodeTranscript.d.ts +36 -0
- package/dist/plus/agents/providers/claudeCodeTranscript.d.ts.map +1 -0
- package/dist/plus/agents/providers/claudeCodeTranscript.js +171 -0
- package/dist/plus/agents/providers/claudeCodeTranscript.js.map +1 -0
- package/dist/plus/agents/sanitizePrompt.d.ts +15 -0
- package/dist/plus/agents/sanitizePrompt.d.ts.map +1 -0
- package/dist/plus/agents/sanitizePrompt.js +103 -0
- package/dist/plus/agents/sanitizePrompt.js.map +1 -0
- package/dist/plus/agents/stateMachine.d.ts +32 -0
- package/dist/plus/agents/stateMachine.d.ts.map +1 -0
- package/dist/plus/agents/stateMachine.js +180 -0
- package/dist/plus/agents/stateMachine.js.map +1 -0
- package/dist/plus/agents/types.d.ts +254 -0
- package/dist/plus/agents/types.d.ts.map +1 -0
- package/dist/plus/agents/types.js +49 -0
- package/dist/plus/agents/types.js.map +1 -0
- package/dist/plus/ai/errors.d.ts +4 -1
- package/dist/plus/ai/errors.d.ts.map +1 -1
- package/dist/plus/ai/errors.js +38 -0
- package/dist/plus/ai/errors.js.map +1 -1
- package/dist/plus/ai/models/model.d.ts +1 -1
- package/dist/plus/ai/models/model.d.ts.map +1 -1
- package/dist/plus/ai/models/model.js.map +1 -1
- package/dist/plus/ai/models/promptTemplates.d.ts +11 -2
- package/dist/plus/ai/models/promptTemplates.d.ts.map +1 -1
- package/dist/plus/ai/models/provider.d.ts +3 -0
- package/dist/plus/ai/models/provider.d.ts.map +1 -1
- package/dist/plus/ai/prompts.d.ts +1 -0
- package/dist/plus/ai/prompts.d.ts.map +1 -1
- package/dist/plus/ai/prompts.js +48 -8
- package/dist/plus/ai/prompts.js.map +1 -1
- package/dist/plus/ai/providers/gitkrakenProvider.d.ts +1 -1
- package/dist/plus/ai/providers/gitkrakenProvider.d.ts.map +1 -1
- package/dist/plus/ai/providers/gitkrakenProvider.js +4 -1
- package/dist/plus/ai/providers/gitkrakenProvider.js.map +1 -1
- package/dist/plus/ai/providers/openAICompatibleProviderBase.d.ts +4 -3
- package/dist/plus/ai/providers/openAICompatibleProviderBase.d.ts.map +1 -1
- package/dist/plus/ai/providers/openAICompatibleProviderBase.js +9 -6
- package/dist/plus/ai/providers/openAICompatibleProviderBase.js.map +1 -1
- package/dist/plus/ai/utils/ai.utils.d.ts.map +1 -1
- package/dist/plus/ai/utils/ai.utils.js +2 -0
- package/dist/plus/ai/utils/ai.utils.js.map +1 -1
- package/dist/plus/ai/utils/results.utils.d.ts.map +1 -1
- package/dist/plus/ai/utils/results.utils.js.map +1 -1
- package/dist/plus/git-github/api/github.d.ts +12 -1
- package/dist/plus/git-github/api/github.d.ts.map +1 -1
- package/dist/plus/git-github/api/github.js +245 -51
- package/dist/plus/git-github/api/github.js.map +1 -1
- package/dist/plus/git-github/api/types.d.ts +8 -0
- package/dist/plus/git-github/api/types.d.ts.map +1 -1
- package/dist/plus/git-github/models.d.ts +1 -1
- package/dist/plus/git-github/models.d.ts.map +1 -1
- package/dist/plus/git-github/models.js.map +1 -1
- package/dist/plus/git-github/providers/github/blame.d.ts.map +1 -1
- package/dist/plus/git-github/providers/github/blame.js.map +1 -1
- package/dist/plus/git-github/providers/github/branches.d.ts +5 -1
- package/dist/plus/git-github/providers/github/branches.d.ts.map +1 -1
- package/dist/plus/git-github/providers/github/branches.js +47 -24
- package/dist/plus/git-github/providers/github/branches.js.map +1 -1
- package/dist/plus/git-github/providers/github/commits.d.ts.map +1 -1
- package/dist/plus/git-github/providers/github/commits.js +144 -92
- package/dist/plus/git-github/providers/github/commits.js.map +1 -1
- package/dist/plus/git-github/providers/github/diff.d.ts +1 -1
- package/dist/plus/git-github/providers/github/diff.d.ts.map +1 -1
- package/dist/plus/git-github/providers/github/diff.js +23 -9
- package/dist/plus/git-github/providers/github/diff.js.map +1 -1
- package/dist/plus/git-github/providers/github/refs.d.ts +9 -1
- package/dist/plus/git-github/providers/github/refs.d.ts.map +1 -1
- package/dist/plus/git-github/providers/github/refs.js +39 -14
- package/dist/plus/git-github/providers/github/refs.js.map +1 -1
- package/dist/plus/git-github/providers/github/revision.d.ts.map +1 -1
- package/dist/plus/git-github/providers/github/revision.js +1 -2
- package/dist/plus/git-github/providers/github/revision.js.map +1 -1
- package/dist/plus/git-github/providers/github/status.d.ts +4 -1
- package/dist/plus/git-github/providers/github/status.d.ts.map +1 -1
- package/dist/plus/git-github/providers/github/status.js +1 -1
- package/dist/plus/git-github/providers/github/status.js.map +1 -1
- package/dist/plus/git-github/providers/github/tags.d.ts.map +1 -1
- package/dist/plus/git-github/providers/github/tags.js +35 -36
- package/dist/plus/git-github/providers/github/tags.js.map +1 -1
- package/dist/plus/git-github/providers/githubGitProvider.d.ts.map +1 -1
- package/dist/plus/git-github/providers/githubGitProvider.js.map +1 -1
- package/dist/utils/color.d.ts.map +1 -1
- package/dist/utils/color.js.map +1 -1
- package/dist/utils/date.d.ts.map +1 -1
- package/dist/utils/date.js +6 -0
- package/dist/utils/date.js.map +1 -1
- package/dist/utils/debounce.js +1 -1
- package/dist/utils/decorators/serializable.d.ts.map +1 -1
- package/dist/utils/decorators/serializable.js.map +1 -1
- package/dist/utils/dedupedAsyncCache.d.ts +37 -0
- package/dist/utils/dedupedAsyncCache.d.ts.map +1 -0
- package/dist/utils/dedupedAsyncCache.js +68 -0
- package/dist/utils/dedupedAsyncCache.js.map +1 -0
- package/dist/utils/diff.d.ts +2 -0
- package/dist/utils/diff.d.ts.map +1 -0
- package/dist/utils/diff.js +53 -0
- package/dist/utils/diff.js.map +1 -0
- package/dist/utils/disposable.d.ts.map +1 -1
- package/dist/utils/disposable.js.map +1 -1
- package/dist/utils/env/node/exec.d.ts.map +1 -1
- package/dist/utils/env/node/exec.js.map +1 -1
- package/dist/utils/error.d.ts.map +1 -1
- package/dist/utils/error.js.map +1 -1
- package/dist/utils/iterable.d.ts +7 -1
- package/dist/utils/iterable.d.ts.map +1 -1
- package/dist/utils/iterable.js +12 -4
- package/dist/utils/iterable.js.map +1 -1
- package/dist/utils/logger.d.ts.map +1 -1
- package/dist/utils/logger.js.map +1 -1
- package/dist/utils/lruMap.d.ts +9 -0
- package/dist/utils/lruMap.d.ts.map +1 -1
- package/dist/utils/lruMap.js +26 -4
- package/dist/utils/lruMap.js.map +1 -1
- package/dist/utils/markdown.d.ts.map +1 -1
- package/dist/utils/markdown.js.map +1 -1
- package/dist/utils/mru.d.ts.map +1 -1
- package/dist/utils/mru.js.map +1 -1
- package/dist/utils/object.d.ts +22 -1
- package/dist/utils/object.d.ts.map +1 -1
- package/dist/utils/object.js +56 -3
- package/dist/utils/object.js.map +1 -1
- package/dist/utils/paging.js +14 -15
- package/dist/utils/paging.js.map +1 -1
- package/dist/utils/path.d.ts.map +1 -1
- package/dist/utils/path.js.map +1 -1
- package/dist/utils/promise.d.ts +1 -0
- package/dist/utils/promise.d.ts.map +1 -1
- package/dist/utils/promise.js +17 -0
- package/dist/utils/promise.js.map +1 -1
- package/dist/utils/promiseCache.d.ts +10 -0
- package/dist/utils/promiseCache.d.ts.map +1 -1
- package/dist/utils/promiseCache.js +34 -4
- package/dist/utils/promiseCache.js.map +1 -1
- package/dist/utils/string.d.ts.map +1 -1
- package/dist/utils/string.js +1 -1
- package/dist/utils/string.js.map +1 -1
- package/dist/utils/uri.d.ts.map +1 -1
- package/dist/utils/uri.js.map +1 -1
- package/dist/utils/version.d.ts.map +1 -1
- package/dist/utils/version.js.map +1 -1
- package/package.json +13 -1
- package/src/git/cache.ts +192 -90
- package/src/git/context.ts +21 -0
- package/src/git/features.ts +2 -0
- package/src/git/models/commit.ts +1 -0
- package/src/git/models/graph.ts +97 -0
- package/src/git/models/reference.ts +33 -0
- package/src/git/models/remote.ts +1 -0
- package/src/git/models/remoteProvider.ts +1 -0
- package/src/git/models/repository.ts +105 -96
- package/src/git/models/search.ts +2 -2
- package/src/git/models/statusFile.ts +12 -0
- package/src/git/models/worktree.ts +10 -2
- package/src/git/parsers/diffParser.ts +2 -0
- package/src/git/providers/branches.ts +22 -4
- package/src/git/providers/commits.ts +4 -0
- package/src/git/providers/config.ts +3 -5
- package/src/git/providers/operations.ts +65 -1
- package/src/git/providers/pausedOperations.ts +1 -0
- package/src/git/providers/refs.ts +32 -3
- package/src/git/providers/staging.ts +12 -0
- package/src/git/providers/status.ts +6 -1
- package/src/git/remotes/azure-devops.ts +2 -0
- package/src/git/remotes/custom.ts +23 -0
- package/src/git/{exec.types.ts → run.types.ts} +22 -2
- package/src/git/service.ts +1 -0
- package/src/git/utils/autolink.utils.ts +1 -0
- package/src/git/utils/blame.utils.ts +2 -0
- package/src/git/utils/conflictResolution.utils.ts +31 -0
- package/src/git/utils/contributor.utils.ts +24 -0
- package/src/git/utils/fileStatus.utils.ts +7 -1
- package/src/git/utils/reachability.utils.ts +109 -0
- package/src/git/utils/search.utils.ts +2 -0
- package/src/git/utils/sorting.ts +17 -0
- package/src/git/utils/status.utils.ts +1 -0
- package/src/git/watching/classifyChange.ts +9 -0
- package/src/git/watching/gitIgnoreFilter.ts +2 -2
- package/src/git/watching/initWatcher.ts +2 -0
- package/src/git/watching/watchGroup.ts +3 -0
- package/src/git/watching/watchService.ts +45 -7
- package/src/git/watching/watchSession.ts +71 -55
- package/src/git-cli/exec/exec.types.ts +2 -2
- package/src/git-cli/exec/git.ts +6 -5
- package/src/git-cli/exec/gitQueue.ts +41 -12
- package/src/git-cli/parsers/blameParser.ts +1 -0
- package/src/git-cli/parsers/logParser.ts +1 -0
- package/src/git-cli/parsers/refParser.ts +33 -34
- package/src/git-cli/providers/blame.ts +1 -0
- package/src/git-cli/providers/branches.ts +165 -93
- package/src/git-cli/providers/commits.ts +107 -37
- package/src/git-cli/providers/config.ts +101 -48
- package/src/git-cli/providers/diff.ts +10 -3
- package/src/git-cli/providers/graph.ts +156 -16
- package/src/git-cli/providers/operations.ts +208 -83
- package/src/git-cli/providers/patch.ts +1 -0
- package/src/git-cli/providers/pausedOperations.ts +8 -0
- package/src/git-cli/providers/refs.ts +247 -3
- package/src/git-cli/providers/revision.ts +2 -2
- package/src/git-cli/providers/staging.ts +33 -0
- package/src/git-cli/providers/stash.ts +20 -2
- package/src/git-cli/providers/status.ts +24 -5
- package/src/git-cli/providers/tags.ts +15 -16
- package/src/ipc/discovery.ts +186 -0
- package/src/ipc/ipcServer.ts +171 -0
- package/src/plus/agents/providers/claudeCodeProvider.ts +2122 -0
- package/src/plus/agents/providers/claudeCodeTranscript.ts +214 -0
- package/src/plus/agents/sanitizePrompt.ts +109 -0
- package/src/plus/agents/stateMachine.ts +197 -0
- package/src/plus/agents/types.ts +325 -0
- package/src/plus/ai/errors.ts +40 -0
- package/src/plus/ai/models/model.ts +1 -0
- package/src/plus/ai/models/promptTemplates.ts +13 -0
- package/src/plus/ai/models/provider.ts +7 -1
- package/src/plus/ai/prompts.ts +49 -8
- package/src/plus/ai/providers/gitkrakenProvider.ts +4 -0
- package/src/plus/ai/providers/openAICompatibleProviderBase.ts +21 -4
- package/src/plus/ai/utils/ai.utils.ts +2 -0
- package/src/plus/ai/utils/results.utils.ts +2 -0
- package/src/plus/git-github/api/github.ts +315 -57
- package/src/plus/git-github/api/types.ts +15 -0
- package/src/plus/git-github/models.ts +1 -1
- package/src/plus/git-github/providers/github/blame.ts +2 -0
- package/src/plus/git-github/providers/github/branches.ts +61 -31
- package/src/plus/git-github/providers/github/commits.ts +231 -160
- package/src/plus/git-github/providers/github/diff.ts +27 -19
- package/src/plus/git-github/providers/github/refs.ts +58 -23
- package/src/plus/git-github/providers/github/revision.ts +1 -2
- package/src/plus/git-github/providers/github/status.ts +6 -1
- package/src/plus/git-github/providers/github/tags.ts +61 -62
- package/src/plus/git-github/providers/githubGitProvider.ts +1 -0
- package/src/utils/color.ts +2 -0
- package/src/utils/date.ts +5 -0
- package/src/utils/debounce.ts +1 -1
- package/src/utils/decorators/serializable.ts +1 -0
- package/src/utils/dedupedAsyncCache.ts +74 -0
- package/src/utils/diff.ts +61 -0
- package/src/utils/disposable.ts +2 -0
- package/src/utils/env/node/exec.ts +2 -0
- package/src/utils/error.ts +1 -0
- package/src/utils/iterable.ts +17 -3
- package/src/utils/logger.ts +1 -0
- package/src/utils/lruMap.ts +29 -4
- package/src/utils/markdown.ts +1 -0
- package/src/utils/mru.ts +2 -0
- package/src/utils/object.ts +55 -4
- package/src/utils/paging.ts +14 -14
- package/src/utils/path.ts +1 -0
- package/src/utils/promise.ts +22 -0
- package/src/utils/promiseCache.ts +48 -16
- package/src/utils/string.ts +3 -1
- package/src/utils/uri.ts +1 -0
- package/src/utils/version.ts +1 -0
- package/dist/git/exec.types.d.ts.map +0 -1
- package/dist/git/exec.types.js +0 -2
- package/dist/git/exec.types.js.map +0 -1
|
@@ -0,0 +1,1786 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
import { readdir, readFile } from 'fs/promises';
|
|
8
|
+
import { join } from 'path';
|
|
9
|
+
import { gate } from '../../../utils/decorators/gate.js';
|
|
10
|
+
import { disposableInterval } from '../../../utils/disposable.js';
|
|
11
|
+
import { Emitter } from '../../../utils/event.js';
|
|
12
|
+
import { Logger } from '../../../utils/logger.js';
|
|
13
|
+
import { normalizePath } from '../../../utils/path.js';
|
|
14
|
+
import { prepareStoredPrompt } from '../sanitizePrompt.js';
|
|
15
|
+
import { classifyPermissionKind, deriveStatusFromEvent, describeToolInput, extractPlanSummary, extractQuestionDetails, getToolFilePath, getToolReadPath, isProcessAlive, rehydrateSubagents, } from '../stateMachine.js';
|
|
16
|
+
import { getPhaseForStatus } from '../types.js';
|
|
17
|
+
import { ClaudeCodeTranscriptReader } from './claudeCodeTranscript.js';
|
|
18
|
+
const staleCheckIntervalMs = 15 * 60 * 1000; // 15 minutes
|
|
19
|
+
/** Default cooldown between PostToolUse and dropping the file from `fileActivity`. Held long
|
|
20
|
+
* enough that the treemap activity overlay can render a decay tail well past the moment the tool
|
|
21
|
+
* call completed. The host may override per-call via `AgentProviderCallbacks.getActivityDecayMs`
|
|
22
|
+
* (driven by the user's `gitlens.graph.experimental.visualizations.activityDecay` setting). */
|
|
23
|
+
const defaultActivityDecayMs = 5 * 60 * 1000; // 5 minutes
|
|
24
|
+
/** Grace period before `Stop` commits to `idle`. Long enough to absorb a same-turn continuation
|
|
25
|
+
* (hook-driven re-prompt, IPC event reordering, auto-resume); short enough that legitimate idle
|
|
26
|
+
* is visible promptly. */
|
|
27
|
+
const stopToIdleDebounceMs = 750;
|
|
28
|
+
/** If a phase transitions away and then back within this window, restore the prior `phaseSince`
|
|
29
|
+
* so the displayed elapsed time doesn't snap to 0 on transient oscillations. Slightly longer
|
|
30
|
+
* than `stopToIdleDebounceMs` so a continuation that just barely crosses the debounce still
|
|
31
|
+
* restores continuity. */
|
|
32
|
+
const phaseSinceRestoreWindowMs = 2000;
|
|
33
|
+
/** Normalize a workspace path to GitLens canonical form (forward slashes, lower-case drive letter
|
|
34
|
+
* on Windows). Comparisons throughout the home view assume this form, but `_workspacePaths` and
|
|
35
|
+
* peer-session `workspacePath` values originate from `Uri.fsPath`, which on Windows uses
|
|
36
|
+
* backslashes and preserves drive-letter casing. Without this, `session.workspacePath ===
|
|
37
|
+
* repository.path` always fails on Windows. */
|
|
38
|
+
function normalizeWorkspacePath(value) {
|
|
39
|
+
return value ? normalizePath(value) : undefined;
|
|
40
|
+
}
|
|
41
|
+
/** Structural comparison of two `fileActivity` arrays — same set of paths, same kinds present,
|
|
42
|
+
* same `reading`/`editing` flags. Ignores numeric timestamp values because those drift between
|
|
43
|
+
* every call (Date.now() advances) even when nothing has actually changed. Used to gate event
|
|
44
|
+
* firing: timestamps still get refreshed via the `_sessions[]` write, but a fire only happens
|
|
45
|
+
* when the structural shape changed. Treats `undefined` and `[]` as equal. */
|
|
46
|
+
function fileActivityStructurallyEqual(a, b) {
|
|
47
|
+
const aLen = a?.length ?? 0;
|
|
48
|
+
const bLen = b?.length ?? 0;
|
|
49
|
+
if (aLen !== bLen)
|
|
50
|
+
return false;
|
|
51
|
+
if (aLen === 0)
|
|
52
|
+
return true;
|
|
53
|
+
const byPath = new Map();
|
|
54
|
+
for (const entry of a) {
|
|
55
|
+
byPath.set(entry.path, entry);
|
|
56
|
+
}
|
|
57
|
+
for (const entry of b) {
|
|
58
|
+
const other = byPath.get(entry.path);
|
|
59
|
+
if (other == null)
|
|
60
|
+
return false;
|
|
61
|
+
if ((entry.readAt != null) !== (other.readAt != null))
|
|
62
|
+
return false;
|
|
63
|
+
if ((entry.editedAt != null) !== (other.editedAt != null))
|
|
64
|
+
return false;
|
|
65
|
+
if ((entry.reading ?? false) !== (other.reading ?? false))
|
|
66
|
+
return false;
|
|
67
|
+
if ((entry.editing ?? false) !== (other.editing ?? false))
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
export class ClaudeCodeProvider {
|
|
73
|
+
callbacks;
|
|
74
|
+
id = 'claudeCode';
|
|
75
|
+
name = 'Claude Code';
|
|
76
|
+
icon = 'robot';
|
|
77
|
+
_onDidChangeSessions = new Emitter();
|
|
78
|
+
onDidChangeSessions = this._onDidChangeSessions.event;
|
|
79
|
+
_sessions = [];
|
|
80
|
+
_ipcStarted = false;
|
|
81
|
+
_disposed = false;
|
|
82
|
+
_handlerDisposables = [];
|
|
83
|
+
_pendingPermissions = new Map();
|
|
84
|
+
_resolveGitInfoInFlight = new Set();
|
|
85
|
+
_sessionBookkeeping = new Map();
|
|
86
|
+
/** Per-session timers for the deferred `Stop → idle` commit. The handle is cleared (and the
|
|
87
|
+
* transition cancelled) by any non-idle status update arriving before the timer fires. */
|
|
88
|
+
_pendingIdleTimers = new Map();
|
|
89
|
+
_workspacePaths = [];
|
|
90
|
+
_staleCheckTimer;
|
|
91
|
+
/** Whether Claude hooks are installed, pushed by the host via {@link setClaudeHooksInstalled}.
|
|
92
|
+
* Fail-open (`true`) until the first push lands so a fresh window with real hooks isn't
|
|
93
|
+
* suppressed on its first ticks. Gates the reconciliation poll in {@link syncSessions}. */
|
|
94
|
+
_claudeHooksInstalled = true;
|
|
95
|
+
_transcriptReader = new ClaudeCodeTranscriptReader();
|
|
96
|
+
constructor(callbacks) {
|
|
97
|
+
this.callbacks = callbacks;
|
|
98
|
+
}
|
|
99
|
+
get sessions() {
|
|
100
|
+
return this._sessions;
|
|
101
|
+
}
|
|
102
|
+
start(workspacePaths) {
|
|
103
|
+
this._workspacePaths = workspacePaths.map(p => normalizePath(p));
|
|
104
|
+
void this.ensureIpcServer();
|
|
105
|
+
}
|
|
106
|
+
stop() {
|
|
107
|
+
// IPC server stays up intentionally — hooks fire even when the window is unfocused
|
|
108
|
+
}
|
|
109
|
+
updateWorkspacePaths(workspacePaths) {
|
|
110
|
+
this._workspacePaths = workspacePaths.map(p => normalizePath(p));
|
|
111
|
+
let changed = false;
|
|
112
|
+
for (let i = 0; i < this._sessions.length; i++) {
|
|
113
|
+
const s = this._sessions[i];
|
|
114
|
+
const nextWorkspacePath = s.cwd != null ? this.resolveWorkspacePath(s.cwd) : undefined;
|
|
115
|
+
const nextIsInWorkspace = nextWorkspacePath != null;
|
|
116
|
+
let subagentsChanged = false;
|
|
117
|
+
const subagents = s.subagents?.map(sub => {
|
|
118
|
+
const subNextWorkspacePath = sub.cwd != null ? this.resolveWorkspacePath(sub.cwd) : nextWorkspacePath;
|
|
119
|
+
const subNextIsInWorkspace = sub.cwd != null ? subNextWorkspacePath != null : nextIsInWorkspace;
|
|
120
|
+
if (sub.isInWorkspace === subNextIsInWorkspace && sub.workspacePath === subNextWorkspacePath) {
|
|
121
|
+
return sub;
|
|
122
|
+
}
|
|
123
|
+
subagentsChanged = true;
|
|
124
|
+
return { ...sub, isInWorkspace: subNextIsInWorkspace, workspacePath: subNextWorkspacePath };
|
|
125
|
+
});
|
|
126
|
+
if (s.isInWorkspace !== nextIsInWorkspace || s.workspacePath !== nextWorkspacePath || subagentsChanged) {
|
|
127
|
+
this._sessions[i] = {
|
|
128
|
+
...s,
|
|
129
|
+
isInWorkspace: nextIsInWorkspace,
|
|
130
|
+
workspacePath: nextWorkspacePath,
|
|
131
|
+
subagents: subagents,
|
|
132
|
+
};
|
|
133
|
+
changed = true;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (changed) {
|
|
137
|
+
this._onDidChangeSessions.fire();
|
|
138
|
+
}
|
|
139
|
+
if (!this._ipcStarted) {
|
|
140
|
+
// IPC wasn't bootstrapped yet — start it. ensureIpcServer publishes with the
|
|
141
|
+
// current `_workspacePaths`.
|
|
142
|
+
void this.ensureIpcServer();
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
// Re-publish so the agents discovery file reflects the new workspacePaths.
|
|
146
|
+
this.callbacks.ipc
|
|
147
|
+
.publishAgents(this._workspacePaths)
|
|
148
|
+
.catch((ex) => Logger.error(ex, 'ClaudeCodeProvider.updateWorkspacePaths: publishAgents failed'));
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
setClaudeHooksInstalled(installed) {
|
|
152
|
+
const wasOff = !this._claudeHooksInstalled;
|
|
153
|
+
this._claudeHooksInstalled = installed;
|
|
154
|
+
// On a fresh off→on transition, reconcile immediately rather than waiting up to a full
|
|
155
|
+
// interval — picks up any session that was already running before hooks were installed.
|
|
156
|
+
// This is a deliberate discovery pass (like the cold-start bootstrap), not a routine tick:
|
|
157
|
+
// hooks were just off, so the live path couldn't have seen these sessions and anything we
|
|
158
|
+
// find here is expected, not drift. Run it ungated so it neither skips nor reports drift
|
|
159
|
+
// telemetry (an ungated `syncSessions()` always polls and never emits `onSyncDiscrepancy`).
|
|
160
|
+
if (installed && wasOff) {
|
|
161
|
+
void this.syncSessions();
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
dispose() {
|
|
165
|
+
this._disposed = true;
|
|
166
|
+
this.stop();
|
|
167
|
+
this._staleCheckTimer?.dispose();
|
|
168
|
+
this._staleCheckTimer = undefined;
|
|
169
|
+
for (const d of this._handlerDisposables) {
|
|
170
|
+
d.dispose();
|
|
171
|
+
}
|
|
172
|
+
this._handlerDisposables = [];
|
|
173
|
+
for (const pending of this._pendingPermissions.values()) {
|
|
174
|
+
pending.reject(new Error('Provider disposed'));
|
|
175
|
+
}
|
|
176
|
+
this._pendingPermissions.clear();
|
|
177
|
+
for (const bk of this._sessionBookkeeping.values()) {
|
|
178
|
+
this.cancelPendingFileClears(bk);
|
|
179
|
+
this.cancelPendingReadClears(bk);
|
|
180
|
+
}
|
|
181
|
+
for (const timer of this._pendingIdleTimers.values()) {
|
|
182
|
+
clearTimeout(timer);
|
|
183
|
+
}
|
|
184
|
+
this._pendingIdleTimers.clear();
|
|
185
|
+
this._sessionBookkeeping.clear();
|
|
186
|
+
if (this._ipcStarted) {
|
|
187
|
+
void this.callbacks.ipc.unpublishAgents();
|
|
188
|
+
this._ipcStarted = false;
|
|
189
|
+
}
|
|
190
|
+
this._onDidChangeSessions.dispose();
|
|
191
|
+
}
|
|
192
|
+
[Symbol.dispose]() {
|
|
193
|
+
this.dispose();
|
|
194
|
+
}
|
|
195
|
+
async ensureIpcServer() {
|
|
196
|
+
if (this._ipcStarted || this._disposed)
|
|
197
|
+
return;
|
|
198
|
+
// Register handlers before any async work so blocking permission requests aren't delayed.
|
|
199
|
+
const handlers = [
|
|
200
|
+
this.callbacks.ipc.registerHandler('agents/session', (request, searchParams) => {
|
|
201
|
+
if (request != null) {
|
|
202
|
+
const isBlocking = searchParams.get('blocking') === 'true';
|
|
203
|
+
return this.handleSessionEvent(request, isBlocking);
|
|
204
|
+
}
|
|
205
|
+
return Promise.resolve();
|
|
206
|
+
}),
|
|
207
|
+
this.callbacks.ipc.registerHandler('agents/sessions/list', () => Promise.resolve(this._sessions.map(s => ({
|
|
208
|
+
...s,
|
|
209
|
+
lastActivity: s.lastActivity.toISOString(),
|
|
210
|
+
phaseSince: s.phaseSince.toISOString(),
|
|
211
|
+
subagents: s.subagents?.map(sub => ({
|
|
212
|
+
...sub,
|
|
213
|
+
lastActivity: sub.lastActivity.toISOString(),
|
|
214
|
+
phaseSince: sub.phaseSince.toISOString(),
|
|
215
|
+
})),
|
|
216
|
+
})))),
|
|
217
|
+
this.callbacks.ipc.registerHandler('agents/sessions/open', async (request) => {
|
|
218
|
+
const sessionId = request?.sessionId;
|
|
219
|
+
if (!sessionId || this.callbacks.openSessionInClaudeExtension == null) {
|
|
220
|
+
return { opened: false };
|
|
221
|
+
}
|
|
222
|
+
try {
|
|
223
|
+
await this.callbacks.openSessionInClaudeExtension(sessionId);
|
|
224
|
+
return { opened: true };
|
|
225
|
+
}
|
|
226
|
+
catch (ex) {
|
|
227
|
+
Logger.warn(`ClaudeCodeProvider.agents/sessions/open: ${ex instanceof Error ? ex.message : String(ex)}`);
|
|
228
|
+
return { opened: false };
|
|
229
|
+
}
|
|
230
|
+
}),
|
|
231
|
+
];
|
|
232
|
+
try {
|
|
233
|
+
await this.callbacks.ipc.publishAgents(this._workspacePaths);
|
|
234
|
+
}
|
|
235
|
+
catch (ex) {
|
|
236
|
+
// Unwind so a retry can re-register without hitting "already registered".
|
|
237
|
+
for (const d of handlers) {
|
|
238
|
+
d.dispose();
|
|
239
|
+
}
|
|
240
|
+
Logger.error(ex, 'ClaudeCodeProvider.ensureIpcServer');
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
// `publishAgents` no-ops silently if the IPC server failed to start; don't seal
|
|
244
|
+
// retries in that case — the next call should re-attempt.
|
|
245
|
+
if (this.callbacks.ipc.port == null) {
|
|
246
|
+
for (const d of handlers) {
|
|
247
|
+
d.dispose();
|
|
248
|
+
}
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
if (this._disposed) {
|
|
252
|
+
for (const d of handlers) {
|
|
253
|
+
d.dispose();
|
|
254
|
+
}
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
this._handlerDisposables = handlers;
|
|
258
|
+
this._ipcStarted = true;
|
|
259
|
+
try {
|
|
260
|
+
await this.syncSessions();
|
|
261
|
+
if (this._disposed)
|
|
262
|
+
return;
|
|
263
|
+
void this.querySiblingWindowSessions();
|
|
264
|
+
this._staleCheckTimer?.dispose();
|
|
265
|
+
this._staleCheckTimer = disposableInterval(() => void this.syncSessions({ gate: true }), staleCheckIntervalMs);
|
|
266
|
+
}
|
|
267
|
+
catch (ex) {
|
|
268
|
+
Logger.error(ex, 'ClaudeCodeProvider.ensureIpcServer');
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
handleSessionEvent(event, isBlocking) {
|
|
272
|
+
const workspacePath = this.resolveWorkspacePath(event.cwd);
|
|
273
|
+
const eventContext = {
|
|
274
|
+
pid: event.pid,
|
|
275
|
+
workspacePath: workspacePath,
|
|
276
|
+
isInWorkspace: workspacePath != null,
|
|
277
|
+
cwd: event.cwd,
|
|
278
|
+
initialCwd: event.initialCwd,
|
|
279
|
+
planFile: event.planFile,
|
|
280
|
+
sessionName: event.sessionName,
|
|
281
|
+
};
|
|
282
|
+
const tag = this.sessionTag(event.sessionId, event.sessionName ?? 'unnamed');
|
|
283
|
+
if (event.event === 'SessionStart' || event.event === 'SessionEnd') {
|
|
284
|
+
Logger.info(`ClaudeCodeProvider.handleSessionEvent: ${event.event} ${tag}`);
|
|
285
|
+
}
|
|
286
|
+
else {
|
|
287
|
+
Logger.debug(`ClaudeCodeProvider.handleSessionEvent: ${event.event} ${tag}${event.toolName ? ` tool=${event.toolName}` : ''}${event.agentId ? ` agent=${event.agentId}` : ''}${event.notificationType ? ` type=${event.notificationType}` : ''}`);
|
|
288
|
+
}
|
|
289
|
+
switch (event.event) {
|
|
290
|
+
case 'SessionStart': {
|
|
291
|
+
const wasNew = this._sessions.findIndex(s => s.id === event.sessionId) < 0;
|
|
292
|
+
const { index } = this.ensureSession(event.sessionId, eventContext);
|
|
293
|
+
if (wasNew) {
|
|
294
|
+
// ensureSession created the session at 'idle' already. Just refresh pid if
|
|
295
|
+
// the event carries one — bookkeeping was implicitly clean.
|
|
296
|
+
this.resetBookkeeping(event.sessionId);
|
|
297
|
+
if (event.pid != null) {
|
|
298
|
+
const prev = this._sessions[index];
|
|
299
|
+
if (prev.pid !== event.pid) {
|
|
300
|
+
this._sessions[index] = { ...prev, pid: event.pid };
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
else {
|
|
305
|
+
// SessionStart for a session we already track is almost always a CLI replay
|
|
306
|
+
// (resume/reconnect/hook re-init). Don't clobber live state — the next real
|
|
307
|
+
// event will re-establish status. Refresh pid only.
|
|
308
|
+
const prev = this._sessions[index];
|
|
309
|
+
if (event.pid != null && event.pid !== prev.pid) {
|
|
310
|
+
this._sessions[index] = { ...prev, pid: event.pid, lastActivity: new Date() };
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
this._onDidChangeSessions.fire();
|
|
314
|
+
void this.resolveTranscriptTitles(event.sessionId, event.cwd);
|
|
315
|
+
this.callbacks.onSessionStarted?.(this.id);
|
|
316
|
+
break;
|
|
317
|
+
}
|
|
318
|
+
case 'SessionEnd': {
|
|
319
|
+
const pending = this._pendingPermissions.get(event.sessionId);
|
|
320
|
+
if (pending != null) {
|
|
321
|
+
pending.reject(new Error('Session ended'));
|
|
322
|
+
this._pendingPermissions.delete(event.sessionId);
|
|
323
|
+
}
|
|
324
|
+
this.cancelPendingIdleTransition(event.sessionId);
|
|
325
|
+
const index = this._sessions.findIndex(s => s.id === event.sessionId);
|
|
326
|
+
if (index >= 0) {
|
|
327
|
+
this._sessions.splice(index, 1);
|
|
328
|
+
this._onDidChangeSessions.fire();
|
|
329
|
+
}
|
|
330
|
+
const bk = this._sessionBookkeeping.get(event.sessionId);
|
|
331
|
+
if (bk != null) {
|
|
332
|
+
this.cancelPendingFileClears(bk);
|
|
333
|
+
this.cancelPendingReadClears(bk);
|
|
334
|
+
}
|
|
335
|
+
this._sessionBookkeeping.delete(event.sessionId);
|
|
336
|
+
this._transcriptReader.forget(event.sessionId);
|
|
337
|
+
this.callbacks.onSessionEnded?.(this.id);
|
|
338
|
+
break;
|
|
339
|
+
}
|
|
340
|
+
case 'UserPromptSubmit': {
|
|
341
|
+
const { index } = this.ensureSession(event.sessionId, eventContext);
|
|
342
|
+
const cleaned = prepareStoredPrompt(event.prompt);
|
|
343
|
+
// A `UserPromptSubmit` whose payload sanitizes to nothing is harness-synthetic
|
|
344
|
+
// (e.g. background-bash <task-notification>, slash-command stdout echo). Treat it
|
|
345
|
+
// as informational so it doesn't flip the session to `thinking` or wipe a pending
|
|
346
|
+
// permission when no real user activity occurred.
|
|
347
|
+
if (!cleaned)
|
|
348
|
+
break;
|
|
349
|
+
const existing = this._sessions[index];
|
|
350
|
+
this._sessions[index] = {
|
|
351
|
+
...existing,
|
|
352
|
+
lastPrompt: cleaned,
|
|
353
|
+
firstPrompt: existing.firstPrompt ?? prepareStoredPrompt(event.firstPrompt),
|
|
354
|
+
};
|
|
355
|
+
this.clearStalePermission(event.sessionId, 'UserPromptSubmit');
|
|
356
|
+
this.updateSessionStatus(event.sessionId, 'thinking', eventContext);
|
|
357
|
+
break;
|
|
358
|
+
}
|
|
359
|
+
case 'PreToolUse': {
|
|
360
|
+
const bk = this.getBookkeeping(event.sessionId);
|
|
361
|
+
bk.activeToolCount++;
|
|
362
|
+
const filesChanged = this.trackToolUseFile(event.sessionId, event);
|
|
363
|
+
const readsChanged = this.trackToolUseRead(event.sessionId, event);
|
|
364
|
+
// Resolve a rich `Bash(grep …)`-style detail via the same tool_input passthrough the
|
|
365
|
+
// PermissionRequest handler uses, so working sessions surface what their tool is
|
|
366
|
+
// actually doing — not just the bare tool name. Falls back to bare name when no
|
|
367
|
+
// toolInput is available (older CLI / unhandled tool).
|
|
368
|
+
const hookInput = event.hookInput;
|
|
369
|
+
const toolInput = hookInput?.tool_input ?? event.toolInput;
|
|
370
|
+
const toolName = hookInput?.tool_name ?? event.toolName ?? '';
|
|
371
|
+
const statusDetail = toolInput != null && toolName ? describeToolInput(toolName, toolInput) : toolName || undefined;
|
|
372
|
+
// Capture pre-update status so we can tell whether the upcoming updateSessionStatus
|
|
373
|
+
// will fire on its own — needed to avoid dropping fileActivity changes when the
|
|
374
|
+
// session is already in tool_use (back-to-back tool calls).
|
|
375
|
+
const sessionIndex = this._sessions.findIndex(s => s.id === event.sessionId);
|
|
376
|
+
const prevStatus = sessionIndex >= 0 ? this._sessions[sessionIndex].status : undefined;
|
|
377
|
+
const prevDetail = sessionIndex >= 0 ? this._sessions[sessionIndex].statusDetail : undefined;
|
|
378
|
+
const statusWillFire = prevStatus !== 'tool_use' || prevDetail !== statusDetail;
|
|
379
|
+
this.updateSessionStatus(event.sessionId, 'tool_use', {
|
|
380
|
+
...eventContext,
|
|
381
|
+
statusDetail: statusDetail,
|
|
382
|
+
});
|
|
383
|
+
if ((filesChanged || readsChanged) && !statusWillFire) {
|
|
384
|
+
this._onDidChangeSessions.fire();
|
|
385
|
+
}
|
|
386
|
+
break;
|
|
387
|
+
}
|
|
388
|
+
case 'PostToolUse':
|
|
389
|
+
case 'PostToolUseFailure': {
|
|
390
|
+
this.clearStalePermission(event.sessionId, event.event);
|
|
391
|
+
const bk = this.getBookkeeping(event.sessionId);
|
|
392
|
+
bk.activeToolCount = Math.max(0, bk.activeToolCount - 1);
|
|
393
|
+
// Cooldown the file-edit decoration instead of dropping it immediately, so a quick
|
|
394
|
+
// follow-up Edit/Write to the same path doesn't blink. The deferred clear fires its
|
|
395
|
+
// own change event when it expires. The immediate re-sync inside each flips
|
|
396
|
+
// `editing`/`reading` off the moment refcount hits zero, though — capture whether that
|
|
397
|
+
// changed the published list so we fire it ourselves when the status update below short-
|
|
398
|
+
// circuits (a parallel tool is still in flight, so activeToolCount stays > 0).
|
|
399
|
+
const filesChanged = this.scheduleClearToolUseFile(event.sessionId, event);
|
|
400
|
+
const readsChanged = this.scheduleClearToolUseRead(event.sessionId, event);
|
|
401
|
+
if (bk.activeToolCount === 0) {
|
|
402
|
+
// updateSessionStatus short-circuits without firing when status+detail are unchanged
|
|
403
|
+
// (already 'thinking' with no detail) — which would drop the editing/reading flag-flip
|
|
404
|
+
// above and leave a stale live pulse. Capture whether it will fire on its own and, if
|
|
405
|
+
// not, fire explicitly — mirrors the PreToolUse / PermissionDenied guards.
|
|
406
|
+
const idx = this._sessions.findIndex(s => s.id === event.sessionId);
|
|
407
|
+
const statusWillFire = idx < 0 ||
|
|
408
|
+
this._sessions[idx].status !== 'thinking' ||
|
|
409
|
+
this._sessions[idx].statusDetail != null;
|
|
410
|
+
this.updateSessionStatus(event.sessionId, 'thinking', eventContext);
|
|
411
|
+
if ((filesChanged || readsChanged) && !statusWillFire) {
|
|
412
|
+
this._onDidChangeSessions.fire();
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
else if (filesChanged || readsChanged) {
|
|
416
|
+
this._onDidChangeSessions.fire();
|
|
417
|
+
}
|
|
418
|
+
break;
|
|
419
|
+
}
|
|
420
|
+
case 'Stop':
|
|
421
|
+
case 'StopFailure': {
|
|
422
|
+
const pending = this._pendingPermissions.get(event.sessionId);
|
|
423
|
+
if (pending != null) {
|
|
424
|
+
pending.reject(new Error('Session stopped'));
|
|
425
|
+
this._pendingPermissions.delete(event.sessionId);
|
|
426
|
+
}
|
|
427
|
+
// Turn ended: stop the "live" pulse but keep the per-operation decay tail fading over
|
|
428
|
+
// the configured window (anchored at each tool's completion, not at the turn end). A full
|
|
429
|
+
// reset here would wipe the tail the instant the agent finishes a response.
|
|
430
|
+
this.settleBookkeeping(event.sessionId);
|
|
431
|
+
// Apply Stop's metadata synchronously so we don't carry stale context through the
|
|
432
|
+
// debounce window — any in-window mutations (e.g. CwdChanged) survive when the
|
|
433
|
+
// timer fires. ensureSession doesn't fire on metadata-only updates of existing
|
|
434
|
+
// sessions, so fire here to match the original Stop-handler's UI-update semantics.
|
|
435
|
+
const { changed } = this.ensureSession(event.sessionId, eventContext);
|
|
436
|
+
if (changed) {
|
|
437
|
+
this._onDidChangeSessions.fire();
|
|
438
|
+
}
|
|
439
|
+
// Defer the status change — if the agent continues within the debounce window
|
|
440
|
+
// (hook-driven re-prompt, IPC reordering, auto-resume), the next non-idle event
|
|
441
|
+
// cancels this and we never flick through idle.
|
|
442
|
+
this.scheduleIdleTransition(event.sessionId);
|
|
443
|
+
break;
|
|
444
|
+
}
|
|
445
|
+
case 'PreCompact':
|
|
446
|
+
this.updateSessionStatus(event.sessionId, 'compacting', eventContext);
|
|
447
|
+
break;
|
|
448
|
+
case 'PostCompact':
|
|
449
|
+
this.updateSessionStatus(event.sessionId, 'thinking', eventContext);
|
|
450
|
+
break;
|
|
451
|
+
case 'Notification':
|
|
452
|
+
switch (event.notificationType) {
|
|
453
|
+
case 'idle_prompt':
|
|
454
|
+
// No-op — session is already idle from the preceding stop/session-start event
|
|
455
|
+
break;
|
|
456
|
+
case 'permission_prompt':
|
|
457
|
+
case 'elicitation_dialog':
|
|
458
|
+
this.updateSessionStatus(event.sessionId, 'permission_requested', {
|
|
459
|
+
...eventContext,
|
|
460
|
+
statusDetail: event.toolName,
|
|
461
|
+
});
|
|
462
|
+
break;
|
|
463
|
+
default:
|
|
464
|
+
// auth_success, unknown, or missing: no status change, just update timestamp
|
|
465
|
+
break;
|
|
466
|
+
}
|
|
467
|
+
break;
|
|
468
|
+
case 'PermissionRequest': {
|
|
469
|
+
// hookInput is the raw passthrough; fall back to top-level fields for older CLI versions.
|
|
470
|
+
const hookInput = event.hookInput;
|
|
471
|
+
const toolInput = hookInput?.tool_input ?? event.toolInput;
|
|
472
|
+
if (isBlocking && toolInput != null) {
|
|
473
|
+
const toolName = hookInput?.tool_name ?? event.toolName ?? '';
|
|
474
|
+
const toolDescription = describeToolInput(toolName, toolInput);
|
|
475
|
+
const toolInputDescription = toolInput.description || undefined;
|
|
476
|
+
const kind = classifyPermissionKind(toolName);
|
|
477
|
+
return new Promise((resolve, reject) => {
|
|
478
|
+
const existing = this._pendingPermissions.get(event.sessionId);
|
|
479
|
+
if (existing != null) {
|
|
480
|
+
Logger.debug(`ClaudeCodeProvider.handleSessionEvent: auto-denying stale permission ${tag} tool=${existing.toolName}`);
|
|
481
|
+
existing.resolve({
|
|
482
|
+
hookSpecificOutput: {
|
|
483
|
+
hookEventName: 'PermissionRequest',
|
|
484
|
+
decision: { behavior: 'deny' },
|
|
485
|
+
},
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
this._pendingPermissions.set(event.sessionId, {
|
|
489
|
+
resolve: resolve,
|
|
490
|
+
reject: reject,
|
|
491
|
+
toolName: toolName,
|
|
492
|
+
toolDescription: toolDescription,
|
|
493
|
+
});
|
|
494
|
+
// Plan-kind body: prefer the existing session's planFile (set via SessionStart/
|
|
495
|
+
// PostToolUse) and fall back to the event's planFile for cold-start cases.
|
|
496
|
+
const planFilePath = kind === 'plan'
|
|
497
|
+
? (this._sessions.find(s => s.id === event.sessionId)?.planFile ?? event.planFile)
|
|
498
|
+
: undefined;
|
|
499
|
+
const planSummary = kind === 'plan' ? extractPlanSummary(toolInput) : undefined;
|
|
500
|
+
const questionDetails = kind === 'question' ? extractQuestionDetails(toolInput) : undefined;
|
|
501
|
+
const permission = {
|
|
502
|
+
kind: kind,
|
|
503
|
+
toolName: toolName,
|
|
504
|
+
toolDescription: toolDescription,
|
|
505
|
+
toolInputDescription: toolInputDescription,
|
|
506
|
+
suggestions: hookInput?.permission_suggestions ??
|
|
507
|
+
event.permissionSuggestions,
|
|
508
|
+
planFilePath: planFilePath,
|
|
509
|
+
planSummary: planSummary,
|
|
510
|
+
questionText: questionDetails?.text,
|
|
511
|
+
questionCount: questionDetails?.count,
|
|
512
|
+
};
|
|
513
|
+
this.updateSessionWithPermission(event.sessionId, permission, event.pid);
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
this.updateSessionStatus(event.sessionId, 'permission_requested', {
|
|
517
|
+
...eventContext,
|
|
518
|
+
statusDetail: event.toolName,
|
|
519
|
+
});
|
|
520
|
+
break;
|
|
521
|
+
}
|
|
522
|
+
case 'PermissionDenied': {
|
|
523
|
+
this.clearStalePermission(event.sessionId, 'PermissionDenied');
|
|
524
|
+
const bk = this.getBookkeeping(event.sessionId);
|
|
525
|
+
bk.activeToolCount = Math.max(0, bk.activeToolCount - 1);
|
|
526
|
+
const filesChanged = this.untrackToolUseFile(event.sessionId, event);
|
|
527
|
+
const readsChanged = this.untrackToolUseRead(event.sessionId, event);
|
|
528
|
+
// When a parallel tool is still active the next status equals the current one and
|
|
529
|
+
// updateSessionStatus short-circuits — without an explicit fire, the dropped path
|
|
530
|
+
// would never reach subscribers (treemap activity overlay, WIP decoration).
|
|
531
|
+
const nextStatus = bk.activeToolCount > 0 ? 'tool_use' : 'thinking';
|
|
532
|
+
const sessionIndex = this._sessions.findIndex(s => s.id === event.sessionId);
|
|
533
|
+
const prevStatus = sessionIndex >= 0 ? this._sessions[sessionIndex].status : undefined;
|
|
534
|
+
const statusWillFire = prevStatus !== nextStatus;
|
|
535
|
+
this.updateSessionStatus(event.sessionId, nextStatus, eventContext);
|
|
536
|
+
if ((filesChanged || readsChanged) && !statusWillFire) {
|
|
537
|
+
this._onDidChangeSessions.fire();
|
|
538
|
+
}
|
|
539
|
+
break;
|
|
540
|
+
}
|
|
541
|
+
case 'Elicitation': {
|
|
542
|
+
const bk = this.getBookkeeping(event.sessionId);
|
|
543
|
+
bk.pendingPermission = {
|
|
544
|
+
kind: 'elicitation',
|
|
545
|
+
toolName: event.toolName ?? 'Input Required',
|
|
546
|
+
toolDescription: event.toolName ?? 'Waiting for input',
|
|
547
|
+
};
|
|
548
|
+
this.updateSessionStatus(event.sessionId, 'permission_requested', {
|
|
549
|
+
...eventContext,
|
|
550
|
+
statusDetail: event.toolName,
|
|
551
|
+
});
|
|
552
|
+
break;
|
|
553
|
+
}
|
|
554
|
+
case 'ElicitationResult': {
|
|
555
|
+
const bk = this.getBookkeeping(event.sessionId);
|
|
556
|
+
bk.pendingPermission = undefined;
|
|
557
|
+
this.updateSessionStatus(event.sessionId, bk.activeToolCount > 0 ? 'tool_use' : 'thinking', eventContext);
|
|
558
|
+
break;
|
|
559
|
+
}
|
|
560
|
+
case 'CwdChanged':
|
|
561
|
+
if (event.cwd) {
|
|
562
|
+
const index = this._sessions.findIndex(s => s.id === event.sessionId);
|
|
563
|
+
if (index >= 0 && this._sessions[index].cwd !== event.cwd) {
|
|
564
|
+
this._sessions[index] = { ...this._sessions[index], cwd: event.cwd };
|
|
565
|
+
this._onDidChangeSessions.fire();
|
|
566
|
+
}
|
|
567
|
+
// Clear the unresolvable flag so the new cwd actually gets re-probed — without
|
|
568
|
+
// this, a session that started in a non-git cwd would stay flagged forever even
|
|
569
|
+
// after moving into a git repo.
|
|
570
|
+
this.getBookkeeping(event.sessionId).gitInfoUnresolvable = false;
|
|
571
|
+
void this.resolveGitInfo(event.sessionId, event.cwd);
|
|
572
|
+
}
|
|
573
|
+
break;
|
|
574
|
+
case 'SubagentStart': {
|
|
575
|
+
const { index: parentIdx } = this.ensureSession(event.sessionId, eventContext);
|
|
576
|
+
const parent = this._sessions[parentIdx];
|
|
577
|
+
if (event.agentId) {
|
|
578
|
+
const now = new Date();
|
|
579
|
+
const subagent = {
|
|
580
|
+
id: event.agentId,
|
|
581
|
+
providerId: this.id,
|
|
582
|
+
providerName: this.name,
|
|
583
|
+
name: event.agentType ?? 'Subagent',
|
|
584
|
+
status: 'thinking',
|
|
585
|
+
phase: 'working',
|
|
586
|
+
phaseSince: now,
|
|
587
|
+
lastActivity: now,
|
|
588
|
+
isSubagent: true,
|
|
589
|
+
parentId: event.sessionId,
|
|
590
|
+
isInWorkspace: workspacePath != null,
|
|
591
|
+
};
|
|
592
|
+
const existingSubs = parent.subagents ? [...parent.subagents] : [];
|
|
593
|
+
existingSubs.push(subagent);
|
|
594
|
+
this._sessions[parentIdx] = { ...parent, subagents: existingSubs };
|
|
595
|
+
this._onDidChangeSessions.fire();
|
|
596
|
+
}
|
|
597
|
+
break;
|
|
598
|
+
}
|
|
599
|
+
case 'SubagentStop': {
|
|
600
|
+
const { index: parentIdx } = this.ensureSession(event.sessionId, eventContext);
|
|
601
|
+
const parentSession = this._sessions[parentIdx];
|
|
602
|
+
if (parentSession.subagents != null && event.agentId) {
|
|
603
|
+
const filtered = parentSession.subagents.filter(s => s.id !== event.agentId);
|
|
604
|
+
if (filtered.length !== parentSession.subagents.length) {
|
|
605
|
+
this._sessions[parentIdx] = {
|
|
606
|
+
...parentSession,
|
|
607
|
+
subagents: filtered.length > 0 ? filtered : undefined,
|
|
608
|
+
};
|
|
609
|
+
this._onDidChangeSessions.fire();
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
break;
|
|
613
|
+
}
|
|
614
|
+
case 'TeammateIdle':
|
|
615
|
+
case 'TaskCompleted':
|
|
616
|
+
case 'InstructionsLoaded':
|
|
617
|
+
case 'ConfigChange':
|
|
618
|
+
case 'WorktreeCreate':
|
|
619
|
+
case 'WorktreeRemove':
|
|
620
|
+
// Not yet handled — intentional no-op.
|
|
621
|
+
break;
|
|
622
|
+
}
|
|
623
|
+
return Promise.resolve();
|
|
624
|
+
}
|
|
625
|
+
sessionTag(sessionId, name) {
|
|
626
|
+
return name != null
|
|
627
|
+
? `[session=${sessionId.substring(0, 8)}(${name})]`
|
|
628
|
+
: `[session=${sessionId.substring(0, 8)}]`;
|
|
629
|
+
}
|
|
630
|
+
getBookkeeping(sessionId) {
|
|
631
|
+
let bk = this._sessionBookkeeping.get(sessionId);
|
|
632
|
+
if (bk == null) {
|
|
633
|
+
bk = {
|
|
634
|
+
activeToolCount: 0,
|
|
635
|
+
currentFileCounts: new Map(),
|
|
636
|
+
pendingFileClears: new Map(),
|
|
637
|
+
currentReadCounts: new Map(),
|
|
638
|
+
pendingReadClears: new Map(),
|
|
639
|
+
lastTouchedAt: new Map(),
|
|
640
|
+
gitInfoUnresolvable: false,
|
|
641
|
+
};
|
|
642
|
+
this._sessionBookkeeping.set(sessionId, bk);
|
|
643
|
+
}
|
|
644
|
+
return bk;
|
|
645
|
+
}
|
|
646
|
+
/** Returns the active decay window in milliseconds — the cooldown between PostToolUse and
|
|
647
|
+
* dropping the path from the bookkeeping. Reads through the host callback every time so a
|
|
648
|
+
* setting change takes effect on the next Pre/Post pair without re-wiring (existing timers
|
|
649
|
+
* keep their original timeout — acceptable since they're short-lived relative to the setting). */
|
|
650
|
+
get activityDecayMs() {
|
|
651
|
+
return this.callbacks.getActivityDecayMs?.() ?? defaultActivityDecayMs;
|
|
652
|
+
}
|
|
653
|
+
/** Locates the *parent* session id that owns the given session id — returns the id itself when
|
|
654
|
+
* it matches a top-level session, otherwise the `id` of the parent that holds it under
|
|
655
|
+
* `subagents[]`. Returns `undefined` when neither match (session no longer exists). Used to
|
|
656
|
+
* route per-session bookkeeping changes to the right top-level `syncSessionFileActivity` call.
|
|
657
|
+
* Tool events are parent-keyed (the CLI sends a sub-agent's tool events under the parent id),
|
|
658
|
+
* so the `subagents[]` branch is a defensive fallback for any other-keyed caller. */
|
|
659
|
+
findOwningParentId(sessionId) {
|
|
660
|
+
for (const s of this._sessions) {
|
|
661
|
+
if (s.id === sessionId)
|
|
662
|
+
return s.id;
|
|
663
|
+
if (s.subagents != null) {
|
|
664
|
+
for (const sub of s.subagents) {
|
|
665
|
+
if (sub.id === sessionId)
|
|
666
|
+
return s.id;
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
return undefined;
|
|
671
|
+
}
|
|
672
|
+
resetBookkeeping(sessionId) {
|
|
673
|
+
const bk = this.getBookkeeping(sessionId);
|
|
674
|
+
bk.activeToolCount = 0;
|
|
675
|
+
bk.pendingPermission = undefined;
|
|
676
|
+
this.cancelPendingFileClears(bk);
|
|
677
|
+
bk.currentFileCounts.clear();
|
|
678
|
+
this.cancelPendingReadClears(bk);
|
|
679
|
+
bk.currentReadCounts.clear();
|
|
680
|
+
bk.lastTouchedAt.clear();
|
|
681
|
+
bk.gitInfoUnresolvable = false;
|
|
682
|
+
const parentId = this.findOwningParentId(sessionId);
|
|
683
|
+
if (parentId != null) {
|
|
684
|
+
this.syncSessionFileActivity(parentId);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
/** Turn-end settle (Stop): the agent finished its turn, so nothing is "live" anymore — but
|
|
688
|
+
* the per-operation decay tail must survive. Heat fades over {@link activityDecayMs} measured
|
|
689
|
+
* from when each *tool* finished (the PostToolUse cooldown), NOT from when the turn ends, so a
|
|
690
|
+
* Stop must not cancel those cooldowns or clear `lastTouchedAt`. We only reset turn-scoped
|
|
691
|
+
* state and force-finish any path whose PostToolUse never arrived before Stop: drop its
|
|
692
|
+
* refcount to 0 (flipping `editing`/`reading` off so the pulse stops) and schedule the same
|
|
693
|
+
* decay eviction a normal completion would. Contrast {@link resetBookkeeping}, which hard-
|
|
694
|
+
* wipes everything for SessionStart/SessionEnd (the agent is gone, not merely between turns). */
|
|
695
|
+
settleBookkeeping(sessionId) {
|
|
696
|
+
const bk = this.getBookkeeping(sessionId);
|
|
697
|
+
bk.activeToolCount = 0;
|
|
698
|
+
bk.pendingPermission = undefined;
|
|
699
|
+
// Allow git re-resolution next turn (matches the prior reset-on-Stop intent).
|
|
700
|
+
bk.gitInfoUnresolvable = false;
|
|
701
|
+
for (const [path, count] of bk.currentFileCounts) {
|
|
702
|
+
if (count > 0) {
|
|
703
|
+
bk.currentFileCounts.set(path, 0);
|
|
704
|
+
this.scheduleFileDecayEviction(bk, sessionId, path);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
for (const [path, count] of bk.currentReadCounts) {
|
|
708
|
+
if (count > 0) {
|
|
709
|
+
bk.currentReadCounts.set(path, 0);
|
|
710
|
+
this.scheduleReadDecayEviction(bk, sessionId, path);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
const parentId = this.findOwningParentId(sessionId);
|
|
714
|
+
if (parentId != null && this.syncSessionFileActivity(parentId)) {
|
|
715
|
+
this._onDidChangeSessions.fire();
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
cancelPendingFileClears(bk) {
|
|
719
|
+
for (const timer of bk.pendingFileClears.values()) {
|
|
720
|
+
clearTimeout(timer);
|
|
721
|
+
}
|
|
722
|
+
bk.pendingFileClears.clear();
|
|
723
|
+
}
|
|
724
|
+
cancelPendingReadClears(bk) {
|
|
725
|
+
for (const timer of bk.pendingReadClears.values()) {
|
|
726
|
+
clearTimeout(timer);
|
|
727
|
+
}
|
|
728
|
+
bk.pendingReadClears.clear();
|
|
729
|
+
}
|
|
730
|
+
/** Extracts the targeted file path from a PreToolUse/PostToolUse event. Tries the raw
|
|
731
|
+
* `hookInput.tool_input` passthrough first, falls back to the projected `event.toolInput`
|
|
732
|
+
* for older CLI versions that only fill the top-level fields. Treats an empty-object
|
|
733
|
+
* `hookInput.tool_input` as missing — `??` would have kept it (truthy) and shadowed a
|
|
734
|
+
* populated `event.toolInput`. */
|
|
735
|
+
getEventFilePath(event) {
|
|
736
|
+
const toolName = event.hookInput?.tool_name ?? event.toolName;
|
|
737
|
+
if (toolName == null)
|
|
738
|
+
return undefined;
|
|
739
|
+
const rawHookInput = event.hookInput?.tool_input;
|
|
740
|
+
const hookInputPopulated = rawHookInput != null && Object.keys(rawHookInput).length > 0;
|
|
741
|
+
const toolInput = hookInputPopulated ? rawHookInput : event.toolInput;
|
|
742
|
+
return getToolFilePath(toolName, toolInput);
|
|
743
|
+
}
|
|
744
|
+
/** Stamps the per-path/per-kind `lastTouchedAt[kind]` to the current epoch ms. Stamped on every
|
|
745
|
+
* PreToolUse for the matching kind so `serializeFileActivity` can emit `readAt`/`editedAt` as
|
|
746
|
+
* a relative `now - timestamp` delta. */
|
|
747
|
+
stampLastTouched(bk, filePath, kind) {
|
|
748
|
+
const existing = bk.lastTouchedAt.get(filePath);
|
|
749
|
+
const next = existing != null ? { ...existing } : {};
|
|
750
|
+
next[kind] = Date.now();
|
|
751
|
+
bk.lastTouchedAt.set(filePath, next);
|
|
752
|
+
}
|
|
753
|
+
/** Drops the `lastTouchedAt[kind]` slot for `filePath`, and the whole entry when neither kind
|
|
754
|
+
* remains. Mirrors the cooldown-timer eviction in `scheduleClear*` — once the path is gone
|
|
755
|
+
* from the count map for that kind, its timestamp is no longer load-bearing. */
|
|
756
|
+
clearLastTouched(bk, filePath, kind) {
|
|
757
|
+
const existing = bk.lastTouchedAt.get(filePath);
|
|
758
|
+
if (existing == null)
|
|
759
|
+
return;
|
|
760
|
+
if (existing[kind] == null)
|
|
761
|
+
return;
|
|
762
|
+
const next = { ...existing, [kind]: undefined };
|
|
763
|
+
if (next.edit == null && next.read == null) {
|
|
764
|
+
bk.lastTouchedAt.delete(filePath);
|
|
765
|
+
}
|
|
766
|
+
else {
|
|
767
|
+
bk.lastTouchedAt.set(filePath, next);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
/** Records that a file-mutating tool call is in flight against `filePath` so consumers can
|
|
771
|
+
* highlight the path. Refcounts per path — keyed by path (not `tool_use_id`, which the GK CLI
|
|
772
|
+
* doesn't reliably surface) so parallel calls bump the count and Post/Pre order doesn't matter.
|
|
773
|
+
* Returns whether the parent's published `fileActivity` actually changed so callers can fire
|
|
774
|
+
* when the surrounding {@link updateSessionStatus} short-circuits. */
|
|
775
|
+
trackToolUseFile(sessionId, event) {
|
|
776
|
+
const filePath = this.getEventFilePath(event);
|
|
777
|
+
if (filePath == null)
|
|
778
|
+
return false;
|
|
779
|
+
const bk = this.getBookkeeping(sessionId);
|
|
780
|
+
// A fresh Pre during a pending Post-cooldown means the file is live again — cancel the
|
|
781
|
+
// scheduled clear so the deferred drop doesn't run after the new tool already finished.
|
|
782
|
+
const pendingClear = bk.pendingFileClears.get(filePath);
|
|
783
|
+
if (pendingClear != null) {
|
|
784
|
+
clearTimeout(pendingClear);
|
|
785
|
+
bk.pendingFileClears.delete(filePath);
|
|
786
|
+
}
|
|
787
|
+
bk.currentFileCounts.set(filePath, (bk.currentFileCounts.get(filePath) ?? 0) + 1);
|
|
788
|
+
this.stampLastTouched(bk, filePath, 'edit');
|
|
789
|
+
return this.syncSessionFileActivityForChild(sessionId);
|
|
790
|
+
}
|
|
791
|
+
/** Decrements the in-flight refcount for a finished tool call's file. While the count stays
|
|
792
|
+
* above zero (overlapping parallel calls) the path remains marked. When the count drops to
|
|
793
|
+
* zero, leaves the entry in place at count `0` and schedules a {@link activityDecayMs}
|
|
794
|
+
* cooldown before actually dropping it — so a recently-edited file lingers as a decay tail
|
|
795
|
+
* on the treemap. A Pre arriving during cooldown cancels the timer and bumps the count back
|
|
796
|
+
* above zero. Returns whether the parent's published `fileActivity` changed (i.e. `editing`
|
|
797
|
+
* flipped off) so the PostToolUse caller can fire when its `updateSessionStatus` short-
|
|
798
|
+
* circuits (a parallel tool still in flight keeps activeToolCount > 0). */
|
|
799
|
+
scheduleClearToolUseFile(sessionId, event) {
|
|
800
|
+
const filePath = this.getEventFilePath(event);
|
|
801
|
+
if (filePath == null)
|
|
802
|
+
return false;
|
|
803
|
+
const bk = this.getBookkeeping(sessionId);
|
|
804
|
+
const count = bk.currentFileCounts.get(filePath);
|
|
805
|
+
// A duplicate / out-of-order Post during cooldown (count is already 0) would drive the
|
|
806
|
+
// refcount negative and schedule a second timer — ignore those so the cooldown stays
|
|
807
|
+
// authoritative until either its timer fires or a fresh Pre bumps the count back up.
|
|
808
|
+
if (count == null || count <= 0)
|
|
809
|
+
return false;
|
|
810
|
+
const next = count - 1;
|
|
811
|
+
bk.currentFileCounts.set(filePath, next);
|
|
812
|
+
// Re-sync so `editing` drops from `true` to `undefined` the moment refcount hits zero —
|
|
813
|
+
// the cooldown only governs when the path itself leaves the snapshot, not when the
|
|
814
|
+
// "live" boolean flips off.
|
|
815
|
+
const changed = this.syncSessionFileActivityForChild(sessionId);
|
|
816
|
+
if (next > 0)
|
|
817
|
+
return changed;
|
|
818
|
+
// Refcount just hit zero — keep the path in `currentFileCounts` for the cooldown window,
|
|
819
|
+
// then drop it.
|
|
820
|
+
this.scheduleFileDecayEviction(bk, sessionId, filePath);
|
|
821
|
+
return changed;
|
|
822
|
+
}
|
|
823
|
+
/** Schedules (replacing any prior timer) the {@link activityDecayMs} cooldown that finally
|
|
824
|
+
* drops `filePath` from the edit bookkeeping once it has fully decayed. Shared by the
|
|
825
|
+
* PostToolUse cooldown path and the Stop settle ({@link settleBookkeeping}); the path stays
|
|
826
|
+
* in `currentFileCounts` at count 0 meanwhile so its `editedAt` keeps aging on the client. */
|
|
827
|
+
scheduleFileDecayEviction(bk, sessionId, filePath) {
|
|
828
|
+
const existing = bk.pendingFileClears.get(filePath);
|
|
829
|
+
if (existing != null) {
|
|
830
|
+
clearTimeout(existing);
|
|
831
|
+
}
|
|
832
|
+
const timer = setTimeout(() => {
|
|
833
|
+
if (this._disposed)
|
|
834
|
+
return;
|
|
835
|
+
const cur = this._sessionBookkeeping.get(sessionId);
|
|
836
|
+
if (cur == null)
|
|
837
|
+
return;
|
|
838
|
+
cur.pendingFileClears.delete(filePath);
|
|
839
|
+
// Re-check: a Pre during cooldown bumped the count and cancelled this timer, but a
|
|
840
|
+
// concurrent reset could have cleared everything — bail in either case.
|
|
841
|
+
if ((cur.currentFileCounts.get(filePath) ?? 0) > 0)
|
|
842
|
+
return;
|
|
843
|
+
cur.currentFileCounts.delete(filePath);
|
|
844
|
+
this.clearLastTouched(cur, filePath, 'edit');
|
|
845
|
+
if (this.syncSessionFileActivityForChild(sessionId)) {
|
|
846
|
+
this._onDidChangeSessions.fire();
|
|
847
|
+
}
|
|
848
|
+
}, this.activityDecayMs);
|
|
849
|
+
bk.pendingFileClears.set(filePath, timer);
|
|
850
|
+
}
|
|
851
|
+
/** Drops a tracked tool call's file immediately (no cooldown). Used for PermissionDenied,
|
|
852
|
+
* where the tool never ran — keeping the "live" badge would be misleading.
|
|
853
|
+
* Returns whether the published list changed. */
|
|
854
|
+
untrackToolUseFile(sessionId, event) {
|
|
855
|
+
const filePath = this.getEventFilePath(event);
|
|
856
|
+
if (filePath == null)
|
|
857
|
+
return false;
|
|
858
|
+
const bk = this.getBookkeeping(sessionId);
|
|
859
|
+
const count = bk.currentFileCounts.get(filePath);
|
|
860
|
+
if (count == null)
|
|
861
|
+
return false;
|
|
862
|
+
if (count > 1) {
|
|
863
|
+
bk.currentFileCounts.set(filePath, count - 1);
|
|
864
|
+
return this.syncSessionFileActivityForChild(sessionId);
|
|
865
|
+
}
|
|
866
|
+
const pending = bk.pendingFileClears.get(filePath);
|
|
867
|
+
if (pending != null) {
|
|
868
|
+
clearTimeout(pending);
|
|
869
|
+
bk.pendingFileClears.delete(filePath);
|
|
870
|
+
}
|
|
871
|
+
bk.currentFileCounts.delete(filePath);
|
|
872
|
+
this.clearLastTouched(bk, filePath, 'edit');
|
|
873
|
+
return this.syncSessionFileActivityForChild(sessionId);
|
|
874
|
+
}
|
|
875
|
+
/** Mirror of {@link getEventFilePath} for read-only file tools. */
|
|
876
|
+
getEventReadPath(event) {
|
|
877
|
+
const toolName = event.hookInput?.tool_name ?? event.toolName;
|
|
878
|
+
if (toolName == null)
|
|
879
|
+
return undefined;
|
|
880
|
+
const rawHookInput = event.hookInput?.tool_input;
|
|
881
|
+
const hookInputPopulated = rawHookInput != null && Object.keys(rawHookInput).length > 0;
|
|
882
|
+
const toolInput = hookInputPopulated ? rawHookInput : event.toolInput;
|
|
883
|
+
return getToolReadPath(toolName, toolInput);
|
|
884
|
+
}
|
|
885
|
+
/** Refcount mirror of {@link trackToolUseFile} for read-only file tools. */
|
|
886
|
+
trackToolUseRead(sessionId, event) {
|
|
887
|
+
const filePath = this.getEventReadPath(event);
|
|
888
|
+
if (filePath == null)
|
|
889
|
+
return false;
|
|
890
|
+
const bk = this.getBookkeeping(sessionId);
|
|
891
|
+
const pendingClear = bk.pendingReadClears.get(filePath);
|
|
892
|
+
if (pendingClear != null) {
|
|
893
|
+
clearTimeout(pendingClear);
|
|
894
|
+
bk.pendingReadClears.delete(filePath);
|
|
895
|
+
}
|
|
896
|
+
bk.currentReadCounts.set(filePath, (bk.currentReadCounts.get(filePath) ?? 0) + 1);
|
|
897
|
+
this.stampLastTouched(bk, filePath, 'read');
|
|
898
|
+
return this.syncSessionFileActivityForChild(sessionId);
|
|
899
|
+
}
|
|
900
|
+
/** Cooldown mirror of {@link scheduleClearToolUseFile} for read-only file tools. Returns
|
|
901
|
+
* whether the parent's published `fileActivity` changed (i.e. `reading` flipped off). */
|
|
902
|
+
scheduleClearToolUseRead(sessionId, event) {
|
|
903
|
+
const filePath = this.getEventReadPath(event);
|
|
904
|
+
if (filePath == null)
|
|
905
|
+
return false;
|
|
906
|
+
const bk = this.getBookkeeping(sessionId);
|
|
907
|
+
const count = bk.currentReadCounts.get(filePath);
|
|
908
|
+
// Same guard as scheduleClearToolUseFile — duplicate / out-of-order Posts during cooldown
|
|
909
|
+
// would otherwise drive the refcount negative and stack up redundant clear timers.
|
|
910
|
+
if (count == null || count <= 0)
|
|
911
|
+
return false;
|
|
912
|
+
const next = count - 1;
|
|
913
|
+
bk.currentReadCounts.set(filePath, next);
|
|
914
|
+
// Re-sync so `reading` drops to `undefined` the moment refcount hits zero.
|
|
915
|
+
const changed = this.syncSessionFileActivityForChild(sessionId);
|
|
916
|
+
if (next > 0)
|
|
917
|
+
return changed;
|
|
918
|
+
this.scheduleReadDecayEviction(bk, sessionId, filePath);
|
|
919
|
+
return changed;
|
|
920
|
+
}
|
|
921
|
+
/** Read-class mirror of {@link scheduleFileDecayEviction}. */
|
|
922
|
+
scheduleReadDecayEviction(bk, sessionId, filePath) {
|
|
923
|
+
const existing = bk.pendingReadClears.get(filePath);
|
|
924
|
+
if (existing != null) {
|
|
925
|
+
clearTimeout(existing);
|
|
926
|
+
}
|
|
927
|
+
const timer = setTimeout(() => {
|
|
928
|
+
if (this._disposed)
|
|
929
|
+
return;
|
|
930
|
+
const cur = this._sessionBookkeeping.get(sessionId);
|
|
931
|
+
if (cur == null)
|
|
932
|
+
return;
|
|
933
|
+
cur.pendingReadClears.delete(filePath);
|
|
934
|
+
if ((cur.currentReadCounts.get(filePath) ?? 0) > 0)
|
|
935
|
+
return;
|
|
936
|
+
cur.currentReadCounts.delete(filePath);
|
|
937
|
+
this.clearLastTouched(cur, filePath, 'read');
|
|
938
|
+
if (this.syncSessionFileActivityForChild(sessionId)) {
|
|
939
|
+
this._onDidChangeSessions.fire();
|
|
940
|
+
}
|
|
941
|
+
}, this.activityDecayMs);
|
|
942
|
+
bk.pendingReadClears.set(filePath, timer);
|
|
943
|
+
}
|
|
944
|
+
/** Immediate-drop mirror of {@link untrackToolUseFile} for read-only file tools. */
|
|
945
|
+
untrackToolUseRead(sessionId, event) {
|
|
946
|
+
const filePath = this.getEventReadPath(event);
|
|
947
|
+
if (filePath == null)
|
|
948
|
+
return false;
|
|
949
|
+
const bk = this.getBookkeeping(sessionId);
|
|
950
|
+
const count = bk.currentReadCounts.get(filePath);
|
|
951
|
+
if (count == null)
|
|
952
|
+
return false;
|
|
953
|
+
if (count > 1) {
|
|
954
|
+
bk.currentReadCounts.set(filePath, count - 1);
|
|
955
|
+
return this.syncSessionFileActivityForChild(sessionId);
|
|
956
|
+
}
|
|
957
|
+
const pending = bk.pendingReadClears.get(filePath);
|
|
958
|
+
if (pending != null) {
|
|
959
|
+
clearTimeout(pending);
|
|
960
|
+
bk.pendingReadClears.delete(filePath);
|
|
961
|
+
}
|
|
962
|
+
bk.currentReadCounts.delete(filePath);
|
|
963
|
+
this.clearLastTouched(bk, filePath, 'read');
|
|
964
|
+
return this.syncSessionFileActivityForChild(sessionId);
|
|
965
|
+
}
|
|
966
|
+
/** Convenience wrapper that resolves the parent for a possibly-sub-agent session id, then calls
|
|
967
|
+
* {@link syncSessionFileActivity}. Tool-call handlers call this without knowing whether the
|
|
968
|
+
* session is a top-level or sub-agent session. Returns `false` when the session isn't found
|
|
969
|
+
* (already pruned / unknown peer id). */
|
|
970
|
+
syncSessionFileActivityForChild(sessionId) {
|
|
971
|
+
const parentId = this.findOwningParentId(sessionId);
|
|
972
|
+
if (parentId == null)
|
|
973
|
+
return false;
|
|
974
|
+
return this.syncSessionFileActivity(parentId);
|
|
975
|
+
}
|
|
976
|
+
/** Rebuilds the parent session's `fileActivity` array from its bookkeeping and writes it onto
|
|
977
|
+
* the session in place. Returns whether the *structural* shape changed (paths/kinds/flags) —
|
|
978
|
+
* timestamps are always refreshed regardless, but a fire is gated on structural change so
|
|
979
|
+
* non-meaningful drift doesn't churn the wire.
|
|
980
|
+
*
|
|
981
|
+
* No separate sub-agent rollup is needed: the GK CLI keys a sub-agent's tool events under its
|
|
982
|
+
* PARENT session id (with `agentId` set), so they accumulate in the parent's own bookkeeping
|
|
983
|
+
* directly and are already reflected here. Sub-agent serialized objects carry no `fileActivity`. */
|
|
984
|
+
syncSessionFileActivity(parentSessionId) {
|
|
985
|
+
const index = this._sessions.findIndex(s => s.id === parentSessionId);
|
|
986
|
+
if (index < 0)
|
|
987
|
+
return false;
|
|
988
|
+
const parent = this._sessions[index];
|
|
989
|
+
const parentBk = this._sessionBookkeeping.get(parentSessionId);
|
|
990
|
+
const merged = new Map();
|
|
991
|
+
const contributeFrom = (bk) => {
|
|
992
|
+
if (bk == null)
|
|
993
|
+
return;
|
|
994
|
+
for (const [path, count] of bk.currentFileCounts) {
|
|
995
|
+
let entry = merged.get(path);
|
|
996
|
+
if (entry == null) {
|
|
997
|
+
entry = { editCount: 0, readCount: 0 };
|
|
998
|
+
merged.set(path, entry);
|
|
999
|
+
}
|
|
1000
|
+
entry.editCount += count;
|
|
1001
|
+
const ts = bk.lastTouchedAt.get(path)?.edit;
|
|
1002
|
+
if (ts != null && (entry.editAt == null || ts > entry.editAt)) {
|
|
1003
|
+
entry.editAt = ts;
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
for (const [path, count] of bk.currentReadCounts) {
|
|
1007
|
+
let entry = merged.get(path);
|
|
1008
|
+
if (entry == null) {
|
|
1009
|
+
entry = { editCount: 0, readCount: 0 };
|
|
1010
|
+
merged.set(path, entry);
|
|
1011
|
+
}
|
|
1012
|
+
entry.readCount += count;
|
|
1013
|
+
const ts = bk.lastTouchedAt.get(path)?.read;
|
|
1014
|
+
if (ts != null && (entry.readAt == null || ts > entry.readAt)) {
|
|
1015
|
+
entry.readAt = ts;
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
};
|
|
1019
|
+
contributeFrom(parentBk);
|
|
1020
|
+
const now = Date.now();
|
|
1021
|
+
let next;
|
|
1022
|
+
if (merged.size > 0) {
|
|
1023
|
+
next = [];
|
|
1024
|
+
for (const [path, contrib] of merged) {
|
|
1025
|
+
const entry = { path: path };
|
|
1026
|
+
if (contrib.editAt != null) {
|
|
1027
|
+
entry.editedAt = Math.max(0, now - contrib.editAt);
|
|
1028
|
+
}
|
|
1029
|
+
if (contrib.readAt != null) {
|
|
1030
|
+
entry.readAt = Math.max(0, now - contrib.readAt);
|
|
1031
|
+
}
|
|
1032
|
+
if (contrib.editCount > 0) {
|
|
1033
|
+
entry.editing = true;
|
|
1034
|
+
}
|
|
1035
|
+
if (contrib.readCount > 0) {
|
|
1036
|
+
entry.reading = true;
|
|
1037
|
+
}
|
|
1038
|
+
next.push(entry);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
const changed = !fileActivityStructurallyEqual(parent.fileActivity, next);
|
|
1042
|
+
// Always replace so timestamps reflect the latest serialization, even when the structural
|
|
1043
|
+
// shape is unchanged (so a downstream fire from anywhere else carries fresh `sinceMs`).
|
|
1044
|
+
this._sessions[index] = { ...parent, fileActivity: next };
|
|
1045
|
+
return changed;
|
|
1046
|
+
}
|
|
1047
|
+
/** Defer the `Stop → idle` commit. If the agent produces a non-idle event within
|
|
1048
|
+
* `stopToIdleDebounceMs`, `cancelPendingIdleTransition` (called from `updateSessionStatus`)
|
|
1049
|
+
* cancels this and the session stays in its prior phase — no working → idle → working flicker.
|
|
1050
|
+
*
|
|
1051
|
+
* Intentionally takes no context: the caller is expected to apply any event metadata
|
|
1052
|
+
* synchronously before scheduling. Carrying Stop-time context into the timer would let
|
|
1053
|
+
* in-window metadata mutations (e.g. `CwdChanged` updating `_sessions[i].cwd` directly)
|
|
1054
|
+
* get reverted when the deferred commit replays the stale context through `ensureSession`. */
|
|
1055
|
+
scheduleIdleTransition(sessionId) {
|
|
1056
|
+
this.cancelPendingIdleTransition(sessionId);
|
|
1057
|
+
const timer = setTimeout(() => {
|
|
1058
|
+
this._pendingIdleTimers.delete(sessionId);
|
|
1059
|
+
// Session may have been removed (SessionEnd, prune) during the window.
|
|
1060
|
+
if (this._sessions.findIndex(s => s.id === sessionId) < 0)
|
|
1061
|
+
return;
|
|
1062
|
+
this.updateSessionStatus(sessionId, 'idle');
|
|
1063
|
+
}, stopToIdleDebounceMs);
|
|
1064
|
+
this._pendingIdleTimers.set(sessionId, timer);
|
|
1065
|
+
}
|
|
1066
|
+
cancelPendingIdleTransition(sessionId) {
|
|
1067
|
+
const timer = this._pendingIdleTimers.get(sessionId);
|
|
1068
|
+
if (timer == null)
|
|
1069
|
+
return;
|
|
1070
|
+
clearTimeout(timer);
|
|
1071
|
+
this._pendingIdleTimers.delete(sessionId);
|
|
1072
|
+
}
|
|
1073
|
+
/** Stable phase-since: if we're oscillating back into the phase we were just in (within a
|
|
1074
|
+
* short window), restore its original timestamp so the displayed elapsed time doesn't snap
|
|
1075
|
+
* to 0. Otherwise records the current phase as the new "prior" and returns `now`. */
|
|
1076
|
+
resolvePhaseSince(sessionId, prevPhase, prevPhaseSince, newPhase) {
|
|
1077
|
+
if (prevPhase === newPhase)
|
|
1078
|
+
return prevPhaseSince;
|
|
1079
|
+
const bk = this.getBookkeeping(sessionId);
|
|
1080
|
+
const now = new Date();
|
|
1081
|
+
if (bk.priorPhase?.phase === newPhase && now.getTime() - prevPhaseSince.getTime() < phaseSinceRestoreWindowMs) {
|
|
1082
|
+
const restored = bk.priorPhase.phaseSince;
|
|
1083
|
+
bk.priorPhase = { phase: prevPhase, phaseSince: prevPhaseSince };
|
|
1084
|
+
return restored;
|
|
1085
|
+
}
|
|
1086
|
+
bk.priorPhase = { phase: prevPhase, phaseSince: prevPhaseSince };
|
|
1087
|
+
return now;
|
|
1088
|
+
}
|
|
1089
|
+
// Called when a pending permission was resolved outside GitLens (e.g. via the CLI terminal).
|
|
1090
|
+
// The 'deny' response is a safe no-op since the tool has already run or been denied upstream.
|
|
1091
|
+
clearStalePermission(sessionId, reason) {
|
|
1092
|
+
const bk = this.getBookkeeping(sessionId);
|
|
1093
|
+
if (bk.pendingPermission == null)
|
|
1094
|
+
return;
|
|
1095
|
+
Logger.debug(`ClaudeCodeProvider.clearStalePermission: ${reason} ${this.sessionTag(sessionId)}`);
|
|
1096
|
+
const pending = this._pendingPermissions.get(sessionId);
|
|
1097
|
+
if (pending != null) {
|
|
1098
|
+
pending.resolve({
|
|
1099
|
+
hookSpecificOutput: { hookEventName: 'PermissionRequest', decision: { behavior: 'deny' } },
|
|
1100
|
+
});
|
|
1101
|
+
this._pendingPermissions.delete(sessionId);
|
|
1102
|
+
}
|
|
1103
|
+
bk.pendingPermission = undefined;
|
|
1104
|
+
}
|
|
1105
|
+
resolvePermission(sessionId, decision, updatedPermissions) {
|
|
1106
|
+
const pending = this._pendingPermissions.get(sessionId);
|
|
1107
|
+
if (pending == null)
|
|
1108
|
+
return false;
|
|
1109
|
+
Logger.debug(`ClaudeCodeProvider.resolvePermission: ${decision} ${this.sessionTag(sessionId)} tool=${pending.toolName}`);
|
|
1110
|
+
pending.resolve({
|
|
1111
|
+
hookSpecificOutput: {
|
|
1112
|
+
hookEventName: 'PermissionRequest',
|
|
1113
|
+
decision: { behavior: decision, updatedPermissions: updatedPermissions },
|
|
1114
|
+
},
|
|
1115
|
+
});
|
|
1116
|
+
this.callbacks.onPermissionResolved?.({
|
|
1117
|
+
provider: this.id,
|
|
1118
|
+
tool: pending.toolName,
|
|
1119
|
+
decision: decision,
|
|
1120
|
+
});
|
|
1121
|
+
this._pendingPermissions.delete(sessionId);
|
|
1122
|
+
const bk = this.getBookkeeping(sessionId);
|
|
1123
|
+
bk.pendingPermission = undefined;
|
|
1124
|
+
const nextStatus = bk.activeToolCount > 0 ? 'tool_use' : 'thinking';
|
|
1125
|
+
this.updateSessionStatus(sessionId, nextStatus);
|
|
1126
|
+
return true;
|
|
1127
|
+
}
|
|
1128
|
+
matchesWorkspace(workspacePath) {
|
|
1129
|
+
if (!workspacePath)
|
|
1130
|
+
return false;
|
|
1131
|
+
// `_workspacePaths` is normalized; normalize the input so prefix comparisons work
|
|
1132
|
+
// regardless of whether the caller passed a raw `fsPath` (CLI hook cwd, peer-session
|
|
1133
|
+
// workspacePath) or an already-normalized path.
|
|
1134
|
+
const normalized = normalizePath(workspacePath);
|
|
1135
|
+
return this._workspacePaths.some(p => normalized === p || normalized.startsWith(`${p}/`) || p.startsWith(`${normalized}/`));
|
|
1136
|
+
}
|
|
1137
|
+
resolveWorkspacePath(cwd) {
|
|
1138
|
+
if (!cwd)
|
|
1139
|
+
return undefined;
|
|
1140
|
+
const normalized = normalizePath(cwd);
|
|
1141
|
+
return this._workspacePaths.find(p => normalized === p || normalized.startsWith(`${p}/`) || p.startsWith(`${normalized}/`));
|
|
1142
|
+
}
|
|
1143
|
+
updateSessionWithPermission(sessionId, permission, pid) {
|
|
1144
|
+
// A pending permission is a working/waiting transition — cancel any deferred Stop → idle
|
|
1145
|
+
// commit so the session doesn't briefly flip to idle before showing the prompt.
|
|
1146
|
+
this.cancelPendingIdleTransition(sessionId);
|
|
1147
|
+
const { index } = this.ensureSession(sessionId, { pid: pid });
|
|
1148
|
+
const prev = this._sessions[index];
|
|
1149
|
+
const newPhase = getPhaseForStatus('permission_requested');
|
|
1150
|
+
this.getBookkeeping(sessionId).pendingPermission = permission;
|
|
1151
|
+
this._sessions[index] = {
|
|
1152
|
+
...prev,
|
|
1153
|
+
status: 'permission_requested',
|
|
1154
|
+
phase: newPhase,
|
|
1155
|
+
phaseSince: this.resolvePhaseSince(sessionId, prev.phase, prev.phaseSince, newPhase),
|
|
1156
|
+
statusDetail: permission.toolDescription,
|
|
1157
|
+
pendingPermission: permission,
|
|
1158
|
+
lastActivity: new Date(),
|
|
1159
|
+
};
|
|
1160
|
+
this._onDidChangeSessions.fire();
|
|
1161
|
+
}
|
|
1162
|
+
updateSessionStatus(sessionId, status, options) {
|
|
1163
|
+
// Any non-idle status update implicitly cancels a deferred Stop → idle commit. The
|
|
1164
|
+
// timer is owned here so the schedule/cancel pair is uniformly enforced regardless of
|
|
1165
|
+
// which event path produced the next status.
|
|
1166
|
+
if (status !== 'idle') {
|
|
1167
|
+
this.cancelPendingIdleTransition(sessionId);
|
|
1168
|
+
}
|
|
1169
|
+
const { index, changed: metadataChanged } = this.ensureSession(sessionId, options);
|
|
1170
|
+
const prev = this._sessions[index];
|
|
1171
|
+
const bk = this.getBookkeeping(sessionId);
|
|
1172
|
+
// If a permission/elicitation is pending, preserve permission_requested state.
|
|
1173
|
+
// Tool counts and other bookkeeping are still updated by callers before this
|
|
1174
|
+
// method, but the visible status remains locked until the wait is explicitly
|
|
1175
|
+
// resolved.
|
|
1176
|
+
if (bk.pendingPermission != null && status !== 'permission_requested') {
|
|
1177
|
+
this._sessions[index] = { ...prev, lastActivity: new Date() };
|
|
1178
|
+
if (metadataChanged) {
|
|
1179
|
+
this._onDidChangeSessions.fire();
|
|
1180
|
+
}
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
const statusDetail = options?.statusDetail;
|
|
1184
|
+
if (prev.status === status && prev.statusDetail === statusDetail) {
|
|
1185
|
+
if (metadataChanged) {
|
|
1186
|
+
this._onDidChangeSessions.fire();
|
|
1187
|
+
}
|
|
1188
|
+
return;
|
|
1189
|
+
}
|
|
1190
|
+
const newPhase = getPhaseForStatus(status);
|
|
1191
|
+
this._sessions[index] = {
|
|
1192
|
+
...prev,
|
|
1193
|
+
status: status,
|
|
1194
|
+
phase: newPhase,
|
|
1195
|
+
phaseSince: this.resolvePhaseSince(sessionId, prev.phase, prev.phaseSince, newPhase),
|
|
1196
|
+
statusDetail: statusDetail,
|
|
1197
|
+
pendingPermission: status === 'permission_requested' ? bk.pendingPermission : undefined,
|
|
1198
|
+
lastActivity: new Date(),
|
|
1199
|
+
};
|
|
1200
|
+
this._onDidChangeSessions.fire();
|
|
1201
|
+
if (status === 'thinking' || status === 'tool_use' || status === 'compacting') {
|
|
1202
|
+
const sessionCwd = this._sessions[index].cwd;
|
|
1203
|
+
if (sessionCwd != null) {
|
|
1204
|
+
this.callbacks.onBranchAgentActivity?.(sessionCwd);
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
// On a fresh transition into idle, recheck transcript titles — Claude typically (re-)writes
|
|
1208
|
+
// `ai-title` right after finishing a response, so this is the prime moment to pick it up.
|
|
1209
|
+
// Tail-read caching makes repeated checks cheap.
|
|
1210
|
+
if (status === 'idle' && prev.status !== 'idle') {
|
|
1211
|
+
void this.resolveTranscriptTitles(sessionId, this._sessions[index].cwd);
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
ensureSession(sessionId, context) {
|
|
1215
|
+
const { pid, workspacePath, isInWorkspace, cwd, initialCwd, planFile, sessionName } = context ?? {};
|
|
1216
|
+
let index = this._sessions.findIndex(s => s.id === sessionId);
|
|
1217
|
+
if (index < 0) {
|
|
1218
|
+
const now = new Date();
|
|
1219
|
+
index = this._sessions.length;
|
|
1220
|
+
this._sessions.push({
|
|
1221
|
+
id: sessionId,
|
|
1222
|
+
providerId: this.id,
|
|
1223
|
+
providerName: this.name,
|
|
1224
|
+
name: sessionName || undefined,
|
|
1225
|
+
status: 'idle',
|
|
1226
|
+
phase: getPhaseForStatus('idle'),
|
|
1227
|
+
phaseSince: now,
|
|
1228
|
+
pid: pid,
|
|
1229
|
+
lastActivity: now,
|
|
1230
|
+
isSubagent: false,
|
|
1231
|
+
workspacePath: workspacePath,
|
|
1232
|
+
cwd: cwd,
|
|
1233
|
+
initialCwd: initialCwd ?? cwd,
|
|
1234
|
+
planFile: planFile,
|
|
1235
|
+
isInWorkspace: isInWorkspace ?? false,
|
|
1236
|
+
});
|
|
1237
|
+
Logger.debug(`ClaudeCodeProvider.ensureSession: implicitly created ${this.sessionTag(sessionId, sessionName ?? 'unnamed')}`);
|
|
1238
|
+
this._onDidChangeSessions.fire();
|
|
1239
|
+
if (cwd != null) {
|
|
1240
|
+
void this.resolveGitInfo(sessionId, cwd);
|
|
1241
|
+
}
|
|
1242
|
+
void this.resolveTranscriptTitles(sessionId, cwd);
|
|
1243
|
+
return { index: index, changed: true };
|
|
1244
|
+
}
|
|
1245
|
+
const existing = this._sessions[index];
|
|
1246
|
+
const updatedPid = pid != null && existing.pid == null ? pid : existing.pid;
|
|
1247
|
+
const updatedWorkspacePath = workspacePath || existing.workspacePath;
|
|
1248
|
+
const updatedIsInWorkspace = workspacePath ? (isInWorkspace ?? existing.isInWorkspace) : existing.isInWorkspace;
|
|
1249
|
+
const updatedPlanFile = planFile ?? existing.planFile;
|
|
1250
|
+
const updatedName = sessionName || existing.name;
|
|
1251
|
+
const updatedCwd = cwd ?? existing.cwd;
|
|
1252
|
+
// Prefer the CLI's authoritative `initialCwd` (the true launch dir it captured first-hand,
|
|
1253
|
+
// even for sessions that started before this window opened); otherwise keep whatever we
|
|
1254
|
+
// already captured, and only as a last resort backfill from the current cwd (older CLIs that
|
|
1255
|
+
// don't send `initialCwd`, or a cold-create before any cwd was known). Comparing live `cwd`
|
|
1256
|
+
// against `initialCwd` is how consumers detect launch-vs-current drift, so it stays stable.
|
|
1257
|
+
const updatedInitialCwd = initialCwd ?? existing.initialCwd ?? cwd;
|
|
1258
|
+
let changed = false;
|
|
1259
|
+
if (updatedPid !== existing.pid ||
|
|
1260
|
+
updatedWorkspacePath !== existing.workspacePath ||
|
|
1261
|
+
updatedIsInWorkspace !== existing.isInWorkspace ||
|
|
1262
|
+
updatedPlanFile !== existing.planFile ||
|
|
1263
|
+
updatedName !== existing.name ||
|
|
1264
|
+
updatedCwd !== existing.cwd ||
|
|
1265
|
+
updatedInitialCwd !== existing.initialCwd) {
|
|
1266
|
+
this._sessions[index] = {
|
|
1267
|
+
...existing,
|
|
1268
|
+
name: updatedName,
|
|
1269
|
+
pid: updatedPid,
|
|
1270
|
+
workspacePath: updatedWorkspacePath,
|
|
1271
|
+
cwd: updatedCwd,
|
|
1272
|
+
initialCwd: updatedInitialCwd,
|
|
1273
|
+
planFile: updatedPlanFile,
|
|
1274
|
+
isInWorkspace: updatedIsInWorkspace,
|
|
1275
|
+
};
|
|
1276
|
+
changed = true;
|
|
1277
|
+
}
|
|
1278
|
+
// Re-fire `resolveGitInfo` if the session is missing either `worktreePath` or `commonPath`.
|
|
1279
|
+
// Peer-synced sessions arrive with `worktreePath` already set (from the peer that owns the
|
|
1280
|
+
// hook flow) but may lack `commonPath` if the peer was running pre-commonPath code; this
|
|
1281
|
+
// gives us a chance to fill it in locally. Idempotent — `resolveGitInfo` only mutates the
|
|
1282
|
+
// session when one of `cwd`/`worktreePath`/`commonPath` actually changes. The
|
|
1283
|
+
// `gitInfoUnresolvable` bookkeeping flag (see `SessionBookkeeping`) is set once
|
|
1284
|
+
// `resolveGitInfo` confirms the cwd isn't a git repo, preventing a retry storm on every
|
|
1285
|
+
// hook event for non-git-repo cwds. The flag is cleared on cwd change (`CwdChanged`) and
|
|
1286
|
+
// on `resetBookkeeping` (Stop/SessionStart) so re-resolution can happen when warranted.
|
|
1287
|
+
if (cwd != null &&
|
|
1288
|
+
(existing.worktreePath == null || existing.commonPath == null) &&
|
|
1289
|
+
!this.getBookkeeping(sessionId).gitInfoUnresolvable) {
|
|
1290
|
+
void this.resolveGitInfo(sessionId, cwd);
|
|
1291
|
+
}
|
|
1292
|
+
return { index: index, changed: changed };
|
|
1293
|
+
}
|
|
1294
|
+
async resolveGitInfo(sessionId, cwd) {
|
|
1295
|
+
const resolveGitInfo = this.callbacks.resolveGitInfo;
|
|
1296
|
+
if (resolveGitInfo == null)
|
|
1297
|
+
return;
|
|
1298
|
+
// Dedupe concurrent calls for the same session — every hook event (PreToolUse, PostToolUse,
|
|
1299
|
+
// UserPromptSubmit, etc.) flows through `ensureSession`, which retries `resolveGitInfo`
|
|
1300
|
+
// whenever `commonPath`/`worktreePath` is missing. Without this guard a non-git-repo cwd
|
|
1301
|
+
// would spawn a fresh git probe per hook event. The `gitInfoUnresolvable` bookkeeping flag
|
|
1302
|
+
// (set below when `info == null`) is the long-lived suppressor across hook events; this
|
|
1303
|
+
// in-flight set only dedupes concurrent overlapping probes within a single resolution.
|
|
1304
|
+
if (this._resolveGitInfoInFlight.has(sessionId))
|
|
1305
|
+
return;
|
|
1306
|
+
this._resolveGitInfoInFlight.add(sessionId);
|
|
1307
|
+
try {
|
|
1308
|
+
let info;
|
|
1309
|
+
try {
|
|
1310
|
+
info = await resolveGitInfo(cwd);
|
|
1311
|
+
}
|
|
1312
|
+
catch {
|
|
1313
|
+
// Git not available or not a git repo — fall through to mark unresolvable below
|
|
1314
|
+
info = undefined;
|
|
1315
|
+
}
|
|
1316
|
+
const index = this._sessions.findIndex(s => s.id === sessionId);
|
|
1317
|
+
if (index < 0)
|
|
1318
|
+
return;
|
|
1319
|
+
const session = this._sessions[index];
|
|
1320
|
+
// `workspacePath` stays as the matched workspace folder (or undefined). Repo identity
|
|
1321
|
+
// flows through `commonPath`, populated here from `info.repoRoot` at the same step as
|
|
1322
|
+
// `worktreePath` — both available together from `resolveGitInfo`, much earlier than the
|
|
1323
|
+
// follow-on worktree-name refresh (which needs `getWorktrees()` on the parent repo).
|
|
1324
|
+
//
|
|
1325
|
+
// When `info == null` (cwd is not inside any git repo), set the `gitInfoUnresolvable`
|
|
1326
|
+
// bookkeeping flag so subsequent `ensureSession`/peer-sync retry checks skip re-firing.
|
|
1327
|
+
// We deliberately do NOT write a tombstone onto the session DTO — keeping `commonPath`
|
|
1328
|
+
// as `undefined` (a) keeps the wire-shape unambiguous for peers, (b) lets consumers
|
|
1329
|
+
// safely treat undefined as "no repo identity", and (c) means peers can still attempt
|
|
1330
|
+
// their own local resolution. The flag is cleared on cwd change (`CwdChanged`) and on
|
|
1331
|
+
// `resetBookkeeping` so re-resolution happens when warranted (e.g. user runs `git init`
|
|
1332
|
+
// followed by a new session start).
|
|
1333
|
+
if (info == null) {
|
|
1334
|
+
this.getBookkeeping(sessionId).gitInfoUnresolvable = true;
|
|
1335
|
+
if (cwd !== session.cwd) {
|
|
1336
|
+
this._sessions[index] = { ...session, cwd: cwd };
|
|
1337
|
+
this._onDidChangeSessions.fire();
|
|
1338
|
+
}
|
|
1339
|
+
return;
|
|
1340
|
+
}
|
|
1341
|
+
// Capture the worktree/commonPath at the first successful resolve so consumers can
|
|
1342
|
+
// detect drift (e.g. an agent that `cd`'d into a sibling worktree after launch). Gated
|
|
1343
|
+
// on `initialCommonPath` — captured together with `initialWorktreePath` so a first
|
|
1344
|
+
// resolve where `info.worktreePath` happens to be undefined doesn't leave the latter
|
|
1345
|
+
// open to a later overwrite. Once set, never overwritten.
|
|
1346
|
+
const firstResolve = session.initialCommonPath == null;
|
|
1347
|
+
const updatedInitialWorktreePath = firstResolve ? info.worktreePath : session.initialWorktreePath;
|
|
1348
|
+
const updatedInitialCommonPath = firstResolve ? info.repoRoot : session.initialCommonPath;
|
|
1349
|
+
if (cwd !== session.cwd ||
|
|
1350
|
+
info.worktreePath !== session.worktreePath ||
|
|
1351
|
+
info.repoRoot !== session.commonPath ||
|
|
1352
|
+
updatedInitialWorktreePath !== session.initialWorktreePath ||
|
|
1353
|
+
updatedInitialCommonPath !== session.initialCommonPath) {
|
|
1354
|
+
this._sessions[index] = {
|
|
1355
|
+
...session,
|
|
1356
|
+
cwd: cwd,
|
|
1357
|
+
worktreePath: info.worktreePath,
|
|
1358
|
+
commonPath: info.repoRoot,
|
|
1359
|
+
initialWorktreePath: updatedInitialWorktreePath,
|
|
1360
|
+
initialCommonPath: updatedInitialCommonPath,
|
|
1361
|
+
};
|
|
1362
|
+
this._onDidChangeSessions.fire();
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
finally {
|
|
1366
|
+
this._resolveGitInfoInFlight.delete(sessionId);
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
async resolveTranscriptTitles(sessionId, cwd) {
|
|
1370
|
+
let titles;
|
|
1371
|
+
try {
|
|
1372
|
+
titles = await this._transcriptReader.resolve(sessionId, cwd);
|
|
1373
|
+
}
|
|
1374
|
+
catch {
|
|
1375
|
+
return;
|
|
1376
|
+
}
|
|
1377
|
+
if (titles == null)
|
|
1378
|
+
return;
|
|
1379
|
+
const index = this._sessions.findIndex(s => s.id === sessionId);
|
|
1380
|
+
if (index < 0)
|
|
1381
|
+
return;
|
|
1382
|
+
const session = this._sessions[index];
|
|
1383
|
+
const prev = session.transcriptTitles;
|
|
1384
|
+
if (prev?.custom === titles.custom && prev?.ai === titles.ai && prev?.agent === titles.agent)
|
|
1385
|
+
return;
|
|
1386
|
+
this._sessions[index] = {
|
|
1387
|
+
...session,
|
|
1388
|
+
transcriptTitles: { custom: titles.custom, ai: titles.ai, agent: titles.agent },
|
|
1389
|
+
};
|
|
1390
|
+
this._onDidChangeSessions.fire();
|
|
1391
|
+
}
|
|
1392
|
+
pruneDeadSessions() {
|
|
1393
|
+
const kept = [];
|
|
1394
|
+
const removedIds = [];
|
|
1395
|
+
for (const s of this._sessions) {
|
|
1396
|
+
// A session blocking on us for a permission decision is by definition alive,
|
|
1397
|
+
// even if `kill(pid, 0)` says otherwise (e.g. transient EPERM/ESRCH). Dropping
|
|
1398
|
+
// it here loses pendingPermission and lastPrompt; the next syncSessions then
|
|
1399
|
+
// re-adds it as a stale shell with `permission_requested` status but no detail.
|
|
1400
|
+
if (s.pid == null || isProcessAlive(s.pid) || this._pendingPermissions.has(s.id)) {
|
|
1401
|
+
kept.push(s);
|
|
1402
|
+
}
|
|
1403
|
+
else {
|
|
1404
|
+
removedIds.push(s.id);
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
if (removedIds.length === 0)
|
|
1408
|
+
return false;
|
|
1409
|
+
this._sessions = kept;
|
|
1410
|
+
for (const id of removedIds) {
|
|
1411
|
+
const pending = this._pendingPermissions.get(id);
|
|
1412
|
+
if (pending != null) {
|
|
1413
|
+
pending.reject(new Error('Session pruned'));
|
|
1414
|
+
this._pendingPermissions.delete(id);
|
|
1415
|
+
}
|
|
1416
|
+
this.cancelPendingIdleTransition(id);
|
|
1417
|
+
// Cancel any in-flight decay-eviction timers before dropping the bookkeeping (mirrors
|
|
1418
|
+
// SessionEnd). A Stopped-then-killed session reaches here with armed cooldown timers
|
|
1419
|
+
// (settleBookkeeping leaves them running), so without this they'd leak until they fire.
|
|
1420
|
+
const bk = this._sessionBookkeeping.get(id);
|
|
1421
|
+
if (bk != null) {
|
|
1422
|
+
this.cancelPendingFileClears(bk);
|
|
1423
|
+
this.cancelPendingReadClears(bk);
|
|
1424
|
+
}
|
|
1425
|
+
this._sessionBookkeeping.delete(id);
|
|
1426
|
+
this._transcriptReader.forget(id);
|
|
1427
|
+
}
|
|
1428
|
+
Logger.debug(`ClaudeCodeProvider.syncSessions: removed ${removedIds.length} stale session(s): ${removedIds.map(id => id.substring(0, 8)).join(', ')}`);
|
|
1429
|
+
return true;
|
|
1430
|
+
}
|
|
1431
|
+
async syncSessions(options) {
|
|
1432
|
+
// Recurring (gated) calls skip the CLI spawn when there's nothing to reconcile: no tracked
|
|
1433
|
+
// sessions AND no installed hooks. Sessions only ever appear via the IPC push path or a peer,
|
|
1434
|
+
// so an empty list with hooks off means no agents are reachable here. We still poll whenever
|
|
1435
|
+
// sessions exist — that's the only local backstop for pruning agents that die without firing
|
|
1436
|
+
// `SessionEnd`, and it keeps us correct even if hook detection is stale/wrong. The bootstrap
|
|
1437
|
+
// call in `ensureIpcServer` passes no options, so cold-start discovery always runs.
|
|
1438
|
+
if (options?.gate && this._sessions.length === 0 && !this._claudeHooksInstalled)
|
|
1439
|
+
return;
|
|
1440
|
+
let sessions;
|
|
1441
|
+
try {
|
|
1442
|
+
const output = await this.callbacks.runCLICommand(['ai', 'hook', 'list-sessions', '--json']);
|
|
1443
|
+
sessions = JSON.parse(output);
|
|
1444
|
+
}
|
|
1445
|
+
catch {
|
|
1446
|
+
if (this.pruneDeadSessions()) {
|
|
1447
|
+
this._onDidChangeSessions.fire();
|
|
1448
|
+
}
|
|
1449
|
+
return;
|
|
1450
|
+
}
|
|
1451
|
+
// Snapshot what the live IPC path had already tracked, so we can detect drift between it and
|
|
1452
|
+
// what the poll returns. Ideally they match exactly — any difference means the live push path
|
|
1453
|
+
// missed an add (poll discovers it) or a teardown (poll no longer reports a session we track).
|
|
1454
|
+
const trackedBefore = new Set(this._sessions.map(s => s.id));
|
|
1455
|
+
const polledAlive = new Set();
|
|
1456
|
+
// Mutable copy of `trackedBefore` that also accumulates ids added during this poll, so the
|
|
1457
|
+
// membership check below is O(1) and duplicate ids within a single poll response are only
|
|
1458
|
+
// added once. `trackedBefore` itself stays the pre-poll snapshot used by the `missing` calc.
|
|
1459
|
+
const known = new Set(trackedBefore);
|
|
1460
|
+
let changed = false;
|
|
1461
|
+
let discovered = 0;
|
|
1462
|
+
for (const data of sessions) {
|
|
1463
|
+
if (!data.sessionId || !data.pid || !isProcessAlive(data.pid)) {
|
|
1464
|
+
continue;
|
|
1465
|
+
}
|
|
1466
|
+
polledAlive.add(data.sessionId);
|
|
1467
|
+
if (known.has(data.sessionId))
|
|
1468
|
+
continue;
|
|
1469
|
+
known.add(data.sessionId);
|
|
1470
|
+
const workspacePath = this.resolveWorkspacePath(data.cwd);
|
|
1471
|
+
const isInWorkspace = workspacePath != null;
|
|
1472
|
+
const status = deriveStatusFromEvent(data.event);
|
|
1473
|
+
const phase = getPhaseForStatus(status);
|
|
1474
|
+
const activityDate = new Date(data.updatedAt);
|
|
1475
|
+
const subagents = data.subagents?.map(sub => ({
|
|
1476
|
+
id: sub.agentId,
|
|
1477
|
+
providerId: this.id,
|
|
1478
|
+
providerName: this.name,
|
|
1479
|
+
name: sub.agentType ?? 'Subagent',
|
|
1480
|
+
status: 'thinking',
|
|
1481
|
+
phase: 'working',
|
|
1482
|
+
phaseSince: activityDate,
|
|
1483
|
+
lastActivity: activityDate,
|
|
1484
|
+
isSubagent: true,
|
|
1485
|
+
parentId: data.sessionId,
|
|
1486
|
+
isInWorkspace: isInWorkspace,
|
|
1487
|
+
}));
|
|
1488
|
+
this._sessions.push({
|
|
1489
|
+
id: data.sessionId,
|
|
1490
|
+
providerId: this.id,
|
|
1491
|
+
providerName: this.name,
|
|
1492
|
+
name: data.sessionName || undefined,
|
|
1493
|
+
status: status,
|
|
1494
|
+
phase: phase,
|
|
1495
|
+
phaseSince: activityDate,
|
|
1496
|
+
pid: data.pid,
|
|
1497
|
+
lastActivity: activityDate,
|
|
1498
|
+
isSubagent: false,
|
|
1499
|
+
workspacePath: workspacePath,
|
|
1500
|
+
cwd: data.cwd,
|
|
1501
|
+
// Prefer the CLI's launch dir; fall back to the snapshot's (possibly drifted) cwd on
|
|
1502
|
+
// older CLIs that don't record it. Without this, a window that cold-starts after the
|
|
1503
|
+
// agent drifted would stamp the drifted cwd as the launch dir.
|
|
1504
|
+
initialCwd: data.initialCwd ?? data.cwd,
|
|
1505
|
+
planFile: data.planFile ?? undefined,
|
|
1506
|
+
isInWorkspace: isInWorkspace,
|
|
1507
|
+
lastPrompt: prepareStoredPrompt(data.prompt ?? undefined),
|
|
1508
|
+
firstPrompt: prepareStoredPrompt(data.firstPrompt ?? undefined),
|
|
1509
|
+
subagents: subagents,
|
|
1510
|
+
});
|
|
1511
|
+
changed = true;
|
|
1512
|
+
discovered++;
|
|
1513
|
+
if (data.cwd) {
|
|
1514
|
+
void this.resolveGitInfo(data.sessionId, data.cwd);
|
|
1515
|
+
}
|
|
1516
|
+
void this.resolveTranscriptTitles(data.sessionId, data.cwd);
|
|
1517
|
+
}
|
|
1518
|
+
if (this.pruneDeadSessions()) {
|
|
1519
|
+
changed = true;
|
|
1520
|
+
}
|
|
1521
|
+
if (changed) {
|
|
1522
|
+
this._onDidChangeSessions.fire();
|
|
1523
|
+
}
|
|
1524
|
+
// Report any drift between the live-synced set and the poll. Only on the recurring (gated)
|
|
1525
|
+
// poll — the ungated bootstrap call runs before the live path has had a chance to receive
|
|
1526
|
+
// any events, so its discoveries are expected cold-start state, not drift. `missing` counts
|
|
1527
|
+
// sessions we still track that the poll no longer reports alive (a teardown the live path
|
|
1528
|
+
// missed, e.g. an agent killed without firing `SessionEnd`).
|
|
1529
|
+
if (options?.gate) {
|
|
1530
|
+
let missing = 0;
|
|
1531
|
+
for (const id of trackedBefore) {
|
|
1532
|
+
if (!polledAlive.has(id)) {
|
|
1533
|
+
missing++;
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
if (discovered > 0 || missing > 0) {
|
|
1537
|
+
this.callbacks.onSyncDiscrepancy?.({
|
|
1538
|
+
provider: this.id,
|
|
1539
|
+
discovered: discovered,
|
|
1540
|
+
missing: missing,
|
|
1541
|
+
polled: polledAlive.size,
|
|
1542
|
+
tracked: trackedBefore.size,
|
|
1543
|
+
});
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
async querySiblingWindowSessions() {
|
|
1548
|
+
const discoveryDir = this.callbacks.ipc.agentDiscoveryDir;
|
|
1549
|
+
if (discoveryDir == null)
|
|
1550
|
+
return;
|
|
1551
|
+
let files;
|
|
1552
|
+
try {
|
|
1553
|
+
files = await readdir(discoveryDir);
|
|
1554
|
+
}
|
|
1555
|
+
catch {
|
|
1556
|
+
return;
|
|
1557
|
+
}
|
|
1558
|
+
const ownPort = this.callbacks.ipc.port;
|
|
1559
|
+
const peerBatches = await Promise.all(files
|
|
1560
|
+
.filter(f => f.startsWith('gitlens-ipc-server-') && f.endsWith('.json'))
|
|
1561
|
+
.map(async (f) => this.fetchPeerSessions(join(discoveryDir, f), ownPort)));
|
|
1562
|
+
let changed = false;
|
|
1563
|
+
// Peer sessions that arrived with `cwd` but no `commonPath` (peer was running pre-
|
|
1564
|
+
// commonPath code, OR the peer's own `resolveGitInfo` failed and we get to retry locally).
|
|
1565
|
+
// Resolved after the merge loop so the local Repository registry is consulted only once
|
|
1566
|
+
// per unique session, off the hot merge path. Keyed by id (value = cwd) so the same
|
|
1567
|
+
// session appearing in multiple peer responses (or re-queued within this loop) only
|
|
1568
|
+
// triggers a single backfill probe.
|
|
1569
|
+
const sessionsNeedingResolve = new Map();
|
|
1570
|
+
for (const peerSessions of peerBatches) {
|
|
1571
|
+
if (peerSessions == null)
|
|
1572
|
+
continue;
|
|
1573
|
+
for (const peerSession of peerSessions) {
|
|
1574
|
+
const peerActivity = new Date(peerSession.lastActivity);
|
|
1575
|
+
const peerPhaseSince = new Date(peerSession.phaseSince);
|
|
1576
|
+
const existing = this._sessions.find(s => s.id === peerSession.id);
|
|
1577
|
+
if (existing != null) {
|
|
1578
|
+
// If the peer reports a different `cwd` than we last saw, the agent moved
|
|
1579
|
+
// (peer fired a `CwdChanged` event we don't receive locally). Pick up the new
|
|
1580
|
+
// cwd AND reset our local `gitInfoUnresolvable` flag — the new cwd might be a
|
|
1581
|
+
// git repo even if the previous one wasn't.
|
|
1582
|
+
const cwdChanged = peerSession.cwd != null && existing.cwd !== peerSession.cwd;
|
|
1583
|
+
if (cwdChanged && this._sessionBookkeeping.get(peerSession.id)?.gitInfoUnresolvable) {
|
|
1584
|
+
this.getBookkeeping(peerSession.id).gitInfoUnresolvable = false;
|
|
1585
|
+
}
|
|
1586
|
+
if (peerActivity > existing.lastActivity) {
|
|
1587
|
+
const idx = this._sessions.indexOf(existing);
|
|
1588
|
+
// Peer is the authoritative hook recipient for this session, so wipe any
|
|
1589
|
+
// local bookkeeping that survived from a previous local-ownership window.
|
|
1590
|
+
// Without this, refcounts/timers from a prior local-hosting stretch would
|
|
1591
|
+
// resurface stale paths if ownership ever flips back to us.
|
|
1592
|
+
const bk = this._sessionBookkeeping.get(peerSession.id);
|
|
1593
|
+
if (bk != null) {
|
|
1594
|
+
this.cancelPendingFileClears(bk);
|
|
1595
|
+
this.cancelPendingReadClears(bk);
|
|
1596
|
+
bk.currentFileCounts.clear();
|
|
1597
|
+
bk.currentReadCounts.clear();
|
|
1598
|
+
bk.lastTouchedAt.clear();
|
|
1599
|
+
}
|
|
1600
|
+
this._sessions[idx] = {
|
|
1601
|
+
...existing,
|
|
1602
|
+
status: peerSession.status,
|
|
1603
|
+
phase: peerSession.phase,
|
|
1604
|
+
phaseSince: peerPhaseSince,
|
|
1605
|
+
statusDetail: peerSession.statusDetail,
|
|
1606
|
+
lastActivity: peerActivity,
|
|
1607
|
+
subagents: rehydrateSubagents(peerSession.subagents),
|
|
1608
|
+
// Carry the peer's published fileActivity across so peer-window WIP
|
|
1609
|
+
// decorations + treemap heatmap follow the agent. Owned by the peer (it's
|
|
1610
|
+
// the hook recipient); we never originate this field for a remote session.
|
|
1611
|
+
fileActivity: peerSession.fileActivity,
|
|
1612
|
+
// Track the peer's resolved repo identity. The peer owns the hook flow and
|
|
1613
|
+
// re-resolves both on `CwdChanged`, so a worktree move (e.g. the agent
|
|
1614
|
+
// `cd`'d into a sibling worktree of the same repo — `commonPath` unchanged
|
|
1615
|
+
// but `worktreePath` changed) only reaches us if we carry BOTH. Carrying
|
|
1616
|
+
// `commonPath` alone froze the displayed worktree at first-discovery.
|
|
1617
|
+
worktreePath: peerSession.worktreePath ?? existing.worktreePath,
|
|
1618
|
+
commonPath: peerSession.commonPath ?? existing.commonPath,
|
|
1619
|
+
// Pick up the peer's latest cwd so our backfill probe (queued below)
|
|
1620
|
+
// targets the right path. Stale-cwd locally would just re-probe the
|
|
1621
|
+
// non-repo dir and hit the gitInfoUnresolvable retry guard again.
|
|
1622
|
+
cwd: cwdChanged ? peerSession.cwd : existing.cwd,
|
|
1623
|
+
// Launch-state fields are immutable per session: prefer whichever side
|
|
1624
|
+
// already set them (peer that owns the hook flow typically sets first),
|
|
1625
|
+
// and never overwrite a populated local value with the peer's.
|
|
1626
|
+
initialCwd: existing.initialCwd ?? peerSession.initialCwd,
|
|
1627
|
+
initialWorktreePath: existing.initialWorktreePath ?? peerSession.initialWorktreePath,
|
|
1628
|
+
initialCommonPath: existing.initialCommonPath ?? peerSession.initialCommonPath,
|
|
1629
|
+
// Forward peer-discovered transcript titles. Both windows can resolve them
|
|
1630
|
+
// independently against the same on-disk transcript, but only the peer's
|
|
1631
|
+
// hook flow drives its updates — without this, we'd freeze the snapshot
|
|
1632
|
+
// taken at first discovery.
|
|
1633
|
+
transcriptTitles: peerSession.transcriptTitles ?? existing.transcriptTitles,
|
|
1634
|
+
};
|
|
1635
|
+
changed = true;
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
else {
|
|
1639
|
+
this._sessions.push({
|
|
1640
|
+
...peerSession,
|
|
1641
|
+
lastActivity: peerActivity,
|
|
1642
|
+
phaseSince: peerPhaseSince,
|
|
1643
|
+
workspacePath: normalizeWorkspacePath(peerSession.workspacePath),
|
|
1644
|
+
isInWorkspace: this.matchesWorkspace(peerSession.workspacePath),
|
|
1645
|
+
subagents: rehydrateSubagents(peerSession.subagents),
|
|
1646
|
+
// Override whatever the peer published — this is OUR ownership view: the peer
|
|
1647
|
+
// (or some other window) hosts the live session, not us. Drives the dispatcher
|
|
1648
|
+
// to route opens through the peer's IPC + OS-level window focus instead of
|
|
1649
|
+
// calling `claude-vscode.editor.open` locally (which would just open an inert
|
|
1650
|
+
// view in our window).
|
|
1651
|
+
isPeerOwned: true,
|
|
1652
|
+
});
|
|
1653
|
+
changed = true;
|
|
1654
|
+
}
|
|
1655
|
+
// Queue a local resolveGitInfo for any peer session that arrived without a
|
|
1656
|
+
// commonPath but has a cwd — we can fill it in from our own git registry. Skip
|
|
1657
|
+
// if our own bookkeeping already marked this session's cwd unresolvable (we tried
|
|
1658
|
+
// locally and the cwd isn't a git repo from our vantage point either).
|
|
1659
|
+
const merged = this._sessions.find(s => s.id === peerSession.id);
|
|
1660
|
+
if (merged?.commonPath == null &&
|
|
1661
|
+
merged?.cwd != null &&
|
|
1662
|
+
!this.getBookkeeping(merged.id).gitInfoUnresolvable) {
|
|
1663
|
+
sessionsNeedingResolve.set(merged.id, merged.cwd);
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
if (changed) {
|
|
1668
|
+
this._onDidChangeSessions.fire();
|
|
1669
|
+
}
|
|
1670
|
+
// Backfill commonPath for peer-synced sessions whose owning peer didn't populate it.
|
|
1671
|
+
// `resolveGitInfo` is idempotent — only mutates + fires if it actually finds new info,
|
|
1672
|
+
// so the worst case here is a few wasted git probes for unresolvable cwds.
|
|
1673
|
+
for (const [id, cwd] of sessionsNeedingResolve) {
|
|
1674
|
+
void this.resolveGitInfo(id, cwd);
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
async fetchPeerSessions(path, ownPort) {
|
|
1678
|
+
let discovery;
|
|
1679
|
+
try {
|
|
1680
|
+
discovery = JSON.parse(await readFile(path, 'utf8'));
|
|
1681
|
+
}
|
|
1682
|
+
catch {
|
|
1683
|
+
return undefined;
|
|
1684
|
+
}
|
|
1685
|
+
if (ownPort != null && discovery.port === ownPort)
|
|
1686
|
+
return undefined;
|
|
1687
|
+
try {
|
|
1688
|
+
const response = await fetch(`${discovery.address}/agents/sessions/list`, {
|
|
1689
|
+
method: 'POST',
|
|
1690
|
+
headers: { Authorization: `Bearer ${discovery.token}`, 'Content-Type': 'application/json' },
|
|
1691
|
+
body: '{}',
|
|
1692
|
+
signal: AbortSignal.timeout(2000),
|
|
1693
|
+
});
|
|
1694
|
+
if (!response.ok)
|
|
1695
|
+
return undefined;
|
|
1696
|
+
return (await response.json());
|
|
1697
|
+
}
|
|
1698
|
+
catch {
|
|
1699
|
+
return undefined;
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
/** Find the peer GitLens window whose discovery file claims `workspacePath`, and POST to its
|
|
1703
|
+
* `/agents/sessions/open` route to ask its Claude Code extension to open the session.
|
|
1704
|
+
*
|
|
1705
|
+
* Resolves to `true` when at least one peer claimed the workspace AND was reachable (the POST
|
|
1706
|
+
* completed with any HTTP status). The peer's response shape (`{ opened: boolean }`) is logged
|
|
1707
|
+
* for diagnostics but does NOT affect the return value — an `opened: false` peer is still the
|
|
1708
|
+
* right window for the caller to focus, since it's the window that owns the session. Resolves
|
|
1709
|
+
* to `false` when no peer claimed the workspace OR every claimer was unreachable; the caller
|
|
1710
|
+
* treats that as "no peer to focus" and opens a new window instead of replacing the current
|
|
1711
|
+
* one. Best-effort: swallows scan, JSON-parse errors. */
|
|
1712
|
+
async notifyPeerOpenSession(workspacePath, sessionId) {
|
|
1713
|
+
const discoveryDir = this.callbacks.ipc.agentDiscoveryDir;
|
|
1714
|
+
if (discoveryDir == null)
|
|
1715
|
+
return false;
|
|
1716
|
+
const target = normalizePath(workspacePath);
|
|
1717
|
+
const ownPort = this.callbacks.ipc.port;
|
|
1718
|
+
let files;
|
|
1719
|
+
try {
|
|
1720
|
+
files = await readdir(discoveryDir);
|
|
1721
|
+
}
|
|
1722
|
+
catch {
|
|
1723
|
+
return false;
|
|
1724
|
+
}
|
|
1725
|
+
const results = await Promise.all(files
|
|
1726
|
+
.filter(f => f.startsWith('gitlens-ipc-server-') && f.endsWith('.json'))
|
|
1727
|
+
.map(async (f) => {
|
|
1728
|
+
let discovery;
|
|
1729
|
+
try {
|
|
1730
|
+
discovery = JSON.parse(await readFile(join(discoveryDir, f), 'utf8'));
|
|
1731
|
+
}
|
|
1732
|
+
catch {
|
|
1733
|
+
return false;
|
|
1734
|
+
}
|
|
1735
|
+
if (ownPort != null && discovery.port === ownPort)
|
|
1736
|
+
return false;
|
|
1737
|
+
// Symmetric prefix containment — same shape as `matchesWorkspace()` above.
|
|
1738
|
+
// Strict equality misses the common case where the dispatcher passes a `cwd`
|
|
1739
|
+
// inside the peer's workspace folder (or, less commonly, a parent dir that
|
|
1740
|
+
// contains the peer's workspace).
|
|
1741
|
+
if (!discovery.workspacePaths?.some(p => {
|
|
1742
|
+
const normalized = normalizePath(p);
|
|
1743
|
+
return (normalized === target ||
|
|
1744
|
+
target.startsWith(`${normalized}/`) ||
|
|
1745
|
+
normalized.startsWith(`${target}/`));
|
|
1746
|
+
})) {
|
|
1747
|
+
return false;
|
|
1748
|
+
}
|
|
1749
|
+
try {
|
|
1750
|
+
const response = await fetch(`${discovery.address}/agents/sessions/open`, {
|
|
1751
|
+
method: 'POST',
|
|
1752
|
+
headers: {
|
|
1753
|
+
Authorization: `Bearer ${discovery.token}`,
|
|
1754
|
+
'Content-Type': 'application/json',
|
|
1755
|
+
},
|
|
1756
|
+
body: JSON.stringify({ sessionId: sessionId }),
|
|
1757
|
+
signal: AbortSignal.timeout(2000),
|
|
1758
|
+
});
|
|
1759
|
+
if (!response.ok) {
|
|
1760
|
+
Logger.warn(`ClaudeCodeProvider.notifyPeerOpenSession: peer at ${discovery.address} returned ${response.status}`);
|
|
1761
|
+
}
|
|
1762
|
+
else {
|
|
1763
|
+
// Log a peer that failed to open the specific session, but still treat it
|
|
1764
|
+
// as a reachable claimer of the workspace — focusing that window is still
|
|
1765
|
+
// what the user wants.
|
|
1766
|
+
const body = (await response.json().catch(() => undefined));
|
|
1767
|
+
if (body?.opened === false) {
|
|
1768
|
+
Logger.warn(`ClaudeCodeProvider.notifyPeerOpenSession: peer at ${discovery.address} could not open session ${sessionId}`);
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
return true;
|
|
1772
|
+
}
|
|
1773
|
+
catch (ex) {
|
|
1774
|
+
// Peer advertised but unreachable (timeout, RST, etc.). Treat as no match so
|
|
1775
|
+
// the caller opens a new window instead of trying to focus a dead window.
|
|
1776
|
+
Logger.warn(`ClaudeCodeProvider.notifyPeerOpenSession: peer at ${discovery.address} unreachable: ${ex instanceof Error ? ex.message : String(ex)}`);
|
|
1777
|
+
return false;
|
|
1778
|
+
}
|
|
1779
|
+
}));
|
|
1780
|
+
return results.some(Boolean);
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
__decorate([
|
|
1784
|
+
gate()
|
|
1785
|
+
], ClaudeCodeProvider.prototype, "ensureIpcServer", null);
|
|
1786
|
+
//# sourceMappingURL=claudeCodeProvider.js.map
|