@gitkraken/core-gitlens 0.1.0 → 0.3.0

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.
Files changed (451) hide show
  1. package/CHANGELOG.md +25 -1
  2. package/dist/git/cache.d.ts +49 -9
  3. package/dist/git/cache.d.ts.map +1 -1
  4. package/dist/git/cache.js +174 -14
  5. package/dist/git/cache.js.map +1 -1
  6. package/dist/git/context.d.ts +11 -2
  7. package/dist/git/context.d.ts.map +1 -1
  8. package/dist/git/context.js.map +1 -1
  9. package/dist/git/models/branch.d.ts +1 -0
  10. package/dist/git/models/branch.d.ts.map +1 -1
  11. package/dist/git/models/branch.js.map +1 -1
  12. package/dist/git/models/commit.d.ts +1 -9
  13. package/dist/git/models/commit.d.ts.map +1 -1
  14. package/dist/git/models/commit.js +4 -9
  15. package/dist/git/models/commit.js.map +1 -1
  16. package/dist/git/models/graph.d.ts +2 -4
  17. package/dist/git/models/graph.d.ts.map +1 -1
  18. package/dist/git/models/reference.d.ts +31 -0
  19. package/dist/git/models/reference.d.ts.map +1 -1
  20. package/dist/git/models/remote.d.ts.map +1 -1
  21. package/dist/git/models/remote.js.map +1 -1
  22. package/dist/git/models/repository.d.ts +20 -3
  23. package/dist/git/models/repository.d.ts.map +1 -1
  24. package/dist/git/models/repository.js +42 -5
  25. package/dist/git/models/repository.js.map +1 -1
  26. package/dist/git/models/search.d.ts +2 -2
  27. package/dist/git/models/search.d.ts.map +1 -1
  28. package/dist/git/models/worktree.d.ts +4 -1
  29. package/dist/git/models/worktree.d.ts.map +1 -1
  30. package/dist/git/models/worktree.js +2 -2
  31. package/dist/git/models/worktree.js.map +1 -1
  32. package/dist/git/parsers/diffParser.d.ts +0 -1
  33. package/dist/git/parsers/diffParser.d.ts.map +1 -1
  34. package/dist/git/parsers/diffParser.js +22 -61
  35. package/dist/git/parsers/diffParser.js.map +1 -1
  36. package/dist/git/providers/branches.d.ts +18 -4
  37. package/dist/git/providers/branches.d.ts.map +1 -1
  38. package/dist/git/providers/commits.d.ts +6 -0
  39. package/dist/git/providers/commits.d.ts.map +1 -1
  40. package/dist/git/providers/config.d.ts +6 -1
  41. package/dist/git/providers/config.d.ts.map +1 -1
  42. package/dist/git/providers/diff.d.ts +2 -0
  43. package/dist/git/providers/diff.d.ts.map +1 -1
  44. package/dist/git/providers/operations.d.ts +39 -10
  45. package/dist/git/providers/operations.d.ts.map +1 -1
  46. package/dist/git/providers/pausedOperations.d.ts +3 -1
  47. package/dist/git/providers/pausedOperations.d.ts.map +1 -1
  48. package/dist/git/providers/refs.d.ts +23 -2
  49. package/dist/git/providers/refs.d.ts.map +1 -1
  50. package/dist/git/providers/revision.d.ts +1 -1
  51. package/dist/git/providers/revision.d.ts.map +1 -1
  52. package/dist/git/providers/staging.d.ts +18 -0
  53. package/dist/git/providers/staging.d.ts.map +1 -1
  54. package/dist/git/providers/status.d.ts +4 -1
  55. package/dist/git/providers/status.d.ts.map +1 -1
  56. package/dist/git/remotes/azure-devops.d.ts.map +1 -1
  57. package/dist/git/remotes/azure-devops.js.map +1 -1
  58. package/dist/git/{exec.types.d.ts → run.types.d.ts} +22 -3
  59. package/dist/git/run.types.d.ts.map +1 -0
  60. package/dist/git/run.types.js +2 -0
  61. package/dist/git/run.types.js.map +1 -0
  62. package/dist/git/service.d.ts.map +1 -1
  63. package/dist/git/service.js.map +1 -1
  64. package/dist/git/utils/autolink.utils.d.ts.map +1 -1
  65. package/dist/git/utils/autolink.utils.js.map +1 -1
  66. package/dist/git/utils/blame.utils.d.ts.map +1 -1
  67. package/dist/git/utils/blame.utils.js.map +1 -1
  68. package/dist/git/utils/conflictResolution.utils.d.ts +6 -0
  69. package/dist/git/utils/conflictResolution.utils.d.ts.map +1 -0
  70. package/dist/git/utils/conflictResolution.utils.js +25 -0
  71. package/dist/git/utils/conflictResolution.utils.js.map +1 -0
  72. package/dist/git/utils/fileStatus.utils.d.ts +2 -1
  73. package/dist/git/utils/fileStatus.utils.d.ts.map +1 -1
  74. package/dist/git/utils/fileStatus.utils.js +4 -0
  75. package/dist/git/utils/fileStatus.utils.js.map +1 -1
  76. package/dist/git/utils/search.utils.d.ts.map +1 -1
  77. package/dist/git/utils/search.utils.js +3 -0
  78. package/dist/git/utils/search.utils.js.map +1 -1
  79. package/dist/git/utils/sorting.d.ts +14 -0
  80. package/dist/git/utils/sorting.d.ts.map +1 -1
  81. package/dist/git/utils/sorting.js +34 -0
  82. package/dist/git/utils/sorting.js.map +1 -1
  83. package/dist/git/utils/status.utils.d.ts.map +1 -1
  84. package/dist/git/utils/status.utils.js.map +1 -1
  85. package/dist/git/watching/classifyChange.d.ts.map +1 -1
  86. package/dist/git/watching/classifyChange.js +8 -0
  87. package/dist/git/watching/classifyChange.js.map +1 -1
  88. package/dist/git/watching/gitIgnoreFilter.js +1 -1
  89. package/dist/git/watching/gitIgnoreFilter.js.map +1 -1
  90. package/dist/git/watching/initWatcher.d.ts.map +1 -1
  91. package/dist/git/watching/initWatcher.js.map +1 -1
  92. package/dist/git/watching/watchGroup.d.ts.map +1 -1
  93. package/dist/git/watching/watchGroup.js.map +1 -1
  94. package/dist/git/watching/watchService.d.ts.map +1 -1
  95. package/dist/git/watching/watchService.js +24 -4
  96. package/dist/git/watching/watchService.js.map +1 -1
  97. package/dist/git/watching/watchSession.d.ts.map +1 -1
  98. package/dist/git/watching/watchSession.js.map +1 -1
  99. package/dist/git-cli/cliGitProvider.js +1 -1
  100. package/dist/git-cli/cliGitProvider.js.map +1 -1
  101. package/dist/git-cli/exec/exec.types.d.ts +1 -1
  102. package/dist/git-cli/exec/exec.types.d.ts.map +1 -1
  103. package/dist/git-cli/exec/git.d.ts +31 -6
  104. package/dist/git-cli/exec/git.d.ts.map +1 -1
  105. package/dist/git-cli/exec/git.js +70 -9
  106. package/dist/git-cli/exec/git.js.map +1 -1
  107. package/dist/git-cli/exec/gitQueue.d.ts +22 -6
  108. package/dist/git-cli/exec/gitQueue.d.ts.map +1 -1
  109. package/dist/git-cli/exec/gitQueue.js +88 -24
  110. package/dist/git-cli/exec/gitQueue.js.map +1 -1
  111. package/dist/git-cli/parsers/blameParser.d.ts.map +1 -1
  112. package/dist/git-cli/parsers/blameParser.js.map +1 -1
  113. package/dist/git-cli/parsers/logParser.d.ts +1 -0
  114. package/dist/git-cli/parsers/logParser.d.ts.map +1 -1
  115. package/dist/git-cli/parsers/logParser.js +4 -0
  116. package/dist/git-cli/parsers/logParser.js.map +1 -1
  117. package/dist/git-cli/parsers/refParser.d.ts +3 -30
  118. package/dist/git-cli/parsers/refParser.d.ts.map +1 -1
  119. package/dist/git-cli/parsers/refParser.js +30 -30
  120. package/dist/git-cli/parsers/refParser.js.map +1 -1
  121. package/dist/git-cli/providers/blame.d.ts.map +1 -1
  122. package/dist/git-cli/providers/blame.js +1 -1
  123. package/dist/git-cli/providers/blame.js.map +1 -1
  124. package/dist/git-cli/providers/branches.d.ts +17 -5
  125. package/dist/git-cli/providers/branches.d.ts.map +1 -1
  126. package/dist/git-cli/providers/branches.js +245 -162
  127. package/dist/git-cli/providers/branches.js.map +1 -1
  128. package/dist/git-cli/providers/commits.d.ts +4 -0
  129. package/dist/git-cli/providers/commits.d.ts.map +1 -1
  130. package/dist/git-cli/providers/commits.js +120 -35
  131. package/dist/git-cli/providers/commits.js.map +1 -1
  132. package/dist/git-cli/providers/config.d.ts +11 -2
  133. package/dist/git-cli/providers/config.d.ts.map +1 -1
  134. package/dist/git-cli/providers/config.js +36 -11
  135. package/dist/git-cli/providers/config.js.map +1 -1
  136. package/dist/git-cli/providers/contributors.d.ts.map +1 -1
  137. package/dist/git-cli/providers/contributors.js +7 -4
  138. package/dist/git-cli/providers/contributors.js.map +1 -1
  139. package/dist/git-cli/providers/diff.d.ts +2 -0
  140. package/dist/git-cli/providers/diff.d.ts.map +1 -1
  141. package/dist/git-cli/providers/diff.js +92 -20
  142. package/dist/git-cli/providers/diff.js.map +1 -1
  143. package/dist/git-cli/providers/graph.d.ts.map +1 -1
  144. package/dist/git-cli/providers/graph.js +49 -28
  145. package/dist/git-cli/providers/graph.js.map +1 -1
  146. package/dist/git-cli/providers/operations.d.ts +30 -11
  147. package/dist/git-cli/providers/operations.d.ts.map +1 -1
  148. package/dist/git-cli/providers/operations.js +146 -43
  149. package/dist/git-cli/providers/operations.js.map +1 -1
  150. package/dist/git-cli/providers/patch.d.ts.map +1 -1
  151. package/dist/git-cli/providers/patch.js +15 -30
  152. package/dist/git-cli/providers/patch.js.map +1 -1
  153. package/dist/git-cli/providers/pausedOperations.d.ts +3 -1
  154. package/dist/git-cli/providers/pausedOperations.d.ts.map +1 -1
  155. package/dist/git-cli/providers/pausedOperations.js +13 -7
  156. package/dist/git-cli/providers/pausedOperations.js.map +1 -1
  157. package/dist/git-cli/providers/refs.d.ts +19 -2
  158. package/dist/git-cli/providers/refs.d.ts.map +1 -1
  159. package/dist/git-cli/providers/refs.js +312 -9
  160. package/dist/git-cli/providers/refs.js.map +1 -1
  161. package/dist/git-cli/providers/remotes.js +4 -4
  162. package/dist/git-cli/providers/remotes.js.map +1 -1
  163. package/dist/git-cli/providers/revision.d.ts +1 -1
  164. package/dist/git-cli/providers/revision.d.ts.map +1 -1
  165. package/dist/git-cli/providers/revision.js +15 -11
  166. package/dist/git-cli/providers/revision.js.map +1 -1
  167. package/dist/git-cli/providers/staging.d.ts +8 -0
  168. package/dist/git-cli/providers/staging.d.ts.map +1 -1
  169. package/dist/git-cli/providers/staging.js +52 -8
  170. package/dist/git-cli/providers/staging.js.map +1 -1
  171. package/dist/git-cli/providers/stash.d.ts +0 -8
  172. package/dist/git-cli/providers/stash.d.ts.map +1 -1
  173. package/dist/git-cli/providers/stash.js +63 -119
  174. package/dist/git-cli/providers/stash.js.map +1 -1
  175. package/dist/git-cli/providers/status.d.ts +4 -1
  176. package/dist/git-cli/providers/status.d.ts.map +1 -1
  177. package/dist/git-cli/providers/status.js +10 -9
  178. package/dist/git-cli/providers/status.js.map +1 -1
  179. package/dist/git-cli/providers/tags.d.ts.map +1 -1
  180. package/dist/git-cli/providers/tags.js +13 -9
  181. package/dist/git-cli/providers/tags.js.map +1 -1
  182. package/dist/git-cli/providers/worktrees.js +3 -3
  183. package/dist/git-cli/providers/worktrees.js.map +1 -1
  184. package/dist/ipc/discovery.d.ts +27 -0
  185. package/dist/ipc/discovery.d.ts.map +1 -0
  186. package/dist/ipc/discovery.js +38 -0
  187. package/dist/ipc/discovery.js.map +1 -0
  188. package/dist/ipc/ipcServer.d.ts +20 -0
  189. package/dist/ipc/ipcServer.d.ts.map +1 -0
  190. package/dist/ipc/ipcServer.js +162 -0
  191. package/dist/ipc/ipcServer.js.map +1 -0
  192. package/dist/plus/agents/providers/claudeCodeProvider.d.ts +114 -0
  193. package/dist/plus/agents/providers/claudeCodeProvider.d.ts.map +1 -0
  194. package/dist/plus/agents/providers/claudeCodeProvider.js +1480 -0
  195. package/dist/plus/agents/providers/claudeCodeProvider.js.map +1 -0
  196. package/dist/plus/agents/providers/claudeCodeTranscript.d.ts +36 -0
  197. package/dist/plus/agents/providers/claudeCodeTranscript.d.ts.map +1 -0
  198. package/dist/plus/agents/providers/claudeCodeTranscript.js +171 -0
  199. package/dist/plus/agents/providers/claudeCodeTranscript.js.map +1 -0
  200. package/dist/plus/agents/sanitizePrompt.d.ts +15 -0
  201. package/dist/plus/agents/sanitizePrompt.d.ts.map +1 -0
  202. package/dist/plus/agents/sanitizePrompt.js +103 -0
  203. package/dist/plus/agents/sanitizePrompt.js.map +1 -0
  204. package/dist/plus/agents/stateMachine.d.ts +32 -0
  205. package/dist/plus/agents/stateMachine.d.ts.map +1 -0
  206. package/dist/plus/agents/stateMachine.js +180 -0
  207. package/dist/plus/agents/stateMachine.js.map +1 -0
  208. package/dist/plus/agents/types.d.ts +203 -0
  209. package/dist/plus/agents/types.d.ts.map +1 -0
  210. package/dist/plus/agents/types.js +49 -0
  211. package/dist/plus/agents/types.js.map +1 -0
  212. package/dist/plus/ai/constants.d.ts +2 -1
  213. package/dist/plus/ai/constants.d.ts.map +1 -1
  214. package/dist/plus/ai/constants.js +7 -0
  215. package/dist/plus/ai/constants.js.map +1 -1
  216. package/dist/plus/ai/errors.d.ts +4 -1
  217. package/dist/plus/ai/errors.d.ts.map +1 -1
  218. package/dist/plus/ai/errors.js +38 -0
  219. package/dist/plus/ai/errors.js.map +1 -1
  220. package/dist/plus/ai/models/model.d.ts +1 -1
  221. package/dist/plus/ai/models/model.d.ts.map +1 -1
  222. package/dist/plus/ai/models/model.js.map +1 -1
  223. package/dist/plus/ai/models/promptTemplates.d.ts +28 -2
  224. package/dist/plus/ai/models/promptTemplates.d.ts.map +1 -1
  225. package/dist/plus/ai/models/results.d.ts +28 -0
  226. package/dist/plus/ai/models/results.d.ts.map +1 -1
  227. package/dist/plus/ai/prompts.d.ts +4 -0
  228. package/dist/plus/ai/prompts.d.ts.map +1 -1
  229. package/dist/plus/ai/prompts.js +167 -1
  230. package/dist/plus/ai/prompts.js.map +1 -1
  231. package/dist/plus/ai/utils/ai.utils.d.ts.map +1 -1
  232. package/dist/plus/ai/utils/ai.utils.js +2 -0
  233. package/dist/plus/ai/utils/ai.utils.js.map +1 -1
  234. package/dist/plus/ai/utils/results.utils.d.ts +3 -0
  235. package/dist/plus/ai/utils/results.utils.d.ts.map +1 -1
  236. package/dist/plus/ai/utils/results.utils.js +75 -0
  237. package/dist/plus/ai/utils/results.utils.js.map +1 -1
  238. package/dist/plus/ai/utils/truncation.utils.d.ts +1 -1
  239. package/dist/plus/ai/utils/truncation.utils.d.ts.map +1 -1
  240. package/dist/plus/ai/utils/truncation.utils.js.map +1 -1
  241. package/dist/plus/git-github/api/github.d.ts +10 -1
  242. package/dist/plus/git-github/api/github.d.ts.map +1 -1
  243. package/dist/plus/git-github/api/github.js +156 -49
  244. package/dist/plus/git-github/api/github.js.map +1 -1
  245. package/dist/plus/git-github/api/types.d.ts +8 -0
  246. package/dist/plus/git-github/api/types.d.ts.map +1 -1
  247. package/dist/plus/git-github/models.d.ts +1 -1
  248. package/dist/plus/git-github/models.d.ts.map +1 -1
  249. package/dist/plus/git-github/models.js.map +1 -1
  250. package/dist/plus/git-github/providers/github/blame.d.ts.map +1 -1
  251. package/dist/plus/git-github/providers/github/blame.js.map +1 -1
  252. package/dist/plus/git-github/providers/github/branches.d.ts +5 -1
  253. package/dist/plus/git-github/providers/github/branches.d.ts.map +1 -1
  254. package/dist/plus/git-github/providers/github/branches.js +60 -22
  255. package/dist/plus/git-github/providers/github/branches.js.map +1 -1
  256. package/dist/plus/git-github/providers/github/commits.d.ts.map +1 -1
  257. package/dist/plus/git-github/providers/github/commits.js +144 -92
  258. package/dist/plus/git-github/providers/github/commits.js.map +1 -1
  259. package/dist/plus/git-github/providers/github/diff.d.ts +3 -1
  260. package/dist/plus/git-github/providers/github/diff.d.ts.map +1 -1
  261. package/dist/plus/git-github/providers/github/diff.js +23 -9
  262. package/dist/plus/git-github/providers/github/diff.js.map +1 -1
  263. package/dist/plus/git-github/providers/github/refs.d.ts +9 -1
  264. package/dist/plus/git-github/providers/github/refs.d.ts.map +1 -1
  265. package/dist/plus/git-github/providers/github/refs.js +38 -13
  266. package/dist/plus/git-github/providers/github/refs.js.map +1 -1
  267. package/dist/plus/git-github/providers/github/revision.d.ts.map +1 -1
  268. package/dist/plus/git-github/providers/github/revision.js +1 -2
  269. package/dist/plus/git-github/providers/github/revision.js.map +1 -1
  270. package/dist/plus/git-github/providers/github/status.d.ts +4 -1
  271. package/dist/plus/git-github/providers/github/status.d.ts.map +1 -1
  272. package/dist/plus/git-github/providers/github/status.js +1 -1
  273. package/dist/plus/git-github/providers/github/status.js.map +1 -1
  274. package/dist/plus/git-github/providers/github/tags.d.ts.map +1 -1
  275. package/dist/plus/git-github/providers/github/tags.js +35 -36
  276. package/dist/plus/git-github/providers/github/tags.js.map +1 -1
  277. package/dist/plus/git-github/providers/githubGitProvider.d.ts.map +1 -1
  278. package/dist/plus/git-github/providers/githubGitProvider.js.map +1 -1
  279. package/dist/utils/color.d.ts.map +1 -1
  280. package/dist/utils/color.js.map +1 -1
  281. package/dist/utils/decorators/log.js +1 -1
  282. package/dist/utils/decorators/log.js.map +1 -1
  283. package/dist/utils/decorators/sequentialize.d.ts.map +1 -1
  284. package/dist/utils/decorators/sequentialize.js +4 -2
  285. package/dist/utils/decorators/sequentialize.js.map +1 -1
  286. package/dist/utils/decorators/serializable.d.ts.map +1 -1
  287. package/dist/utils/decorators/serializable.js.map +1 -1
  288. package/dist/utils/dedupedAsyncCache.d.ts +37 -0
  289. package/dist/utils/dedupedAsyncCache.d.ts.map +1 -0
  290. package/dist/utils/dedupedAsyncCache.js +68 -0
  291. package/dist/utils/dedupedAsyncCache.js.map +1 -0
  292. package/dist/utils/diff.d.ts +2 -0
  293. package/dist/utils/diff.d.ts.map +1 -0
  294. package/dist/utils/diff.js +53 -0
  295. package/dist/utils/diff.js.map +1 -0
  296. package/dist/utils/disposable.d.ts.map +1 -1
  297. package/dist/utils/disposable.js.map +1 -1
  298. package/dist/utils/env/node/base64.js.map +1 -1
  299. package/dist/utils/env/node/exec.d.ts.map +1 -1
  300. package/dist/utils/env/node/exec.js.map +1 -1
  301. package/dist/utils/error.d.ts.map +1 -1
  302. package/dist/utils/error.js.map +1 -1
  303. package/dist/utils/formatter.d.ts.map +1 -1
  304. package/dist/utils/formatter.js +4 -10
  305. package/dist/utils/formatter.js.map +1 -1
  306. package/dist/utils/iterable.d.ts.map +1 -1
  307. package/dist/utils/iterable.js.map +1 -1
  308. package/dist/utils/logger.d.ts.map +1 -1
  309. package/dist/utils/logger.js.map +1 -1
  310. package/dist/utils/lruMap.d.ts +49 -0
  311. package/dist/utils/lruMap.d.ts.map +1 -0
  312. package/dist/utils/lruMap.js +103 -0
  313. package/dist/utils/lruMap.js.map +1 -0
  314. package/dist/utils/markdown.d.ts.map +1 -1
  315. package/dist/utils/markdown.js.map +1 -1
  316. package/dist/utils/mru.d.ts.map +1 -1
  317. package/dist/utils/mru.js.map +1 -1
  318. package/dist/utils/path.d.ts.map +1 -1
  319. package/dist/utils/path.js.map +1 -1
  320. package/dist/utils/promise.d.ts +1 -0
  321. package/dist/utils/promise.d.ts.map +1 -1
  322. package/dist/utils/promise.js +17 -0
  323. package/dist/utils/promise.js.map +1 -1
  324. package/dist/utils/promiseCache.d.ts +10 -0
  325. package/dist/utils/promiseCache.d.ts.map +1 -1
  326. package/dist/utils/promiseCache.js +22 -0
  327. package/dist/utils/promiseCache.js.map +1 -1
  328. package/dist/utils/string.d.ts.map +1 -1
  329. package/dist/utils/string.js.map +1 -1
  330. package/dist/utils/uri.d.ts.map +1 -1
  331. package/dist/utils/uri.js.map +1 -1
  332. package/dist/utils/version.d.ts +14 -0
  333. package/dist/utils/version.d.ts.map +1 -1
  334. package/dist/utils/version.js +48 -0
  335. package/dist/utils/version.js.map +1 -1
  336. package/package.json +13 -1
  337. package/src/git/cache.ts +309 -29
  338. package/src/git/context.ts +11 -2
  339. package/src/git/models/branch.ts +1 -0
  340. package/src/git/models/commit.ts +2 -17
  341. package/src/git/models/graph.ts +2 -4
  342. package/src/git/models/reference.ts +33 -0
  343. package/src/git/models/remote.ts +1 -0
  344. package/src/git/models/repository.ts +44 -6
  345. package/src/git/models/search.ts +2 -2
  346. package/src/git/models/worktree.ts +10 -2
  347. package/src/git/parsers/diffParser.ts +9 -44
  348. package/src/git/providers/branches.ts +25 -4
  349. package/src/git/providers/commits.ts +7 -0
  350. package/src/git/providers/config.ts +4 -0
  351. package/src/git/providers/diff.ts +8 -2
  352. package/src/git/providers/operations.ts +54 -3
  353. package/src/git/providers/pausedOperations.ts +1 -0
  354. package/src/git/providers/refs.ts +32 -3
  355. package/src/git/providers/revision.ts +5 -1
  356. package/src/git/providers/staging.ts +14 -0
  357. package/src/git/providers/status.ts +6 -1
  358. package/src/git/remotes/azure-devops.ts +2 -0
  359. package/src/git/{exec.types.ts → run.types.ts} +22 -2
  360. package/src/git/service.ts +1 -0
  361. package/src/git/utils/autolink.utils.ts +1 -0
  362. package/src/git/utils/blame.utils.ts +2 -0
  363. package/src/git/utils/conflictResolution.utils.ts +31 -0
  364. package/src/git/utils/fileStatus.utils.ts +7 -1
  365. package/src/git/utils/search.utils.ts +2 -0
  366. package/src/git/utils/sorting.ts +38 -0
  367. package/src/git/utils/status.utils.ts +1 -0
  368. package/src/git/watching/classifyChange.ts +9 -0
  369. package/src/git/watching/gitIgnoreFilter.ts +2 -2
  370. package/src/git/watching/initWatcher.ts +2 -0
  371. package/src/git/watching/watchGroup.ts +3 -0
  372. package/src/git/watching/watchService.ts +38 -5
  373. package/src/git/watching/watchSession.ts +10 -0
  374. package/src/git-cli/cliGitProvider.ts +1 -1
  375. package/src/git-cli/exec/exec.types.ts +2 -2
  376. package/src/git-cli/exec/git.ts +76 -23
  377. package/src/git-cli/exec/gitQueue.ts +98 -25
  378. package/src/git-cli/parsers/blameParser.ts +1 -0
  379. package/src/git-cli/parsers/logParser.ts +6 -1
  380. package/src/git-cli/parsers/refParser.ts +33 -34
  381. package/src/git-cli/providers/blame.ts +2 -1
  382. package/src/git-cli/providers/branches.ts +341 -196
  383. package/src/git-cli/providers/commits.ts +145 -46
  384. package/src/git-cli/providers/config.ts +50 -16
  385. package/src/git-cli/providers/contributors.ts +7 -12
  386. package/src/git-cli/providers/diff.ts +107 -20
  387. package/src/git-cli/providers/graph.ts +58 -29
  388. package/src/git-cli/providers/operations.ts +253 -57
  389. package/src/git-cli/providers/patch.ts +16 -37
  390. package/src/git-cli/providers/pausedOperations.ts +14 -6
  391. package/src/git-cli/providers/refs.ts +274 -11
  392. package/src/git-cli/providers/remotes.ts +4 -4
  393. package/src/git-cli/providers/revision.ts +22 -15
  394. package/src/git-cli/providers/staging.ts +51 -8
  395. package/src/git-cli/providers/stash.ts +67 -134
  396. package/src/git-cli/providers/status.ts +21 -10
  397. package/src/git-cli/providers/tags.ts +18 -19
  398. package/src/git-cli/providers/worktrees.ts +3 -3
  399. package/src/ipc/discovery.ts +56 -0
  400. package/src/ipc/ipcServer.ts +171 -0
  401. package/src/plus/agents/providers/claudeCodeProvider.ts +1782 -0
  402. package/src/plus/agents/providers/claudeCodeTranscript.ts +214 -0
  403. package/src/plus/agents/sanitizePrompt.ts +109 -0
  404. package/src/plus/agents/stateMachine.ts +197 -0
  405. package/src/plus/agents/types.ts +277 -0
  406. package/src/plus/ai/constants.ts +8 -0
  407. package/src/plus/ai/errors.ts +40 -0
  408. package/src/plus/ai/models/model.ts +1 -0
  409. package/src/plus/ai/models/promptTemplates.ts +42 -0
  410. package/src/plus/ai/models/results.ts +30 -0
  411. package/src/plus/ai/prompts.ts +171 -1
  412. package/src/plus/ai/utils/ai.utils.ts +2 -0
  413. package/src/plus/ai/utils/results.utils.ts +101 -0
  414. package/src/plus/ai/utils/truncation.utils.ts +3 -1
  415. package/src/plus/git-github/api/github.ts +199 -53
  416. package/src/plus/git-github/api/types.ts +15 -0
  417. package/src/plus/git-github/models.ts +1 -1
  418. package/src/plus/git-github/providers/github/blame.ts +2 -0
  419. package/src/plus/git-github/providers/github/branches.ts +75 -33
  420. package/src/plus/git-github/providers/github/commits.ts +231 -160
  421. package/src/plus/git-github/providers/github/diff.ts +35 -21
  422. package/src/plus/git-github/providers/github/refs.ts +57 -22
  423. package/src/plus/git-github/providers/github/revision.ts +1 -2
  424. package/src/plus/git-github/providers/github/status.ts +6 -1
  425. package/src/plus/git-github/providers/github/tags.ts +61 -62
  426. package/src/plus/git-github/providers/githubGitProvider.ts +1 -0
  427. package/src/utils/color.ts +2 -0
  428. package/src/utils/decorators/log.ts +1 -1
  429. package/src/utils/decorators/sequentialize.ts +8 -6
  430. package/src/utils/decorators/serializable.ts +1 -0
  431. package/src/utils/dedupedAsyncCache.ts +74 -0
  432. package/src/utils/diff.ts +61 -0
  433. package/src/utils/disposable.ts +2 -0
  434. package/src/utils/env/node/base64.ts +1 -1
  435. package/src/utils/env/node/exec.ts +4 -2
  436. package/src/utils/error.ts +1 -0
  437. package/src/utils/formatter.ts +4 -11
  438. package/src/utils/iterable.ts +4 -1
  439. package/src/utils/logger.ts +1 -0
  440. package/src/utils/lruMap.ts +112 -0
  441. package/src/utils/markdown.ts +1 -0
  442. package/src/utils/mru.ts +2 -0
  443. package/src/utils/path.ts +1 -0
  444. package/src/utils/promise.ts +22 -0
  445. package/src/utils/promiseCache.ts +24 -0
  446. package/src/utils/string.ts +2 -0
  447. package/src/utils/uri.ts +1 -0
  448. package/src/utils/version.ts +49 -0
  449. package/dist/git/exec.types.d.ts.map +0 -1
  450. package/dist/git/exec.types.js +0 -2
  451. package/dist/git/exec.types.js.map +0 -1
