@kenkaiiii/gg-engine 0.0.0-stage → 7.0.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 (850) hide show
  1. package/LICENSE +661 -0
  2. package/NOTICE +43 -0
  3. package/README.md +53 -2
  4. package/assets/skills/bulletproof/SKILL.md +132 -0
  5. package/assets/skills/bulletproof/references/agent-surface.md +113 -0
  6. package/assets/skills/bulletproof/references/attack-classes.md +226 -0
  7. package/assets/skills/bulletproof/references/audit-protocol.md +232 -0
  8. package/assets/skills/bulletproof/references/platform-playbooks.md +196 -0
  9. package/assets/skills/bulletproof/references/provenance.md +146 -0
  10. package/assets/skills/bulletproof/references/secure-defaults.md +137 -0
  11. package/assets/skills/bulletproof/references/supply-chain.md +84 -0
  12. package/assets/skills/bulletproof/references/threat-landscape.md +66 -0
  13. package/assets/skills/bulletproof/references/verification.md +74 -0
  14. package/assets/skills/compliance-guard/SKILL.md +115 -0
  15. package/assets/skills/compliance-guard/references/artifacts.md +199 -0
  16. package/assets/skills/compliance-guard/references/eu-uk.md +162 -0
  17. package/assets/skills/compliance-guard/references/exposure-triage.md +177 -0
  18. package/assets/skills/compliance-guard/references/full-review.md +155 -0
  19. package/assets/skills/compliance-guard/references/lawsuit-vectors.md +153 -0
  20. package/assets/skills/compliance-guard/references/provenance.md +135 -0
  21. package/assets/skills/compliance-guard/references/sector-gates.md +187 -0
  22. package/assets/skills/compliance-guard/references/security-baseline.md +117 -0
  23. package/assets/skills/compliance-guard/references/trigger-map.md +177 -0
  24. package/assets/skills/compliance-guard/references/us.md +194 -0
  25. package/assets/skills/durable/SKILL.md +114 -0
  26. package/assets/skills/durable/references/agent-db-safety.md +76 -0
  27. package/assets/skills/durable/references/backups-and-runtime.md +93 -0
  28. package/assets/skills/durable/references/migrations-and-schema.md +87 -0
  29. package/assets/skills/gg-guide/SKILL.md +43 -0
  30. package/assets/skills/gg-guide/references/chat-motion-goals.md +217 -0
  31. package/assets/skills/gg-guide/references/checklist-and-safety.md +177 -0
  32. package/assets/skills/gg-guide/references/code-mode.md +269 -0
  33. package/assets/skills/gg-guide/references/getting-started.md +290 -0
  34. package/assets/skills/gg-guide/references/ken-and-autopilot.md +172 -0
  35. package/assets/skills/gg-guide/references/mcp-and-skills.md +204 -0
  36. package/assets/skills/gg-guide/references/models-and-sign-in.md +200 -0
  37. package/assets/skills/gg-guide/references/sessions-and-history.md +213 -0
  38. package/assets/skills/gg-guide/references/settings.md +193 -0
  39. package/assets/skills/gg-guide/references/troubleshooting-and-data.md +186 -0
  40. package/assets/skills/lean/SKILL.md +117 -0
  41. package/assets/skills/lean/references/memory-and-processes.md +99 -0
  42. package/assets/skills/lean/references/playbooks.md +134 -0
  43. package/dist/app-error.d.ts +22 -0
  44. package/dist/app-error.js +41 -0
  45. package/dist/app-error.js.map +1 -0
  46. package/dist/config.d.ts +90 -0
  47. package/dist/config.js +240 -0
  48. package/dist/config.js.map +1 -0
  49. package/dist/core/acceptance-checks.d.ts +48 -0
  50. package/dist/core/acceptance-checks.js +151 -0
  51. package/dist/core/acceptance-checks.js.map +1 -0
  52. package/dist/core/action-threats.d.ts +68 -0
  53. package/dist/core/action-threats.js +894 -0
  54. package/dist/core/action-threats.js.map +1 -0
  55. package/dist/core/agent-notifications.d.ts +79 -0
  56. package/dist/core/agent-notifications.js +125 -0
  57. package/dist/core/agent-notifications.js.map +1 -0
  58. package/dist/core/agent-session/helpers.d.ts +26 -0
  59. package/dist/core/agent-session/helpers.js +47 -0
  60. package/dist/core/agent-session/helpers.js.map +1 -0
  61. package/dist/core/agent-session/mcp-tools.d.ts +87 -0
  62. package/dist/core/agent-session/mcp-tools.js +227 -0
  63. package/dist/core/agent-session/mcp-tools.js.map +1 -0
  64. package/dist/core/agent-session/run-loop-monitor.d.ts +63 -0
  65. package/dist/core/agent-session/run-loop-monitor.js +164 -0
  66. package/dist/core/agent-session/run-loop-monitor.js.map +1 -0
  67. package/dist/core/agent-session/transcript-markers.d.ts +57 -0
  68. package/dist/core/agent-session/transcript-markers.js +166 -0
  69. package/dist/core/agent-session/transcript-markers.js.map +1 -0
  70. package/dist/core/agent-session/verification-tracker.d.ts +71 -0
  71. package/dist/core/agent-session/verification-tracker.js +295 -0
  72. package/dist/core/agent-session/verification-tracker.js.map +1 -0
  73. package/dist/core/agent-session.d.ts +1401 -0
  74. package/dist/core/agent-session.js +5160 -0
  75. package/dist/core/agent-session.js.map +1 -0
  76. package/dist/core/agents.d.ts +63 -0
  77. package/dist/core/agents.js +160 -0
  78. package/dist/core/agents.js.map +1 -0
  79. package/dist/core/ask-user.d.ts +163 -0
  80. package/dist/core/ask-user.js +178 -0
  81. package/dist/core/ask-user.js.map +1 -0
  82. package/dist/core/auto-update.d.ts +32 -0
  83. package/dist/core/auto-update.js +218 -0
  84. package/dist/core/auto-update.js.map +1 -0
  85. package/dist/core/autopilot-cycle.d.ts +127 -0
  86. package/dist/core/autopilot-cycle.js +182 -0
  87. package/dist/core/autopilot-cycle.js.map +1 -0
  88. package/dist/core/autopilot-gate.d.ts +106 -0
  89. package/dist/core/autopilot-gate.js +192 -0
  90. package/dist/core/autopilot-gate.js.map +1 -0
  91. package/dist/core/autopilot-verdict.d.ts +55 -0
  92. package/dist/core/autopilot-verdict.js +226 -0
  93. package/dist/core/autopilot-verdict.js.map +1 -0
  94. package/dist/core/blocked-packages-file.d.ts +33 -0
  95. package/dist/core/blocked-packages-file.js +274 -0
  96. package/dist/core/blocked-packages-file.js.map +1 -0
  97. package/dist/core/bundled-agents.d.ts +2 -0
  98. package/dist/core/bundled-agents.js +253 -0
  99. package/dist/core/bundled-agents.js.map +1 -0
  100. package/dist/core/cache-diagnostics.d.ts +72 -0
  101. package/dist/core/cache-diagnostics.js +200 -0
  102. package/dist/core/cache-diagnostics.js.map +1 -0
  103. package/dist/core/cache-expiry.d.ts +89 -0
  104. package/dist/core/cache-expiry.js +117 -0
  105. package/dist/core/cache-expiry.js.map +1 -0
  106. package/dist/core/checklist-detection.d.ts +8 -0
  107. package/dist/core/checklist-detection.js +238 -0
  108. package/dist/core/checklist-detection.js.map +1 -0
  109. package/dist/core/checklist-git.d.ts +19 -0
  110. package/dist/core/checklist-git.js +54 -0
  111. package/dist/core/checklist-git.js.map +1 -0
  112. package/dist/core/checklist-items.d.ts +182 -0
  113. package/dist/core/checklist-items.js +228 -0
  114. package/dist/core/checklist-items.js.map +1 -0
  115. package/dist/core/checklist-prompt.d.ts +14 -0
  116. package/dist/core/checklist-prompt.js +64 -0
  117. package/dist/core/checklist-prompt.js.map +1 -0
  118. package/dist/core/checklist-snapshot.d.ts +7 -0
  119. package/dist/core/checklist-snapshot.js +46 -0
  120. package/dist/core/checklist-snapshot.js.map +1 -0
  121. package/dist/core/checklist-store.d.ts +45 -0
  122. package/dist/core/checklist-store.js +278 -0
  123. package/dist/core/checklist-store.js.map +1 -0
  124. package/dist/core/checkout-record.d.ts +22 -0
  125. package/dist/core/checkout-record.js +68 -0
  126. package/dist/core/checkout-record.js.map +1 -0
  127. package/dist/core/checkpoint-store.d.ts +109 -0
  128. package/dist/core/checkpoint-store.js +260 -0
  129. package/dist/core/checkpoint-store.js.map +1 -0
  130. package/dist/core/claude-code/complete.d.ts +35 -0
  131. package/dist/core/claude-code/complete.js +125 -0
  132. package/dist/core/claude-code/complete.js.map +1 -0
  133. package/dist/core/claude-code/events.d.ts +67 -0
  134. package/dist/core/claude-code/events.js +460 -0
  135. package/dist/core/claude-code/events.js.map +1 -0
  136. package/dist/core/claude-code/live-session.d.ts +94 -0
  137. package/dist/core/claude-code/live-session.js +525 -0
  138. package/dist/core/claude-code/live-session.js.map +1 -0
  139. package/dist/core/claude-code/loop.d.ts +9 -0
  140. package/dist/core/claude-code/loop.js +15 -0
  141. package/dist/core/claude-code/loop.js.map +1 -0
  142. package/dist/core/claude-code/session-sync.d.ts +28 -0
  143. package/dist/core/claude-code/session-sync.js +53 -0
  144. package/dist/core/claude-code/session-sync.js.map +1 -0
  145. package/dist/core/claude-code/tool-bridge.d.ts +49 -0
  146. package/dist/core/claude-code/tool-bridge.js +352 -0
  147. package/dist/core/claude-code/tool-bridge.js.map +1 -0
  148. package/dist/core/claude-code/transcripts.d.ts +39 -0
  149. package/dist/core/claude-code/transcripts.js +195 -0
  150. package/dist/core/claude-code/transcripts.js.map +1 -0
  151. package/dist/core/code-retrieval-chunkers.d.ts +26 -0
  152. package/dist/core/code-retrieval-chunkers.js +264 -0
  153. package/dist/core/code-retrieval-chunkers.js.map +1 -0
  154. package/dist/core/code-retrieval.d.ts +18 -0
  155. package/dist/core/code-retrieval.js +124 -0
  156. package/dist/core/code-retrieval.js.map +1 -0
  157. package/dist/core/codex-request-shape.d.ts +7 -0
  158. package/dist/core/codex-request-shape.js +19 -0
  159. package/dist/core/codex-request-shape.js.map +1 -0
  160. package/dist/core/compaction/active-context.d.ts +16 -0
  161. package/dist/core/compaction/active-context.js +20 -0
  162. package/dist/core/compaction/active-context.js.map +1 -0
  163. package/dist/core/compaction/compactor.d.ts +281 -0
  164. package/dist/core/compaction/compactor.js +1451 -0
  165. package/dist/core/compaction/compactor.js.map +1 -0
  166. package/dist/core/compaction/plan-step-policy.d.ts +46 -0
  167. package/dist/core/compaction/plan-step-policy.js +57 -0
  168. package/dist/core/compaction/plan-step-policy.js.map +1 -0
  169. package/dist/core/compaction/policy.d.ts +36 -0
  170. package/dist/core/compaction/policy.js +144 -0
  171. package/dist/core/compaction/policy.js.map +1 -0
  172. package/dist/core/compaction/query-aware-selector.d.ts +32 -0
  173. package/dist/core/compaction/query-aware-selector.js +202 -0
  174. package/dist/core/compaction/query-aware-selector.js.map +1 -0
  175. package/dist/core/compaction/token-estimator.d.ts +36 -0
  176. package/dist/core/compaction/token-estimator.js +180 -0
  177. package/dist/core/compaction/token-estimator.js.map +1 -0
  178. package/dist/core/compaction/tool-result-pruner.d.ts +90 -0
  179. package/dist/core/compaction/tool-result-pruner.js +238 -0
  180. package/dist/core/compaction/tool-result-pruner.js.map +1 -0
  181. package/dist/core/completion-review.d.ts +24 -0
  182. package/dist/core/completion-review.js +2 -0
  183. package/dist/core/completion-review.js.map +1 -0
  184. package/dist/core/context-files.d.ts +8 -0
  185. package/dist/core/context-files.js +46 -0
  186. package/dist/core/context-files.js.map +1 -0
  187. package/dist/core/context-limits.d.ts +40 -0
  188. package/dist/core/context-limits.js +43 -0
  189. package/dist/core/context-limits.js.map +1 -0
  190. package/dist/core/custom-commands.d.ts +18 -0
  191. package/dist/core/custom-commands.js +57 -0
  192. package/dist/core/custom-commands.js.map +1 -0
  193. package/dist/core/destructive-git-guard.d.ts +113 -0
  194. package/dist/core/destructive-git-guard.js +874 -0
  195. package/dist/core/destructive-git-guard.js.map +1 -0
  196. package/dist/core/display-items.d.ts +8 -0
  197. package/dist/core/display-items.js +2 -0
  198. package/dist/core/display-items.js.map +1 -0
  199. package/dist/core/encode-cwd.d.ts +41 -0
  200. package/dist/core/encode-cwd.js +53 -0
  201. package/dist/core/encode-cwd.js.map +1 -0
  202. package/dist/core/env-delta.d.ts +34 -0
  203. package/dist/core/env-delta.js +84 -0
  204. package/dist/core/env-delta.js.map +1 -0
  205. package/dist/core/event-bus.d.ts +178 -0
  206. package/dist/core/event-bus.js +171 -0
  207. package/dist/core/event-bus.js.map +1 -0
  208. package/dist/core/extensions/loader.d.ts +7 -0
  209. package/dist/core/extensions/loader.js +68 -0
  210. package/dist/core/extensions/loader.js.map +1 -0
  211. package/dist/core/extensions/plugin-bundles.d.ts +13 -0
  212. package/dist/core/extensions/plugin-bundles.js +45 -0
  213. package/dist/core/extensions/plugin-bundles.js.map +1 -0
  214. package/dist/core/extensions/types.d.ts +18 -0
  215. package/dist/core/extensions/types.js +2 -0
  216. package/dist/core/extensions/types.js.map +1 -0
  217. package/dist/core/foreign-session-import.d.ts +119 -0
  218. package/dist/core/foreign-session-import.js +598 -0
  219. package/dist/core/foreign-session-import.js.map +1 -0
  220. package/dist/core/foreign-transcript-blocks.d.ts +50 -0
  221. package/dist/core/foreign-transcript-blocks.js +151 -0
  222. package/dist/core/foreign-transcript-blocks.js.map +1 -0
  223. package/dist/core/frontmatter.d.ts +22 -0
  224. package/dist/core/frontmatter.js +90 -0
  225. package/dist/core/frontmatter.js.map +1 -0
  226. package/dist/core/goal-run-marker.d.ts +32 -0
  227. package/dist/core/goal-run-marker.js +178 -0
  228. package/dist/core/goal-run-marker.js.map +1 -0
  229. package/dist/core/goal-summary.d.ts +15 -0
  230. package/dist/core/goal-summary.js +110 -0
  231. package/dist/core/goal-summary.js.map +1 -0
  232. package/dist/core/goals-store.d.ts +208 -0
  233. package/dist/core/goals-store.js +577 -0
  234. package/dist/core/goals-store.js.map +1 -0
  235. package/dist/core/hashline.d.ts +51 -0
  236. package/dist/core/hashline.js +76 -0
  237. package/dist/core/hashline.js.map +1 -0
  238. package/dist/core/idle-wake.d.ts +62 -0
  239. package/dist/core/idle-wake.js +103 -0
  240. package/dist/core/idle-wake.js.map +1 -0
  241. package/dist/core/index.d.ts +15 -0
  242. package/dist/core/index.js +15 -0
  243. package/dist/core/index.js.map +1 -0
  244. package/dist/core/injection-detect.d.ts +39 -0
  245. package/dist/core/injection-detect.js +241 -0
  246. package/dist/core/injection-detect.js.map +1 -0
  247. package/dist/core/installed-threats.d.ts +23 -0
  248. package/dist/core/installed-threats.js +71 -0
  249. package/dist/core/installed-threats.js.map +1 -0
  250. package/dist/core/internal-diagnostics.d.ts +159 -0
  251. package/dist/core/internal-diagnostics.js +495 -0
  252. package/dist/core/internal-diagnostics.js.map +1 -0
  253. package/dist/core/keep-awake.d.ts +88 -0
  254. package/dist/core/keep-awake.js +251 -0
  255. package/dist/core/keep-awake.js.map +1 -0
  256. package/dist/core/ken-ask-answer.d.ts +24 -0
  257. package/dist/core/ken-ask-answer.js +96 -0
  258. package/dist/core/ken-ask-answer.js.map +1 -0
  259. package/dist/core/ken-context.d.ts +119 -0
  260. package/dist/core/ken-context.js +447 -0
  261. package/dist/core/ken-context.js.map +1 -0
  262. package/dist/core/ken-model.d.ts +45 -0
  263. package/dist/core/ken-model.js +26 -0
  264. package/dist/core/ken-model.js.map +1 -0
  265. package/dist/core/ken-prompt.d.ts +21 -0
  266. package/dist/core/ken-prompt.js +370 -0
  267. package/dist/core/ken-prompt.js.map +1 -0
  268. package/dist/core/language-detector.d.ts +41 -0
  269. package/dist/core/language-detector.js +293 -0
  270. package/dist/core/language-detector.js.map +1 -0
  271. package/dist/core/live-preview.d.ts +26 -0
  272. package/dist/core/live-preview.js +80 -0
  273. package/dist/core/live-preview.js.map +1 -0
  274. package/dist/core/local-endpoint-store.d.ts +53 -0
  275. package/dist/core/local-endpoint-store.js +221 -0
  276. package/dist/core/local-endpoint-store.js.map +1 -0
  277. package/dist/core/logger.d.ts +21 -0
  278. package/dist/core/logger.js +94 -0
  279. package/dist/core/logger.js.map +1 -0
  280. package/dist/core/loop-breaker.d.ts +89 -0
  281. package/dist/core/loop-breaker.js +204 -0
  282. package/dist/core/loop-breaker.js.map +1 -0
  283. package/dist/core/lsp/client.d.ts +206 -0
  284. package/dist/core/lsp/client.js +685 -0
  285. package/dist/core/lsp/client.js.map +1 -0
  286. package/dist/core/lsp/edit-telemetry.d.ts +26 -0
  287. package/dist/core/lsp/edit-telemetry.js +52 -0
  288. package/dist/core/lsp/edit-telemetry.js.map +1 -0
  289. package/dist/core/lsp/format.d.ts +11 -0
  290. package/dist/core/lsp/format.js +30 -0
  291. package/dist/core/lsp/format.js.map +1 -0
  292. package/dist/core/lsp/jsonrpc.d.ts +68 -0
  293. package/dist/core/lsp/jsonrpc.js +153 -0
  294. package/dist/core/lsp/jsonrpc.js.map +1 -0
  295. package/dist/core/lsp/manager.d.ts +188 -0
  296. package/dist/core/lsp/manager.js +576 -0
  297. package/dist/core/lsp/manager.js.map +1 -0
  298. package/dist/core/lsp/pool.d.ts +114 -0
  299. package/dist/core/lsp/pool.js +259 -0
  300. package/dist/core/lsp/pool.js.map +1 -0
  301. package/dist/core/lsp/project-root.d.ts +9 -0
  302. package/dist/core/lsp/project-root.js +75 -0
  303. package/dist/core/lsp/project-root.js.map +1 -0
  304. package/dist/core/lsp/reference-project.d.ts +6 -0
  305. package/dist/core/lsp/reference-project.js +110 -0
  306. package/dist/core/lsp/reference-project.js.map +1 -0
  307. package/dist/core/lsp/servers.d.ts +44 -0
  308. package/dist/core/lsp/servers.js +289 -0
  309. package/dist/core/lsp/servers.js.map +1 -0
  310. package/dist/core/lsp/test-support.d.ts +17 -0
  311. package/dist/core/lsp/test-support.js +27 -0
  312. package/dist/core/lsp/test-support.js.map +1 -0
  313. package/dist/core/mcp/catalog-cache.d.ts +64 -0
  314. package/dist/core/mcp/catalog-cache.js +166 -0
  315. package/dist/core/mcp/catalog-cache.js.map +1 -0
  316. package/dist/core/mcp/client.d.ts +317 -0
  317. package/dist/core/mcp/client.js +1168 -0
  318. package/dist/core/mcp/client.js.map +1 -0
  319. package/dist/core/mcp/content.d.ts +23 -0
  320. package/dist/core/mcp/content.js +194 -0
  321. package/dist/core/mcp/content.js.map +1 -0
  322. package/dist/core/mcp/defaults.d.ts +26 -0
  323. package/dist/core/mcp/defaults.js +81 -0
  324. package/dist/core/mcp/defaults.js.map +1 -0
  325. package/dist/core/mcp/deferred-catalog.d.ts +53 -0
  326. package/dist/core/mcp/deferred-catalog.js +117 -0
  327. package/dist/core/mcp/deferred-catalog.js.map +1 -0
  328. package/dist/core/mcp/elicitation-bridge.d.ts +40 -0
  329. package/dist/core/mcp/elicitation-bridge.js +36 -0
  330. package/dist/core/mcp/elicitation-bridge.js.map +1 -0
  331. package/dist/core/mcp/index.d.ts +16 -0
  332. package/dist/core/mcp/index.js +10 -0
  333. package/dist/core/mcp/index.js.map +1 -0
  334. package/dist/core/mcp/loopback.d.ts +26 -0
  335. package/dist/core/mcp/loopback.js +66 -0
  336. package/dist/core/mcp/loopback.js.map +1 -0
  337. package/dist/core/mcp/oauth-provider.d.ts +55 -0
  338. package/dist/core/mcp/oauth-provider.js +106 -0
  339. package/dist/core/mcp/oauth-provider.js.map +1 -0
  340. package/dist/core/mcp/oauth-store.d.ts +44 -0
  341. package/dist/core/mcp/oauth-store.js +76 -0
  342. package/dist/core/mcp/oauth-store.js.map +1 -0
  343. package/dist/core/mcp/parse-add-command.d.ts +50 -0
  344. package/dist/core/mcp/parse-add-command.js +391 -0
  345. package/dist/core/mcp/parse-add-command.js.map +1 -0
  346. package/dist/core/mcp/resolve-stdio.d.ts +77 -0
  347. package/dist/core/mcp/resolve-stdio.js +359 -0
  348. package/dist/core/mcp/resolve-stdio.js.map +1 -0
  349. package/dist/core/mcp/shared-pool.d.ts +157 -0
  350. package/dist/core/mcp/shared-pool.js +236 -0
  351. package/dist/core/mcp/shared-pool.js.map +1 -0
  352. package/dist/core/mcp/store.d.ts +100 -0
  353. package/dist/core/mcp/store.js +202 -0
  354. package/dist/core/mcp/store.js.map +1 -0
  355. package/dist/core/mcp/tool-guard.d.ts +58 -0
  356. package/dist/core/mcp/tool-guard.js +215 -0
  357. package/dist/core/mcp/tool-guard.js.map +1 -0
  358. package/dist/core/mcp/types.d.ts +57 -0
  359. package/dist/core/mcp/types.js +2 -0
  360. package/dist/core/mcp/types.js.map +1 -0
  361. package/dist/core/message-images.d.ts +11 -0
  362. package/dist/core/message-images.js +52 -0
  363. package/dist/core/message-images.js.map +1 -0
  364. package/dist/core/model-unavailable.d.ts +14 -0
  365. package/dist/core/model-unavailable.js +23 -0
  366. package/dist/core/model-unavailable.js.map +1 -0
  367. package/dist/core/network-guard.d.ts +28 -0
  368. package/dist/core/network-guard.js +251 -0
  369. package/dist/core/network-guard.js.map +1 -0
  370. package/dist/core/node-debugger.d.ts +148 -0
  371. package/dist/core/node-debugger.js +642 -0
  372. package/dist/core/node-debugger.js.map +1 -0
  373. package/dist/core/opencode-catalog-store.d.ts +20 -0
  374. package/dist/core/opencode-catalog-store.js +82 -0
  375. package/dist/core/opencode-catalog-store.js.map +1 -0
  376. package/dist/core/openrouter-catalog-store.d.ts +24 -0
  377. package/dist/core/openrouter-catalog-store.js +140 -0
  378. package/dist/core/openrouter-catalog-store.js.map +1 -0
  379. package/dist/core/package-cooldown.d.ts +69 -0
  380. package/dist/core/package-cooldown.js +297 -0
  381. package/dist/core/package-cooldown.js.map +1 -0
  382. package/dist/core/package-threats.d.ts +92 -0
  383. package/dist/core/package-threats.js +1339 -0
  384. package/dist/core/package-threats.js.map +1 -0
  385. package/dist/core/parked-requests.d.ts +43 -0
  386. package/dist/core/parked-requests.js +34 -0
  387. package/dist/core/parked-requests.js.map +1 -0
  388. package/dist/core/persistent-shell.d.ts +81 -0
  389. package/dist/core/persistent-shell.js +452 -0
  390. package/dist/core/persistent-shell.js.map +1 -0
  391. package/dist/core/plan-delta.d.ts +23 -0
  392. package/dist/core/plan-delta.js +36 -0
  393. package/dist/core/plan-delta.js.map +1 -0
  394. package/dist/core/plan-handoff.d.ts +38 -0
  395. package/dist/core/plan-handoff.js +21 -0
  396. package/dist/core/plan-handoff.js.map +1 -0
  397. package/dist/core/plan-submission-gate.d.ts +28 -0
  398. package/dist/core/plan-submission-gate.js +27 -0
  399. package/dist/core/plan-submission-gate.js.map +1 -0
  400. package/dist/core/platform-clis.d.ts +15 -0
  401. package/dist/core/platform-clis.js +299 -0
  402. package/dist/core/platform-clis.js.map +1 -0
  403. package/dist/core/process-gate.d.ts +61 -0
  404. package/dist/core/process-gate.js +103 -0
  405. package/dist/core/process-gate.js.map +1 -0
  406. package/dist/core/process-manager.d.ts +242 -0
  407. package/dist/core/process-manager.js +902 -0
  408. package/dist/core/process-manager.js.map +1 -0
  409. package/dist/core/progress/engine.d.ts +22 -0
  410. package/dist/core/progress/engine.js +131 -0
  411. package/dist/core/progress/engine.js.map +1 -0
  412. package/dist/core/progress/git-xp.d.ts +15 -0
  413. package/dist/core/progress/git-xp.js +100 -0
  414. package/dist/core/progress/git-xp.js.map +1 -0
  415. package/dist/core/progress/ranks.d.ts +31 -0
  416. package/dist/core/progress/ranks.js +310 -0
  417. package/dist/core/progress/ranks.js.map +1 -0
  418. package/dist/core/progress/rebuild.d.ts +8 -0
  419. package/dist/core/progress/rebuild.js +125 -0
  420. package/dist/core/progress/rebuild.js.map +1 -0
  421. package/dist/core/progress/store.d.ts +34 -0
  422. package/dist/core/progress/store.js +200 -0
  423. package/dist/core/progress/store.js.map +1 -0
  424. package/dist/core/progress/types.d.ts +56 -0
  425. package/dist/core/progress/types.js +2 -0
  426. package/dist/core/progress/types.js.map +1 -0
  427. package/dist/core/project-discovery.d.ts +64 -0
  428. package/dist/core/project-discovery.js +908 -0
  429. package/dist/core/project-discovery.js.map +1 -0
  430. package/dist/core/project-files.d.ts +15 -0
  431. package/dist/core/project-files.js +37 -0
  432. package/dist/core/project-files.js.map +1 -0
  433. package/dist/core/project-health-scan.d.ts +109 -0
  434. package/dist/core/project-health-scan.js +673 -0
  435. package/dist/core/project-health-scan.js.map +1 -0
  436. package/dist/core/project-health-score.d.ts +41 -0
  437. package/dist/core/project-health-score.js +257 -0
  438. package/dist/core/project-health-score.js.map +1 -0
  439. package/dist/core/prompt-command-expansion.d.ts +13 -0
  440. package/dist/core/prompt-command-expansion.js +48 -0
  441. package/dist/core/prompt-command-expansion.js.map +1 -0
  442. package/dist/core/prompt-commands.d.ts +13 -0
  443. package/dist/core/prompt-commands.js +370 -0
  444. package/dist/core/prompt-commands.js.map +1 -0
  445. package/dist/core/radio-players.d.ts +28 -0
  446. package/dist/core/radio-players.js +132 -0
  447. package/dist/core/radio-players.js.map +1 -0
  448. package/dist/core/radio.d.ts +42 -0
  449. package/dist/core/radio.js +499 -0
  450. package/dist/core/radio.js.map +1 -0
  451. package/dist/core/regrounding.d.ts +37 -0
  452. package/dist/core/regrounding.js +89 -0
  453. package/dist/core/regrounding.js.map +1 -0
  454. package/dist/core/resolve-start.d.ts +28 -0
  455. package/dist/core/resolve-start.js +35 -0
  456. package/dist/core/resolve-start.js.map +1 -0
  457. package/dist/core/run-claim.d.ts +36 -0
  458. package/dist/core/run-claim.js +46 -0
  459. package/dist/core/run-claim.js.map +1 -0
  460. package/dist/core/run-lifecycle.d.ts +58 -0
  461. package/dist/core/run-lifecycle.js +104 -0
  462. package/dist/core/run-lifecycle.js.map +1 -0
  463. package/dist/core/run-status.d.ts +17 -0
  464. package/dist/core/run-status.js +28 -0
  465. package/dist/core/run-status.js.map +1 -0
  466. package/dist/core/runtime-mode.d.ts +21 -0
  467. package/dist/core/runtime-mode.js +43 -0
  468. package/dist/core/runtime-mode.js.map +1 -0
  469. package/dist/core/sandbox-domains.d.ts +13 -0
  470. package/dist/core/sandbox-domains.js +76 -0
  471. package/dist/core/sandbox-domains.js.map +1 -0
  472. package/dist/core/sandbox-feedback.d.ts +21 -0
  473. package/dist/core/sandbox-feedback.js +69 -0
  474. package/dist/core/sandbox-feedback.js.map +1 -0
  475. package/dist/core/sandbox.d.ts +106 -0
  476. package/dist/core/sandbox.js +383 -0
  477. package/dist/core/sandbox.js.map +1 -0
  478. package/dist/core/semantic-loop-check.d.ts +58 -0
  479. package/dist/core/semantic-loop-check.js +103 -0
  480. package/dist/core/semantic-loop-check.js.map +1 -0
  481. package/dist/core/session-compaction.d.ts +23 -0
  482. package/dist/core/session-compaction.js +54 -0
  483. package/dist/core/session-compaction.js.map +1 -0
  484. package/dist/core/session-export.d.ts +97 -0
  485. package/dist/core/session-export.js +368 -0
  486. package/dist/core/session-export.js.map +1 -0
  487. package/dist/core/session-history.d.ts +160 -0
  488. package/dist/core/session-history.js +467 -0
  489. package/dist/core/session-history.js.map +1 -0
  490. package/dist/core/session-manager.d.ts +510 -0
  491. package/dist/core/session-manager.js +1368 -0
  492. package/dist/core/session-manager.js.map +1 -0
  493. package/dist/core/session-preview.d.ts +12 -0
  494. package/dist/core/session-preview.js +58 -0
  495. package/dist/core/session-preview.js.map +1 -0
  496. package/dist/core/session-storage.d.ts +78 -0
  497. package/dist/core/session-storage.js +659 -0
  498. package/dist/core/session-storage.js.map +1 -0
  499. package/dist/core/session-summary-index.d.ts +51 -0
  500. package/dist/core/session-summary-index.js +192 -0
  501. package/dist/core/session-summary-index.js.map +1 -0
  502. package/dist/core/settings-manager.d.ts +113 -0
  503. package/dist/core/settings-manager.js +281 -0
  504. package/dist/core/settings-manager.js.map +1 -0
  505. package/dist/core/shared-checkout-guard.d.ts +78 -0
  506. package/dist/core/shared-checkout-guard.js +219 -0
  507. package/dist/core/shared-checkout-guard.js.map +1 -0
  508. package/dist/core/shell-path.d.ts +13 -0
  509. package/dist/core/shell-path.js +175 -0
  510. package/dist/core/shell-path.js.map +1 -0
  511. package/dist/core/shell-threats-popular-packages.d.ts +11 -0
  512. package/dist/core/shell-threats-popular-packages.js +675 -0
  513. package/dist/core/shell-threats-popular-packages.js.map +1 -0
  514. package/dist/core/shell-threats.d.ts +21 -0
  515. package/dist/core/shell-threats.js +235 -0
  516. package/dist/core/shell-threats.js.map +1 -0
  517. package/dist/core/shell.d.ts +54 -0
  518. package/dist/core/shell.js +99 -0
  519. package/dist/core/shell.js.map +1 -0
  520. package/dist/core/shutdown.d.ts +70 -0
  521. package/dist/core/shutdown.js +144 -0
  522. package/dist/core/shutdown.js.map +1 -0
  523. package/dist/core/skill-scan.d.ts +112 -0
  524. package/dist/core/skill-scan.js +781 -0
  525. package/dist/core/skill-scan.js.map +1 -0
  526. package/dist/core/skills.d.ts +80 -0
  527. package/dist/core/skills.js +270 -0
  528. package/dist/core/skills.js.map +1 -0
  529. package/dist/core/slash-commands.d.ts +58 -0
  530. package/dist/core/slash-commands.js +242 -0
  531. package/dist/core/slash-commands.js.map +1 -0
  532. package/dist/core/steering.d.ts +47 -0
  533. package/dist/core/steering.js +65 -0
  534. package/dist/core/steering.js.map +1 -0
  535. package/dist/core/steroids.d.ts +66 -0
  536. package/dist/core/steroids.js +243 -0
  537. package/dist/core/steroids.js.map +1 -0
  538. package/dist/core/stream-diag-level.d.ts +3 -0
  539. package/dist/core/stream-diag-level.js +24 -0
  540. package/dist/core/stream-diag-level.js.map +1 -0
  541. package/dist/core/stream-rules.d.ts +30 -0
  542. package/dist/core/stream-rules.js +151 -0
  543. package/dist/core/stream-rules.js.map +1 -0
  544. package/dist/core/subagent-manager.d.ts +239 -0
  545. package/dist/core/subagent-manager.js +1059 -0
  546. package/dist/core/subagent-manager.js.map +1 -0
  547. package/dist/core/subagent-policy.d.ts +9 -0
  548. package/dist/core/subagent-policy.js +41 -0
  549. package/dist/core/subagent-policy.js.map +1 -0
  550. package/dist/core/subagent-receipt.d.ts +54 -0
  551. package/dist/core/subagent-receipt.js +274 -0
  552. package/dist/core/subagent-receipt.js.map +1 -0
  553. package/dist/core/subagent-store.d.ts +41 -0
  554. package/dist/core/subagent-store.js +284 -0
  555. package/dist/core/subagent-store.js.map +1 -0
  556. package/dist/core/subagent-turn-record.d.ts +18 -0
  557. package/dist/core/subagent-turn-record.js +82 -0
  558. package/dist/core/subagent-turn-record.js.map +1 -0
  559. package/dist/core/tasks-store.d.ts +31 -0
  560. package/dist/core/tasks-store.js +97 -0
  561. package/dist/core/tasks-store.js.map +1 -0
  562. package/dist/core/telegram-config.d.ts +20 -0
  563. package/dist/core/telegram-config.js +52 -0
  564. package/dist/core/telegram-config.js.map +1 -0
  565. package/dist/core/telegram.d.ts +114 -0
  566. package/dist/core/telegram.js +275 -0
  567. package/dist/core/telegram.js.map +1 -0
  568. package/dist/core/temp-paths.d.ts +5 -0
  569. package/dist/core/temp-paths.js +50 -0
  570. package/dist/core/temp-paths.js.map +1 -0
  571. package/dist/core/test-impact.d.ts +73 -0
  572. package/dist/core/test-impact.js +467 -0
  573. package/dist/core/test-impact.js.map +1 -0
  574. package/dist/core/threat-feed.d.ts +65 -0
  575. package/dist/core/threat-feed.js +334 -0
  576. package/dist/core/threat-feed.js.map +1 -0
  577. package/dist/core/trophies/catalog-more.d.ts +2 -0
  578. package/dist/core/trophies/catalog-more.js +837 -0
  579. package/dist/core/trophies/catalog-more.js.map +1 -0
  580. package/dist/core/trophies/catalog.d.ts +4 -0
  581. package/dist/core/trophies/catalog.js +649 -0
  582. package/dist/core/trophies/catalog.js.map +1 -0
  583. package/dist/core/trophies/engine.d.ts +70 -0
  584. package/dist/core/trophies/engine.js +347 -0
  585. package/dist/core/trophies/engine.js.map +1 -0
  586. package/dist/core/trophies/store.d.ts +17 -0
  587. package/dist/core/trophies/store.js +113 -0
  588. package/dist/core/trophies/store.js.map +1 -0
  589. package/dist/core/trophies/types.d.ts +87 -0
  590. package/dist/core/trophies/types.js +74 -0
  591. package/dist/core/trophies/types.js.map +1 -0
  592. package/dist/core/ui-adoption.d.ts +32 -0
  593. package/dist/core/ui-adoption.js +302 -0
  594. package/dist/core/ui-adoption.js.map +1 -0
  595. package/dist/core/ui-compatibility.d.ts +10 -0
  596. package/dist/core/ui-compatibility.js +51 -0
  597. package/dist/core/ui-compatibility.js.map +1 -0
  598. package/dist/core/ui-registry.d.ts +101 -0
  599. package/dist/core/ui-registry.js +292 -0
  600. package/dist/core/ui-registry.js.map +1 -0
  601. package/dist/core/user-shell-context.d.ts +8 -0
  602. package/dist/core/user-shell-context.js +12 -0
  603. package/dist/core/user-shell-context.js.map +1 -0
  604. package/dist/core/verification-evidence.d.ts +49 -0
  605. package/dist/core/verification-evidence.js +816 -0
  606. package/dist/core/verification-evidence.js.map +1 -0
  607. package/dist/core/verification-gate.d.ts +77 -0
  608. package/dist/core/verification-gate.js +504 -0
  609. package/dist/core/verification-gate.js.map +1 -0
  610. package/dist/core/verification-snapshot.d.ts +7 -0
  611. package/dist/core/verification-snapshot.js +109 -0
  612. package/dist/core/verification-snapshot.js.map +1 -0
  613. package/dist/core/verify-commands.d.ts +34 -0
  614. package/dist/core/verify-commands.js +203 -0
  615. package/dist/core/verify-commands.js.map +1 -0
  616. package/dist/core/voice-transcriber.d.ts +32 -0
  617. package/dist/core/voice-transcriber.js +114 -0
  618. package/dist/core/voice-transcriber.js.map +1 -0
  619. package/dist/core/workspace-guard.d.ts +56 -0
  620. package/dist/core/workspace-guard.js +334 -0
  621. package/dist/core/workspace-guard.js.map +1 -0
  622. package/dist/index.d.ts +15 -0
  623. package/dist/index.js +21 -0
  624. package/dist/index.js.map +1 -0
  625. package/dist/session.d.ts +44 -0
  626. package/dist/session.js +105 -0
  627. package/dist/session.js.map +1 -0
  628. package/dist/system-prompt.d.ts +104 -0
  629. package/dist/system-prompt.js +480 -0
  630. package/dist/system-prompt.js.map +1 -0
  631. package/dist/test-support/fake-home.d.ts +19 -0
  632. package/dist/test-support/fake-home.js +37 -0
  633. package/dist/test-support/fake-home.js.map +1 -0
  634. package/dist/test-support/keep-alive.d.ts +14 -0
  635. package/dist/test-support/keep-alive.js +17 -0
  636. package/dist/test-support/keep-alive.js.map +1 -0
  637. package/dist/test-support/slow-git.d.ts +1 -0
  638. package/dist/test-support/slow-git.js +21 -0
  639. package/dist/test-support/slow-git.js.map +1 -0
  640. package/dist/test-support/system-tools.d.ts +6 -0
  641. package/dist/test-support/system-tools.js +36 -0
  642. package/dist/test-support/system-tools.js.map +1 -0
  643. package/dist/tools/ask-user.d.ts +34 -0
  644. package/dist/tools/ask-user.js +99 -0
  645. package/dist/tools/ask-user.js.map +1 -0
  646. package/dist/tools/background-watch-lint.d.ts +18 -0
  647. package/dist/tools/background-watch-lint.js +102 -0
  648. package/dist/tools/background-watch-lint.js.map +1 -0
  649. package/dist/tools/bash-read-evidence.d.ts +23 -0
  650. package/dist/tools/bash-read-evidence.js +180 -0
  651. package/dist/tools/bash-read-evidence.js.map +1 -0
  652. package/dist/tools/bash.d.ts +64 -0
  653. package/dist/tools/bash.js +552 -0
  654. package/dist/tools/bash.js.map +1 -0
  655. package/dist/tools/browser-api.d.ts +27 -0
  656. package/dist/tools/browser-api.js +449 -0
  657. package/dist/tools/browser-api.js.map +1 -0
  658. package/dist/tools/browser-sandbox.d.ts +16 -0
  659. package/dist/tools/browser-sandbox.js +158 -0
  660. package/dist/tools/browser-sandbox.js.map +1 -0
  661. package/dist/tools/browser-session.d.ts +84 -0
  662. package/dist/tools/browser-session.js +304 -0
  663. package/dist/tools/browser-session.js.map +1 -0
  664. package/dist/tools/browser-snapshot.d.ts +19 -0
  665. package/dist/tools/browser-snapshot.js +109 -0
  666. package/dist/tools/browser-snapshot.js.map +1 -0
  667. package/dist/tools/browser.d.ts +11 -0
  668. package/dist/tools/browser.js +106 -0
  669. package/dist/tools/browser.js.map +1 -0
  670. package/dist/tools/checklist.d.ts +49 -0
  671. package/dist/tools/checklist.js +154 -0
  672. package/dist/tools/checklist.js.map +1 -0
  673. package/dist/tools/compress.d.ts +56 -0
  674. package/dist/tools/compress.js +226 -0
  675. package/dist/tools/compress.js.map +1 -0
  676. package/dist/tools/debug.d.ts +54 -0
  677. package/dist/tools/debug.js +230 -0
  678. package/dist/tools/debug.js.map +1 -0
  679. package/dist/tools/document-text.d.ts +6 -0
  680. package/dist/tools/document-text.js +154 -0
  681. package/dist/tools/document-text.js.map +1 -0
  682. package/dist/tools/edit-diff.d.ts +123 -0
  683. package/dist/tools/edit-diff.js +476 -0
  684. package/dist/tools/edit-diff.js.map +1 -0
  685. package/dist/tools/edit-targets.d.ts +10 -0
  686. package/dist/tools/edit-targets.js +31 -0
  687. package/dist/tools/edit-targets.js.map +1 -0
  688. package/dist/tools/edit.d.ts +38 -0
  689. package/dist/tools/edit.js +695 -0
  690. package/dist/tools/edit.js.map +1 -0
  691. package/dist/tools/enter-plan.d.ts +7 -0
  692. package/dist/tools/enter-plan.js +20 -0
  693. package/dist/tools/enter-plan.js.map +1 -0
  694. package/dist/tools/exit-plan.d.ts +7 -0
  695. package/dist/tools/exit-plan.js +51 -0
  696. package/dist/tools/exit-plan.js.map +1 -0
  697. package/dist/tools/find.d.ts +17 -0
  698. package/dist/tools/find.js +100 -0
  699. package/dist/tools/find.js.map +1 -0
  700. package/dist/tools/generate-image.d.ts +83 -0
  701. package/dist/tools/generate-image.js +625 -0
  702. package/dist/tools/generate-image.js.map +1 -0
  703. package/dist/tools/grep-scan.d.ts +96 -0
  704. package/dist/tools/grep-scan.js +283 -0
  705. package/dist/tools/grep-scan.js.map +1 -0
  706. package/dist/tools/grep.d.ts +48 -0
  707. package/dist/tools/grep.js +1013 -0
  708. package/dist/tools/grep.js.map +1 -0
  709. package/dist/tools/html-extract.d.ts +57 -0
  710. package/dist/tools/html-extract.js +130 -0
  711. package/dist/tools/html-extract.js.map +1 -0
  712. package/dist/tools/index.d.ts +198 -0
  713. package/dist/tools/index.js +216 -0
  714. package/dist/tools/index.js.map +1 -0
  715. package/dist/tools/live-preview.d.ts +23 -0
  716. package/dist/tools/live-preview.js +41 -0
  717. package/dist/tools/live-preview.js.map +1 -0
  718. package/dist/tools/ls.d.ts +9 -0
  719. package/dist/tools/ls.js +59 -0
  720. package/dist/tools/ls.js.map +1 -0
  721. package/dist/tools/operations.d.ts +86 -0
  722. package/dist/tools/operations.js +117 -0
  723. package/dist/tools/operations.js.map +1 -0
  724. package/dist/tools/overflow.d.ts +17 -0
  725. package/dist/tools/overflow.js +68 -0
  726. package/dist/tools/overflow.js.map +1 -0
  727. package/dist/tools/path-utils.d.ts +30 -0
  728. package/dist/tools/path-utils.js +74 -0
  729. package/dist/tools/path-utils.js.map +1 -0
  730. package/dist/tools/pdf-extract.d.ts +17 -0
  731. package/dist/tools/pdf-extract.js +43 -0
  732. package/dist/tools/pdf-extract.js.map +1 -0
  733. package/dist/tools/prompt-hints.d.ts +46 -0
  734. package/dist/tools/prompt-hints.js +171 -0
  735. package/dist/tools/prompt-hints.js.map +1 -0
  736. package/dist/tools/read-only-bash.d.ts +31 -0
  737. package/dist/tools/read-only-bash.js +338 -0
  738. package/dist/tools/read-only-bash.js.map +1 -0
  739. package/dist/tools/read-tracker.d.ts +43 -0
  740. package/dist/tools/read-tracker.js +120 -0
  741. package/dist/tools/read-tracker.js.map +1 -0
  742. package/dist/tools/read.d.ts +18 -0
  743. package/dist/tools/read.js +316 -0
  744. package/dist/tools/read.js.map +1 -0
  745. package/dist/tools/redaction-guard.d.ts +10 -0
  746. package/dist/tools/redaction-guard.js +55 -0
  747. package/dist/tools/redaction-guard.js.map +1 -0
  748. package/dist/tools/routine-output.d.ts +39 -0
  749. package/dist/tools/routine-output.js +281 -0
  750. package/dist/tools/routine-output.js.map +1 -0
  751. package/dist/tools/safe-env.d.ts +1 -0
  752. package/dist/tools/safe-env.js +79 -0
  753. package/dist/tools/safe-env.js.map +1 -0
  754. package/dist/tools/session-stats.d.ts +26 -0
  755. package/dist/tools/session-stats.js +51 -0
  756. package/dist/tools/session-stats.js.map +1 -0
  757. package/dist/tools/side-web-search.d.ts +34 -0
  758. package/dist/tools/side-web-search.js +146 -0
  759. package/dist/tools/side-web-search.js.map +1 -0
  760. package/dist/tools/skill.d.ts +12 -0
  761. package/dist/tools/skill.js +94 -0
  762. package/dist/tools/skill.js.map +1 -0
  763. package/dist/tools/source-path.d.ts +8 -0
  764. package/dist/tools/source-path.js +135 -0
  765. package/dist/tools/source-path.js.map +1 -0
  766. package/dist/tools/steroids.d.ts +44 -0
  767. package/dist/tools/steroids.js +356 -0
  768. package/dist/tools/steroids.js.map +1 -0
  769. package/dist/tools/subagent-control.d.ts +5 -0
  770. package/dist/tools/subagent-control.js +211 -0
  771. package/dist/tools/subagent-control.js.map +1 -0
  772. package/dist/tools/subagent-shared.d.ts +115 -0
  773. package/dist/tools/subagent-shared.js +182 -0
  774. package/dist/tools/subagent-shared.js.map +1 -0
  775. package/dist/tools/subagent.d.ts +37 -0
  776. package/dist/tools/subagent.js +406 -0
  777. package/dist/tools/subagent.js.map +1 -0
  778. package/dist/tools/task-output.d.ts +10 -0
  779. package/dist/tools/task-output.js +74 -0
  780. package/dist/tools/task-output.js.map +1 -0
  781. package/dist/tools/task-send.d.ts +11 -0
  782. package/dist/tools/task-send.js +36 -0
  783. package/dist/tools/task-send.js.map +1 -0
  784. package/dist/tools/task-stop.d.ts +8 -0
  785. package/dist/tools/task-stop.js +15 -0
  786. package/dist/tools/task-stop.js.map +1 -0
  787. package/dist/tools/tasks.d.ts +15 -0
  788. package/dist/tools/tasks.js +94 -0
  789. package/dist/tools/tasks.js.map +1 -0
  790. package/dist/tools/tool-search.d.ts +26 -0
  791. package/dist/tools/tool-search.js +81 -0
  792. package/dist/tools/tool-search.js.map +1 -0
  793. package/dist/tools/tool-tiers.d.ts +65 -0
  794. package/dist/tools/tool-tiers.js +121 -0
  795. package/dist/tools/tool-tiers.js.map +1 -0
  796. package/dist/tools/truncate.d.ts +39 -0
  797. package/dist/tools/truncate.js +242 -0
  798. package/dist/tools/truncate.js.map +1 -0
  799. package/dist/tools/ui-adopt.d.ts +16 -0
  800. package/dist/tools/ui-adopt.js +66 -0
  801. package/dist/tools/ui-adopt.js.map +1 -0
  802. package/dist/tools/ui-registry.d.ts +15 -0
  803. package/dist/tools/ui-registry.js +39 -0
  804. package/dist/tools/ui-registry.js.map +1 -0
  805. package/dist/tools/verification-review.d.ts +2 -0
  806. package/dist/tools/verification-review.js +41 -0
  807. package/dist/tools/verification-review.js.map +1 -0
  808. package/dist/tools/web-fetch.d.ts +52 -0
  809. package/dist/tools/web-fetch.js +986 -0
  810. package/dist/tools/web-fetch.js.map +1 -0
  811. package/dist/tools/web-search.d.ts +35 -0
  812. package/dist/tools/web-search.js +926 -0
  813. package/dist/tools/web-search.js.map +1 -0
  814. package/dist/tools/write.d.ts +16 -0
  815. package/dist/tools/write.js +196 -0
  816. package/dist/tools/write.js.map +1 -0
  817. package/dist/types.d.ts +44 -0
  818. package/dist/types.js +2 -0
  819. package/dist/types.js.map +1 -0
  820. package/dist/utils/commit-message.d.ts +25 -0
  821. package/dist/utils/commit-message.js +72 -0
  822. package/dist/utils/commit-message.js.map +1 -0
  823. package/dist/utils/git.d.ts +102 -0
  824. package/dist/utils/git.js +325 -0
  825. package/dist/utils/git.js.map +1 -0
  826. package/dist/utils/github-ci.d.ts +9 -0
  827. package/dist/utils/github-ci.js +138 -0
  828. package/dist/utils/github-ci.js.map +1 -0
  829. package/dist/utils/github.d.ts +19 -0
  830. package/dist/utils/github.js +67 -0
  831. package/dist/utils/github.js.map +1 -0
  832. package/dist/utils/image.d.ts +166 -0
  833. package/dist/utils/image.js +673 -0
  834. package/dist/utils/image.js.map +1 -0
  835. package/dist/utils/open-browser.d.ts +13 -0
  836. package/dist/utils/open-browser.js +31 -0
  837. package/dist/utils/open-browser.js.map +1 -0
  838. package/dist/utils/plan-steps.d.ts +90 -0
  839. package/dist/utils/plan-steps.js +209 -0
  840. package/dist/utils/plan-steps.js.map +1 -0
  841. package/dist/utils/process.d.ts +48 -0
  842. package/dist/utils/process.js +175 -0
  843. package/dist/utils/process.js.map +1 -0
  844. package/dist/utils/prompt-enhancer.d.ts +34 -0
  845. package/dist/utils/prompt-enhancer.js +178 -0
  846. package/dist/utils/prompt-enhancer.js.map +1 -0
  847. package/dist/utils/text.d.ts +61 -0
  848. package/dist/utils/text.js +68 -0
  849. package/dist/utils/text.js.map +1 -0
  850. package/package.json +87 -3