@@ -0,0 +1,1480 @@
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 = 60 * 1000; // 1 minute
19
+ /** Cooldown between PostToolUse and dropping the file from `currentFiles`. Held long enough that
20
+ * surfaces consuming the list (WIP file decoration, treemap activity overlay) keep showing a file
21
+ * the agent just touched well past the moment the tool call completed — a single edit reads as a
22
+ * sustained presence rather than a flash. */
23
+ const postToolUseClearDelayMs = 120000;
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
+ /** Order-insensitive comparison — entries come from a `Map.values()` iterator, but tracked
42
+ * tool-use ids are uncorrelated with file order, so two snapshots with the same files in a
43
+ * different order shouldn't fire a no-op change event. Treats `undefined` and `[]` as equal. */
44
+ function currentFilesEqual(a, b) {
45
+ const aLen = a?.length ?? 0;
46
+ const bLen = b?.length ?? 0;
47
+ if (aLen !== bLen)
48
+ return false;
49
+ if (aLen === 0)
50
+ return true;
51
+ if (aLen === 1)
52
+ return a[0] === b[0];
53
+ const set = new Set(a);
54
+ for (const v of b) {
55
+ if (!set.has(v))
56
+ return false;
57
+ }
58
+ return true;
59
+ }
60
+ export class ClaudeCodeProvider {
61
+ callbacks;
62
+ id = 'claudeCode';
63
+ name = 'Claude Code';
64
+ icon = 'robot';
65
+ _onDidChangeSessions = new Emitter();
66
+ onDidChangeSessions = this._onDidChangeSessions.event;
67
+ _sessions = [];
68
+ _ipcStarted = false;
69
+ _disposed = false;
70
+ _handlerDisposables = [];
71
+ _pendingPermissions = new Map();
72
+ _resolveGitInfoInFlight = new Set();
73
+ _sessionBookkeeping = new Map();
74
+ /** Per-session timers for the deferred `Stop → idle` commit. The handle is cleared (and the
75
+ * transition cancelled) by any non-idle status update arriving before the timer fires. */
76
+ _pendingIdleTimers = new Map();
77
+ _workspacePaths = [];
78
+ _staleCheckTimer;
79
+ _transcriptReader = new ClaudeCodeTranscriptReader();
80
+ constructor(callbacks) {
81
+ this.callbacks = callbacks;
82
+ }
83
+ get sessions() {
84
+ return this._sessions;
85
+ }
86
+ start(workspacePaths) {
87
+ this._workspacePaths = workspacePaths.map(p => normalizePath(p));
88
+ void this.ensureIpcServer();
89
+ }
90
+ stop() {
91
+ // IPC server stays up intentionally — hooks fire even when the window is unfocused
92
+ }
93
+ updateWorkspacePaths(workspacePaths) {
94
+ this._workspacePaths = workspacePaths.map(p => normalizePath(p));
95
+ let changed = false;
96
+ for (let i = 0; i < this._sessions.length; i++) {
97
+ const s = this._sessions[i];
98
+ const nextWorkspacePath = s.cwd != null ? this.resolveWorkspacePath(s.cwd) : undefined;
99
+ const nextIsInWorkspace = nextWorkspacePath != null;
100
+ let subagentsChanged = false;
101
+ const subagents = s.subagents?.map(sub => {
102
+ const subNextWorkspacePath = sub.cwd != null ? this.resolveWorkspacePath(sub.cwd) : nextWorkspacePath;
103
+ const subNextIsInWorkspace = sub.cwd != null ? subNextWorkspacePath != null : nextIsInWorkspace;
104
+ if (sub.isInWorkspace === subNextIsInWorkspace && sub.workspacePath === subNextWorkspacePath) {
105
+ return sub;
106
+ }
107
+ subagentsChanged = true;
108
+ return { ...sub, isInWorkspace: subNextIsInWorkspace, workspacePath: subNextWorkspacePath };
109
+ });
110
+ if (s.isInWorkspace !== nextIsInWorkspace || s.workspacePath !== nextWorkspacePath || subagentsChanged) {
111
+ this._sessions[i] = {
112
+ ...s,
113
+ isInWorkspace: nextIsInWorkspace,
114
+ workspacePath: nextWorkspacePath,
115
+ subagents: subagents,
116
+ };
117
+ changed = true;
118
+ }
119
+ }
120
+ if (changed) {
121
+ this._onDidChangeSessions.fire();
122
+ }
123
+ if (!this._ipcStarted) {
124
+ // IPC wasn't bootstrapped yet — start it. ensureIpcServer publishes with the
125
+ // current `_workspacePaths`.
126
+ void this.ensureIpcServer();
127
+ }
128
+ else {
129
+ // Re-publish so the agents discovery file reflects the new workspacePaths.
130
+ this.callbacks.ipc
131
+ .publishAgents(this._workspacePaths)
132
+ .catch((ex) => Logger.error(ex, 'ClaudeCodeProvider.updateWorkspacePaths: publishAgents failed'));
133
+ }
134
+ }
135
+ dispose() {
136
+ this._disposed = true;
137
+ this.stop();
138
+ this._staleCheckTimer?.dispose();
139
+ this._staleCheckTimer = undefined;
140
+ for (const d of this._handlerDisposables) {
141
+ d.dispose();
142
+ }
143
+ this._handlerDisposables = [];
144
+ for (const pending of this._pendingPermissions.values()) {
145
+ pending.reject(new Error('Provider disposed'));
146
+ }
147
+ this._pendingPermissions.clear();
148
+ for (const bk of this._sessionBookkeeping.values()) {
149
+ this.cancelPendingFileClears(bk);
150
+ this.cancelPendingReadClears(bk);
151
+ }
152
+ for (const timer of this._pendingIdleTimers.values()) {
153
+ clearTimeout(timer);
154
+ }
155
+ this._pendingIdleTimers.clear();
156
+ this._sessionBookkeeping.clear();
157
+ if (this._ipcStarted) {
158
+ void this.callbacks.ipc.unpublishAgents();
159
+ this._ipcStarted = false;
160
+ }
161
+ this._onDidChangeSessions.dispose();
162
+ }
163
+ [Symbol.dispose]() {
164
+ this.dispose();
165
+ }
166
+ async ensureIpcServer() {
167
+ if (this._ipcStarted || this._disposed)
168
+ return;
169
+ // Register handlers before any async work so blocking permission requests aren't delayed.
170
+ const handlers = [
171
+ this.callbacks.ipc.registerHandler('agents/session', (request, searchParams) => {
172
+ if (request != null) {
173
+ const isBlocking = searchParams.get('blocking') === 'true';
174
+ return this.handleSessionEvent(request, isBlocking);
175
+ }
176
+ return Promise.resolve();
177
+ }),
178
+ this.callbacks.ipc.registerHandler('agents/sessions/list', () => Promise.resolve(this._sessions.map(s => ({
179
+ ...s,
180
+ lastActivity: s.lastActivity.toISOString(),
181
+ phaseSince: s.phaseSince.toISOString(),
182
+ subagents: s.subagents?.map(sub => ({
183
+ ...sub,
184
+ lastActivity: sub.lastActivity.toISOString(),
185
+ phaseSince: sub.phaseSince.toISOString(),
186
+ })),
187
+ })))),
188
+ this.callbacks.ipc.registerHandler('agents/sessions/open', async (request) => {
189
+ const sessionId = request?.sessionId;
190
+ if (!sessionId || this.callbacks.openSessionInClaudeExtension == null) {
191
+ return { opened: false };
192
+ }
193
+ try {
194
+ await this.callbacks.openSessionInClaudeExtension(sessionId);
195
+ return { opened: true };
196
+ }
197
+ catch (ex) {
198
+ Logger.warn(`ClaudeCodeProvider.agents/sessions/open: ${ex instanceof Error ? ex.message : String(ex)}`);
199
+ return { opened: false };
200
+ }
201
+ }),
202
+ ];
203
+ try {
204
+ await this.callbacks.ipc.publishAgents(this._workspacePaths);
205
+ }
206
+ catch (ex) {
207
+ // Unwind so a retry can re-register without hitting "already registered".
208
+ for (const d of handlers) {
209
+ d.dispose();
210
+ }
211
+ Logger.error(ex, 'ClaudeCodeProvider.ensureIpcServer');
212
+ return;
213
+ }
214
+ // `publishAgents` no-ops silently if the IPC server failed to start; don't seal
215
+ // retries in that case — the next call should re-attempt.
216
+ if (this.callbacks.ipc.port == null) {
217
+ for (const d of handlers) {
218
+ d.dispose();
219
+ }
220
+ return;
221
+ }
222
+ if (this._disposed) {
223
+ for (const d of handlers) {
224
+ d.dispose();
225
+ }
226
+ return;
227
+ }
228
+ this._handlerDisposables = handlers;
229
+ this._ipcStarted = true;
230
+ try {
231
+ await this.syncSessions();
232
+ if (this._disposed)
233
+ return;
234
+ void this.querySiblingWindowSessions();
235
+ this._staleCheckTimer?.dispose();
236
+ this._staleCheckTimer = disposableInterval(() => void this.syncSessions(), staleCheckIntervalMs);
237
+ }
238
+ catch (ex) {
239
+ Logger.error(ex, 'ClaudeCodeProvider.ensureIpcServer');
240
+ }
241
+ }
242
+ handleSessionEvent(event, isBlocking) {
243
+ const workspacePath = this.resolveWorkspacePath(event.cwd);
244
+ const eventContext = {
245
+ pid: event.pid,
246
+ workspacePath: workspacePath,
247
+ isInWorkspace: workspacePath != null,
248
+ cwd: event.cwd,
249
+ planFile: event.planFile,
250
+ sessionName: event.sessionName,
251
+ };
252
+ const tag = this.sessionTag(event.sessionId, event.sessionName ?? 'unnamed');
253
+ if (event.event === 'SessionStart' || event.event === 'SessionEnd') {
254
+ Logger.info(`ClaudeCodeProvider.handleSessionEvent: ${event.event} ${tag}`);
255
+ }
256
+ else {
257
+ Logger.debug(`ClaudeCodeProvider.handleSessionEvent: ${event.event} ${tag}${event.toolName ? ` tool=${event.toolName}` : ''}${event.agentId ? ` agent=${event.agentId}` : ''}${event.notificationType ? ` type=${event.notificationType}` : ''}`);
258
+ }
259
+ switch (event.event) {
260
+ case 'SessionStart': {
261
+ const wasNew = this._sessions.findIndex(s => s.id === event.sessionId) < 0;
262
+ const { index } = this.ensureSession(event.sessionId, eventContext);
263
+ if (wasNew) {
264
+ // ensureSession created the session at 'idle' already. Just refresh pid if
265
+ // the event carries one — bookkeeping was implicitly clean.
266
+ this.resetBookkeeping(event.sessionId);
267
+ if (event.pid != null) {
268
+ const prev = this._sessions[index];
269
+ if (prev.pid !== event.pid) {
270
+ this._sessions[index] = { ...prev, pid: event.pid };
271
+ }
272
+ }
273
+ }
274
+ else {
275
+ // SessionStart for a session we already track is almost always a CLI replay
276
+ // (resume/reconnect/hook re-init). Don't clobber live state — the next real
277
+ // event will re-establish status. Refresh pid only.
278
+ const prev = this._sessions[index];
279
+ if (event.pid != null && event.pid !== prev.pid) {
280
+ this._sessions[index] = { ...prev, pid: event.pid, lastActivity: new Date() };
281
+ }
282
+ }
283
+ this._onDidChangeSessions.fire();
284
+ void this.resolveTranscriptTitles(event.sessionId, event.cwd);
285
+ this.callbacks.onSessionStarted?.(this.id);
286
+ break;
287
+ }
288
+ case 'SessionEnd': {
289
+ const pending = this._pendingPermissions.get(event.sessionId);
290
+ if (pending != null) {
291
+ pending.reject(new Error('Session ended'));
292
+ this._pendingPermissions.delete(event.sessionId);
293
+ }
294
+ this.cancelPendingIdleTransition(event.sessionId);
295
+ const index = this._sessions.findIndex(s => s.id === event.sessionId);
296
+ if (index >= 0) {
297
+ this._sessions.splice(index, 1);
298
+ this._onDidChangeSessions.fire();
299
+ }
300
+ const bk = this._sessionBookkeeping.get(event.sessionId);
301
+ if (bk != null) {
302
+ this.cancelPendingFileClears(bk);
303
+ this.cancelPendingReadClears(bk);
304
+ }
305
+ this._sessionBookkeeping.delete(event.sessionId);
306
+ this._transcriptReader.forget(event.sessionId);
307
+ this.callbacks.onSessionEnded?.(this.id);
308
+ break;
309
+ }
310
+ case 'UserPromptSubmit': {
311
+ const { index } = this.ensureSession(event.sessionId, eventContext);
312
+ const cleaned = prepareStoredPrompt(event.prompt);
313
+ // A `UserPromptSubmit` whose payload sanitizes to nothing is harness-synthetic
314
+ // (e.g. background-bash <task-notification>, slash-command stdout echo). Treat it
315
+ // as informational so it doesn't flip the session to `thinking` or wipe a pending
316
+ // permission when no real user activity occurred.
317
+ if (!cleaned)
318
+ break;
319
+ const existing = this._sessions[index];
320
+ this._sessions[index] = {
321
+ ...existing,
322
+ lastPrompt: cleaned,
323
+ firstPrompt: existing.firstPrompt ?? prepareStoredPrompt(event.firstPrompt),
324
+ };
325
+ this.clearStalePermission(event.sessionId, 'UserPromptSubmit');
326
+ this.updateSessionStatus(event.sessionId, 'thinking', eventContext);
327
+ break;
328
+ }
329
+ case 'PreToolUse': {
330
+ const bk = this.getBookkeeping(event.sessionId);
331
+ bk.activeToolCount++;
332
+ const filesChanged = this.trackToolUseFile(event.sessionId, event);
333
+ const readsChanged = this.trackToolUseRead(event.sessionId, event);
334
+ // Resolve a rich `Bash(grep …)`-style detail via the same tool_input passthrough the
335
+ // PermissionRequest handler uses, so working sessions surface what their tool is
336
+ // actually doing — not just the bare tool name. Falls back to bare name when no
337
+ // toolInput is available (older CLI / unhandled tool).
338
+ const hookInput = event.hookInput;
339
+ const toolInput = hookInput?.tool_input ?? event.toolInput;
340
+ const toolName = hookInput?.tool_name ?? event.toolName ?? '';
341
+ const statusDetail = toolInput != null && toolName ? describeToolInput(toolName, toolInput) : toolName || undefined;
342
+ // Capture pre-update status so we can tell whether the upcoming updateSessionStatus
343
+ // will fire on its own — needed to avoid dropping currentFiles changes when the
344
+ // session is already in tool_use (back-to-back tool calls).
345
+ const sessionIndex = this._sessions.findIndex(s => s.id === event.sessionId);
346
+ const prevStatus = sessionIndex >= 0 ? this._sessions[sessionIndex].status : undefined;
347
+ const prevDetail = sessionIndex >= 0 ? this._sessions[sessionIndex].statusDetail : undefined;
348
+ const statusWillFire = prevStatus !== 'tool_use' || prevDetail !== statusDetail;
349
+ this.updateSessionStatus(event.sessionId, 'tool_use', {
350
+ ...eventContext,
351
+ statusDetail: statusDetail,
352
+ });
353
+ if ((filesChanged || readsChanged) && !statusWillFire) {
354
+ this._onDidChangeSessions.fire();
355
+ }
356
+ break;
357
+ }
358
+ case 'PostToolUse':
359
+ case 'PostToolUseFailure': {
360
+ this.clearStalePermission(event.sessionId, event.event);
361
+ const bk = this.getBookkeeping(event.sessionId);
362
+ bk.activeToolCount = Math.max(0, bk.activeToolCount - 1);
363
+ // Cooldown the file-edit decoration instead of dropping it immediately, so a quick
364
+ // follow-up Edit/Write to the same path doesn't blink. The deferred clear fires its
365
+ // own change event when it expires.
366
+ this.scheduleClearToolUseFile(event.sessionId, event);
367
+ this.scheduleClearToolUseRead(event.sessionId, event);
368
+ if (bk.activeToolCount === 0) {
369
+ this.updateSessionStatus(event.sessionId, 'thinking', eventContext);
370
+ }
371
+ break;
372
+ }
373
+ case 'Stop':
374
+ case 'StopFailure': {
375
+ const pending = this._pendingPermissions.get(event.sessionId);
376
+ if (pending != null) {
377
+ pending.reject(new Error('Session stopped'));
378
+ this._pendingPermissions.delete(event.sessionId);
379
+ }
380
+ this.resetBookkeeping(event.sessionId);
381
+ // Apply Stop's metadata synchronously so we don't carry stale context through the
382
+ // debounce window — any in-window mutations (e.g. CwdChanged) survive when the
383
+ // timer fires. ensureSession doesn't fire on metadata-only updates of existing
384
+ // sessions, so fire here to match the original Stop-handler's UI-update semantics.
385
+ const { changed } = this.ensureSession(event.sessionId, eventContext);
386
+ if (changed) {
387
+ this._onDidChangeSessions.fire();
388
+ }
389
+ // Defer the status change — if the agent continues within the debounce window
390
+ // (hook-driven re-prompt, IPC reordering, auto-resume), the next non-idle event
391
+ // cancels this and we never flick through idle.
392
+ this.scheduleIdleTransition(event.sessionId);
393
+ break;
394
+ }
395
+ case 'PreCompact':
396
+ this.updateSessionStatus(event.sessionId, 'compacting', eventContext);
397
+ break;
398
+ case 'PostCompact':
399
+ this.updateSessionStatus(event.sessionId, 'thinking', eventContext);
400
+ break;
401
+ case 'Notification':
402
+ switch (event.notificationType) {
403
+ case 'idle_prompt':
404
+ // No-op — session is already idle from the preceding stop/session-start event
405
+ break;
406
+ case 'permission_prompt':
407
+ case 'elicitation_dialog':
408
+ this.updateSessionStatus(event.sessionId, 'permission_requested', {
409
+ ...eventContext,
410
+ statusDetail: event.toolName,
411
+ });
412
+ break;
413
+ default:
414
+ // auth_success, unknown, or missing: no status change, just update timestamp
415
+ break;
416
+ }
417
+ break;
418
+ case 'PermissionRequest': {
419
+ // hookInput is the raw passthrough; fall back to top-level fields for older CLI versions.
420
+ const hookInput = event.hookInput;
421
+ const toolInput = hookInput?.tool_input ?? event.toolInput;
422
+ if (isBlocking && toolInput != null) {
423
+ const toolName = hookInput?.tool_name ?? event.toolName ?? '';
424
+ const toolDescription = describeToolInput(toolName, toolInput);
425
+ const toolInputDescription = toolInput.description || undefined;
426
+ const kind = classifyPermissionKind(toolName);
427
+ return new Promise((resolve, reject) => {
428
+ const existing = this._pendingPermissions.get(event.sessionId);
429
+ if (existing != null) {
430
+ Logger.debug(`ClaudeCodeProvider.handleSessionEvent: auto-denying stale permission ${tag} tool=${existing.toolName}`);
431
+ existing.resolve({
432
+ hookSpecificOutput: {
433
+ hookEventName: 'PermissionRequest',
434
+ decision: { behavior: 'deny' },
435
+ },
436
+ });
437
+ }
438
+ this._pendingPermissions.set(event.sessionId, {
439
+ resolve: resolve,
440
+ reject: reject,
441
+ toolName: toolName,
442
+ toolDescription: toolDescription,
443
+ });
444
+ // Plan-kind body: prefer the existing session's planFile (set via SessionStart/
445
+ // PostToolUse) and fall back to the event's planFile for cold-start cases.
446
+ const planFilePath = kind === 'plan'
447
+ ? (this._sessions.find(s => s.id === event.sessionId)?.planFile ?? event.planFile)
448
+ : undefined;
449
+ const planSummary = kind === 'plan' ? extractPlanSummary(toolInput) : undefined;
450
+ const questionDetails = kind === 'question' ? extractQuestionDetails(toolInput) : undefined;
451
+ const permission = {
452
+ kind: kind,
453
+ toolName: toolName,
454
+ toolDescription: toolDescription,
455
+ toolInputDescription: toolInputDescription,
456
+ suggestions: hookInput?.permission_suggestions ??
457
+ event.permissionSuggestions,
458
+ planFilePath: planFilePath,
459
+ planSummary: planSummary,
460
+ questionText: questionDetails?.text,
461
+ questionCount: questionDetails?.count,
462
+ };
463
+ this.updateSessionWithPermission(event.sessionId, permission, event.pid);
464
+ });
465
+ }
466
+ this.updateSessionStatus(event.sessionId, 'permission_requested', {
467
+ ...eventContext,
468
+ statusDetail: event.toolName,
469
+ });
470
+ break;
471
+ }
472
+ case 'PermissionDenied': {
473
+ this.clearStalePermission(event.sessionId, 'PermissionDenied');
474
+ const bk = this.getBookkeeping(event.sessionId);
475
+ bk.activeToolCount = Math.max(0, bk.activeToolCount - 1);
476
+ const filesChanged = this.untrackToolUseFile(event.sessionId, event);
477
+ const readsChanged = this.untrackToolUseRead(event.sessionId, event);
478
+ // When a parallel tool is still active the next status equals the current one and
479
+ // updateSessionStatus short-circuits — without an explicit fire, the dropped path
480
+ // would never reach subscribers (treemap activity overlay, WIP decoration).
481
+ const nextStatus = bk.activeToolCount > 0 ? 'tool_use' : 'thinking';
482
+ const sessionIndex = this._sessions.findIndex(s => s.id === event.sessionId);
483
+ const prevStatus = sessionIndex >= 0 ? this._sessions[sessionIndex].status : undefined;
484
+ const statusWillFire = prevStatus !== nextStatus;
485
+ this.updateSessionStatus(event.sessionId, nextStatus, eventContext);
486
+ if ((filesChanged || readsChanged) && !statusWillFire) {
487
+ this._onDidChangeSessions.fire();
488
+ }
489
+ break;
490
+ }
491
+ case 'Elicitation': {
492
+ const bk = this.getBookkeeping(event.sessionId);
493
+ bk.pendingPermission = {
494
+ kind: 'elicitation',
495
+ toolName: event.toolName ?? 'Input Required',
496
+ toolDescription: event.toolName ?? 'Waiting for input',
497
+ };
498
+ this.updateSessionStatus(event.sessionId, 'permission_requested', {
499
+ ...eventContext,
500
+ statusDetail: event.toolName,
501
+ });
502
+ break;
503
+ }
504
+ case 'ElicitationResult': {
505
+ const bk = this.getBookkeeping(event.sessionId);
506
+ bk.pendingPermission = undefined;
507
+ this.updateSessionStatus(event.sessionId, bk.activeToolCount > 0 ? 'tool_use' : 'thinking', eventContext);
508
+ break;
509
+ }
510
+ case 'CwdChanged':
511
+ if (event.cwd) {
512
+ const index = this._sessions.findIndex(s => s.id === event.sessionId);
513
+ if (index >= 0 && this._sessions[index].cwd !== event.cwd) {
514
+ this._sessions[index] = { ...this._sessions[index], cwd: event.cwd };
515
+ this._onDidChangeSessions.fire();
516
+ }
517
+ // Clear the unresolvable flag so the new cwd actually gets re-probed — without
518
+ // this, a session that started in a non-git cwd would stay flagged forever even
519
+ // after moving into a git repo.
520
+ this.getBookkeeping(event.sessionId).gitInfoUnresolvable = false;
521
+ void this.resolveGitInfo(event.sessionId, event.cwd);
522
+ }
523
+ break;
524
+ case 'SubagentStart': {
525
+ const { index: parentIdx } = this.ensureSession(event.sessionId, eventContext);
526
+ const parent = this._sessions[parentIdx];
527
+ if (event.agentId) {
528
+ const now = new Date();
529
+ const subagent = {
530
+ id: event.agentId,
531
+ providerId: this.id,
532
+ providerName: this.name,
533
+ name: event.agentType ?? 'Subagent',
534
+ status: 'thinking',
535
+ phase: 'working',
536
+ phaseSince: now,
537
+ lastActivity: now,
538
+ isSubagent: true,
539
+ parentId: event.sessionId,
540
+ isInWorkspace: workspacePath != null,
541
+ };
542
+ const existingSubs = parent.subagents ? [...parent.subagents] : [];
543
+ existingSubs.push(subagent);
544
+ this._sessions[parentIdx] = { ...parent, subagents: existingSubs };
545
+ this._onDidChangeSessions.fire();
546
+ }
547
+ break;
548
+ }
549
+ case 'SubagentStop': {
550
+ const { index: parentIdx } = this.ensureSession(event.sessionId, eventContext);
551
+ const parentSession = this._sessions[parentIdx];
552
+ if (parentSession.subagents != null && event.agentId) {
553
+ const filtered = parentSession.subagents.filter(s => s.id !== event.agentId);
554
+ if (filtered.length !== parentSession.subagents.length) {
555
+ this._sessions[parentIdx] = {
556
+ ...parentSession,
557
+ subagents: filtered.length > 0 ? filtered : undefined,
558
+ };
559
+ this._onDidChangeSessions.fire();
560
+ }
561
+ }
562
+ break;
563
+ }
564
+ case 'TeammateIdle':
565
+ case 'TaskCompleted':
566
+ case 'InstructionsLoaded':
567
+ case 'ConfigChange':
568
+ case 'WorktreeCreate':
569
+ case 'WorktreeRemove':
570
+ // Not yet handled — intentional no-op.
571
+ break;
572
+ }
573
+ return Promise.resolve();
574
+ }
575
+ sessionTag(sessionId, name) {
576
+ return name != null
577
+ ? `[session=${sessionId.substring(0, 8)}(${name})]`
578
+ : `[session=${sessionId.substring(0, 8)}]`;
579
+ }
580
+ getBookkeeping(sessionId) {
581
+ let bk = this._sessionBookkeeping.get(sessionId);
582
+ if (bk == null) {
583
+ bk = {
584
+ activeToolCount: 0,
585
+ currentFileCounts: new Map(),
586
+ pendingFileClears: new Map(),
587
+ currentReadCounts: new Map(),
588
+ pendingReadClears: new Map(),
589
+ gitInfoUnresolvable: false,
590
+ };
591
+ this._sessionBookkeeping.set(sessionId, bk);
592
+ }
593
+ return bk;
594
+ }
595
+ resetBookkeeping(sessionId) {
596
+ const bk = this.getBookkeeping(sessionId);
597
+ bk.activeToolCount = 0;
598
+ bk.pendingPermission = undefined;
599
+ this.cancelPendingFileClears(bk);
600
+ bk.currentFileCounts.clear();
601
+ this.cancelPendingReadClears(bk);
602
+ bk.currentReadCounts.clear();
603
+ bk.gitInfoUnresolvable = false;
604
+ this.syncSessionCurrentFiles(sessionId, bk);
605
+ this.syncSessionCurrentReads(sessionId, bk);
606
+ }
607
+ cancelPendingFileClears(bk) {
608
+ for (const timer of bk.pendingFileClears.values()) {
609
+ clearTimeout(timer);
610
+ }
611
+ bk.pendingFileClears.clear();
612
+ }
613
+ cancelPendingReadClears(bk) {
614
+ for (const timer of bk.pendingReadClears.values()) {
615
+ clearTimeout(timer);
616
+ }
617
+ bk.pendingReadClears.clear();
618
+ }
619
+ /** Extracts the targeted file path from a PreToolUse/PostToolUse event. Tries the raw
620
+ * `hookInput.tool_input` passthrough first, falls back to the projected `event.toolInput`
621
+ * for older CLI versions that only fill the top-level fields. Treats an empty-object
622
+ * `hookInput.tool_input` as missing — `??` would have kept it (truthy) and shadowed a
623
+ * populated `event.toolInput`. */
624
+ getEventFilePath(event) {
625
+ const toolName = event.hookInput?.tool_name ?? event.toolName;
626
+ if (toolName == null)
627
+ return undefined;
628
+ const rawHookInput = event.hookInput?.tool_input;
629
+ const hookInputPopulated = rawHookInput != null && Object.keys(rawHookInput).length > 0;
630
+ const toolInput = hookInputPopulated ? rawHookInput : event.toolInput;
631
+ return getToolFilePath(toolName, toolInput);
632
+ }
633
+ /** Records that a file-mutating tool call is in flight against `filePath` so the WIP details
634
+ * panel can decorate the row. Refcounts per path — keyed by path (not `tool_use_id`, which
635
+ * the GK CLI doesn't reliably surface) so parallel calls bump the count and Post/Pre order
636
+ * doesn't matter. Returns whether the session's published list actually changed so callers
637
+ * can fire when the surrounding {@link updateSessionStatus} short-circuits. */
638
+ trackToolUseFile(sessionId, event) {
639
+ const filePath = this.getEventFilePath(event);
640
+ if (filePath == null)
641
+ return false;
642
+ const bk = this.getBookkeeping(sessionId);
643
+ // A fresh Pre during a pending Post-cooldown means the file is live again — cancel the
644
+ // scheduled clear so the deferred drop doesn't run after the new tool already finished.
645
+ const pendingClear = bk.pendingFileClears.get(filePath);
646
+ if (pendingClear != null) {
647
+ clearTimeout(pendingClear);
648
+ bk.pendingFileClears.delete(filePath);
649
+ }
650
+ bk.currentFileCounts.set(filePath, (bk.currentFileCounts.get(filePath) ?? 0) + 1);
651
+ return this.syncSessionCurrentFiles(sessionId, bk);
652
+ }
653
+ /** Decrements the in-flight refcount for a finished tool call's file. While the count stays
654
+ * above zero (overlapping parallel calls) the path remains decorated. When the count drops
655
+ * to zero, leaves the entry in place at count `0` and schedules a {@link postToolUseClearDelayMs}
656
+ * cooldown before actually dropping it — so back-to-back Edit/Write to the same file doesn't
657
+ * flicker the decoration. A Pre arriving during cooldown cancels the timer and bumps the
658
+ * count back above zero. */
659
+ scheduleClearToolUseFile(sessionId, event) {
660
+ const filePath = this.getEventFilePath(event);
661
+ if (filePath == null)
662
+ return;
663
+ const bk = this.getBookkeeping(sessionId);
664
+ const count = bk.currentFileCounts.get(filePath);
665
+ // A duplicate / out-of-order Post during cooldown (count is already 0) would drive the
666
+ // refcount negative and schedule a second timer — ignore those so the cooldown stays
667
+ // authoritative until either its timer fires or a fresh Pre bumps the count back up.
668
+ if (count == null || count <= 0)
669
+ return;
670
+ const next = count - 1;
671
+ bk.currentFileCounts.set(filePath, next);
672
+ if (next > 0)
673
+ return;
674
+ // Refcount just hit zero — keep the path in `currentFileCounts` (still decorated) for the
675
+ // cooldown window, then drop it.
676
+ const existing = bk.pendingFileClears.get(filePath);
677
+ if (existing != null) {
678
+ clearTimeout(existing);
679
+ }
680
+ const timer = setTimeout(() => {
681
+ if (this._disposed)
682
+ return;
683
+ const cur = this._sessionBookkeeping.get(sessionId);
684
+ if (cur == null)
685
+ return;
686
+ cur.pendingFileClears.delete(filePath);
687
+ // Re-check: a Pre during cooldown bumped the count and cancelled this timer, but a
688
+ // concurrent reset could have cleared everything — bail in either case.
689
+ if ((cur.currentFileCounts.get(filePath) ?? 0) > 0)
690
+ return;
691
+ cur.currentFileCounts.delete(filePath);
692
+ if (this.syncSessionCurrentFiles(sessionId, cur)) {
693
+ this._onDidChangeSessions.fire();
694
+ }
695
+ }, postToolUseClearDelayMs);
696
+ bk.pendingFileClears.set(filePath, timer);
697
+ }
698
+ /** Drops a tracked tool call's file immediately (no cooldown). Used for PermissionDenied,
699
+ * where the tool never ran — keeping a "currently editing" badge would be misleading.
700
+ * Returns whether the published list changed. */
701
+ untrackToolUseFile(sessionId, event) {
702
+ const filePath = this.getEventFilePath(event);
703
+ if (filePath == null)
704
+ return false;
705
+ const bk = this.getBookkeeping(sessionId);
706
+ const count = bk.currentFileCounts.get(filePath);
707
+ if (count == null)
708
+ return false;
709
+ if (count > 1) {
710
+ bk.currentFileCounts.set(filePath, count - 1);
711
+ return false;
712
+ }
713
+ const pending = bk.pendingFileClears.get(filePath);
714
+ if (pending != null) {
715
+ clearTimeout(pending);
716
+ bk.pendingFileClears.delete(filePath);
717
+ }
718
+ bk.currentFileCounts.delete(filePath);
719
+ return this.syncSessionCurrentFiles(sessionId, bk);
720
+ }
721
+ /** Writes the bookkeeping's tracked file paths onto the session in place. Returns whether the
722
+ * session's `currentFiles` actually changed. Keys (not values) — entries with count `0` are
723
+ * cooldown-residents, still part of the published list. */
724
+ syncSessionCurrentFiles(sessionId, bk) {
725
+ const index = this._sessions.findIndex(s => s.id === sessionId);
726
+ if (index < 0)
727
+ return false;
728
+ const prev = this._sessions[index];
729
+ const next = bk.currentFileCounts.size > 0 ? [...bk.currentFileCounts.keys()] : undefined;
730
+ if (currentFilesEqual(prev.currentFiles, next))
731
+ return false;
732
+ this._sessions[index] = { ...prev, currentFiles: next };
733
+ return true;
734
+ }
735
+ /** Mirror of {@link getEventFilePath} for read-only file tools. */
736
+ getEventReadPath(event) {
737
+ const toolName = event.hookInput?.tool_name ?? event.toolName;
738
+ if (toolName == null)
739
+ return undefined;
740
+ const rawHookInput = event.hookInput?.tool_input;
741
+ const hookInputPopulated = rawHookInput != null && Object.keys(rawHookInput).length > 0;
742
+ const toolInput = hookInputPopulated ? rawHookInput : event.toolInput;
743
+ return getToolReadPath(toolName, toolInput);
744
+ }
745
+ /** Refcount mirror of {@link trackToolUseFile} for read-only file tools. */
746
+ trackToolUseRead(sessionId, event) {
747
+ const filePath = this.getEventReadPath(event);
748
+ if (filePath == null)
749
+ return false;
750
+ const bk = this.getBookkeeping(sessionId);
751
+ const pendingClear = bk.pendingReadClears.get(filePath);
752
+ if (pendingClear != null) {
753
+ clearTimeout(pendingClear);
754
+ bk.pendingReadClears.delete(filePath);
755
+ }
756
+ bk.currentReadCounts.set(filePath, (bk.currentReadCounts.get(filePath) ?? 0) + 1);
757
+ return this.syncSessionCurrentReads(sessionId, bk);
758
+ }
759
+ /** Cooldown mirror of {@link scheduleClearToolUseFile} for read-only file tools. */
760
+ scheduleClearToolUseRead(sessionId, event) {
761
+ const filePath = this.getEventReadPath(event);
762
+ if (filePath == null)
763
+ return;
764
+ const bk = this.getBookkeeping(sessionId);
765
+ const count = bk.currentReadCounts.get(filePath);
766
+ // Same guard as scheduleClearToolUseFile — duplicate / out-of-order Posts during cooldown
767
+ // would otherwise drive the refcount negative and stack up redundant clear timers.
768
+ if (count == null || count <= 0)
769
+ return;
770
+ const next = count - 1;
771
+ bk.currentReadCounts.set(filePath, next);
772
+ if (next > 0)
773
+ return;
774
+ const existing = bk.pendingReadClears.get(filePath);
775
+ if (existing != null) {
776
+ clearTimeout(existing);
777
+ }
778
+ const timer = setTimeout(() => {
779
+ if (this._disposed)
780
+ return;
781
+ const cur = this._sessionBookkeeping.get(sessionId);
782
+ if (cur == null)
783
+ return;
784
+ cur.pendingReadClears.delete(filePath);
785
+ if ((cur.currentReadCounts.get(filePath) ?? 0) > 0)
786
+ return;
787
+ cur.currentReadCounts.delete(filePath);
788
+ if (this.syncSessionCurrentReads(sessionId, cur)) {
789
+ this._onDidChangeSessions.fire();
790
+ }
791
+ }, postToolUseClearDelayMs);
792
+ bk.pendingReadClears.set(filePath, timer);
793
+ }
794
+ /** Immediate-drop mirror of {@link untrackToolUseFile} for read-only file tools. */
795
+ untrackToolUseRead(sessionId, event) {
796
+ const filePath = this.getEventReadPath(event);
797
+ if (filePath == null)
798
+ return false;
799
+ const bk = this.getBookkeeping(sessionId);
800
+ const count = bk.currentReadCounts.get(filePath);
801
+ if (count == null)
802
+ return false;
803
+ if (count > 1) {
804
+ bk.currentReadCounts.set(filePath, count - 1);
805
+ return false;
806
+ }
807
+ const pending = bk.pendingReadClears.get(filePath);
808
+ if (pending != null) {
809
+ clearTimeout(pending);
810
+ bk.pendingReadClears.delete(filePath);
811
+ }
812
+ bk.currentReadCounts.delete(filePath);
813
+ return this.syncSessionCurrentReads(sessionId, bk);
814
+ }
815
+ /** Sync mirror of {@link syncSessionCurrentFiles} for read paths. Uses {@link currentFilesEqual}
816
+ * (which is just a generic order-insensitive `string[] | undefined` comparator). */
817
+ syncSessionCurrentReads(sessionId, bk) {
818
+ const index = this._sessions.findIndex(s => s.id === sessionId);
819
+ if (index < 0)
820
+ return false;
821
+ const prev = this._sessions[index];
822
+ const next = bk.currentReadCounts.size > 0 ? [...bk.currentReadCounts.keys()] : undefined;
823
+ if (currentFilesEqual(prev.currentReads, next))
824
+ return false;
825
+ this._sessions[index] = { ...prev, currentReads: next };
826
+ return true;
827
+ }
828
+ /** Defer the `Stop → idle` commit. If the agent produces a non-idle event within
829
+ * `stopToIdleDebounceMs`, `cancelPendingIdleTransition` (called from `updateSessionStatus`)
830
+ * cancels this and the session stays in its prior phase — no working → idle → working flicker.
831
+ *
832
+ * Intentionally takes no context: the caller is expected to apply any event metadata
833
+ * synchronously before scheduling. Carrying Stop-time context into the timer would let
834
+ * in-window metadata mutations (e.g. `CwdChanged` updating `_sessions[i].cwd` directly)
835
+ * get reverted when the deferred commit replays the stale context through `ensureSession`. */
836
+ scheduleIdleTransition(sessionId) {
837
+ this.cancelPendingIdleTransition(sessionId);
838
+ const timer = setTimeout(() => {
839
+ this._pendingIdleTimers.delete(sessionId);
840
+ // Session may have been removed (SessionEnd, prune) during the window.
841
+ if (this._sessions.findIndex(s => s.id === sessionId) < 0)
842
+ return;
843
+ this.updateSessionStatus(sessionId, 'idle');
844
+ }, stopToIdleDebounceMs);
845
+ this._pendingIdleTimers.set(sessionId, timer);
846
+ }
847
+ cancelPendingIdleTransition(sessionId) {
848
+ const timer = this._pendingIdleTimers.get(sessionId);
849
+ if (timer == null)
850
+ return;
851
+ clearTimeout(timer);
852
+ this._pendingIdleTimers.delete(sessionId);
853
+ }
854
+ /** Stable phase-since: if we're oscillating back into the phase we were just in (within a
855
+ * short window), restore its original timestamp so the displayed elapsed time doesn't snap
856
+ * to 0. Otherwise records the current phase as the new "prior" and returns `now`. */
857
+ resolvePhaseSince(sessionId, prevPhase, prevPhaseSince, newPhase) {
858
+ if (prevPhase === newPhase)
859
+ return prevPhaseSince;
860
+ const bk = this.getBookkeeping(sessionId);
861
+ const now = new Date();
862
+ if (bk.priorPhase?.phase === newPhase && now.getTime() - prevPhaseSince.getTime() < phaseSinceRestoreWindowMs) {
863
+ const restored = bk.priorPhase.phaseSince;
864
+ bk.priorPhase = { phase: prevPhase, phaseSince: prevPhaseSince };
865
+ return restored;
866
+ }
867
+ bk.priorPhase = { phase: prevPhase, phaseSince: prevPhaseSince };
868
+ return now;
869
+ }
870
+ // Called when a pending permission was resolved outside GitLens (e.g. via the CLI terminal).
871
+ // The 'deny' response is a safe no-op since the tool has already run or been denied upstream.
872
+ clearStalePermission(sessionId, reason) {
873
+ const bk = this.getBookkeeping(sessionId);
874
+ if (bk.pendingPermission == null)
875
+ return;
876
+ Logger.debug(`ClaudeCodeProvider.clearStalePermission: ${reason} ${this.sessionTag(sessionId)}`);
877
+ const pending = this._pendingPermissions.get(sessionId);
878
+ if (pending != null) {
879
+ pending.resolve({
880
+ hookSpecificOutput: { hookEventName: 'PermissionRequest', decision: { behavior: 'deny' } },
881
+ });
882
+ this._pendingPermissions.delete(sessionId);
883
+ }
884
+ bk.pendingPermission = undefined;
885
+ }
886
+ resolvePermission(sessionId, decision, updatedPermissions) {
887
+ const pending = this._pendingPermissions.get(sessionId);
888
+ if (pending == null)
889
+ return false;
890
+ Logger.debug(`ClaudeCodeProvider.resolvePermission: ${decision} ${this.sessionTag(sessionId)} tool=${pending.toolName}`);
891
+ pending.resolve({
892
+ hookSpecificOutput: {
893
+ hookEventName: 'PermissionRequest',
894
+ decision: { behavior: decision, updatedPermissions: updatedPermissions },
895
+ },
896
+ });
897
+ this.callbacks.onPermissionResolved?.({
898
+ provider: this.id,
899
+ tool: pending.toolName,
900
+ decision: decision,
901
+ });
902
+ this._pendingPermissions.delete(sessionId);
903
+ const bk = this.getBookkeeping(sessionId);
904
+ bk.pendingPermission = undefined;
905
+ const nextStatus = bk.activeToolCount > 0 ? 'tool_use' : 'thinking';
906
+ this.updateSessionStatus(sessionId, nextStatus);
907
+ return true;
908
+ }
909
+ matchesWorkspace(workspacePath) {
910
+ if (!workspacePath)
911
+ return false;
912
+ // `_workspacePaths` is normalized; normalize the input so prefix comparisons work
913
+ // regardless of whether the caller passed a raw `fsPath` (CLI hook cwd, peer-session
914
+ // workspacePath) or an already-normalized path.
915
+ const normalized = normalizePath(workspacePath);
916
+ return this._workspacePaths.some(p => normalized === p || normalized.startsWith(`${p}/`) || p.startsWith(`${normalized}/`));
917
+ }
918
+ resolveWorkspacePath(cwd) {
919
+ if (!cwd)
920
+ return undefined;
921
+ const normalized = normalizePath(cwd);
922
+ return this._workspacePaths.find(p => normalized === p || normalized.startsWith(`${p}/`) || p.startsWith(`${normalized}/`));
923
+ }
924
+ updateSessionWithPermission(sessionId, permission, pid) {
925
+ // A pending permission is a working/waiting transition — cancel any deferred Stop → idle
926
+ // commit so the session doesn't briefly flip to idle before showing the prompt.
927
+ this.cancelPendingIdleTransition(sessionId);
928
+ const { index } = this.ensureSession(sessionId, { pid: pid });
929
+ const prev = this._sessions[index];
930
+ const newPhase = getPhaseForStatus('permission_requested');
931
+ this.getBookkeeping(sessionId).pendingPermission = permission;
932
+ this._sessions[index] = {
933
+ ...prev,
934
+ status: 'permission_requested',
935
+ phase: newPhase,
936
+ phaseSince: this.resolvePhaseSince(sessionId, prev.phase, prev.phaseSince, newPhase),
937
+ statusDetail: permission.toolDescription,
938
+ pendingPermission: permission,
939
+ lastActivity: new Date(),
940
+ };
941
+ this._onDidChangeSessions.fire();
942
+ }
943
+ updateSessionStatus(sessionId, status, options) {
944
+ // Any non-idle status update implicitly cancels a deferred Stop → idle commit. The
945
+ // timer is owned here so the schedule/cancel pair is uniformly enforced regardless of
946
+ // which event path produced the next status.
947
+ if (status !== 'idle') {
948
+ this.cancelPendingIdleTransition(sessionId);
949
+ }
950
+ const { index, changed: metadataChanged } = this.ensureSession(sessionId, options);
951
+ const prev = this._sessions[index];
952
+ const bk = this.getBookkeeping(sessionId);
953
+ // If a permission/elicitation is pending, preserve permission_requested state.
954
+ // Tool counts and other bookkeeping are still updated by callers before this
955
+ // method, but the visible status remains locked until the wait is explicitly
956
+ // resolved.
957
+ if (bk.pendingPermission != null && status !== 'permission_requested') {
958
+ this._sessions[index] = { ...prev, lastActivity: new Date() };
959
+ if (metadataChanged) {
960
+ this._onDidChangeSessions.fire();
961
+ }
962
+ return;
963
+ }
964
+ const statusDetail = options?.statusDetail;
965
+ if (prev.status === status && prev.statusDetail === statusDetail) {
966
+ if (metadataChanged) {
967
+ this._onDidChangeSessions.fire();
968
+ }
969
+ return;
970
+ }
971
+ const newPhase = getPhaseForStatus(status);
972
+ this._sessions[index] = {
973
+ ...prev,
974
+ status: status,
975
+ phase: newPhase,
976
+ phaseSince: this.resolvePhaseSince(sessionId, prev.phase, prev.phaseSince, newPhase),
977
+ statusDetail: statusDetail,
978
+ pendingPermission: status === 'permission_requested' ? bk.pendingPermission : undefined,
979
+ lastActivity: new Date(),
980
+ };
981
+ this._onDidChangeSessions.fire();
982
+ if (status === 'thinking' || status === 'tool_use' || status === 'compacting') {
983
+ const sessionCwd = this._sessions[index].cwd;
984
+ if (sessionCwd != null) {
985
+ this.callbacks.onBranchAgentActivity?.(sessionCwd);
986
+ }
987
+ }
988
+ // On a fresh transition into idle, recheck transcript titles — Claude typically (re-)writes
989
+ // `ai-title` right after finishing a response, so this is the prime moment to pick it up.
990
+ // Tail-read caching makes repeated checks cheap.
991
+ if (status === 'idle' && prev.status !== 'idle') {
992
+ void this.resolveTranscriptTitles(sessionId, this._sessions[index].cwd);
993
+ }
994
+ }
995
+ ensureSession(sessionId, context) {
996
+ const { pid, workspacePath, isInWorkspace, cwd, planFile, sessionName } = context ?? {};
997
+ let index = this._sessions.findIndex(s => s.id === sessionId);
998
+ if (index < 0) {
999
+ const now = new Date();
1000
+ index = this._sessions.length;
1001
+ this._sessions.push({
1002
+ id: sessionId,
1003
+ providerId: this.id,
1004
+ providerName: this.name,
1005
+ name: sessionName || undefined,
1006
+ status: 'idle',
1007
+ phase: getPhaseForStatus('idle'),
1008
+ phaseSince: now,
1009
+ pid: pid,
1010
+ lastActivity: now,
1011
+ isSubagent: false,
1012
+ workspacePath: workspacePath,
1013
+ cwd: cwd,
1014
+ planFile: planFile,
1015
+ isInWorkspace: isInWorkspace ?? false,
1016
+ });
1017
+ Logger.debug(`ClaudeCodeProvider.ensureSession: implicitly created ${this.sessionTag(sessionId, sessionName ?? 'unnamed')}`);
1018
+ this._onDidChangeSessions.fire();
1019
+ if (cwd != null) {
1020
+ void this.resolveGitInfo(sessionId, cwd);
1021
+ }
1022
+ void this.resolveTranscriptTitles(sessionId, cwd);
1023
+ return { index: index, changed: true };
1024
+ }
1025
+ const existing = this._sessions[index];
1026
+ const updatedPid = pid != null && existing.pid == null ? pid : existing.pid;
1027
+ const updatedWorkspacePath = workspacePath || existing.workspacePath;
1028
+ const updatedIsInWorkspace = workspacePath ? (isInWorkspace ?? existing.isInWorkspace) : existing.isInWorkspace;
1029
+ const updatedPlanFile = planFile ?? existing.planFile;
1030
+ const updatedName = sessionName || existing.name;
1031
+ const updatedCwd = cwd ?? existing.cwd;
1032
+ let changed = false;
1033
+ if (updatedPid !== existing.pid ||
1034
+ updatedWorkspacePath !== existing.workspacePath ||
1035
+ updatedIsInWorkspace !== existing.isInWorkspace ||
1036
+ updatedPlanFile !== existing.planFile ||
1037
+ updatedName !== existing.name ||
1038
+ updatedCwd !== existing.cwd) {
1039
+ this._sessions[index] = {
1040
+ ...existing,
1041
+ name: updatedName,
1042
+ pid: updatedPid,
1043
+ workspacePath: updatedWorkspacePath,
1044
+ cwd: updatedCwd,
1045
+ planFile: updatedPlanFile,
1046
+ isInWorkspace: updatedIsInWorkspace,
1047
+ };
1048
+ changed = true;
1049
+ }
1050
+ // Re-fire `resolveGitInfo` if the session is missing either `worktreePath` or `commonPath`.
1051
+ // Peer-synced sessions arrive with `worktreePath` already set (from the peer that owns the
1052
+ // hook flow) but may lack `commonPath` if the peer was running pre-commonPath code; this
1053
+ // gives us a chance to fill it in locally. Idempotent — `resolveGitInfo` only mutates the
1054
+ // session when one of `cwd`/`worktreePath`/`commonPath` actually changes. The
1055
+ // `gitInfoUnresolvable` bookkeeping flag (see `SessionBookkeeping`) is set once
1056
+ // `resolveGitInfo` confirms the cwd isn't a git repo, preventing a retry storm on every
1057
+ // hook event for non-git-repo cwds. The flag is cleared on cwd change (`CwdChanged`) and
1058
+ // on `resetBookkeeping` (Stop/SessionStart) so re-resolution can happen when warranted.
1059
+ if (cwd != null &&
1060
+ (existing.worktreePath == null || existing.commonPath == null) &&
1061
+ !this.getBookkeeping(sessionId).gitInfoUnresolvable) {
1062
+ void this.resolveGitInfo(sessionId, cwd);
1063
+ }
1064
+ return { index: index, changed: changed };
1065
+ }
1066
+ async resolveGitInfo(sessionId, cwd) {
1067
+ const resolveGitInfo = this.callbacks.resolveGitInfo;
1068
+ if (resolveGitInfo == null)
1069
+ return;
1070
+ // Dedupe concurrent calls for the same session — every hook event (PreToolUse, PostToolUse,
1071
+ // UserPromptSubmit, etc.) flows through `ensureSession`, which retries `resolveGitInfo`
1072
+ // whenever `commonPath`/`worktreePath` is missing. Without this guard a non-git-repo cwd
1073
+ // would spawn a fresh git probe per hook event. The `gitInfoUnresolvable` bookkeeping flag
1074
+ // (set below when `info == null`) is the long-lived suppressor across hook events; this
1075
+ // in-flight set only dedupes concurrent overlapping probes within a single resolution.
1076
+ if (this._resolveGitInfoInFlight.has(sessionId))
1077
+ return;
1078
+ this._resolveGitInfoInFlight.add(sessionId);
1079
+ try {
1080
+ let info;
1081
+ try {
1082
+ info = await resolveGitInfo(cwd);
1083
+ }
1084
+ catch {
1085
+ // Git not available or not a git repo — fall through to mark unresolvable below
1086
+ info = undefined;
1087
+ }
1088
+ const index = this._sessions.findIndex(s => s.id === sessionId);
1089
+ if (index < 0)
1090
+ return;
1091
+ const session = this._sessions[index];
1092
+ // `workspacePath` stays as the matched workspace folder (or undefined). Repo identity
1093
+ // flows through `commonPath`, populated here from `info.repoRoot` at the same step as
1094
+ // `worktreePath` — both available together from `resolveGitInfo`, much earlier than the
1095
+ // follow-on worktree-name refresh (which needs `getWorktrees()` on the parent repo).
1096
+ //
1097
+ // When `info == null` (cwd is not inside any git repo), set the `gitInfoUnresolvable`
1098
+ // bookkeeping flag so subsequent `ensureSession`/peer-sync retry checks skip re-firing.
1099
+ // We deliberately do NOT write a tombstone onto the session DTO — keeping `commonPath`
1100
+ // as `undefined` (a) keeps the wire-shape unambiguous for peers, (b) lets consumers
1101
+ // safely treat undefined as "no repo identity", and (c) means peers can still attempt
1102
+ // their own local resolution. The flag is cleared on cwd change (`CwdChanged`) and on
1103
+ // `resetBookkeeping` so re-resolution happens when warranted (e.g. user runs `git init`
1104
+ // followed by a new session start).
1105
+ if (info == null) {
1106
+ this.getBookkeeping(sessionId).gitInfoUnresolvable = true;
1107
+ if (cwd !== session.cwd) {
1108
+ this._sessions[index] = { ...session, cwd: cwd };
1109
+ this._onDidChangeSessions.fire();
1110
+ }
1111
+ return;
1112
+ }
1113
+ if (cwd !== session.cwd ||
1114
+ info.worktreePath !== session.worktreePath ||
1115
+ info.repoRoot !== session.commonPath) {
1116
+ this._sessions[index] = {
1117
+ ...session,
1118
+ cwd: cwd,
1119
+ worktreePath: info.worktreePath,
1120
+ commonPath: info.repoRoot,
1121
+ };
1122
+ this._onDidChangeSessions.fire();
1123
+ }
1124
+ }
1125
+ finally {
1126
+ this._resolveGitInfoInFlight.delete(sessionId);
1127
+ }
1128
+ }
1129
+ async resolveTranscriptTitles(sessionId, cwd) {
1130
+ let titles;
1131
+ try {
1132
+ titles = await this._transcriptReader.resolve(sessionId, cwd);
1133
+ }
1134
+ catch {
1135
+ return;
1136
+ }
1137
+ if (titles == null)
1138
+ return;
1139
+ const index = this._sessions.findIndex(s => s.id === sessionId);
1140
+ if (index < 0)
1141
+ return;
1142
+ const session = this._sessions[index];
1143
+ const prev = session.transcriptTitles;
1144
+ if (prev?.custom === titles.custom && prev?.ai === titles.ai && prev?.agent === titles.agent)
1145
+ return;
1146
+ this._sessions[index] = {
1147
+ ...session,
1148
+ transcriptTitles: { custom: titles.custom, ai: titles.ai, agent: titles.agent },
1149
+ };
1150
+ this._onDidChangeSessions.fire();
1151
+ }
1152
+ pruneDeadSessions() {
1153
+ const kept = [];
1154
+ const removedIds = [];
1155
+ for (const s of this._sessions) {
1156
+ // A session blocking on us for a permission decision is by definition alive,
1157
+ // even if `kill(pid, 0)` says otherwise (e.g. transient EPERM/ESRCH). Dropping
1158
+ // it here loses pendingPermission and lastPrompt; the next syncSessions then
1159
+ // re-adds it as a stale shell with `permission_requested` status but no detail.
1160
+ if (s.pid == null || isProcessAlive(s.pid) || this._pendingPermissions.has(s.id)) {
1161
+ kept.push(s);
1162
+ }
1163
+ else {
1164
+ removedIds.push(s.id);
1165
+ }
1166
+ }
1167
+ if (removedIds.length === 0)
1168
+ return false;
1169
+ this._sessions = kept;
1170
+ for (const id of removedIds) {
1171
+ const pending = this._pendingPermissions.get(id);
1172
+ if (pending != null) {
1173
+ pending.reject(new Error('Session pruned'));
1174
+ this._pendingPermissions.delete(id);
1175
+ }
1176
+ this.cancelPendingIdleTransition(id);
1177
+ this._sessionBookkeeping.delete(id);
1178
+ this._transcriptReader.forget(id);
1179
+ }
1180
+ Logger.debug(`ClaudeCodeProvider.syncSessions: removed ${removedIds.length} stale session(s): ${removedIds.map(id => id.substring(0, 8)).join(', ')}`);
1181
+ return true;
1182
+ }
1183
+ async syncSessions() {
1184
+ let sessions;
1185
+ try {
1186
+ const output = await this.callbacks.runCLICommand(['ai', 'hook', 'list-sessions', '--json']);
1187
+ sessions = JSON.parse(output);
1188
+ }
1189
+ catch {
1190
+ if (this.pruneDeadSessions()) {
1191
+ this._onDidChangeSessions.fire();
1192
+ }
1193
+ return;
1194
+ }
1195
+ let changed = false;
1196
+ for (const data of sessions) {
1197
+ if (!data.sessionId || !data.pid || !isProcessAlive(data.pid)) {
1198
+ continue;
1199
+ }
1200
+ if (this._sessions.some(s => s.id === data.sessionId))
1201
+ continue;
1202
+ const workspacePath = this.resolveWorkspacePath(data.cwd);
1203
+ const isInWorkspace = workspacePath != null;
1204
+ const status = deriveStatusFromEvent(data.event);
1205
+ const phase = getPhaseForStatus(status);
1206
+ const activityDate = new Date(data.updatedAt);
1207
+ const subagents = data.subagents?.map(sub => ({
1208
+ id: sub.agentId,
1209
+ providerId: this.id,
1210
+ providerName: this.name,
1211
+ name: sub.agentType ?? 'Subagent',
1212
+ status: 'thinking',
1213
+ phase: 'working',
1214
+ phaseSince: activityDate,
1215
+ lastActivity: activityDate,
1216
+ isSubagent: true,
1217
+ parentId: data.sessionId,
1218
+ isInWorkspace: isInWorkspace,
1219
+ }));
1220
+ this._sessions.push({
1221
+ id: data.sessionId,
1222
+ providerId: this.id,
1223
+ providerName: this.name,
1224
+ name: data.sessionName || undefined,
1225
+ status: status,
1226
+ phase: phase,
1227
+ phaseSince: activityDate,
1228
+ pid: data.pid,
1229
+ lastActivity: activityDate,
1230
+ isSubagent: false,
1231
+ workspacePath: workspacePath,
1232
+ cwd: data.cwd,
1233
+ planFile: data.planFile ?? undefined,
1234
+ isInWorkspace: isInWorkspace,
1235
+ lastPrompt: prepareStoredPrompt(data.prompt ?? undefined),
1236
+ firstPrompt: prepareStoredPrompt(data.firstPrompt ?? undefined),
1237
+ subagents: subagents,
1238
+ });
1239
+ changed = true;
1240
+ if (data.cwd) {
1241
+ void this.resolveGitInfo(data.sessionId, data.cwd);
1242
+ }
1243
+ void this.resolveTranscriptTitles(data.sessionId, data.cwd);
1244
+ }
1245
+ if (this.pruneDeadSessions()) {
1246
+ changed = true;
1247
+ }
1248
+ if (changed) {
1249
+ this._onDidChangeSessions.fire();
1250
+ }
1251
+ }
1252
+ async querySiblingWindowSessions() {
1253
+ const discoveryDir = this.callbacks.ipc.agentDiscoveryDir;
1254
+ if (discoveryDir == null)
1255
+ return;
1256
+ let files;
1257
+ try {
1258
+ files = await readdir(discoveryDir);
1259
+ }
1260
+ catch {
1261
+ return;
1262
+ }
1263
+ const ownPort = this.callbacks.ipc.port;
1264
+ const peerBatches = await Promise.all(files
1265
+ .filter(f => f.startsWith('gitlens-ipc-server-') && f.endsWith('.json'))
1266
+ .map(async (f) => this.fetchPeerSessions(join(discoveryDir, f), ownPort)));
1267
+ let changed = false;
1268
+ // Peer sessions that arrived with `cwd` but no `commonPath` (peer was running pre-
1269
+ // commonPath code, OR the peer's own `resolveGitInfo` failed and we get to retry locally).
1270
+ // Resolved after the merge loop so the local Repository registry is consulted only once
1271
+ // per unique session, off the hot merge path. Keyed by id (value = cwd) so the same
1272
+ // session appearing in multiple peer responses (or re-queued within this loop) only
1273
+ // triggers a single backfill probe.
1274
+ const sessionsNeedingResolve = new Map();
1275
+ for (const peerSessions of peerBatches) {
1276
+ if (peerSessions == null)
1277
+ continue;
1278
+ for (const peerSession of peerSessions) {
1279
+ const peerActivity = new Date(peerSession.lastActivity);
1280
+ const peerPhaseSince = new Date(peerSession.phaseSince);
1281
+ const existing = this._sessions.find(s => s.id === peerSession.id);
1282
+ if (existing != null) {
1283
+ // If the peer reports a different `cwd` than we last saw, the agent moved
1284
+ // (peer fired a `CwdChanged` event we don't receive locally). Pick up the new
1285
+ // cwd AND reset our local `gitInfoUnresolvable` flag — the new cwd might be a
1286
+ // git repo even if the previous one wasn't.
1287
+ const cwdChanged = peerSession.cwd != null && existing.cwd !== peerSession.cwd;
1288
+ if (cwdChanged && this._sessionBookkeeping.get(peerSession.id)?.gitInfoUnresolvable) {
1289
+ this.getBookkeeping(peerSession.id).gitInfoUnresolvable = false;
1290
+ }
1291
+ if (peerActivity > existing.lastActivity) {
1292
+ const idx = this._sessions.indexOf(existing);
1293
+ // Peer is the authoritative hook recipient for this session, so wipe any
1294
+ // local bookkeeping that survived from a previous local-ownership window.
1295
+ // Without this, refcounts/timers from a prior local-hosting stretch would
1296
+ // resurface stale paths if ownership ever flips back to us.
1297
+ const bk = this._sessionBookkeeping.get(peerSession.id);
1298
+ if (bk != null) {
1299
+ this.cancelPendingFileClears(bk);
1300
+ this.cancelPendingReadClears(bk);
1301
+ bk.currentFileCounts.clear();
1302
+ bk.currentReadCounts.clear();
1303
+ }
1304
+ this._sessions[idx] = {
1305
+ ...existing,
1306
+ status: peerSession.status,
1307
+ phase: peerSession.phase,
1308
+ phaseSince: peerPhaseSince,
1309
+ statusDetail: peerSession.statusDetail,
1310
+ lastActivity: peerActivity,
1311
+ subagents: rehydrateSubagents(peerSession.subagents),
1312
+ // Carry the peer's in-flight file-edit set + repo identity across so
1313
+ // peer-window WIP decorations + sameFamily anchoring follow the agent.
1314
+ // Owned by the peer (it's the hook recipient); we never originate these
1315
+ // fields for a remote session.
1316
+ currentFiles: peerSession.currentFiles,
1317
+ currentReads: peerSession.currentReads,
1318
+ commonPath: peerSession.commonPath ?? existing.commonPath,
1319
+ // Pick up the peer's latest cwd so our backfill probe (queued below)
1320
+ // targets the right path. Stale-cwd locally would just re-probe the
1321
+ // non-repo dir and hit the gitInfoUnresolvable retry guard again.
1322
+ cwd: cwdChanged ? peerSession.cwd : existing.cwd,
1323
+ // Forward peer-discovered transcript titles. Both windows can resolve them
1324
+ // independently against the same on-disk transcript, but only the peer's
1325
+ // hook flow drives its updates — without this, we'd freeze the snapshot
1326
+ // taken at first discovery.
1327
+ transcriptTitles: peerSession.transcriptTitles ?? existing.transcriptTitles,
1328
+ };
1329
+ changed = true;
1330
+ }
1331
+ }
1332
+ else {
1333
+ this._sessions.push({
1334
+ ...peerSession,
1335
+ lastActivity: peerActivity,
1336
+ phaseSince: peerPhaseSince,
1337
+ workspacePath: normalizeWorkspacePath(peerSession.workspacePath),
1338
+ isInWorkspace: this.matchesWorkspace(peerSession.workspacePath),
1339
+ subagents: rehydrateSubagents(peerSession.subagents),
1340
+ // Override whatever the peer published — this is OUR ownership view: the peer
1341
+ // (or some other window) hosts the live session, not us. Drives the dispatcher
1342
+ // to route opens through the peer's IPC + OS-level window focus instead of
1343
+ // calling `claude-vscode.editor.open` locally (which would just open an inert
1344
+ // view in our window).
1345
+ isPeerOwned: true,
1346
+ });
1347
+ changed = true;
1348
+ }
1349
+ // Queue a local resolveGitInfo for any peer session that arrived without a
1350
+ // commonPath but has a cwd — we can fill it in from our own git registry. Skip
1351
+ // if our own bookkeeping already marked this session's cwd unresolvable (we tried
1352
+ // locally and the cwd isn't a git repo from our vantage point either).
1353
+ const merged = this._sessions.find(s => s.id === peerSession.id);
1354
+ if (merged?.commonPath == null &&
1355
+ merged?.cwd != null &&
1356
+ !this.getBookkeeping(merged.id).gitInfoUnresolvable) {
1357
+ sessionsNeedingResolve.set(merged.id, merged.cwd);
1358
+ }
1359
+ }
1360
+ }
1361
+ if (changed) {
1362
+ this._onDidChangeSessions.fire();
1363
+ }
1364
+ // Backfill commonPath for peer-synced sessions whose owning peer didn't populate it.
1365
+ // `resolveGitInfo` is idempotent — only mutates + fires if it actually finds new info,
1366
+ // so the worst case here is a few wasted git probes for unresolvable cwds.
1367
+ for (const [id, cwd] of sessionsNeedingResolve) {
1368
+ void this.resolveGitInfo(id, cwd);
1369
+ }
1370
+ }
1371
+ async fetchPeerSessions(path, ownPort) {
1372
+ let discovery;
1373
+ try {
1374
+ discovery = JSON.parse(await readFile(path, 'utf8'));
1375
+ }
1376
+ catch {
1377
+ return undefined;
1378
+ }
1379
+ if (ownPort != null && discovery.port === ownPort)
1380
+ return undefined;
1381
+ try {
1382
+ const response = await fetch(`${discovery.address}/agents/sessions/list`, {
1383
+ method: 'POST',
1384
+ headers: { Authorization: `Bearer ${discovery.token}`, 'Content-Type': 'application/json' },
1385
+ body: '{}',
1386
+ signal: AbortSignal.timeout(2000),
1387
+ });
1388
+ if (!response.ok)
1389
+ return undefined;
1390
+ return (await response.json());
1391
+ }
1392
+ catch {
1393
+ return undefined;
1394
+ }
1395
+ }
1396
+ /** Find the peer GitLens window whose discovery file claims `workspacePath`, and POST to its
1397
+ * `/agents/sessions/open` route to ask its Claude Code extension to open the session.
1398
+ *
1399
+ * Resolves to `true` when at least one peer claimed the workspace AND was reachable (the POST
1400
+ * completed with any HTTP status). The peer's response shape (`{ opened: boolean }`) is logged
1401
+ * for diagnostics but does NOT affect the return value — an `opened: false` peer is still the
1402
+ * right window for the caller to focus, since it's the window that owns the session. Resolves
1403
+ * to `false` when no peer claimed the workspace OR every claimer was unreachable; the caller
1404
+ * treats that as "no peer to focus" and opens a new window instead of replacing the current
1405
+ * one. Best-effort: swallows scan, JSON-parse errors. */
1406
+ async notifyPeerOpenSession(workspacePath, sessionId) {
1407
+ const discoveryDir = this.callbacks.ipc.agentDiscoveryDir;
1408
+ if (discoveryDir == null)
1409
+ return false;
1410
+ const target = normalizePath(workspacePath);
1411
+ const ownPort = this.callbacks.ipc.port;
1412
+ let files;
1413
+ try {
1414
+ files = await readdir(discoveryDir);
1415
+ }
1416
+ catch {
1417
+ return false;
1418
+ }
1419
+ const results = await Promise.all(files
1420
+ .filter(f => f.startsWith('gitlens-ipc-server-') && f.endsWith('.json'))
1421
+ .map(async (f) => {
1422
+ let discovery;
1423
+ try {
1424
+ discovery = JSON.parse(await readFile(join(discoveryDir, f), 'utf8'));
1425
+ }
1426
+ catch {
1427
+ return false;
1428
+ }
1429
+ if (ownPort != null && discovery.port === ownPort)
1430
+ return false;
1431
+ // Symmetric prefix containment — same shape as `matchesWorkspace()` above.
1432
+ // Strict equality misses the common case where the dispatcher passes a `cwd`
1433
+ // inside the peer's workspace folder (or, less commonly, a parent dir that
1434
+ // contains the peer's workspace).
1435
+ if (!discovery.workspacePaths?.some(p => {
1436
+ const normalized = normalizePath(p);
1437
+ return (normalized === target ||
1438
+ target.startsWith(`${normalized}/`) ||
1439
+ normalized.startsWith(`${target}/`));
1440
+ })) {
1441
+ return false;
1442
+ }
1443
+ try {
1444
+ const response = await fetch(`${discovery.address}/agents/sessions/open`, {
1445
+ method: 'POST',
1446
+ headers: {
1447
+ Authorization: `Bearer ${discovery.token}`,
1448
+ 'Content-Type': 'application/json',
1449
+ },
1450
+ body: JSON.stringify({ sessionId: sessionId }),
1451
+ signal: AbortSignal.timeout(2000),
1452
+ });
1453
+ if (!response.ok) {
1454
+ Logger.warn(`ClaudeCodeProvider.notifyPeerOpenSession: peer at ${discovery.address} returned ${response.status}`);
1455
+ }
1456
+ else {
1457
+ // Log a peer that failed to open the specific session, but still treat it
1458
+ // as a reachable claimer of the workspace — focusing that window is still
1459
+ // what the user wants.
1460
+ const body = (await response.json().catch(() => undefined));
1461
+ if (body?.opened === false) {
1462
+ Logger.warn(`ClaudeCodeProvider.notifyPeerOpenSession: peer at ${discovery.address} could not open session ${sessionId}`);
1463
+ }
1464
+ }
1465
+ return true;
1466
+ }
1467
+ catch (ex) {
1468
+ // Peer advertised but unreachable (timeout, RST, etc.). Treat as no match so
1469
+ // the caller opens a new window instead of trying to focus a dead window.
1470
+ Logger.warn(`ClaudeCodeProvider.notifyPeerOpenSession: peer at ${discovery.address} unreachable: ${ex instanceof Error ? ex.message : String(ex)}`);
1471
+ return false;
1472
+ }
1473
+ }));
1474
+ return results.some(Boolean);
1475
+ }
1476
+ }
1477
+ __decorate([
1478
+ gate()
1479
+ ], ClaudeCodeProvider.prototype, "ensureIpcServer", null);
1480
+ //# sourceMappingURL=claudeCodeProvider.js.map