@@ -0,0 +1,1368 @@
1
+ import fs from "node:fs/promises";
2
+ import { createInterface } from "node:readline";
3
+ import path from "node:path";
4
+ import crypto from "node:crypto";
5
+ import { environmentSecrets, redactValue, } from "@kenkaiiii/gg-ai";
6
+ import { indeterminateOutcomeText } from "@kenkaiiii/gg-agent";
7
+ import { log } from "@kenkaiiii/gg-core";
8
+ /** Sibling turn record a sub-agent writes next to its child transcript. */
9
+ const TURN_RECORD_SUFFIX = ".turn.json";
10
+ import { encodeCwd } from "./encode-cwd.js";
11
+ import { getUserSessionPrompt } from "./session-preview.js";
12
+ import { SESSION_INFO_INDEX_FILE, SESSION_SUMMARY_INDEX_FILE, SessionSummaryIndex, } from "./session-summary-index.js";
13
+ import { archiveColdSession, archiveSessionPath, cleanupOldSessionTemps, COLD_SESSION_AGE_DAYS, emptyStorageNormalizationMetrics, hydrateSessionEntry, isSessionPath, normalizeSessionEntryForStorage, openSessionReadStream, plainSessionPath, resolveSessionPath, sessionAssetDir, thawSessionArchive, } from "./session-storage.js";
14
+ export const DISPLAY_ITEM_CUSTOM_KIND = "display_item";
15
+ export const TURN_METRIC_CUSTOM_KIND = "turn_metric";
16
+ function finiteNumber(value) {
17
+ return typeof value === "number" && Number.isFinite(value);
18
+ }
19
+ function parseTurnMetric(value) {
20
+ if (!value || typeof value !== "object")
21
+ return undefined;
22
+ const payload = value;
23
+ const usage = payload.usage;
24
+ const timing = payload.timing;
25
+ const cost = payload.cost;
26
+ if (payload.version !== 1 ||
27
+ !finiteNumber(payload.turn) ||
28
+ typeof payload.provider !== "string" ||
29
+ typeof payload.model !== "string" ||
30
+ typeof payload.stopReason !== "string" ||
31
+ !usage ||
32
+ !finiteNumber(usage.inputTokens) ||
33
+ !finiteNumber(usage.outputTokens) ||
34
+ !timing ||
35
+ !finiteNumber(timing.startedAt) ||
36
+ !finiteNumber(timing.completedAt) ||
37
+ !finiteNumber(timing.providerDurationMs) ||
38
+ !cost ||
39
+ (cost.status !== "known" && cost.status !== "unavailable")) {
40
+ return undefined;
41
+ }
42
+ if ((usage.cacheRead !== undefined && !finiteNumber(usage.cacheRead)) ||
43
+ (usage.cacheWrite !== undefined && !finiteNumber(usage.cacheWrite)) ||
44
+ (timing.firstProviderEventAt !== undefined && !finiteNumber(timing.firstProviderEventAt)) ||
45
+ (timing.ttftMs !== undefined && !finiteNumber(timing.ttftMs)) ||
46
+ (timing.outputTokensPerSecond !== undefined && !finiteNumber(timing.outputTokensPerSecond)) ||
47
+ (cost.status === "known" &&
48
+ (!finiteNumber(cost.usd) ||
49
+ typeof cost.source !== "string" ||
50
+ typeof cost.effectiveAt !== "string")) ||
51
+ (cost.status === "unavailable" && typeof cost.reason !== "string")) {
52
+ return undefined;
53
+ }
54
+ return payload;
55
+ }
56
+ /** Custom-entry kind for a Ken Kai (mentor agent) turn. Ken's advisory
57
+ * conversation is NOT part of the LLM message history (GG Coder never sees it),
58
+ * but it's persisted alongside the build session so it survives resume. Stored
59
+ * as a `custom` entry with `parentId: null` so it is NEVER on the message DAG
60
+ * branch — this keeps it out of `getMessages()` AND avoids racing the build
61
+ * session's leaf pointer (Ken runs concurrently). `afterMessageCount` is the
62
+ * number of non-system messages that existed when the turn was recorded, used
63
+ * to interleave Ken turns back into the transcript chronologically. */
64
+ export const KEN_TURN_CUSTOM_KIND = "ken_turn";
65
+ /** Custom-entry kind for an autopilot verdict marker. Mirrors `ken_turn`:
66
+ * persisted as a `custom` entry with `parentId: null` so it's never on the
67
+ * message DAG (GG Coder never sees it) but survives resume/compaction and
68
+ * interleaves back into the transcript via `afterMessageCount`. Covers all
69
+ * four terminal/near-terminal autopilot markers so a resumed session renders
70
+ * the exact same Ken bubble the live run showed — never the raw verdict
71
+ * keyword (e.g. `ALL_CLEAR`) the model actually replied with. */
72
+ export const AUTOPILOT_MARKER_CUSTOM_KIND = "autopilot_marker";
73
+ /** Custom-entry kind for a generic app transcript marker (plan-mode banner,
74
+ * task header, error row, user-bubble display hint). Same not-on-the-DAG
75
+ * treatment as Ken turns / autopilot markers: persisted with `parentId: null`
76
+ * so the LLM never sees it, anchored by `afterMessageCount` so the host can
77
+ * interleave it back into the transcript on resume. */
78
+ export const APP_MARKER_CUSTOM_KIND = "app_transcript_marker";
79
+ /**
80
+ * Run journal — a matched pair of custom entries bracketing every provider run.
81
+ *
82
+ * Same not-on-the-DAG treatment as Ken turns (`parentId: null`): the model never
83
+ * sees them, and they can't race the message branch's leaf pointer. A
84
+ * `run_started` with no matching `run_finished` is the on-disk signature of a
85
+ * run that died mid-flight — the host surfaces it on load instead of silently
86
+ * resuming work whose tools already half-mutated the repo.
87
+ *
88
+ * `generation` is the `RunLifecycle` generation, so the pairing inherits that
89
+ * class's generation-safety: a stale run cannot close a newer one's journal.
90
+ */
91
+ export const RUN_STARTED_CUSTOM_KIND = "run_started";
92
+ export const RUN_FINISHED_CUSTOM_KIND = "run_finished";
93
+ /** True unless the OS says no such process exists (EPERM means it does). */
94
+ export function processIsAlive(pid) {
95
+ try {
96
+ process.kill(pid, 0);
97
+ return true;
98
+ }
99
+ catch (error) {
100
+ return error.code !== "ESRCH";
101
+ }
102
+ }
103
+ function isDisplayItemLike(value) {
104
+ return (typeof value === "object" &&
105
+ value !== null &&
106
+ typeof value.kind === "string" &&
107
+ typeof value.id === "string");
108
+ }
109
+ const COMPACTION_COORDINATION_DIR = ".compaction-coordination";
110
+ const CORRUPT_LEASE_STALE_MS = 60_000;
111
+ const LEASE_POLL_MS = 50;
112
+ // ── Session Manager ────────────────────────────────────────
113
+ export class SessionManager {
114
+ static activePathsByRoot = new Map();
115
+ static maintenanceByRoot = new Map();
116
+ sessionsDir;
117
+ warnedPersistCodes = new Set();
118
+ /** Session files whose tail this process already checked (see {@link sealTornTail}). */
119
+ sealedTails = new Set();
120
+ /** Fingerprint-checked summary caches, one per storage directory. */
121
+ summaryIndexes = new Map();
122
+ infoIndexes = new Map();
123
+ /** Called once per error code when session persistence fails (e.g. ENOSPC). */
124
+ onPersistError;
125
+ constructor(sessionsDir) {
126
+ this.sessionsDir = path.resolve(sessionsDir);
127
+ }
128
+ coordinationKey(conversationId) {
129
+ return crypto.createHash("sha256").update(conversationId).digest("hex");
130
+ }
131
+ coordinationRoot() {
132
+ return path.join(this.sessionsDir, COMPACTION_COORDINATION_DIR);
133
+ }
134
+ async leaseOwner(lockPath) {
135
+ try {
136
+ const parsed = JSON.parse(await fs.readFile(path.join(lockPath, "owner.json"), "utf-8"));
137
+ return typeof parsed.token === "string" &&
138
+ typeof parsed.pid === "number" &&
139
+ typeof parsed.createdAt === "string"
140
+ ? parsed
141
+ : null;
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ }
147
+ processIsAlive(pid) {
148
+ return processIsAlive(pid);
149
+ }
150
+ async waitForLease(signal) {
151
+ if (signal?.aborted)
152
+ throw new DOMException("Aborted", "AbortError");
153
+ await new Promise((resolve, reject) => {
154
+ const finish = () => {
155
+ signal?.removeEventListener("abort", onAbort);
156
+ resolve();
157
+ };
158
+ const timer = setTimeout(finish, LEASE_POLL_MS);
159
+ const onAbort = () => {
160
+ clearTimeout(timer);
161
+ signal?.removeEventListener("abort", onAbort);
162
+ reject(new DOMException("Aborted", "AbortError"));
163
+ };
164
+ signal?.addEventListener("abort", onAbort, { once: true });
165
+ timer.unref?.();
166
+ });
167
+ }
168
+ /** Serialize compaction work across processes for one logical conversation. */
169
+ async withCompactionLease(conversationId, signal, work) {
170
+ const root = this.coordinationRoot();
171
+ await fs.mkdir(root, { recursive: true });
172
+ const lockPath = path.join(root, `${this.coordinationKey(conversationId)}.lock`);
173
+ const token = crypto.randomUUID();
174
+ // Windows can report EPERM/EBUSY/EACCES on `mkdir` while the previous
175
+ // holder's `rm` has the lock dir in pending-delete. A few immediate retries
176
+ // cover the case where the dir vanishes between mkdir and stat; a genuine
177
+ // permission error on the root never produces a lock dir and gives up here.
178
+ let vanishedRetries = 0;
179
+ while (true) {
180
+ try {
181
+ await fs.mkdir(lockPath);
182
+ const owner = {
183
+ token,
184
+ pid: process.pid,
185
+ createdAt: new Date().toISOString(),
186
+ };
187
+ await fs.writeFile(path.join(lockPath, "owner.json"), JSON.stringify(owner), "utf-8");
188
+ break;
189
+ }
190
+ catch (error) {
191
+ // EEXIST is the normal "someone holds it" signal. EPERM/EBUSY/EACCES
192
+ // only count as contention when the lock dir is actually there
193
+ // (pending-delete); otherwise it is a real permission fault and must
194
+ // surface rather than spin in waitForLease forever.
195
+ const code = error.code;
196
+ const contentionCode = code === "EPERM" || code === "EBUSY" || code === "EACCES";
197
+ if (code !== "EEXIST" && !contentionCode)
198
+ throw error;
199
+ const stat = await fs.stat(lockPath).catch(() => null);
200
+ if (contentionCode && stat === null) {
201
+ if (++vanishedRetries > 3)
202
+ throw error;
203
+ continue;
204
+ }
205
+ const owner = await this.leaseOwner(lockPath);
206
+ const corruptAndOld = !owner && stat !== null && Date.now() - stat.mtimeMs > CORRUPT_LEASE_STALE_MS;
207
+ const deadOwner = owner !== null && !this.processIsAlive(owner.pid);
208
+ if (deadOwner || corruptAndOld) {
209
+ await fs.rm(lockPath, { recursive: true, force: true });
210
+ continue;
211
+ }
212
+ await this.waitForLease(signal);
213
+ }
214
+ }
215
+ try {
216
+ return await work();
217
+ }
218
+ finally {
219
+ const owner = await this.leaseOwner(lockPath);
220
+ if (owner?.token === token)
221
+ await fs.rm(lockPath, { recursive: true, force: true });
222
+ }
223
+ }
224
+ async readCompactionAttemptState(conversationId) {
225
+ const statePath = path.join(this.coordinationRoot(), `${this.coordinationKey(conversationId)}.state.json`);
226
+ try {
227
+ const state = JSON.parse(await fs.readFile(statePath, "utf-8"));
228
+ return typeof state.fingerprint === "string" &&
229
+ typeof state.policyKey === "string" &&
230
+ ["success", "failed", "noop"].includes(state.outcome) &&
231
+ typeof state.updatedAt === "string"
232
+ ? state
233
+ : null;
234
+ }
235
+ catch {
236
+ return null;
237
+ }
238
+ }
239
+ async writeCompactionAttemptState(conversationId, state) {
240
+ const root = this.coordinationRoot();
241
+ await fs.mkdir(root, { recursive: true });
242
+ const statePath = path.join(root, `${this.coordinationKey(conversationId)}.state.json`);
243
+ const temporaryPath = `${statePath}.${process.pid}.${crypto.randomUUID()}.tmp`;
244
+ await fs.writeFile(temporaryPath, JSON.stringify(state), "utf-8");
245
+ await fs.rename(temporaryPath, statePath);
246
+ }
247
+ /**
248
+ * Terminate a half-written last line before appending after it.
249
+ *
250
+ * Entries are one JSON object per line, appended with a trailing newline. A
251
+ * process killed mid-append leaves that final line without its newline — and
252
+ * the next append then fuses onto it, so ONE torn write destroys TWO records:
253
+ * the incomplete one and the first record of the resumed turn. Both are then
254
+ * silently skipped as malformed at load, so the user loses a message from
255
+ * their own history with no error shown. Writing the missing newline first
256
+ * confines the loss to the record that was actually torn.
257
+ *
258
+ * Once per file per process: the fuse can only happen on the first append
259
+ * after opening a file that someone else left torn.
260
+ */
261
+ async sealTornTail(filePath) {
262
+ if (this.sealedTails.has(filePath))
263
+ return;
264
+ this.sealedTails.add(filePath);
265
+ let handle;
266
+ try {
267
+ handle = await fs.open(filePath, "r+");
268
+ const { size } = await handle.stat();
269
+ if (size === 0)
270
+ return;
271
+ const tail = Buffer.alloc(1);
272
+ await handle.read(tail, 0, 1, size - 1);
273
+ if (tail[0] === 0x0a)
274
+ return;
275
+ await handle.write("\n", size, "utf-8");
276
+ log("WARN", "session", "Repaired a session file whose last line was cut short", {
277
+ path: filePath,
278
+ });
279
+ }
280
+ catch {
281
+ // Missing file (the append below creates it) or an unwritable one — the
282
+ // append itself reports anything that actually matters.
283
+ }
284
+ finally {
285
+ await handle?.close().catch(() => { });
286
+ }
287
+ }
288
+ /**
289
+ * Session persistence must never crash a live session. Disk-full (ENOSPC),
290
+ * permission, or quota errors during transcript writes are reported once
291
+ * per error code and otherwise swallowed — the in-memory session keeps going.
292
+ */
293
+ handlePersistError(error, op) {
294
+ const err = error;
295
+ const code = err?.code ?? "UNKNOWN";
296
+ if (this.warnedPersistCodes.has(code))
297
+ return;
298
+ this.warnedPersistCodes.add(code);
299
+ log("WARN", "session", `Session persistence failed (${op}); continuing without saving`, {
300
+ code,
301
+ message: err?.message ?? String(error),
302
+ });
303
+ this.onPersistError?.(err);
304
+ }
305
+ dirForCwd(cwd) {
306
+ return path.join(this.sessionsDir, encodeCwd(cwd));
307
+ }
308
+ async create(cwd, provider, model, options) {
309
+ const id = crypto.randomUUID();
310
+ const timestamp = new Date().toISOString();
311
+ const dir = this.dirForCwd(cwd);
312
+ await fs.mkdir(dir, { recursive: true });
313
+ const fileName = `${timestamp.replace(/[:.]/g, "-")}_${id.slice(0, 8)}.jsonl`;
314
+ const filePath = path.join(dir, fileName);
315
+ const normalizedPreview = options?.preview?.replace(/\s+/g, " ").trim().slice(0, 80);
316
+ const safePreview = normalizedPreview
317
+ ? String(redactValue(normalizedPreview, { secrets: environmentSecrets(process.env) }))
318
+ : undefined;
319
+ const header = {
320
+ type: "session",
321
+ version: 2,
322
+ id,
323
+ conversationId: options?.conversationId ?? id,
324
+ generation: options?.generation ?? 0,
325
+ ...(options?.parentSessionId ? { parentSessionId: options.parentSessionId } : {}),
326
+ ...(options?.sourceFingerprint ? { sourceFingerprint: options.sourceFingerprint } : {}),
327
+ ...(typeof options?.retainedMessageCount === "number"
328
+ ? { retainedMessageCount: options.retainedMessageCount }
329
+ : {}),
330
+ ...(safePreview ? { preview: safePreview } : {}),
331
+ timestamp,
332
+ cwd,
333
+ provider,
334
+ model,
335
+ leafId: null,
336
+ };
337
+ await fs.appendFile(filePath, JSON.stringify(header) + "\n", "utf-8");
338
+ return { id, path: filePath, header };
339
+ }
340
+ registerActivePath(sessionPath) {
341
+ const root = this.sessionsDir;
342
+ const active = SessionManager.activePathsByRoot.get(root) ?? new Map();
343
+ const basePath = path.resolve(plainSessionPath(sessionPath));
344
+ active.set(basePath, (active.get(basePath) ?? 0) + 1);
345
+ SessionManager.activePathsByRoot.set(root, active);
346
+ }
347
+ unregisterActivePath(sessionPath) {
348
+ const active = SessionManager.activePathsByRoot.get(this.sessionsDir);
349
+ if (!active)
350
+ return;
351
+ const basePath = path.resolve(plainSessionPath(sessionPath));
352
+ const registrations = active.get(basePath) ?? 0;
353
+ if (registrations <= 1)
354
+ active.delete(basePath);
355
+ else
356
+ active.set(basePath, registrations - 1);
357
+ if (active.size === 0)
358
+ SessionManager.activePathsByRoot.delete(this.sessionsDir);
359
+ }
360
+ /**
361
+ * Whether maintenance must leave `basePath` alone. Keep paths are resolved
362
+ * once per pass by the caller; open sessions are read live, so a session
363
+ * opened while a long pass is running is still protected.
364
+ */
365
+ isProtectedSessionBase(basePath, keepBases) {
366
+ return (keepBases.has(basePath) ||
367
+ (SessionManager.activePathsByRoot.get(this.sessionsDir)?.has(basePath) ?? false));
368
+ }
369
+ static resolveKeepBases(keepPaths = []) {
370
+ return new Set(keepPaths.map((sessionPath) => path.resolve(plainSessionPath(sessionPath))));
371
+ }
372
+ async load(sessionPath, options) {
373
+ // Resuming is a write operation, so transparently thaw a gzip archive and
374
+ // return the effective plain path every future append must use.
375
+ const canonicalPath = options?.canonical
376
+ ? sessionPath
377
+ : ((await this.resolveCanonicalSession(sessionPath)) ?? sessionPath);
378
+ const effectivePath = await thawSessionArchive(canonicalPath);
379
+ return this.loadPhysicalCheckpoint(effectivePath);
380
+ }
381
+ /**
382
+ * Load the contiguous checkpoint ancestry ending at the canonical newest file.
383
+ *
384
+ * The returned order is oldest → newest. A missing, corrupt, cyclic, or
385
+ * cross-conversation parent stops traversal at the oldest readable checkpoint,
386
+ * allowing display callers to retain that checkpoint's compaction summary as a
387
+ * fallback. Parent archives are read in place rather than thawed because this
388
+ * API is for history reconstruction, not resuming writes.
389
+ */
390
+ async loadCheckpointChain(sessionPath) {
391
+ const requestedSummary = await this.readSessionSummary(sessionPath);
392
+ // A resumed session can compact under a different cwd than its parent (for
393
+ // example, a remote ACP client reconnecting from another workspace). The
394
+ // physical ancestry is therefore machine-wide, not confined to the newest
395
+ // checkpoint's encoded-cwd directory.
396
+ const summaries = (await this.indexedSummariesIn(await this.storageDirectories())).filter((summary) => summary !== null);
397
+ const requestedIdentity = requestedSummary?.conversationId ??
398
+ summaries.find((summary) => summary.id === sessionPath)?.conversationId;
399
+ const newestSummary = requestedIdentity
400
+ ? summaries
401
+ .filter((summary) => summary.conversationId === requestedIdentity)
402
+ .sort((left, right) => SessionManager.compareCheckpoints(right, left))[0]
403
+ : undefined;
404
+ const newestPath = newestSummary?.path ?? sessionPath;
405
+ // Resuming the newest checkpoint is a write operation, so thaw only that
406
+ // generation. Historical parents stay archived and read-only.
407
+ const newest = await this.loadPhysicalCheckpoint(await thawSessionArchive(newestPath));
408
+ const newestConversationId = newest.header.conversationId ?? newest.header.id;
409
+ const byPhysicalId = new Map(summaries.map((summary) => [summary.id, summary.path]));
410
+ const newestResolvedPath = path.resolve(newest.path);
411
+ const visited = new Set([newest.header.id]);
412
+ const chain = [newest];
413
+ let current = newest;
414
+ while (current.header.parentSessionId) {
415
+ const parentId = current.header.parentSessionId;
416
+ if (visited.has(parentId))
417
+ break;
418
+ const parentPath = byPhysicalId.get(parentId);
419
+ if (!parentPath || path.resolve(parentPath) === newestResolvedPath)
420
+ break;
421
+ try {
422
+ const parent = await this.loadPhysicalCheckpoint(parentPath, true);
423
+ if ((parent.header.conversationId ?? parent.header.id) !== newestConversationId)
424
+ break;
425
+ visited.add(parentId);
426
+ chain.unshift(parent);
427
+ current = parent;
428
+ }
429
+ catch {
430
+ break;
431
+ }
432
+ }
433
+ return chain;
434
+ }
435
+ async loadPhysicalCheckpoint(sessionPath, rejectMalformedLines = false) {
436
+ const effectivePath = await resolveSessionPath(sessionPath);
437
+ const { stream, close } = await openSessionReadStream(effectivePath);
438
+ let header = null;
439
+ const entries = [];
440
+ const rl = createInterface({ input: stream, crlfDelay: Infinity });
441
+ // rejectMalformedLines can throw mid-transcript; close() on the way out.
442
+ try {
443
+ for await (const line of rl) {
444
+ if (!line)
445
+ continue;
446
+ try {
447
+ const parsed = JSON.parse(line);
448
+ if (parsed.type === "session") {
449
+ if (parsed.version === 2) {
450
+ header = parsed;
451
+ }
452
+ else {
453
+ const v1 = parsed;
454
+ header = {
455
+ type: "session",
456
+ version: 2,
457
+ id: v1.id,
458
+ conversationId: v1.id,
459
+ generation: 0,
460
+ timestamp: v1.timestamp,
461
+ cwd: v1.cwd,
462
+ provider: v1.provider,
463
+ model: v1.model,
464
+ leafId: null,
465
+ };
466
+ }
467
+ continue;
468
+ }
469
+ const entry = parsed;
470
+ if (entry.type === "message" && !entry.id) {
471
+ entry.id = crypto.randomUUID();
472
+ entry.parentId = null;
473
+ }
474
+ // Only media-bearing lines need the async asset read; everything else
475
+ // is returned as parsed (hydration would only shallow-copy it).
476
+ entries.push(line.includes("gg-session-asset:")
477
+ ? await hydrateSessionEntry(entry, effectivePath)
478
+ : entry);
479
+ }
480
+ catch (error) {
481
+ if (rejectMalformedLines)
482
+ throw error;
483
+ // Skip malformed JSON lines — cold migration preserves their raw bytes
484
+ // so a future recovery tool still has a chance to repair them.
485
+ }
486
+ }
487
+ }
488
+ finally {
489
+ rl.close();
490
+ close();
491
+ }
492
+ if (!header) {
493
+ throw new Error(`Invalid session file: no header found in ${sessionPath}`);
494
+ }
495
+ return { header, entries, path: effectivePath };
496
+ }
497
+ async readSessionInfo(candidatePath) {
498
+ try {
499
+ const resolvedPath = await resolveSessionPath(candidatePath);
500
+ const { stream, close } = await openSessionReadStream(resolvedPath);
501
+ const rl = createInterface({ input: stream, crlfDelay: Infinity });
502
+ let first = null;
503
+ let messageCount = 0;
504
+ let lastActivity = null;
505
+ let preview;
506
+ try {
507
+ for await (const line of rl) {
508
+ if (!line)
509
+ continue;
510
+ try {
511
+ const parsed = JSON.parse(line);
512
+ if (!first) {
513
+ if (parsed.type !== "session")
514
+ break;
515
+ first = parsed;
516
+ // v2 headers usually carry the preview already; when they do,
517
+ // nothing below has to look for one.
518
+ preview = parsed.preview?.trim() || undefined;
519
+ }
520
+ else if (parsed.type === "message") {
521
+ messageCount += 1;
522
+ if (parsed.timestamp)
523
+ lastActivity = parsed.timestamp;
524
+ // Recover a title for the sessions whose header predates `preview`.
525
+ // Free here: this pass already reads every line. `getUserSessionPrompt`
526
+ // rejects compaction summaries and autopilot/status injections, so a
527
+ // session is titled by what its user actually asked.
528
+ if (!preview && parsed.message?.role === "user") {
529
+ preview =
530
+ getUserSessionPrompt(parsed.message.content, parsed.message.provenance)
531
+ ?.replace(/\s+/g, " ")
532
+ .trim() || undefined;
533
+ }
534
+ }
535
+ }
536
+ catch {
537
+ // Skip malformed lines while retaining readable entries around them.
538
+ }
539
+ }
540
+ }
541
+ finally {
542
+ rl.close();
543
+ close();
544
+ }
545
+ if (!first || first.type !== "session")
546
+ return null;
547
+ return {
548
+ id: first.id,
549
+ conversationId: first.version === 2
550
+ ? (first.conversationId ?? first.id)
551
+ : first.id,
552
+ generation: first.version === 2 ? (first.generation ?? 0) : 0,
553
+ path: resolvedPath,
554
+ timestamp: first.timestamp,
555
+ lastActivity: lastActivity ?? first.timestamp,
556
+ cwd: first.cwd,
557
+ messageCount,
558
+ ...(preview ? { preview: preview.slice(0, 100) } : {}),
559
+ };
560
+ }
561
+ catch {
562
+ return null;
563
+ }
564
+ }
565
+ async sessionCandidates(directory) {
566
+ let files;
567
+ try {
568
+ files = await fs.readdir(directory);
569
+ }
570
+ catch {
571
+ return [];
572
+ }
573
+ return files.filter(isSessionPath).map((file) => path.join(directory, file));
574
+ }
575
+ /**
576
+ * Summaries of every session in one directory, served from the persisted
577
+ * fingerprint index so only changed files are re-read.
578
+ */
579
+ async indexedSummaries(directory) {
580
+ const resolved = path.resolve(directory);
581
+ let index = this.summaryIndexes.get(resolved);
582
+ if (!index) {
583
+ index = new SessionSummaryIndex(resolved);
584
+ this.summaryIndexes.set(resolved, index);
585
+ }
586
+ return index.summaries(await this.sessionCandidates(resolved), (candidate) => this.readSessionSummary(candidate));
587
+ }
588
+ /** {@link indexedSummaries} across several directories, flattened. */
589
+ async indexedSummariesIn(directories) {
590
+ return (await Promise.all(directories.map((directory) => this.indexedSummaries(directory)))).flat();
591
+ }
592
+ /**
593
+ * Read just enough of a session file to summarize it.
594
+ *
595
+ * Stops at the first user prompt (or the first message, when the header
596
+ * already carries a preview) instead of parsing the whole transcript — this
597
+ * is what makes listing every session on the machine cheap. Files whose
598
+ * first user message is far down (long tool runs before the user speaks)
599
+ * are capped rather than allowed to stall the list.
600
+ */
601
+ async readSessionSummary(candidatePath) {
602
+ try {
603
+ const resolvedPath = await resolveSessionPath(candidatePath);
604
+ const { stream, close } = await openSessionReadStream(resolvedPath);
605
+ const rl = createInterface({ input: stream, crlfDelay: Infinity });
606
+ let first = null;
607
+ let preview;
608
+ let hasMessages = false;
609
+ let lines = 0;
610
+ const MAX_SCAN_LINES = 500;
611
+ try {
612
+ for await (const line of rl) {
613
+ if (!line)
614
+ continue;
615
+ if (++lines > MAX_SCAN_LINES)
616
+ break;
617
+ try {
618
+ const parsed = JSON.parse(line);
619
+ if (!first) {
620
+ if (parsed.type !== "session")
621
+ break;
622
+ first = parsed;
623
+ preview = parsed.preview?.trim() || undefined;
624
+ }
625
+ else if (parsed.type === "message") {
626
+ hasMessages = true;
627
+ // Header preview + any message: done. Otherwise keep scanning for
628
+ // the first user-authored prompt to title by.
629
+ if (preview)
630
+ break;
631
+ if (parsed.message?.role === "user") {
632
+ preview =
633
+ getUserSessionPrompt(parsed.message.content, parsed.message.provenance)
634
+ ?.replace(/\s+/g, " ")
635
+ .trim() || undefined;
636
+ if (preview)
637
+ break;
638
+ }
639
+ }
640
+ }
641
+ catch {
642
+ // Skip malformed lines while retaining readable entries around them.
643
+ }
644
+ }
645
+ }
646
+ finally {
647
+ // close() destroys the gunzip AND its source. Destroying only the
648
+ // stream orphans the underlying fd — this listing runs over every
649
+ // session on the machine, so that leaked one fd per archive per call.
650
+ rl.close();
651
+ close();
652
+ }
653
+ if (!first || first.type !== "session")
654
+ return null;
655
+ const stat = await fs.stat(resolvedPath);
656
+ return {
657
+ id: first.id,
658
+ conversationId: first.version === 2
659
+ ? (first.conversationId ?? first.id)
660
+ : first.id,
661
+ generation: first.version === 2 ? (first.generation ?? 0) : 0,
662
+ path: resolvedPath,
663
+ timestamp: first.timestamp,
664
+ lastActivity: stat.mtime.toISOString(),
665
+ cwd: first.cwd,
666
+ hasMessages,
667
+ ...(preview ? { preview: preview.slice(0, 100) } : {}),
668
+ };
669
+ }
670
+ catch {
671
+ return null;
672
+ }
673
+ }
674
+ /**
675
+ * Keep the newest file per conversation and sort newest first.
676
+ *
677
+ * A conversation can span several files (compaction forks a fresh one), so
678
+ * without this collapse a resumed thread appears once per checkpoint.
679
+ */
680
+ static dedupeByConversation(summaries) {
681
+ const byConversation = new Map();
682
+ const seenResolvedPaths = new Set();
683
+ for (const summary of summaries) {
684
+ if (!summary || seenResolvedPaths.has(summary.path))
685
+ continue;
686
+ seenResolvedPaths.add(summary.path);
687
+ const current = byConversation.get(summary.conversationId);
688
+ if (!current || SessionManager.compareCheckpoints(summary, current) > 0) {
689
+ byConversation.set(summary.conversationId, summary);
690
+ }
691
+ }
692
+ return [...byConversation.values()]
693
+ .sort((a, b) => b.lastActivity.localeCompare(a.lastActivity) ||
694
+ b.timestamp.localeCompare(a.timestamp) ||
695
+ b.path.localeCompare(a.path))
696
+ .map(({ conversationId: _conversationId, generation: _generation, ...info }) => info);
697
+ }
698
+ static compareCheckpoints(left, right) {
699
+ return ((left.generation ?? 0) - (right.generation ?? 0) ||
700
+ left.lastActivity.localeCompare(right.lastActivity) ||
701
+ left.timestamp.localeCompare(right.timestamp) ||
702
+ left.path.localeCompare(right.path));
703
+ }
704
+ async list(cwd) {
705
+ return this.summarize(this.dirForCwd(cwd));
706
+ }
707
+ /**
708
+ * One project's sessions, newest first, using the early-exit summary read.
709
+ *
710
+ * For callers that render a list rather than exact message counts — on a
711
+ * project with hundreds of sessions this is the difference between instant
712
+ * and a noticeable stall.
713
+ */
714
+ async listSummaries(cwd) {
715
+ return SessionManager.dedupeByConversation(await this.indexedSummaries(this.dirForCwd(cwd)));
716
+ }
717
+ /**
718
+ * Every session on this machine, across every project, newest first.
719
+ *
720
+ * A remote client is not browsing one checkout the way the TUI is — it is
721
+ * asking "what have I been working on?", and the answer spans projects. Each
722
+ * entry carries its own `cwd`, so the caller can group by project. Uses the
723
+ * early-exit summary read, because "every session on the machine" is exactly
724
+ * where a full parse of each file becomes a multi-second stall.
725
+ */
726
+ async listAllSummaries() {
727
+ return SessionManager.dedupeByConversation(await this.indexedSummariesIn(await this.storageDirectories()));
728
+ }
729
+ /**
730
+ * Summarize session files, keeping the newest file per conversation.
731
+ *
732
+ * A conversation can span several files (compaction forks a fresh one), so
733
+ * without this collapse a resumed thread appears once per checkpoint.
734
+ */
735
+ async summarize(directory) {
736
+ const resolved = path.resolve(directory);
737
+ let index = this.infoIndexes.get(resolved);
738
+ if (!index) {
739
+ index = SessionSummaryIndex.forInfo(resolved);
740
+ this.infoIndexes.set(resolved, index);
741
+ }
742
+ // Fingerprint-cached full parses: only files changed since the last scan
743
+ // are re-read, so results stay identical to a fresh full parse.
744
+ const summaries = await index.summaries(await this.sessionCandidates(resolved), (candidate) => this.readSessionInfo(candidate));
745
+ return SessionManager.dedupeByConversation(summaries);
746
+ }
747
+ async getMostRecent(cwd) {
748
+ const sessions = await this.list(cwd);
749
+ return sessions.find((session) => session.messageCount > 0)?.path ?? null;
750
+ }
751
+ /** Resolve an id, conversation id, or stale physical path to the newest checkpoint. */
752
+ async resolveCanonicalSession(requested, cwd) {
753
+ const looksLikePath = path.isAbsolute(requested) || requested.includes(path.sep) || isSessionPath(requested);
754
+ let directories;
755
+ let requestedSummary = null;
756
+ if (looksLikePath) {
757
+ requestedSummary = await this.readSessionSummary(requested);
758
+ if (!requestedSummary)
759
+ return null;
760
+ directories = [path.dirname(requestedSummary.path)];
761
+ }
762
+ else if (cwd) {
763
+ directories = [this.dirForCwd(cwd)];
764
+ }
765
+ else {
766
+ directories = await this.storageDirectories();
767
+ }
768
+ const summaries = (await this.indexedSummariesIn(directories)).filter((summary) => summary !== null);
769
+ if (requestedSummary && !summaries.some((summary) => summary.path === requestedSummary?.path)) {
770
+ summaries.push(requestedSummary);
771
+ }
772
+ const identityMatches = requestedSummary
773
+ ? [requestedSummary]
774
+ : summaries.filter((summary) => summary.id === requested || summary.conversationId === requested);
775
+ if (identityMatches.length === 0)
776
+ return null;
777
+ const requestedIdentity = identityMatches.sort((a, b) => SessionManager.compareCheckpoints(b, a))[0].conversationId;
778
+ const checkpoints = summaries.filter((summary) => summary.conversationId === requestedIdentity);
779
+ return (checkpoints.sort((a, b) => SessionManager.compareCheckpoints(b, a))[0]?.path ??
780
+ identityMatches[0].path);
781
+ }
782
+ async findById(cwd, sessionId) {
783
+ return this.resolveCanonicalSession(sessionId, cwd);
784
+ }
785
+ /** Locate and canonicalize a session identity across every project directory. */
786
+ async findAnyById(sessionId, cwd) {
787
+ if (cwd) {
788
+ const local = await this.resolveCanonicalSession(sessionId, cwd);
789
+ if (local)
790
+ return local;
791
+ }
792
+ return this.resolveCanonicalSession(sessionId);
793
+ }
794
+ async storageDirectories() {
795
+ let entries;
796
+ try {
797
+ entries = await fs.readdir(this.sessionsDir, { withFileTypes: true });
798
+ }
799
+ catch {
800
+ return [];
801
+ }
802
+ return entries
803
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
804
+ .map((entry) => path.join(this.sessionsDir, entry.name));
805
+ }
806
+ async logicalSessionBases(directory) {
807
+ let entries;
808
+ try {
809
+ entries = await fs.readdir(directory, { withFileTypes: true });
810
+ }
811
+ catch {
812
+ return [];
813
+ }
814
+ const bases = new Set();
815
+ for (const entry of entries) {
816
+ const entryPath = path.join(directory, entry.name);
817
+ if (entry.isFile() && isSessionPath(entry.name)) {
818
+ bases.add(path.resolve(plainSessionPath(entryPath)));
819
+ }
820
+ else if (entry.isDirectory() && entry.name.endsWith(".jsonl.assets")) {
821
+ bases.add(path.resolve(entryPath.slice(0, -".assets".length)));
822
+ }
823
+ else if (entry.isFile() && entry.name.endsWith(TURN_RECORD_SUFFIX)) {
824
+ // Sub-agent turn records (<child>.jsonl.turn.json) can outlive their
825
+ // transcript; track them so retention can clear the orphan too.
826
+ bases.add(path.resolve(entryPath.slice(0, -TURN_RECORD_SUFFIX.length)));
827
+ }
828
+ }
829
+ return [...bases];
830
+ }
831
+ async removeStoragePath(targetPath) {
832
+ let stat;
833
+ try {
834
+ stat = await fs.lstat(targetPath);
835
+ }
836
+ catch {
837
+ return { deletedFiles: 0, deletedBytes: 0 };
838
+ }
839
+ if (stat.isDirectory()) {
840
+ const result = { deletedFiles: 0, deletedBytes: 0 };
841
+ for (const name of await fs.readdir(targetPath)) {
842
+ const removed = await this.removeStoragePath(path.join(targetPath, name));
843
+ result.deletedFiles += removed.deletedFiles;
844
+ result.deletedBytes += removed.deletedBytes;
845
+ }
846
+ await fs.rmdir(targetPath).catch(() => { });
847
+ return result;
848
+ }
849
+ await fs.unlink(targetPath);
850
+ return { deletedFiles: 1, deletedBytes: stat.size };
851
+ }
852
+ async pruneOldSessions(options) {
853
+ const result = { deletedFiles: 0, freedBytes: 0 };
854
+ if (options.maxAgeDays <= 0)
855
+ return result;
856
+ const cutoffMs = Date.now() - options.maxAgeDays * 86_400_000;
857
+ // Resolved once per pass: re-resolving every keep path for every file was
858
+ // quadratic (1,200 keeps x 4,000 sessions held the event loop ~0.8s).
859
+ const keepBases = SessionManager.resolveKeepBases(options.keepPaths);
860
+ for (const directory of await this.storageDirectories()) {
861
+ for (const basePath of await this.logicalSessionBases(directory)) {
862
+ if (this.isProtectedSessionBase(basePath, keepBases))
863
+ continue;
864
+ try {
865
+ const resolved = await resolveSessionPath(basePath);
866
+ // An orphaned turn record (transcript already gone) ages on its own
867
+ // mtime; lstat so a symlink is judged — and later unlinked — as the
868
+ // link itself, never followed out of the sessions directory.
869
+ const stat = await fs
870
+ .stat(resolved)
871
+ .catch(() => fs.lstat(`${basePath}${TURN_RECORD_SUFFIX}`));
872
+ if (stat.mtimeMs >= cutoffMs)
873
+ continue;
874
+ for (const target of [
875
+ basePath,
876
+ archiveSessionPath(basePath),
877
+ sessionAssetDir(basePath),
878
+ `${basePath}${TURN_RECORD_SUFFIX}`,
879
+ ]) {
880
+ const removed = await this.removeStoragePath(target);
881
+ result.deletedFiles += removed.deletedFiles;
882
+ result.freedBytes += removed.deletedBytes;
883
+ }
884
+ }
885
+ catch {
886
+ // A raced, corrupt, or inaccessible logical group is skipped safely.
887
+ }
888
+ }
889
+ // The summary index is only a cache; drop it once no sessions remain so
890
+ // the emptied directory can still be removed.
891
+ if ((await this.sessionCandidates(directory)).length === 0) {
892
+ await fs.unlink(path.join(directory, SESSION_SUMMARY_INDEX_FILE)).catch(() => { });
893
+ await fs.unlink(path.join(directory, SESSION_INFO_INDEX_FILE)).catch(() => { });
894
+ this.summaryIndexes.delete(path.resolve(directory));
895
+ this.infoIndexes.delete(path.resolve(directory));
896
+ }
897
+ await fs.rmdir(directory).catch(() => { });
898
+ }
899
+ return result;
900
+ }
901
+ async runMaintenance(options) {
902
+ const existing = SessionManager.maintenanceByRoot.get(this.sessionsDir);
903
+ if (existing)
904
+ return existing;
905
+ const maintenance = this.runMaintenanceUnsafe(options).finally(() => {
906
+ SessionManager.maintenanceByRoot.delete(this.sessionsDir);
907
+ });
908
+ SessionManager.maintenanceByRoot.set(this.sessionsDir, maintenance);
909
+ return maintenance;
910
+ }
911
+ async runMaintenanceUnsafe(options) {
912
+ const metrics = {
913
+ deletedFiles: 0,
914
+ deletedBytes: 0,
915
+ archivedFiles: 0,
916
+ archivedSourceBytes: 0,
917
+ archivedBytes: 0,
918
+ bytesSaved: 0,
919
+ failures: 0,
920
+ ...emptyStorageNormalizationMetrics(),
921
+ };
922
+ const pruned = await this.pruneOldSessions({
923
+ maxAgeDays: options.retentionDays,
924
+ keepPaths: options.keepPaths,
925
+ });
926
+ metrics.deletedFiles = pruned.deletedFiles;
927
+ metrics.deletedBytes = pruned.freedBytes;
928
+ const now = options.now ?? Date.now();
929
+ const coldCutoff = now - COLD_SESSION_AGE_DAYS * 86_400_000;
930
+ const keepBases = SessionManager.resolveKeepBases(options.keepPaths);
931
+ for (const directory of await this.storageDirectories()) {
932
+ const tempCleanup = await cleanupOldSessionTemps(directory, now - 86_400_000);
933
+ metrics.deletedFiles += tempCleanup.deletedFiles;
934
+ metrics.deletedBytes += tempCleanup.freedBytes;
935
+ for (const basePath of await this.logicalSessionBases(directory)) {
936
+ if (this.isProtectedSessionBase(basePath, keepBases))
937
+ continue;
938
+ try {
939
+ const resolved = await resolveSessionPath(basePath);
940
+ const stat = await fs.stat(resolved);
941
+ if (stat.mtimeMs >= coldCutoff || resolved.endsWith(".jsonl.gz"))
942
+ continue;
943
+ const archived = await archiveColdSession(resolved);
944
+ if (!archived.archived)
945
+ continue;
946
+ metrics.archivedFiles += 1;
947
+ metrics.archivedSourceBytes += archived.sourceBytes;
948
+ metrics.archivedBytes += archived.archiveBytes;
949
+ metrics.bytesSaved += archived.bytesSaved;
950
+ metrics.truncatedToolTexts += archived.truncatedToolTexts;
951
+ metrics.externalizedMedia += archived.externalizedMedia;
952
+ metrics.omittedPathMedia += archived.omittedPathMedia;
953
+ metrics.removedDisplayItems += archived.removedDisplayItems;
954
+ }
955
+ catch (error) {
956
+ metrics.failures += 1;
957
+ log("WARN", "session", "Cold session maintenance failed", {
958
+ path: basePath,
959
+ message: error instanceof Error ? error.message : String(error),
960
+ });
961
+ }
962
+ }
963
+ }
964
+ return metrics;
965
+ }
966
+ async appendEntry(sessionPath, entry) {
967
+ try {
968
+ // Persist a sanitized, bounded clone. The live conversation remains
969
+ // untouched so the current turn keeps full tool output and media.
970
+ const safeEntry = redactValue(entry, { secrets: environmentSecrets(process.env) });
971
+ const writablePath = await thawSessionArchive(sessionPath);
972
+ const normalized = await normalizeSessionEntryForStorage(safeEntry, writablePath);
973
+ if (normalized === null)
974
+ return;
975
+ await this.sealTornTail(writablePath);
976
+ await fs.appendFile(writablePath, `${JSON.stringify(normalized)}\n`, "utf-8");
977
+ }
978
+ catch (error) {
979
+ this.handlePersistError(error, "appendEntry");
980
+ }
981
+ }
982
+ async appendTurnMetric(sessionPath, payload) {
983
+ const entry = {
984
+ type: "custom",
985
+ kind: TURN_METRIC_CUSTOM_KIND,
986
+ id: crypto.randomUUID(),
987
+ parentId: null,
988
+ timestamp: new Date().toISOString(),
989
+ data: payload,
990
+ };
991
+ await this.appendEntry(sessionPath, entry);
992
+ }
993
+ /** Open the run journal for one `RunLifecycle` generation. */
994
+ async appendRunStarted(sessionPath, payload) {
995
+ await this.appendEntry(sessionPath, {
996
+ type: "custom",
997
+ kind: RUN_STARTED_CUSTOM_KIND,
998
+ id: crypto.randomUUID(),
999
+ parentId: null,
1000
+ timestamp: new Date().toISOString(),
1001
+ data: payload,
1002
+ });
1003
+ }
1004
+ /** Close the run journal for one generation. Its absence marks a crashed run. */
1005
+ async appendRunFinished(sessionPath, payload) {
1006
+ await this.appendEntry(sessionPath, {
1007
+ type: "custom",
1008
+ kind: RUN_FINISHED_CUSTOM_KIND,
1009
+ id: crypto.randomUUID(),
1010
+ parentId: null,
1011
+ timestamp: new Date().toISOString(),
1012
+ data: payload,
1013
+ });
1014
+ }
1015
+ /**
1016
+ * Reconstruct the run journal in file order, pairing each `run_started` with
1017
+ * the `run_finished` carrying the same generation.
1018
+ *
1019
+ * Generations are NOT unique across a session file. `RunLifecycle` counts
1020
+ * from zero per instance, and a resumed session builds a fresh one — so the
1021
+ * first run after every app restart is generation 1 again. Pairing therefore
1022
+ * tracks only the runs still OPEN: a `run_finished` closes its generation and
1023
+ * releases the number, and a later `run_started` reusing it opens a new run.
1024
+ *
1025
+ * Without that release, a crash in a resumed session was invisible: the
1026
+ * reused `run_started` looked like a duplicate and was dropped, which is
1027
+ * exactly the case this journal exists to catch.
1028
+ *
1029
+ * A repeat `run_started` for a generation that is still open IS ignored, so a
1030
+ * truncated or replayed log reports one unfinished run — never a phantom pile.
1031
+ */
1032
+ getRunJournal(entries) {
1033
+ const runs = [];
1034
+ const openByGeneration = new Map();
1035
+ for (const entry of entries) {
1036
+ if (entry.type !== "custom")
1037
+ continue;
1038
+ if (entry.kind === RUN_STARTED_CUSTOM_KIND) {
1039
+ const p = entry.data;
1040
+ if (p?.version !== 1 || typeof p.generation !== "number")
1041
+ continue;
1042
+ if (openByGeneration.has(p.generation))
1043
+ continue;
1044
+ const run = {
1045
+ generation: p.generation,
1046
+ startedAt: typeof p.startedAt === "string" ? p.startedAt : entry.timestamp,
1047
+ afterMessageCount: typeof p.afterMessageCount === "number" ? p.afterMessageCount : 0,
1048
+ ...(typeof p.pid === "number" ? { pid: p.pid } : {}),
1049
+ };
1050
+ openByGeneration.set(p.generation, run);
1051
+ runs.push(run);
1052
+ continue;
1053
+ }
1054
+ if (entry.kind === RUN_FINISHED_CUSTOM_KIND) {
1055
+ const p = entry.data;
1056
+ if (p?.version !== 1 || typeof p.generation !== "number")
1057
+ continue;
1058
+ const run = openByGeneration.get(p.generation);
1059
+ if (!run || !p.outcome)
1060
+ continue;
1061
+ run.outcome = p.outcome;
1062
+ // Closed — the number is free for the next app run to reuse.
1063
+ openByGeneration.delete(p.generation);
1064
+ }
1065
+ }
1066
+ return runs;
1067
+ }
1068
+ /** Runs that opened the journal but never closed it — i.e. crashed mid-flight. */
1069
+ getUnfinishedRuns(entries) {
1070
+ return this.getRunJournal(entries).filter((run) => run.outcome === undefined);
1071
+ }
1072
+ async updateLeaf(sessionPath, leafId) {
1073
+ try {
1074
+ const writablePath = await thawSessionArchive(sessionPath);
1075
+ await this.updateLeafUnsafe(writablePath, leafId);
1076
+ }
1077
+ catch (error) {
1078
+ this.handlePersistError(error, "updateLeaf");
1079
+ }
1080
+ }
1081
+ async updateLeafUnsafe(sessionPath, leafId) {
1082
+ // Read only the first line (the header) instead of loading the entire file.
1083
+ // For large session files (100MB+), this avoids a full file read+write.
1084
+ const fd = await fs.open(sessionPath, "r+");
1085
+ try {
1086
+ // Read enough bytes to cover the header line (typically <500 bytes)
1087
+ const buf = Buffer.alloc(4096);
1088
+ const { bytesRead } = await fd.read(buf, 0, 4096, 0);
1089
+ const chunk = buf.toString("utf-8", 0, bytesRead);
1090
+ const newlineIdx = chunk.indexOf("\n");
1091
+ if (newlineIdx === -1)
1092
+ return;
1093
+ const headerLine = chunk.slice(0, newlineIdx);
1094
+ const header = JSON.parse(headerLine);
1095
+ if (header.type !== "session")
1096
+ return;
1097
+ header.leafId = leafId;
1098
+ const newHeaderLine = JSON.stringify(header);
1099
+ if (newHeaderLine.length === headerLine.length) {
1100
+ // Same length — overwrite in place (fast path)
1101
+ await fd.write(newHeaderLine, 0, "utf-8");
1102
+ }
1103
+ else {
1104
+ // Different length — must rewrite the file (rare: only on first leafId set)
1105
+ await fd.close();
1106
+ const content = await fs.readFile(sessionPath, "utf-8");
1107
+ const firstNewline = content.indexOf("\n");
1108
+ await fs.writeFile(sessionPath, newHeaderLine + content.slice(firstNewline), "utf-8");
1109
+ return;
1110
+ }
1111
+ }
1112
+ finally {
1113
+ // fd.close() may have already been called in the else branch above,
1114
+ // but calling it again on a closed handle is a no-op in Node >= 20.
1115
+ await fd.close().catch(() => { });
1116
+ }
1117
+ }
1118
+ /**
1119
+ * Get messages for the current branch. If leafId is set, walks the
1120
+ * DAG from leaf to root. Otherwise returns all entries linearly.
1121
+ */
1122
+ getMessages(entries, leafId) {
1123
+ const branch = leafId ? this.getBranch(entries, leafId) : entries;
1124
+ const messages = branch
1125
+ .filter((e) => e.type === "message")
1126
+ .map((e) => e.message)
1127
+ .filter((m) => m.role !== "system");
1128
+ // Repair orphaned tool_use blocks that lack matching tool_result messages.
1129
+ // This can happen when a session is interrupted mid-tool-execution.
1130
+ return SessionManager.repairToolPairs(messages);
1131
+ }
1132
+ /** Saved UI transcript items; `T` is the caller's own item type, which the engine doesn't check. */
1133
+ getDisplayItems(entries, _leafId) {
1134
+ return entries.flatMap((entry) => {
1135
+ if (entry.type !== "custom" || entry.kind !== DISPLAY_ITEM_CUSTOM_KIND)
1136
+ return [];
1137
+ const payload = entry.data;
1138
+ const item = payload?.version === 1 ? payload.item : undefined;
1139
+ return isDisplayItemLike(item) ? [item] : [];
1140
+ });
1141
+ }
1142
+ /**
1143
+ * Walk entries in file order, tracking how many branch (non-system) messages
1144
+ * have been written so far, and hand each custom entry that count. This is
1145
+ * the independent position estimate behind {@link RecordedPosition}.
1146
+ */
1147
+ mapCustomEntriesInFileOrder(entries, leafId, project) {
1148
+ // Only branch messages count — an off-branch fork's entries are not part of
1149
+ // the restored transcript the anchors are measured against.
1150
+ const onBranch = leafId
1151
+ ? new Set(this.getBranch(entries, leafId).map((e) => e.id))
1152
+ : new Set(entries.map((e) => e.id));
1153
+ const out = [];
1154
+ let messagesSoFar = 0;
1155
+ for (const entry of entries) {
1156
+ if (entry.type === "message") {
1157
+ if (onBranch.has(entry.id) && entry.message.role !== "system")
1158
+ messagesSoFar++;
1159
+ continue;
1160
+ }
1161
+ if (entry.type !== "custom")
1162
+ continue;
1163
+ out.push(...project(entry, messagesSoFar));
1164
+ }
1165
+ return out;
1166
+ }
1167
+ /** Read all persisted Ken turns in file order. Returns them regardless of
1168
+ * branch (Ken turns are not chained into the DAG), validated + normalized. */
1169
+ getKenTurns(entries, leafId) {
1170
+ return this.mapCustomEntriesInFileOrder(entries, leafId, (entry, recordedAfterMessageCount) => {
1171
+ if (entry.kind !== KEN_TURN_CUSTOM_KIND)
1172
+ return [];
1173
+ const p = entry.data;
1174
+ if (p?.version === 1 && typeof p.question === "string" && typeof p.reply === "string") {
1175
+ return [
1176
+ {
1177
+ version: 1,
1178
+ question: p.question,
1179
+ reply: p.reply,
1180
+ afterMessageCount: typeof p.afterMessageCount === "number" ? p.afterMessageCount : 0,
1181
+ recordedAfterMessageCount,
1182
+ },
1183
+ ];
1184
+ }
1185
+ return [];
1186
+ });
1187
+ }
1188
+ /** Read all persisted app transcript markers in file order, validated +
1189
+ * normalized (same not-on-the-DAG treatment as Ken turns). */
1190
+ getAppMarkers(entries, leafId) {
1191
+ return this.mapCustomEntriesInFileOrder(entries, leafId, (entry, recordedAfterMessageCount) => {
1192
+ if (entry.kind !== APP_MARKER_CUSTOM_KIND)
1193
+ return [];
1194
+ const p = entry.data;
1195
+ const kind = p?.kind;
1196
+ if (p?.version === 1 &&
1197
+ (kind === "plan" ||
1198
+ kind === "task" ||
1199
+ kind === "error" ||
1200
+ kind === "user_hint" ||
1201
+ kind === "compaction" ||
1202
+ kind === "agent_handoff" ||
1203
+ kind === "model_switch" ||
1204
+ kind === "import" ||
1205
+ kind === "interrupted_run" ||
1206
+ kind === "security" ||
1207
+ kind === "shell")) {
1208
+ return [
1209
+ {
1210
+ version: 1,
1211
+ kind,
1212
+ afterMessageCount: typeof p.afterMessageCount === "number" ? p.afterMessageCount : 0,
1213
+ data: typeof p.data === "object" && p.data !== null ? p.data : {},
1214
+ recordedAfterMessageCount,
1215
+ },
1216
+ ];
1217
+ }
1218
+ return [];
1219
+ });
1220
+ }
1221
+ /** Read validated per-turn usage and timing records in file order. */
1222
+ getTurnMetrics(entries) {
1223
+ return entries.flatMap((entry) => {
1224
+ if (entry.type !== "custom" || entry.kind !== TURN_METRIC_CUSTOM_KIND)
1225
+ return [];
1226
+ const metric = parseTurnMetric(entry.data);
1227
+ return metric ? [metric] : [];
1228
+ });
1229
+ }
1230
+ /** Read all persisted autopilot markers in file order, validated + normalized
1231
+ * (same not-on-the-DAG treatment as Ken turns). */
1232
+ getAutopilotMarkers(entries, leafId) {
1233
+ return this.mapCustomEntriesInFileOrder(entries, leafId, (entry, recordedAfterMessageCount) => {
1234
+ if (entry.kind !== AUTOPILOT_MARKER_CUSTOM_KIND)
1235
+ return [];
1236
+ const p = entry.data;
1237
+ const phase = p?.phase;
1238
+ if (p?.version === 1 &&
1239
+ (phase === "prompted" ||
1240
+ phase === "done" ||
1241
+ phase === "human" ||
1242
+ phase === "capped" ||
1243
+ phase === "plan_approved")) {
1244
+ return [
1245
+ {
1246
+ version: 1,
1247
+ phase,
1248
+ ...(typeof p.reason === "string" ? { reason: p.reason } : {}),
1249
+ ...(typeof p.body === "string" ? { body: p.body } : {}),
1250
+ afterMessageCount: typeof p.afterMessageCount === "number" ? p.afterMessageCount : 0,
1251
+ recordedAfterMessageCount,
1252
+ },
1253
+ ];
1254
+ }
1255
+ return [];
1256
+ });
1257
+ }
1258
+ /**
1259
+ * Ensure every assistant message with tool_use blocks is followed by a tool
1260
+ * message containing matching tool_result entries. Inserts synthetic
1261
+ * tool_result messages where needed to prevent Anthropic API 400 errors.
1262
+ */
1263
+ static repairToolPairs(messages) {
1264
+ const repaired = [];
1265
+ for (let i = 0; i < messages.length; i++) {
1266
+ const msg = messages[i];
1267
+ repaired.push(msg);
1268
+ if (msg.role !== "assistant")
1269
+ continue;
1270
+ const content = Array.isArray(msg.content) ? msg.content : [];
1271
+ const toolUses = content
1272
+ .filter((p) => p.type === "tool_call")
1273
+ .map((p) => p);
1274
+ if (toolUses.length === 0)
1275
+ continue;
1276
+ // The transcript stops before the result, so whether the tool ran is
1277
+ // unrecoverable here. Say "unknown" rather than "interrupted": a resumed
1278
+ // session must not re-run a push or a migration that already landed.
1279
+ const repair = (call) => ({
1280
+ type: "tool_result",
1281
+ toolCallId: call.id,
1282
+ content: indeterminateOutcomeText(call.name),
1283
+ isError: true,
1284
+ });
1285
+ // Check if the next message is a tool message with matching results
1286
+ const next = messages[i + 1];
1287
+ if (next?.role === "tool" && Array.isArray(next.content)) {
1288
+ const existingIds = new Set(next.content.map((r) => r.toolCallId));
1289
+ for (const call of toolUses) {
1290
+ if (existingIds.has(call.id))
1291
+ continue;
1292
+ next.content.push(repair(call));
1293
+ }
1294
+ }
1295
+ else {
1296
+ // No tool message follows — insert a synthetic one
1297
+ repaired.push({ role: "tool", content: toolUses.map(repair) });
1298
+ }
1299
+ }
1300
+ return repaired;
1301
+ }
1302
+ /**
1303
+ * Build a lookup Map from entry id → entry. Reusable across multiple
1304
+ * getBranch / listBranches calls on the same entry set.
1305
+ */
1306
+ buildIndex(entries) {
1307
+ return new Map(entries.map((e) => [e.id, e]));
1308
+ }
1309
+ /**
1310
+ * Walk the DAG from a leaf entry back to the root, returning entries
1311
+ * in chronological order (root → leaf). This is the "branch" — the
1312
+ * path through the conversation tree that leads to the given leaf.
1313
+ *
1314
+ * Accepts an optional pre-built index to avoid redundant Map allocations
1315
+ * when called in a loop.
1316
+ */
1317
+ getBranch(entries, leafId, byId) {
1318
+ if (!leafId)
1319
+ return entries;
1320
+ const index = byId ?? this.buildIndex(entries);
1321
+ const branch = [];
1322
+ let current = leafId;
1323
+ while (current) {
1324
+ const entry = index.get(current);
1325
+ if (!entry)
1326
+ break;
1327
+ branch.push(entry);
1328
+ current = entry.parentId;
1329
+ }
1330
+ return branch.reverse();
1331
+ }
1332
+ /**
1333
+ * List all branches (leaf nodes) in a session's entry DAG.
1334
+ * A leaf is any entry whose id is not referenced as a parentId by any other entry.
1335
+ */
1336
+ listBranches(entries) {
1337
+ if (entries.length === 0)
1338
+ return [];
1339
+ // Build shared index once — reused by every getBranch call below
1340
+ const byId = this.buildIndex(entries);
1341
+ // Find all ids that are referenced as parentId
1342
+ const parentIds = new Set(entries.map((e) => e.parentId).filter(Boolean));
1343
+ // Leaves = entries whose id is NOT in parentIds
1344
+ const leaves = entries.filter((e) => !parentIds.has(e.id));
1345
+ // Build childCount once — was previously rebuilt per-leaf (O(n²))
1346
+ const childCount = new Map();
1347
+ for (const e of entries) {
1348
+ childCount.set(e.parentId, (childCount.get(e.parentId) ?? 0) + 1);
1349
+ }
1350
+ return leaves.map((leaf) => {
1351
+ const branch = this.getBranch(entries, leaf.id, byId);
1352
+ let branchPointId = branch[0]?.id ?? leaf.id;
1353
+ for (const e of branch) {
1354
+ if ((childCount.get(e.parentId) ?? 0) > 1) {
1355
+ branchPointId = e.id;
1356
+ break;
1357
+ }
1358
+ }
1359
+ return {
1360
+ branchPointId,
1361
+ leafId: leaf.id,
1362
+ entryCount: branch.length,
1363
+ timestamp: branch[0]?.timestamp ?? leaf.timestamp,
1364
+ };
1365
+ });
1366
+ }
1367
+ }
1368
+ //# sourceMappingURL=session-manager.js.map