@opengsd/gsd-pi 1.2.0-dev.955e4da0 → 1.2.0-dev.a6376d75

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 (726) hide show
  1. package/dist/cli-model-override.d.ts +15 -0
  2. package/dist/cli-model-override.js +21 -0
  3. package/dist/cli-style.d.ts +17 -0
  4. package/dist/cli-style.js +28 -0
  5. package/dist/cli.js +2 -19
  6. package/dist/headless-events.d.ts +4 -2
  7. package/dist/headless-events.js +14 -34
  8. package/dist/loader.js +6 -4
  9. package/dist/mcp-server.js +2 -1
  10. package/dist/models-resolver.d.ts +3 -13
  11. package/dist/models-resolver.js +3 -22
  12. package/dist/register-agent-bundles.d.ts +11 -2
  13. package/dist/register-agent-bundles.js +18 -4
  14. package/dist/resource-loader.d.ts +10 -5
  15. package/dist/resource-loader.js +123 -20
  16. package/dist/resources/.managed-resources-content-hash +1 -1
  17. package/dist/resources/GSD-WORKFLOW.md +5 -4
  18. package/dist/resources/extensions/ask-user-questions.js +3 -2
  19. package/dist/resources/extensions/async-jobs/async-bash-tool.js +30 -64
  20. package/dist/resources/extensions/async-jobs/await-tool.js +80 -12
  21. package/dist/resources/extensions/async-jobs/index.js +65 -0
  22. package/dist/resources/extensions/async-jobs/job-manager.js +12 -1
  23. package/dist/resources/extensions/bg-shell/bg-shell-command.js +6 -6
  24. package/dist/resources/extensions/bg-shell/bg-shell-tool.js +10 -7
  25. package/dist/resources/extensions/bg-shell/overlay.js +9 -6
  26. package/dist/resources/extensions/bg-shell/process-manager.js +54 -25
  27. package/dist/resources/extensions/bg-shell/readiness-detector.js +11 -0
  28. package/dist/resources/extensions/bg-shell/utilities.js +3 -0
  29. package/dist/resources/extensions/browser-tools/engine/managed-gsd-browser.js +209 -88
  30. package/dist/resources/extensions/browser-tools/engine/selection.js +73 -5
  31. package/dist/resources/extensions/browser-tools/index.js +69 -12
  32. package/dist/resources/extensions/claude-code-cli/stream-adapter.js +456 -198
  33. package/dist/resources/extensions/claude-code-cli/turn-assembler.js +33 -1
  34. package/dist/resources/extensions/gsd/auto/closeout.js +215 -0
  35. package/dist/resources/extensions/gsd/auto/custom-verify-retry-store.js +17 -2
  36. package/dist/resources/extensions/gsd/auto/detect-stuck.js +33 -13
  37. package/dist/resources/extensions/gsd/auto/dispatch-history.js +120 -0
  38. package/dist/resources/extensions/gsd/auto/dispatch-key.js +37 -0
  39. package/dist/resources/extensions/gsd/auto/dispatch.js +365 -0
  40. package/dist/resources/extensions/gsd/auto/finalize.js +347 -0
  41. package/dist/resources/extensions/gsd/auto/loop.js +7 -1
  42. package/dist/resources/extensions/gsd/auto/milestone-lease-reclaim.js +56 -0
  43. package/dist/resources/extensions/gsd/auto/orchestrator.js +174 -69
  44. package/dist/resources/extensions/gsd/auto/phase-helpers.js +146 -0
  45. package/dist/resources/extensions/gsd/auto/phases.js +17 -2329
  46. package/dist/resources/extensions/gsd/auto/pre-dispatch.js +534 -0
  47. package/dist/resources/extensions/gsd/auto/session.js +3 -0
  48. package/dist/resources/extensions/gsd/auto/unit-phase.js +694 -0
  49. package/dist/resources/extensions/gsd/auto/workflow-unit-dispatch.js +1 -1
  50. package/dist/resources/extensions/gsd/auto/worktree-safety-phase.js +125 -0
  51. package/dist/resources/extensions/gsd/auto-direct-dispatch.js +11 -34
  52. package/dist/resources/extensions/gsd/auto-dispatch.js +50 -58
  53. package/dist/resources/extensions/gsd/auto-model-selection.js +36 -13
  54. package/dist/resources/extensions/gsd/auto-post-unit.js +35 -8
  55. package/dist/resources/extensions/gsd/auto-prompts.js +81 -19
  56. package/dist/resources/extensions/gsd/auto-start.js +41 -18
  57. package/dist/resources/extensions/gsd/auto-tool-tracking.js +18 -0
  58. package/dist/resources/extensions/gsd/auto-unit-closeout.js +45 -21
  59. package/dist/resources/extensions/gsd/auto-unit-tool-scope.js +12 -20
  60. package/dist/resources/extensions/gsd/auto-verification.js +23 -30
  61. package/dist/resources/extensions/gsd/auto-worktree.js +45 -92
  62. package/dist/resources/extensions/gsd/auto.js +56 -15
  63. package/dist/resources/extensions/gsd/blocked-models.js +28 -0
  64. package/dist/resources/extensions/gsd/bootstrap/agent-end-recovery.js +29 -8
  65. package/dist/resources/extensions/gsd/bootstrap/dynamic-tools.js +60 -13
  66. package/dist/resources/extensions/gsd/bootstrap/exec-tools.js +2 -2
  67. package/dist/resources/extensions/gsd/bootstrap/register-extension.js +19 -0
  68. package/dist/resources/extensions/gsd/bootstrap/register-hooks.js +212 -48
  69. package/dist/resources/extensions/gsd/bootstrap/write-gate.js +303 -77
  70. package/dist/resources/extensions/gsd/branch-patterns.js +2 -0
  71. package/dist/resources/extensions/gsd/browser-daemon-auto-prep.js +83 -0
  72. package/dist/resources/extensions/gsd/browser-evidence.js +8 -2
  73. package/dist/resources/extensions/gsd/captures.js +4 -6
  74. package/dist/resources/extensions/gsd/closeout-wizard.js +92 -0
  75. package/dist/resources/extensions/gsd/commands/context.js +16 -2
  76. package/dist/resources/extensions/gsd/commands-handlers.js +46 -3
  77. package/dist/resources/extensions/gsd/commands-mcp-status.js +2 -2
  78. package/dist/resources/extensions/gsd/commands-workflow-templates.js +9 -2
  79. package/dist/resources/extensions/gsd/consent-question.js +353 -0
  80. package/dist/resources/extensions/gsd/consent-verdict.js +63 -0
  81. package/dist/resources/extensions/gsd/constants.js +0 -2
  82. package/dist/resources/extensions/gsd/crash-recovery.js +12 -15
  83. package/dist/resources/extensions/gsd/db/queries.js +56 -0
  84. package/dist/resources/extensions/gsd/db-writer.js +8 -17
  85. package/dist/resources/extensions/gsd/dispatch-guard.js +10 -35
  86. package/dist/resources/extensions/gsd/doctor-engine-checks.js +5 -5
  87. package/dist/resources/extensions/gsd/doctor-environment.js +258 -131
  88. package/dist/resources/extensions/gsd/doctor-format.js +9 -6
  89. package/dist/resources/extensions/gsd/doctor-git-checks.js +2 -18
  90. package/dist/resources/extensions/gsd/doctor-runtime-checks.js +13 -15
  91. package/dist/resources/extensions/gsd/engine-hook-contract.js +70 -0
  92. package/dist/resources/extensions/gsd/error-classifier.js +9 -0
  93. package/dist/resources/extensions/gsd/exec-sandbox.js +30 -10
  94. package/dist/resources/extensions/gsd/files.js +33 -19
  95. package/dist/resources/extensions/gsd/gsd-command-home.js +22 -12
  96. package/dist/resources/extensions/gsd/gsd-db.js +2 -1
  97. package/dist/resources/extensions/gsd/guidance.js +158 -0
  98. package/dist/resources/extensions/gsd/guided-flow.js +110 -6
  99. package/dist/resources/extensions/gsd/health-widget.js +87 -28
  100. package/dist/resources/extensions/gsd/markdown-renderer.js +10 -0
  101. package/dist/resources/extensions/gsd/mcp-bridge.js +10 -0
  102. package/dist/resources/extensions/gsd/mcp-filter.js +2 -19
  103. package/dist/resources/extensions/gsd/mcp-tool-name.js +5 -13
  104. package/dist/resources/extensions/gsd/memory-consolidation-scanner.js +1 -1
  105. package/dist/resources/extensions/gsd/migrate/safety.js +4 -1
  106. package/dist/resources/extensions/gsd/milestone-closeout.js +85 -24
  107. package/dist/resources/extensions/gsd/milestone-planning-persistence.js +2 -2
  108. package/dist/resources/extensions/gsd/milestone-reopen-events.js +3 -5
  109. package/dist/resources/extensions/gsd/milestone-settlement.js +2 -2
  110. package/dist/resources/extensions/gsd/notification-store.js +11 -4
  111. package/dist/resources/extensions/gsd/notifications.js +12 -7
  112. package/dist/resources/extensions/gsd/parallel-monitor-overlay.js +6 -4
  113. package/dist/resources/extensions/gsd/parsers-legacy.js +16 -4
  114. package/dist/resources/extensions/gsd/paths.js +27 -0
  115. package/dist/resources/extensions/gsd/pre-execution-checks.js +91 -3
  116. package/dist/resources/extensions/gsd/preferences-models.js +14 -48
  117. package/dist/resources/extensions/gsd/projection-flush.js +7 -0
  118. package/dist/resources/extensions/gsd/prompts/complete-slice.md +4 -4
  119. package/dist/resources/extensions/gsd/prompts/execute-task.md +3 -2
  120. package/dist/resources/extensions/gsd/prompts/plan-milestone.md +1 -1
  121. package/dist/resources/extensions/gsd/prompts/plan-slice.md +2 -2
  122. package/dist/resources/extensions/gsd/prompts/quick-task.md +1 -1
  123. package/dist/resources/extensions/gsd/prompts/reassess-roadmap.md +1 -1
  124. package/dist/resources/extensions/gsd/prompts/refine-slice.md +2 -2
  125. package/dist/resources/extensions/gsd/prompts/replan-slice.md +2 -2
  126. package/dist/resources/extensions/gsd/prompts/research-milestone.md +1 -1
  127. package/dist/resources/extensions/gsd/prompts/research-slice.md +1 -1
  128. package/dist/resources/extensions/gsd/prompts/rewrite-docs.md +1 -1
  129. package/dist/resources/extensions/gsd/prompts/run-uat.md +9 -5
  130. package/dist/resources/extensions/gsd/prompts/system.md +5 -2
  131. package/dist/resources/extensions/gsd/prompts/triage-captures.md +1 -1
  132. package/dist/resources/extensions/gsd/prompts/validate-milestone.md +1 -1
  133. package/dist/resources/extensions/gsd/prompts/workflow-start.md +2 -1
  134. package/dist/resources/extensions/gsd/provider-error-guidance.js +1 -5
  135. package/dist/resources/extensions/gsd/provider-switch-observer.js +1 -1
  136. package/dist/resources/extensions/gsd/publication.js +87 -0
  137. package/dist/resources/extensions/gsd/reactive-graph.js +8 -1
  138. package/dist/resources/extensions/gsd/recovery-classification.js +37 -94
  139. package/dist/resources/extensions/gsd/roadmap-slices.js +25 -3
  140. package/dist/resources/extensions/gsd/safety/destructive-confirmation.js +108 -0
  141. package/dist/resources/extensions/gsd/session-lock.js +1 -1
  142. package/dist/resources/extensions/gsd/skill-activation.js +3 -6
  143. package/dist/resources/extensions/gsd/state.js +12 -22
  144. package/dist/resources/extensions/gsd/stop-notice.js +57 -0
  145. package/dist/resources/extensions/gsd/tool-contract.js +14 -3
  146. package/dist/resources/extensions/gsd/tool-presentation-plan.js +4 -4
  147. package/dist/resources/extensions/gsd/tool-surface-readiness.js +108 -0
  148. package/dist/resources/extensions/gsd/tools/complete-milestone.js +3 -2
  149. package/dist/resources/extensions/gsd/tools/complete-slice.js +22 -12
  150. package/dist/resources/extensions/gsd/tools/complete-task.js +65 -2
  151. package/dist/resources/extensions/gsd/tools/exec-tool.js +9 -7
  152. package/dist/resources/extensions/gsd/tools/plan-slice.js +14 -8
  153. package/dist/resources/extensions/gsd/tools/plan-task.js +2 -2
  154. package/dist/resources/extensions/gsd/tools/reassess-roadmap.js +2 -2
  155. package/dist/resources/extensions/gsd/tools/reopen-milestone.js +2 -2
  156. package/dist/resources/extensions/gsd/tools/reopen-slice.js +2 -2
  157. package/dist/resources/extensions/gsd/tools/reopen-task.js +2 -2
  158. package/dist/resources/extensions/gsd/tools/replan-slice.js +2 -2
  159. package/dist/resources/extensions/gsd/tools/workflow-tool-executors.js +67 -2
  160. package/dist/resources/extensions/gsd/uat-policy.js +42 -16
  161. package/dist/resources/extensions/gsd/unit-closeout.js +138 -0
  162. package/dist/resources/extensions/gsd/unit-context-composer.js +74 -1
  163. package/dist/resources/extensions/gsd/unit-context-manifest.js +4 -27
  164. package/dist/resources/extensions/gsd/unit-registry.js +367 -0
  165. package/dist/resources/extensions/gsd/unit-tool-contracts.js +9 -182
  166. package/dist/resources/extensions/gsd/verdict-parser.js +1 -1
  167. package/dist/resources/extensions/gsd/verification-verdict.js +2 -1
  168. package/dist/resources/extensions/gsd/web-app-uat.js +45 -8
  169. package/dist/resources/extensions/gsd/workflow-event-ledger.js +91 -0
  170. package/dist/resources/extensions/gsd/workflow-event-vocabulary.js +46 -0
  171. package/dist/resources/extensions/gsd/workflow-events.js +6 -18
  172. package/dist/resources/extensions/gsd/workflow-mcp-auto-prep.js +2 -0
  173. package/dist/resources/extensions/gsd/workflow-mcp-readiness-cache.js +105 -0
  174. package/dist/resources/extensions/gsd/workflow-reconcile.js +21 -56
  175. package/dist/resources/extensions/gsd/workflow-tool-surface.js +1 -1
  176. package/dist/resources/extensions/gsd/worktree-git-recovery.js +15 -9
  177. package/dist/resources/extensions/gsd/worktree-lifecycle.js +3 -2
  178. package/dist/resources/extensions/gsd/worktree-manager.js +7 -1
  179. package/dist/resources/extensions/gsd/worktree-root.js +11 -0
  180. package/dist/resources/extensions/gsd/worktree-safety.js +28 -26
  181. package/dist/resources/extensions/gsd/worktree-session-state.js +4 -5
  182. package/dist/resources/extensions/gsd/worktree.js +8 -1
  183. package/dist/resources/extensions/mcp-client/manager.js +6 -1
  184. package/dist/resources/extensions/search-the-web/native-search.js +5 -3
  185. package/dist/resources/extensions/shared/browser-contract.js +59 -0
  186. package/dist/resources/extensions/shared/gsd-browser-cli.js +116 -6
  187. package/dist/resources/shared/gsd-browser-path-sync.js +214 -0
  188. package/dist/resources/shared/package-manager-detection.js +1 -1
  189. package/dist/resources/shared/package.json +3 -0
  190. package/dist/resources/skills/create-skill/SKILL.md +3 -0
  191. package/dist/resources/skills/create-skill/references/executable-code.md +1 -1
  192. package/dist/resources/skills/create-skill/references/skill-structure.md +1 -0
  193. package/dist/resources/skills/create-skill/workflows/add-reference.md +8 -3
  194. package/dist/resources/skills/create-skill/workflows/add-script.md +4 -2
  195. package/dist/resources/skills/create-skill/workflows/add-template.md +3 -1
  196. package/dist/resources/skills/create-skill/workflows/add-workflow.md +8 -3
  197. package/dist/resources/skills/create-skill/workflows/upgrade-to-router.md +10 -5
  198. package/dist/resources/skills/create-skill/workflows/verify-skill.md +9 -4
  199. package/dist/resources/skills/spike-wrap-up/SKILL.md +9 -9
  200. package/dist/runtime-checks.d.ts +10 -0
  201. package/dist/runtime-checks.js +27 -0
  202. package/dist/tsconfig.extensions.tsbuildinfo +1 -1
  203. package/dist/update-check.d.ts +2 -0
  204. package/dist/update-check.js +24 -1
  205. package/dist/update-cmd.js +20 -3
  206. package/dist/web/standalone/.next/BUILD_ID +1 -1
  207. package/dist/web/standalone/.next/app-path-routes-manifest.json +13 -13
  208. package/dist/web/standalone/.next/build-manifest.json +3 -3
  209. package/dist/web/standalone/.next/prerender-manifest.json +3 -3
  210. package/dist/web/standalone/.next/react-loadable-manifest.json +1 -1
  211. package/dist/web/standalone/.next/server/app/_global-error.html +1 -1
  212. package/dist/web/standalone/.next/server/app/_global-error.rsc +1 -1
  213. package/dist/web/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  214. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  215. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  216. package/dist/web/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  217. package/dist/web/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  218. package/dist/web/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  219. package/dist/web/standalone/.next/server/app/_not-found.html +1 -1
  220. package/dist/web/standalone/.next/server/app/_not-found.rsc +1 -1
  221. package/dist/web/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  222. package/dist/web/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  223. package/dist/web/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  224. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  225. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  226. package/dist/web/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  227. package/dist/web/standalone/.next/server/app/api/update/route.js +1 -1
  228. package/dist/web/standalone/.next/server/app/api/update/route.js.nft.json +1 -1
  229. package/dist/web/standalone/.next/server/app/index.html +1 -1
  230. package/dist/web/standalone/.next/server/app/index.rsc +1 -1
  231. package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  232. package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +1 -1
  233. package/dist/web/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  234. package/dist/web/standalone/.next/server/app/index.segments/_index.segment.rsc +1 -1
  235. package/dist/web/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  236. package/dist/web/standalone/.next/server/app-paths-manifest.json +13 -13
  237. package/dist/web/standalone/.next/server/chunks/5124.js +1 -1
  238. package/dist/web/standalone/.next/server/chunks/8357.js +2 -2
  239. package/dist/web/standalone/.next/server/middleware-build-manifest.js +1 -1
  240. package/dist/web/standalone/.next/server/middleware-react-loadable-manifest.js +1 -1
  241. package/dist/web/standalone/.next/server/pages/404.html +1 -1
  242. package/dist/web/standalone/.next/server/pages/500.html +1 -1
  243. package/dist/web/standalone/.next/server/server-reference-manifest.json +1 -1
  244. package/dist/web/standalone/.next/static/chunks/{796.cf859a427a2cb2ac.js → 796.e0bdc932325d7e03.js} +1 -1
  245. package/dist/web/standalone/.next/static/chunks/{webpack-fbea77b5f9953368.js → webpack-f0285ce91d4ec9ef.js} +1 -1
  246. package/dist/web/standalone/node_modules/node-pty/build/Makefile +1 -1
  247. package/dist/web/standalone/package.json +1 -1
  248. package/dist/worktree-cli.js +3 -6
  249. package/dist/worktree-status-banner.js +7 -15
  250. package/package.json +3 -3
  251. package/packages/cloud-mcp-gateway/package.json +2 -2
  252. package/packages/contracts/dist/rpc.d.ts +1 -0
  253. package/packages/contracts/dist/rpc.d.ts.map +1 -1
  254. package/packages/contracts/dist/rpc.js.map +1 -1
  255. package/packages/contracts/dist/workflow.d.ts +4 -0
  256. package/packages/contracts/dist/workflow.d.ts.map +1 -1
  257. package/packages/contracts/dist/workflow.js.map +1 -1
  258. package/packages/contracts/package.json +1 -1
  259. package/packages/daemon/package.json +4 -4
  260. package/packages/gsd-agent-core/dist/sdk.d.ts.map +1 -1
  261. package/packages/gsd-agent-core/dist/sdk.js +6 -4
  262. package/packages/gsd-agent-core/dist/sdk.js.map +1 -1
  263. package/packages/gsd-agent-core/package.json +5 -5
  264. package/packages/gsd-agent-modes/dist/modes/interactive/components/settings-selector.d.ts +2 -0
  265. package/packages/gsd-agent-modes/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  266. package/packages/gsd-agent-modes/dist/modes/interactive/components/settings-selector.js +10 -0
  267. package/packages/gsd-agent-modes/dist/modes/interactive/components/settings-selector.js.map +1 -1
  268. package/packages/gsd-agent-modes/dist/modes/interactive/components/tool-execution.d.ts +13 -0
  269. package/packages/gsd-agent-modes/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  270. package/packages/gsd-agent-modes/dist/modes/interactive/components/tool-execution.js +55 -6
  271. package/packages/gsd-agent-modes/dist/modes/interactive/components/tool-execution.js.map +1 -1
  272. package/packages/gsd-agent-modes/dist/modes/interactive/components/transcript-design.d.ts +2 -0
  273. package/packages/gsd-agent-modes/dist/modes/interactive/components/transcript-design.d.ts.map +1 -1
  274. package/packages/gsd-agent-modes/dist/modes/interactive/components/transcript-design.js +34 -5
  275. package/packages/gsd-agent-modes/dist/modes/interactive/components/transcript-design.js.map +1 -1
  276. package/packages/gsd-agent-modes/dist/modes/interactive/controllers/chat-controller.d.ts.map +1 -1
  277. package/packages/gsd-agent-modes/dist/modes/interactive/controllers/chat-controller.js +7 -0
  278. package/packages/gsd-agent-modes/dist/modes/interactive/controllers/chat-controller.js.map +1 -1
  279. package/packages/gsd-agent-modes/dist/modes/interactive/controllers/input-controller.d.ts.map +1 -1
  280. package/packages/gsd-agent-modes/dist/modes/interactive/controllers/input-controller.js +8 -1
  281. package/packages/gsd-agent-modes/dist/modes/interactive/controllers/input-controller.js.map +1 -1
  282. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-chat-render.d.ts.map +1 -1
  283. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-chat-render.js +11 -1
  284. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-chat-render.js.map +1 -1
  285. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode.d.ts +1 -0
  286. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  287. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode.js +12 -0
  288. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode.js.map +1 -1
  289. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-selectors-auth.d.ts.map +1 -1
  290. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-selectors-auth.js +4 -4
  291. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-selectors-auth.js.map +1 -1
  292. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-selectors-settings.d.ts.map +1 -1
  293. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-selectors-settings.js +4 -0
  294. package/packages/gsd-agent-modes/dist/modes/interactive/interactive-selectors-settings.js.map +1 -1
  295. package/packages/gsd-agent-modes/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  296. package/packages/gsd-agent-modes/dist/modes/rpc/rpc-mode.js +3 -1
  297. package/packages/gsd-agent-modes/dist/modes/rpc/rpc-mode.js.map +1 -1
  298. package/packages/gsd-agent-modes/package.json +7 -7
  299. package/packages/mcp-server/README.md +12 -3
  300. package/packages/mcp-server/dist/cli-runner.d.ts +40 -0
  301. package/packages/mcp-server/dist/cli-runner.d.ts.map +1 -0
  302. package/packages/mcp-server/dist/cli-runner.js +137 -0
  303. package/packages/mcp-server/dist/cli-runner.js.map +1 -0
  304. package/packages/mcp-server/dist/cli.js +2 -50
  305. package/packages/mcp-server/dist/cli.js.map +1 -1
  306. package/packages/mcp-server/dist/moonshot-tool-schema.d.ts +29 -0
  307. package/packages/mcp-server/dist/moonshot-tool-schema.d.ts.map +1 -0
  308. package/packages/mcp-server/dist/moonshot-tool-schema.js +50 -0
  309. package/packages/mcp-server/dist/moonshot-tool-schema.js.map +1 -0
  310. package/packages/mcp-server/dist/pid-registry.d.ts +46 -0
  311. package/packages/mcp-server/dist/pid-registry.d.ts.map +1 -0
  312. package/packages/mcp-server/dist/pid-registry.js +452 -0
  313. package/packages/mcp-server/dist/pid-registry.js.map +1 -0
  314. package/packages/mcp-server/dist/probe-mode.d.ts +4 -0
  315. package/packages/mcp-server/dist/probe-mode.d.ts.map +1 -0
  316. package/packages/mcp-server/dist/probe-mode.js +10 -0
  317. package/packages/mcp-server/dist/probe-mode.js.map +1 -0
  318. package/packages/mcp-server/dist/server.d.ts.map +1 -1
  319. package/packages/mcp-server/dist/server.js +4 -0
  320. package/packages/mcp-server/dist/server.js.map +1 -1
  321. package/packages/mcp-server/dist/stdio-watchdog.d.ts +8 -0
  322. package/packages/mcp-server/dist/stdio-watchdog.d.ts.map +1 -0
  323. package/packages/mcp-server/dist/stdio-watchdog.js +40 -0
  324. package/packages/mcp-server/dist/stdio-watchdog.js.map +1 -0
  325. package/packages/mcp-server/dist/workflow-tools.d.ts +26 -18
  326. package/packages/mcp-server/dist/workflow-tools.d.ts.map +1 -1
  327. package/packages/mcp-server/dist/workflow-tools.js +178 -82
  328. package/packages/mcp-server/dist/workflow-tools.js.map +1 -1
  329. package/packages/mcp-server/package.json +5 -4
  330. package/packages/native/package.json +1 -1
  331. package/packages/pi-agent-core/dist/agent-loop.js +43 -2
  332. package/packages/pi-agent-core/dist/agent-loop.js.map +1 -1
  333. package/packages/pi-agent-core/dist/harness/env/nodejs.d.ts +1 -0
  334. package/packages/pi-agent-core/dist/harness/env/nodejs.d.ts.map +1 -1
  335. package/packages/pi-agent-core/dist/harness/env/nodejs.js +34 -3
  336. package/packages/pi-agent-core/dist/harness/env/nodejs.js.map +1 -1
  337. package/packages/pi-agent-core/dist/index.d.ts +1 -0
  338. package/packages/pi-agent-core/dist/index.d.ts.map +1 -1
  339. package/packages/pi-agent-core/dist/index.js +3 -0
  340. package/packages/pi-agent-core/dist/index.js.map +1 -1
  341. package/packages/pi-agent-core/package.json +1 -1
  342. package/packages/pi-ai/README.md +1 -0
  343. package/packages/pi-ai/dist/image-models.generated.d.ts +2 -2
  344. package/packages/pi-ai/dist/image-models.generated.js +6 -6
  345. package/packages/pi-ai/dist/image-models.generated.js.map +1 -1
  346. package/packages/pi-ai/dist/index.d.ts +2 -0
  347. package/packages/pi-ai/dist/index.d.ts.map +1 -1
  348. package/packages/pi-ai/dist/index.js +2 -0
  349. package/packages/pi-ai/dist/index.js.map +1 -1
  350. package/packages/pi-ai/dist/models.generated.d.ts +35 -125
  351. package/packages/pi-ai/dist/models.generated.d.ts.map +1 -1
  352. package/packages/pi-ai/dist/models.generated.js +46 -120
  353. package/packages/pi-ai/dist/models.generated.js.map +1 -1
  354. package/packages/pi-ai/dist/providers/anthropic.d.ts.map +1 -1
  355. package/packages/pi-ai/dist/providers/anthropic.js +12 -7
  356. package/packages/pi-ai/dist/providers/anthropic.js.map +1 -1
  357. package/packages/pi-ai/dist/providers/google-shared.d.ts +5 -0
  358. package/packages/pi-ai/dist/providers/google-shared.d.ts.map +1 -1
  359. package/packages/pi-ai/dist/providers/google-shared.js +12 -3
  360. package/packages/pi-ai/dist/providers/google-shared.js.map +1 -1
  361. package/packages/pi-ai/dist/providers/openai-completions.d.ts.map +1 -1
  362. package/packages/pi-ai/dist/providers/openai-completions.js +7 -3
  363. package/packages/pi-ai/dist/providers/openai-completions.js.map +1 -1
  364. package/packages/pi-ai/dist/utils/moonshot-tool-schema.d.ts +9 -0
  365. package/packages/pi-ai/dist/utils/moonshot-tool-schema.d.ts.map +1 -0
  366. package/packages/pi-ai/dist/utils/moonshot-tool-schema.js +34 -0
  367. package/packages/pi-ai/dist/utils/moonshot-tool-schema.js.map +1 -0
  368. package/packages/pi-ai/dist/utils/oauth/github-copilot.d.ts.map +1 -1
  369. package/packages/pi-ai/dist/utils/oauth/github-copilot.js +6 -2
  370. package/packages/pi-ai/dist/utils/oauth/github-copilot.js.map +1 -1
  371. package/packages/pi-ai/package.json +3 -2
  372. package/packages/pi-coding-agent/dist/core/auth-storage.d.ts +2 -2
  373. package/packages/pi-coding-agent/dist/core/auth-storage.d.ts.map +1 -1
  374. package/packages/pi-coding-agent/dist/core/auth-storage.js +19 -13
  375. package/packages/pi-coding-agent/dist/core/auth-storage.js.map +1 -1
  376. package/packages/pi-coding-agent/dist/core/provider-readiness.d.ts.map +1 -1
  377. package/packages/pi-coding-agent/dist/core/provider-readiness.js +13 -6
  378. package/packages/pi-coding-agent/dist/core/provider-readiness.js.map +1 -1
  379. package/packages/pi-coding-agent/dist/core/settings-manager.d.ts +3 -0
  380. package/packages/pi-coding-agent/dist/core/settings-manager.d.ts.map +1 -1
  381. package/packages/pi-coding-agent/dist/core/settings-manager.js +11 -0
  382. package/packages/pi-coding-agent/dist/core/settings-manager.js.map +1 -1
  383. package/packages/pi-coding-agent/dist/core/tools/bash.d.ts +11 -0
  384. package/packages/pi-coding-agent/dist/core/tools/bash.d.ts.map +1 -1
  385. package/packages/pi-coding-agent/dist/core/tools/bash.js +53 -11
  386. package/packages/pi-coding-agent/dist/core/tools/bash.js.map +1 -1
  387. package/packages/pi-coding-agent/dist/index.d.ts +1 -1
  388. package/packages/pi-coding-agent/dist/index.d.ts.map +1 -1
  389. package/packages/pi-coding-agent/dist/index.js +1 -1
  390. package/packages/pi-coding-agent/dist/index.js.map +1 -1
  391. package/packages/pi-coding-agent/dist/theme/theme.d.ts.map +1 -1
  392. package/packages/pi-coding-agent/dist/theme/theme.js +45 -17
  393. package/packages/pi-coding-agent/dist/theme/theme.js.map +1 -1
  394. package/packages/pi-coding-agent/dist/utils/shell.d.ts +28 -2
  395. package/packages/pi-coding-agent/dist/utils/shell.d.ts.map +1 -1
  396. package/packages/pi-coding-agent/dist/utils/shell.js +56 -10
  397. package/packages/pi-coding-agent/dist/utils/shell.js.map +1 -1
  398. package/packages/pi-coding-agent/package.json +7 -7
  399. package/packages/pi-tui/dist/index.d.ts +1 -1
  400. package/packages/pi-tui/dist/index.d.ts.map +1 -1
  401. package/packages/pi-tui/dist/index.js +1 -1
  402. package/packages/pi-tui/dist/index.js.map +1 -1
  403. package/packages/pi-tui/dist/terminal-image.d.ts +33 -0
  404. package/packages/pi-tui/dist/terminal-image.d.ts.map +1 -1
  405. package/packages/pi-tui/dist/terminal-image.js +54 -2
  406. package/packages/pi-tui/dist/terminal-image.js.map +1 -1
  407. package/packages/pi-tui/dist/tui.d.ts +8 -0
  408. package/packages/pi-tui/dist/tui.d.ts.map +1 -1
  409. package/packages/pi-tui/dist/tui.js +72 -18
  410. package/packages/pi-tui/dist/tui.js.map +1 -1
  411. package/packages/pi-tui/dist/utils.d.ts.map +1 -1
  412. package/packages/pi-tui/dist/utils.js +110 -36
  413. package/packages/pi-tui/dist/utils.js.map +1 -1
  414. package/packages/pi-tui/package.json +2 -2
  415. package/packages/rpc-client/package.json +2 -2
  416. package/pkg/dist/theme/theme.d.ts.map +1 -1
  417. package/pkg/dist/theme/theme.js +45 -17
  418. package/pkg/dist/theme/theme.js.map +1 -1
  419. package/pkg/package.json +1 -1
  420. package/src/resources/GSD-WORKFLOW.md +5 -4
  421. package/src/resources/extensions/ask-user-questions.ts +7 -2
  422. package/src/resources/extensions/async-jobs/async-bash-cancel.test.ts +360 -0
  423. package/src/resources/extensions/async-jobs/async-bash-tool.ts +33 -56
  424. package/src/resources/extensions/async-jobs/await-tool.test.ts +139 -0
  425. package/src/resources/extensions/async-jobs/await-tool.ts +82 -12
  426. package/src/resources/extensions/async-jobs/index.ts +79 -0
  427. package/src/resources/extensions/async-jobs/job-manager.ts +21 -1
  428. package/src/resources/extensions/bg-shell/bg-shell-command.ts +6 -6
  429. package/src/resources/extensions/bg-shell/bg-shell-tool.ts +10 -6
  430. package/src/resources/extensions/bg-shell/overlay.ts +9 -5
  431. package/src/resources/extensions/bg-shell/process-manager.ts +50 -25
  432. package/src/resources/extensions/bg-shell/readiness-detector.ts +12 -0
  433. package/src/resources/extensions/bg-shell/tests/lifecycle-and-utilities.test.ts +48 -1
  434. package/src/resources/extensions/bg-shell/utilities.ts +3 -0
  435. package/src/resources/extensions/browser-tools/engine/managed-gsd-browser.ts +265 -98
  436. package/src/resources/extensions/browser-tools/engine/selection.ts +90 -4
  437. package/src/resources/extensions/browser-tools/index.ts +71 -13
  438. package/src/resources/extensions/browser-tools/tests/browser-engine-selection.test.mjs +83 -13
  439. package/src/resources/extensions/browser-tools/tests/gsd-browser-launch-config.test.mjs +40 -1
  440. package/src/resources/extensions/browser-tools/tests/managed-gsd-browser-tools.test.mjs +136 -0
  441. package/src/resources/extensions/claude-code-cli/stream-adapter.ts +537 -202
  442. package/src/resources/extensions/claude-code-cli/tests/stream-adapter.test.ts +672 -7
  443. package/src/resources/extensions/claude-code-cli/turn-assembler.ts +38 -1
  444. package/src/resources/extensions/gsd/auto/closeout.ts +309 -0
  445. package/src/resources/extensions/gsd/auto/custom-verify-retry-store.ts +21 -3
  446. package/src/resources/extensions/gsd/auto/detect-stuck.ts +32 -9
  447. package/src/resources/extensions/gsd/auto/dispatch-history.ts +168 -0
  448. package/src/resources/extensions/gsd/auto/dispatch-key.ts +39 -0
  449. package/src/resources/extensions/gsd/auto/dispatch.ts +449 -0
  450. package/src/resources/extensions/gsd/auto/finalize.ts +445 -0
  451. package/src/resources/extensions/gsd/auto/loop.ts +7 -1
  452. package/src/resources/extensions/gsd/auto/milestone-lease-reclaim.ts +74 -0
  453. package/src/resources/extensions/gsd/auto/orchestrator.ts +193 -71
  454. package/src/resources/extensions/gsd/auto/phase-helpers.ts +199 -0
  455. package/src/resources/extensions/gsd/auto/phases.ts +58 -3022
  456. package/src/resources/extensions/gsd/auto/pre-dispatch.ts +704 -0
  457. package/src/resources/extensions/gsd/auto/session.ts +3 -0
  458. package/src/resources/extensions/gsd/auto/unit-phase.ts +910 -0
  459. package/src/resources/extensions/gsd/auto/workflow-unit-dispatch.ts +1 -1
  460. package/src/resources/extensions/gsd/auto/worktree-safety-phase.ts +149 -0
  461. package/src/resources/extensions/gsd/auto-direct-dispatch.ts +18 -48
  462. package/src/resources/extensions/gsd/auto-dispatch.ts +48 -61
  463. package/src/resources/extensions/gsd/auto-model-selection.ts +41 -12
  464. package/src/resources/extensions/gsd/auto-post-unit.ts +40 -8
  465. package/src/resources/extensions/gsd/auto-prompts.ts +118 -35
  466. package/src/resources/extensions/gsd/auto-start.ts +42 -21
  467. package/src/resources/extensions/gsd/auto-tool-tracking.ts +19 -0
  468. package/src/resources/extensions/gsd/auto-unit-closeout.ts +83 -28
  469. package/src/resources/extensions/gsd/auto-unit-tool-scope.ts +14 -21
  470. package/src/resources/extensions/gsd/auto-verification.ts +26 -28
  471. package/src/resources/extensions/gsd/auto-worktree.ts +45 -95
  472. package/src/resources/extensions/gsd/auto.ts +72 -17
  473. package/src/resources/extensions/gsd/blocked-models.ts +49 -0
  474. package/src/resources/extensions/gsd/bootstrap/agent-end-recovery.ts +37 -10
  475. package/src/resources/extensions/gsd/bootstrap/dynamic-tools.ts +79 -12
  476. package/src/resources/extensions/gsd/bootstrap/exec-tools.ts +2 -2
  477. package/src/resources/extensions/gsd/bootstrap/register-extension.ts +24 -0
  478. package/src/resources/extensions/gsd/bootstrap/register-hooks.ts +251 -47
  479. package/src/resources/extensions/gsd/bootstrap/write-gate.ts +352 -84
  480. package/src/resources/extensions/gsd/branch-patterns.ts +3 -0
  481. package/src/resources/extensions/gsd/browser-daemon-auto-prep.ts +108 -0
  482. package/src/resources/extensions/gsd/browser-evidence.ts +18 -2
  483. package/src/resources/extensions/gsd/captures.ts +4 -6
  484. package/src/resources/extensions/gsd/closeout-wizard.ts +102 -0
  485. package/src/resources/extensions/gsd/commands/context.ts +16 -2
  486. package/src/resources/extensions/gsd/commands-handlers.ts +46 -3
  487. package/src/resources/extensions/gsd/commands-mcp-status.ts +2 -2
  488. package/src/resources/extensions/gsd/commands-workflow-templates.ts +11 -4
  489. package/src/resources/extensions/gsd/consent-question.ts +431 -0
  490. package/src/resources/extensions/gsd/consent-verdict.ts +86 -0
  491. package/src/resources/extensions/gsd/constants.ts +0 -3
  492. package/src/resources/extensions/gsd/crash-recovery.ts +13 -11
  493. package/src/resources/extensions/gsd/db/queries.ts +66 -0
  494. package/src/resources/extensions/gsd/db-writer.ts +11 -19
  495. package/src/resources/extensions/gsd/dispatch-guard.ts +8 -31
  496. package/src/resources/extensions/gsd/doctor-engine-checks.ts +5 -4
  497. package/src/resources/extensions/gsd/doctor-environment.ts +269 -149
  498. package/src/resources/extensions/gsd/doctor-format.ts +12 -7
  499. package/src/resources/extensions/gsd/doctor-git-checks.ts +2 -19
  500. package/src/resources/extensions/gsd/doctor-runtime-checks.ts +13 -15
  501. package/src/resources/extensions/gsd/engine-hook-contract.ts +79 -0
  502. package/src/resources/extensions/gsd/error-classifier.ts +11 -0
  503. package/src/resources/extensions/gsd/exec-sandbox.ts +49 -9
  504. package/src/resources/extensions/gsd/files.ts +33 -12
  505. package/src/resources/extensions/gsd/gsd-command-home.ts +13 -3
  506. package/src/resources/extensions/gsd/gsd-db.ts +4 -3
  507. package/src/resources/extensions/gsd/guidance.ts +217 -0
  508. package/src/resources/extensions/gsd/guided-flow.ts +161 -26
  509. package/src/resources/extensions/gsd/health-widget.ts +91 -27
  510. package/src/resources/extensions/gsd/markdown-renderer.ts +11 -0
  511. package/src/resources/extensions/gsd/mcp-bridge.ts +39 -0
  512. package/src/resources/extensions/gsd/mcp-filter.ts +2 -23
  513. package/src/resources/extensions/gsd/mcp-tool-name.ts +6 -11
  514. package/src/resources/extensions/gsd/memory-consolidation-scanner.ts +1 -1
  515. package/src/resources/extensions/gsd/migrate/safety.ts +4 -1
  516. package/src/resources/extensions/gsd/milestone-closeout.ts +109 -24
  517. package/src/resources/extensions/gsd/milestone-planning-persistence.ts +2 -2
  518. package/src/resources/extensions/gsd/milestone-reopen-events.ts +3 -6
  519. package/src/resources/extensions/gsd/milestone-settlement.ts +2 -2
  520. package/src/resources/extensions/gsd/notification-store.ts +26 -3
  521. package/src/resources/extensions/gsd/notifications.ts +13 -6
  522. package/src/resources/extensions/gsd/parallel-monitor-overlay.ts +6 -4
  523. package/src/resources/extensions/gsd/parsers-legacy.ts +16 -4
  524. package/src/resources/extensions/gsd/paths.ts +33 -0
  525. package/src/resources/extensions/gsd/pre-execution-checks.ts +109 -3
  526. package/src/resources/extensions/gsd/preferences-models.ts +12 -47
  527. package/src/resources/extensions/gsd/projection-flush.ts +20 -0
  528. package/src/resources/extensions/gsd/prompts/complete-slice.md +4 -4
  529. package/src/resources/extensions/gsd/prompts/execute-task.md +3 -2
  530. package/src/resources/extensions/gsd/prompts/plan-milestone.md +1 -1
  531. package/src/resources/extensions/gsd/prompts/plan-slice.md +2 -2
  532. package/src/resources/extensions/gsd/prompts/quick-task.md +1 -1
  533. package/src/resources/extensions/gsd/prompts/reassess-roadmap.md +1 -1
  534. package/src/resources/extensions/gsd/prompts/refine-slice.md +2 -2
  535. package/src/resources/extensions/gsd/prompts/replan-slice.md +2 -2
  536. package/src/resources/extensions/gsd/prompts/research-milestone.md +1 -1
  537. package/src/resources/extensions/gsd/prompts/research-slice.md +1 -1
  538. package/src/resources/extensions/gsd/prompts/rewrite-docs.md +1 -1
  539. package/src/resources/extensions/gsd/prompts/run-uat.md +9 -5
  540. package/src/resources/extensions/gsd/prompts/system.md +5 -2
  541. package/src/resources/extensions/gsd/prompts/triage-captures.md +1 -1
  542. package/src/resources/extensions/gsd/prompts/validate-milestone.md +1 -1
  543. package/src/resources/extensions/gsd/prompts/workflow-start.md +2 -1
  544. package/src/resources/extensions/gsd/provider-error-guidance.ts +4 -9
  545. package/src/resources/extensions/gsd/provider-switch-observer.ts +1 -1
  546. package/src/resources/extensions/gsd/publication.ts +122 -0
  547. package/src/resources/extensions/gsd/reactive-graph.ts +11 -1
  548. package/src/resources/extensions/gsd/recovery-classification.ts +42 -96
  549. package/src/resources/extensions/gsd/roadmap-slices.ts +28 -3
  550. package/src/resources/extensions/gsd/safety/destructive-confirmation.ts +134 -0
  551. package/src/resources/extensions/gsd/session-lock.ts +1 -1
  552. package/src/resources/extensions/gsd/skill-activation.ts +3 -6
  553. package/src/resources/extensions/gsd/state.ts +16 -22
  554. package/src/resources/extensions/gsd/stop-notice.ts +75 -0
  555. package/src/resources/extensions/gsd/tests/auto-abort-pause-regression.test.ts +1 -1
  556. package/src/resources/extensions/gsd/tests/auto-blocked-remediation-message.test.ts +1 -1
  557. package/src/resources/extensions/gsd/tests/auto-loop.test.ts +206 -22
  558. package/src/resources/extensions/gsd/tests/auto-model-selection.test.ts +97 -1
  559. package/src/resources/extensions/gsd/tests/auto-orchestrator.test.ts +273 -37
  560. package/src/resources/extensions/gsd/tests/auto-pause-double-entry-guard.test.ts +1 -1
  561. package/src/resources/extensions/gsd/tests/auto-paused-ui-cleanup.test.ts +77 -1
  562. package/src/resources/extensions/gsd/tests/auto-phases-lifecycle.test.ts +2 -1
  563. package/src/resources/extensions/gsd/tests/auto-remote-session-lock-cleanup.test.ts +65 -3
  564. package/src/resources/extensions/gsd/tests/auto-start-orphan-bootstrap.test.ts +236 -0
  565. package/src/resources/extensions/gsd/tests/auto-unit-closeout.test.ts +169 -1
  566. package/src/resources/extensions/gsd/tests/blocked-models.test.ts +19 -0
  567. package/src/resources/extensions/gsd/tests/browser-automation-contract-fixture.ts +39 -0
  568. package/src/resources/extensions/gsd/tests/browser-contract.test.ts +44 -0
  569. package/src/resources/extensions/gsd/tests/browser-daemon-auto-prep.test.ts +144 -0
  570. package/src/resources/extensions/gsd/tests/checkout-branch-stash-guard.test.ts +66 -1
  571. package/src/resources/extensions/gsd/tests/clear-stale-autostart.test.ts +22 -0
  572. package/src/resources/extensions/gsd/tests/commands-verdict.test.ts +8 -7
  573. package/src/resources/extensions/gsd/tests/complete-slice-verification-gate.test.ts +42 -0
  574. package/src/resources/extensions/gsd/tests/complete-task.test.ts +141 -5
  575. package/src/resources/extensions/gsd/tests/consent-question.test.ts +351 -0
  576. package/src/resources/extensions/gsd/tests/custom-verify-retry-store.test.ts +67 -0
  577. package/src/resources/extensions/gsd/tests/db-writer.test.ts +15 -4
  578. package/src/resources/extensions/gsd/tests/deep-project-auto-loop.test.ts +12 -11
  579. package/src/resources/extensions/gsd/tests/derive-state-helpers.test.ts +36 -0
  580. package/src/resources/extensions/gsd/tests/destructive-confirmation.test.ts +303 -0
  581. package/src/resources/extensions/gsd/tests/discuss-routing-fixes.test.ts +12 -2
  582. package/src/resources/extensions/gsd/tests/dispatch-history.test.ts +328 -0
  583. package/src/resources/extensions/gsd/tests/dispatch-run-uat-browser-tools.test.ts +2 -1
  584. package/src/resources/extensions/gsd/tests/dist-redirect.mjs +8 -0
  585. package/src/resources/extensions/gsd/tests/doctor-git-checks-terminal.test.ts +73 -0
  586. package/src/resources/extensions/gsd/tests/dynamic-bash-no-cap.test.ts +132 -0
  587. package/src/resources/extensions/gsd/tests/engine-hook-contract.test.ts +148 -0
  588. package/src/resources/extensions/gsd/tests/engine-interfaces-contract.test.ts +117 -91
  589. package/src/resources/extensions/gsd/tests/ensure-db-open.test.ts +113 -0
  590. package/src/resources/extensions/gsd/tests/exec-graceful-kill.test.ts +193 -0
  591. package/src/resources/extensions/gsd/tests/exec-tool.test.ts +29 -1
  592. package/src/resources/extensions/gsd/tests/extension-bootstrap-isolation.test.ts +35 -1
  593. package/src/resources/extensions/gsd/tests/gsd-command-home.test.ts +120 -0
  594. package/src/resources/extensions/gsd/tests/gsd-db.test.ts +27 -0
  595. package/src/resources/extensions/gsd/tests/guidance.test.ts +148 -0
  596. package/src/resources/extensions/gsd/tests/guided-dispatch-root.test.ts +18 -6
  597. package/src/resources/extensions/gsd/tests/integration/auto-worktree-milestone-merge.test.ts +53 -11
  598. package/src/resources/extensions/gsd/tests/integration/auto-worktree.test.ts +88 -58
  599. package/src/resources/extensions/gsd/tests/integration/doctor-environment-async.test.ts +104 -0
  600. package/src/resources/extensions/gsd/tests/integration/gsd-integration-fixture.ts +80 -0
  601. package/src/resources/extensions/gsd/tests/integration/run-uat.test.ts +217 -0
  602. package/src/resources/extensions/gsd/tests/journal-integration.test.ts +47 -16
  603. package/src/resources/extensions/gsd/tests/mcp-project-config.test.ts +3 -1
  604. package/src/resources/extensions/gsd/tests/mcp-readiness-preflight.test.ts +205 -0
  605. package/src/resources/extensions/gsd/tests/mcp-status.test.ts +6 -5
  606. package/src/resources/extensions/gsd/tests/milestone-closeout.test.ts +95 -4
  607. package/src/resources/extensions/gsd/tests/milestone-merge-stash-restore.test.ts +1 -1
  608. package/src/resources/extensions/gsd/tests/milestone-report-path.test.ts +1 -1
  609. package/src/resources/extensions/gsd/tests/milestone-settlement.test.ts +92 -0
  610. package/src/resources/extensions/gsd/tests/milestone-transition-state-rebuild.test.ts +1 -1
  611. package/src/resources/extensions/gsd/tests/model-unittype-mapping.test.ts +32 -1
  612. package/src/resources/extensions/gsd/tests/notification-store.test.ts +32 -0
  613. package/src/resources/extensions/gsd/tests/notifications.test.ts +64 -9
  614. package/src/resources/extensions/gsd/tests/oauth-api-model-routing.test.ts +167 -0
  615. package/src/resources/extensions/gsd/tests/parallel-research-dispatch.test.ts +18 -0
  616. package/src/resources/extensions/gsd/tests/parallel-skill-prompt-integration.test.ts +2 -2
  617. package/src/resources/extensions/gsd/tests/parsers-legacy-importers.test.ts +143 -0
  618. package/src/resources/extensions/gsd/tests/phases-merge-error-stops-auto.test.ts +1 -1
  619. package/src/resources/extensions/gsd/tests/phases-terminal-complete-idempotent.test.ts +242 -0
  620. package/src/resources/extensions/gsd/tests/plan-gate-failed-doctor-heal-hint.test.ts +3 -3
  621. package/src/resources/extensions/gsd/tests/post-exec-retry-bypass.test.ts +63 -2
  622. package/src/resources/extensions/gsd/tests/pre-execution-checks.test.ts +193 -1
  623. package/src/resources/extensions/gsd/tests/prompt-contracts.test.ts +10 -2
  624. package/src/resources/extensions/gsd/tests/prompt-db.test.ts +124 -6
  625. package/src/resources/extensions/gsd/tests/provider-error-guidance.test.ts +3 -3
  626. package/src/resources/extensions/gsd/tests/provider-errors.test.ts +2 -4
  627. package/src/resources/extensions/gsd/tests/publication.test.ts +120 -0
  628. package/src/resources/extensions/gsd/tests/register-hooks-depth-verification.test.ts +157 -0
  629. package/src/resources/extensions/gsd/tests/remote-notification-from-desktop.test.ts +31 -81
  630. package/src/resources/extensions/gsd/tests/roadmap-slices.test.ts +68 -0
  631. package/src/resources/extensions/gsd/tests/runtime-invariant-modules.test.ts +27 -2
  632. package/src/resources/extensions/gsd/tests/skill-activation.test.ts +20 -17
  633. package/src/resources/extensions/gsd/tests/start-auto-detached.test.ts +7 -3
  634. package/src/resources/extensions/gsd/tests/stop-auto-race-null-unit.test.ts +1 -1
  635. package/src/resources/extensions/gsd/tests/stop-notice.test.ts +70 -0
  636. package/src/resources/extensions/gsd/tests/teardown-chdir-failure-clears-registry.test.ts +17 -0
  637. package/src/resources/extensions/gsd/tests/token-tool-gating.test.ts +80 -2
  638. package/src/resources/extensions/gsd/tests/tool-invocation-error-loop-break.test.ts +8 -0
  639. package/src/resources/extensions/gsd/tests/tool-surface-readiness.test.ts +329 -0
  640. package/src/resources/extensions/gsd/tests/tool-unavailable-retry.test.ts +33 -0
  641. package/src/resources/extensions/gsd/tests/transport-gate-double-complete.test.ts +139 -0
  642. package/src/resources/extensions/gsd/tests/uat-policy.test.ts +112 -29
  643. package/src/resources/extensions/gsd/tests/unit-closeout.test.ts +209 -0
  644. package/src/resources/extensions/gsd/tests/unit-context-composer.test.ts +67 -2
  645. package/src/resources/extensions/gsd/tests/unit-registry.test.ts +163 -0
  646. package/src/resources/extensions/gsd/tests/uok-audit-unified.test.ts +8 -0
  647. package/src/resources/extensions/gsd/tests/uok-plan-v2-wiring.test.ts +1 -1
  648. package/src/resources/extensions/gsd/tests/verification-verdict.test.ts +2 -0
  649. package/src/resources/extensions/gsd/tests/web-app-uat.test.ts +44 -1
  650. package/src/resources/extensions/gsd/tests/workflow-events.test.ts +19 -0
  651. package/src/resources/extensions/gsd/tests/workflow-mcp-readiness-cache.test.ts +119 -0
  652. package/src/resources/extensions/gsd/tests/workflow-mcp.test.ts +67 -4
  653. package/src/resources/extensions/gsd/tests/workflow-phase-contract-matrix.test.ts +332 -0
  654. package/src/resources/extensions/gsd/tests/workflow-reconcile.test.ts +20 -0
  655. package/src/resources/extensions/gsd/tests/workflow-templates.test.ts +92 -0
  656. package/src/resources/extensions/gsd/tests/workflow-tool-executors.test.ts +275 -40
  657. package/src/resources/extensions/gsd/tests/worktree-health-dispatch.test.ts +1 -1
  658. package/src/resources/extensions/gsd/tests/worktree-project-root-degrade.test.ts +1 -1
  659. package/src/resources/extensions/gsd/tests/worktree-safety-phase.test.ts +100 -0
  660. package/src/resources/extensions/gsd/tests/worktree-safety.test.ts +72 -0
  661. package/src/resources/extensions/gsd/tests/worktree-teardown-safety.test.ts +22 -0
  662. package/src/resources/extensions/gsd/tests/worktree.test.ts +18 -0
  663. package/src/resources/extensions/gsd/tests/write-gate-seam.test.ts +358 -0
  664. package/src/resources/extensions/gsd/tests/write-gate.test.ts +67 -1
  665. package/src/resources/extensions/gsd/tool-contract.ts +38 -3
  666. package/src/resources/extensions/gsd/tool-presentation-plan.ts +4 -4
  667. package/src/resources/extensions/gsd/tool-surface-readiness.ts +183 -0
  668. package/src/resources/extensions/gsd/tools/complete-milestone.ts +3 -2
  669. package/src/resources/extensions/gsd/tools/complete-slice.ts +22 -12
  670. package/src/resources/extensions/gsd/tools/complete-task.ts +90 -2
  671. package/src/resources/extensions/gsd/tools/exec-tool.ts +8 -7
  672. package/src/resources/extensions/gsd/tools/plan-slice.ts +14 -8
  673. package/src/resources/extensions/gsd/tools/plan-task.ts +2 -2
  674. package/src/resources/extensions/gsd/tools/reassess-roadmap.ts +2 -2
  675. package/src/resources/extensions/gsd/tools/reopen-milestone.ts +2 -2
  676. package/src/resources/extensions/gsd/tools/reopen-slice.ts +2 -2
  677. package/src/resources/extensions/gsd/tools/reopen-task.ts +2 -2
  678. package/src/resources/extensions/gsd/tools/replan-slice.ts +2 -2
  679. package/src/resources/extensions/gsd/tools/workflow-tool-executors.ts +81 -2
  680. package/src/resources/extensions/gsd/uat-policy.ts +62 -16
  681. package/src/resources/extensions/gsd/unit-closeout.ts +201 -0
  682. package/src/resources/extensions/gsd/unit-context-composer.ts +111 -1
  683. package/src/resources/extensions/gsd/unit-context-manifest.ts +4 -28
  684. package/src/resources/extensions/gsd/unit-registry.ts +442 -0
  685. package/src/resources/extensions/gsd/unit-tool-contracts.ts +27 -192
  686. package/src/resources/extensions/gsd/verdict-parser.ts +1 -1
  687. package/src/resources/extensions/gsd/verification-verdict.ts +4 -2
  688. package/src/resources/extensions/gsd/web-app-uat.ts +51 -8
  689. package/src/resources/extensions/gsd/workflow-event-ledger.ts +131 -0
  690. package/src/resources/extensions/gsd/workflow-event-vocabulary.ts +59 -0
  691. package/src/resources/extensions/gsd/workflow-events.ts +12 -20
  692. package/src/resources/extensions/gsd/workflow-mcp-auto-prep.ts +2 -0
  693. package/src/resources/extensions/gsd/workflow-mcp-readiness-cache.ts +150 -0
  694. package/src/resources/extensions/gsd/workflow-reconcile.ts +29 -62
  695. package/src/resources/extensions/gsd/workflow-tool-surface.ts +4 -1
  696. package/src/resources/extensions/gsd/worktree-git-recovery.ts +15 -9
  697. package/src/resources/extensions/gsd/worktree-lifecycle.ts +3 -8
  698. package/src/resources/extensions/gsd/worktree-manager.ts +6 -1
  699. package/src/resources/extensions/gsd/worktree-root.ts +12 -0
  700. package/src/resources/extensions/gsd/worktree-safety.ts +41 -39
  701. package/src/resources/extensions/gsd/worktree-session-state.ts +3 -5
  702. package/src/resources/extensions/gsd/worktree.ts +7 -1
  703. package/src/resources/extensions/mcp-client/manager.ts +7 -1
  704. package/src/resources/extensions/search-the-web/native-search.ts +5 -3
  705. package/src/resources/extensions/shared/browser-contract.ts +66 -0
  706. package/src/resources/extensions/shared/gsd-browser-cli.ts +141 -6
  707. package/src/resources/shared/gsd-browser-path-sync.ts +273 -0
  708. package/src/resources/shared/package-manager-detection.ts +1 -1
  709. package/src/resources/shared/package.json +3 -0
  710. package/src/resources/skills/create-skill/SKILL.md +3 -0
  711. package/src/resources/skills/create-skill/references/executable-code.md +1 -1
  712. package/src/resources/skills/create-skill/references/skill-structure.md +1 -0
  713. package/src/resources/skills/create-skill/workflows/add-reference.md +8 -3
  714. package/src/resources/skills/create-skill/workflows/add-script.md +4 -2
  715. package/src/resources/skills/create-skill/workflows/add-template.md +3 -1
  716. package/src/resources/skills/create-skill/workflows/add-workflow.md +8 -3
  717. package/src/resources/skills/create-skill/workflows/upgrade-to-router.md +10 -5
  718. package/src/resources/skills/create-skill/workflows/verify-skill.md +9 -4
  719. package/src/resources/skills/spike-wrap-up/SKILL.md +9 -9
  720. package/dist/resources/extensions/gsd/user-input-boundary.js +0 -218
  721. package/dist/resources/skills/gsd-browser/SKILL.md +0 -41
  722. package/src/resources/extensions/gsd/tests/user-input-boundary.test.ts +0 -173
  723. package/src/resources/extensions/gsd/user-input-boundary.ts +0 -216
  724. package/src/resources/skills/gsd-browser/SKILL.md +0 -41
  725. /package/dist/web/standalone/.next/static/{C24pqUd-aru-l0Dp0gLZP → xyMkEaICFHJoa98VgJyzY}/_buildManifest.js +0 -0
  726. /package/dist/web/standalone/.next/static/{C24pqUd-aru-l0Dp0gLZP → xyMkEaICFHJoa98VgJyzY}/_ssgManifest.js +0 -0
@@ -1 +1 @@
1
- <!DOCTYPE html><html id="__next_error__"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/webpack-fbea77b5f9953368.js"/><script src="/_next/static/chunks/51aff721-df603e9695992f6b.js" async=""></script><script src="/_next/static/chunks/686-9424f271d9ce5d07.js" async=""></script><script src="/_next/static/chunks/main-app-90d1d8d5e5d2dc6b.js" async=""></script><title>500: This page couldn’t load</title><style>:root {--next-error-bg: #fff;--next-error-text: #171717;--next-error-title: #171717;--next-error-message: #171717;--next-error-digest: #666666;--next-error-btn-text: #fff;--next-error-btn-bg: #171717;--next-error-btn-border: none;--next-error-btn-secondary-text: #171717;--next-error-btn-secondary-bg: transparent;--next-error-btn-secondary-border: 1px solid rgba(0,0,0,0.08);}@media (prefers-color-scheme: dark) {:root {--next-error-bg: #0a0a0a;--next-error-text: #ededed;--next-error-title: #ededed;--next-error-message: #ededed;--next-error-digest: #a0a0a0;--next-error-btn-text: #0a0a0a;--next-error-btn-bg: #ededed;--next-error-btn-border: none;--next-error-btn-secondary-text: #ededed;--next-error-btn-secondary-bg: transparent;--next-error-btn-secondary-border: 1px solid rgba(255,255,255,0.14);}}body { margin: 0; color: var(--next-error-text); background: var(--next-error-bg); }</style><script src="/_next/static/chunks/polyfills-42372ed130431b0a.js" noModule=""></script></head><body><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,&quot;Segoe UI&quot;,Roboto,Helvetica,Arial,sans-serif,&quot;Apple Color Emoji&quot;,&quot;Segoe UI Emoji&quot;;height:100vh;display:flex;align-items:center;justify-content:center"><div style="margin-top:-32px;max-width:325px;padding:32px 28px;text-align:left"><svg width="32" height="32" viewBox="-0.2 -1.5 32 32" fill="none" style="margin-bottom:24px"><path d="M16.9328 0C18.0839 0.000116771 19.1334 0.658832 19.634 1.69531L31.4299 26.1309C32.0708 27.4588 31.1036 28.9999 29.6291 29H2.00215C0.527541 29 -0.439628 27.4588 0.201371 26.1309L11.9973 1.69531C12.4979 0.658823 13.5474 7.75066e-05 14.6984 0H16.9328ZM3.59493 26H28.0363L16.9328 3H14.6984L3.59493 26ZM15.8156 19C16.9202 19.0001 17.8156 19.8955 17.8156 21C17.8156 22.1045 16.9202 22.9999 15.8156 23C14.7111 23 13.8156 22.1046 13.8156 21C13.8156 19.8954 14.7111 19 15.8156 19ZM17.3156 16.5H14.3156V8.5H17.3156V16.5Z" fill="var(--next-error-title)"></path></svg><h1 style="font-size:24px;font-weight:500;letter-spacing:-0.02em;line-height:32px;margin:0 0 12px 0;color:var(--next-error-title)">This page couldn’t load</h1><p style="font-size:14px;font-weight:400;line-height:21px;margin:0 0 20px 0;color:var(--next-error-message)">A server error occurred. Reload to try again.</p><form style="margin:0"><button type="submit" style="display:inline-flex;align-items:center;justify-content:center;height:32px;padding:0 12px;font-size:14px;font-weight:500;line-height:20px;border-radius:6px;cursor:pointer;color:var(--next-error-btn-text);background:var(--next-error-btn-bg);border:var(--next-error-btn-border)">Reload</button></form></div></div><!--$--><!--/$--><script src="/_next/static/chunks/webpack-fbea77b5f9953368.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[25020,[],\"\"]\n3:I[81130,[],\"\"]\n4:I[84649,[],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[84649,[],\"ViewportBoundary\"]\na:I[84649,[],\"MetadataBoundary\"]\nc:I[45336,[],\"default\",1]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_global-error\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"_global-error\",{\"children\":[\"__PAGE__\",{}]}]}],[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[\"$\",\"html\",null,{\"id\":\"__next_error__\",\"children\":[[\"$\",\"head\",null,{\"children\":[[\"$\",\"title\",null,{\"children\":\"500: This page couldn’t load\"}],[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\":root {--next-error-bg: #fff;--next-error-text: #171717;--next-error-title: #171717;--next-error-message: #171717;--next-error-digest: #666666;--next-error-btn-text: #fff;--next-error-btn-bg: #171717;--next-error-btn-border: none;--next-error-btn-secondary-text: #171717;--next-error-btn-secondary-bg: transparent;--next-error-btn-secondary-border: 1px solid rgba(0,0,0,0.08);}@media (prefers-color-scheme: dark) {:root {--next-error-bg: #0a0a0a;--next-error-text: #ededed;--next-error-title: #ededed;--next-error-message: #ededed;--next-error-digest: #a0a0a0;--next-error-btn-text: #0a0a0a;--next-error-btn-bg: #ededed;--next-error-btn-border: none;--next-error-btn-secondary-text: #ededed;--next-error-btn-secondary-bg: transparent;--next-error-btn-secondary-border: 1px solid rgba(255,255,255,0.14);}}body { margin: 0; color: var(--next-error-text); background: var(--next-error-bg); }\"}}]]}],[\"$\",\"body\",null,{\"children\":[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"display\":\"flex\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"style\":{\"marginTop\":\"-32px\",\"maxWidth\":\"325px\",\"padding\":\"32px 28px\",\"textAlign\":\"left\"},\"children\":[[\"$\",\"svg\",null,{\"width\":\"32\",\"height\":\"32\",\"viewBox\":\"-0.2 -1.5 32 32\",\"fill\":\"none\",\"style\":{\"marginBottom\":\"24px\"},\"children\":[\"$\",\"path\",null,{\"d\":\"M16.9328 0C18.0839 0.000116771 19.1334 0.658832 19.634 1.69531L31.4299 26.1309C32.0708 27.4588 31.1036 28.9999 29.6291 29H2.00215C0.527541 29 -0.439628 27.4588 0.201371 26.1309L11.9973 1.69531C12.4979 0.658823 13.5474 7.75066e-05 14.6984 0H16.9328ZM3.59493 26H28.0363L16.9328 3H14.6984L3.59493 26ZM15.8156 19C16.9202 19.0001 17.8156 19.8955 17.8156 21C17.8156 22.1045 16.9202 22.9999 15.8156 23C14.7111 23 13.8156 22.1046 13.8156 21C13.8156 19.8954 14.7111 19 15.8156 19ZM17.3156 16.5H14.3156V8.5H17.3156V16.5Z\",\"fill\":\"var(--next-error-title)\"}]}],[\"$\",\"h1\",null,{\"style\":{\"fontSize\":\"24px\",\"fontWeight\":500,\"letterSpacing\":\"-0.02em\",\"lineHeight\":\"32px\",\"margin\":\"0 0 12px 0\",\"color\":\"var(--next-error-title)\"},\"children\":\"This page couldn’t load\"}],[\"$\",\"p\",null,{\"style\":{\"fontSize\":\"14px\",\"fontWeight\":400,\"lineHeight\":\"21px\",\"margin\":\"0 0 20px 0\",\"color\":\"var(--next-error-message)\"},\"children\":\"A server error occurred. Reload to try again.\"}],[\"$\",\"form\",null,{\"style\":{\"margin\":0},\"children\":[\"$\",\"button\",null,{\"type\":\"submit\",\"style\":{\"display\":\"inline-flex\",\"alignItems\":\"center\",\"justifyContent\":\"center\",\"height\":\"32px\",\"padding\":\"0 12px\",\"fontSize\":\"14px\",\"fontWeight\":500,\"lineHeight\":\"20px\",\"borderRadius\":\"6px\",\"cursor\":\"pointer\",\"color\":\"var(--next-error-btn-text)\",\"background\":\"var(--next-error-btn-bg)\",\"border\":\"var(--next-error-btn-border)\"},\"children\":\"Reload\"}]}]]}]}]}]]}],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,\"$@7\"],[\"$\",\"$1\",\"h\",{\"children\":[null,[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"C24pqUd-aru-l0Dp0gLZP\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[]\n"])</script></body></html>
1
+ <!DOCTYPE html><html id="__next_error__"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/webpack-f0285ce91d4ec9ef.js"/><script src="/_next/static/chunks/51aff721-df603e9695992f6b.js" async=""></script><script src="/_next/static/chunks/686-9424f271d9ce5d07.js" async=""></script><script src="/_next/static/chunks/main-app-90d1d8d5e5d2dc6b.js" async=""></script><title>500: This page couldn’t load</title><style>:root {--next-error-bg: #fff;--next-error-text: #171717;--next-error-title: #171717;--next-error-message: #171717;--next-error-digest: #666666;--next-error-btn-text: #fff;--next-error-btn-bg: #171717;--next-error-btn-border: none;--next-error-btn-secondary-text: #171717;--next-error-btn-secondary-bg: transparent;--next-error-btn-secondary-border: 1px solid rgba(0,0,0,0.08);}@media (prefers-color-scheme: dark) {:root {--next-error-bg: #0a0a0a;--next-error-text: #ededed;--next-error-title: #ededed;--next-error-message: #ededed;--next-error-digest: #a0a0a0;--next-error-btn-text: #0a0a0a;--next-error-btn-bg: #ededed;--next-error-btn-border: none;--next-error-btn-secondary-text: #ededed;--next-error-btn-secondary-bg: transparent;--next-error-btn-secondary-border: 1px solid rgba(255,255,255,0.14);}}body { margin: 0; color: var(--next-error-text); background: var(--next-error-bg); }</style><script src="/_next/static/chunks/polyfills-42372ed130431b0a.js" noModule=""></script></head><body><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,&quot;Segoe UI&quot;,Roboto,Helvetica,Arial,sans-serif,&quot;Apple Color Emoji&quot;,&quot;Segoe UI Emoji&quot;;height:100vh;display:flex;align-items:center;justify-content:center"><div style="margin-top:-32px;max-width:325px;padding:32px 28px;text-align:left"><svg width="32" height="32" viewBox="-0.2 -1.5 32 32" fill="none" style="margin-bottom:24px"><path d="M16.9328 0C18.0839 0.000116771 19.1334 0.658832 19.634 1.69531L31.4299 26.1309C32.0708 27.4588 31.1036 28.9999 29.6291 29H2.00215C0.527541 29 -0.439628 27.4588 0.201371 26.1309L11.9973 1.69531C12.4979 0.658823 13.5474 7.75066e-05 14.6984 0H16.9328ZM3.59493 26H28.0363L16.9328 3H14.6984L3.59493 26ZM15.8156 19C16.9202 19.0001 17.8156 19.8955 17.8156 21C17.8156 22.1045 16.9202 22.9999 15.8156 23C14.7111 23 13.8156 22.1046 13.8156 21C13.8156 19.8954 14.7111 19 15.8156 19ZM17.3156 16.5H14.3156V8.5H17.3156V16.5Z" fill="var(--next-error-title)"></path></svg><h1 style="font-size:24px;font-weight:500;letter-spacing:-0.02em;line-height:32px;margin:0 0 12px 0;color:var(--next-error-title)">This page couldn’t load</h1><p style="font-size:14px;font-weight:400;line-height:21px;margin:0 0 20px 0;color:var(--next-error-message)">A server error occurred. Reload to try again.</p><form style="margin:0"><button type="submit" style="display:inline-flex;align-items:center;justify-content:center;height:32px;padding:0 12px;font-size:14px;font-weight:500;line-height:20px;border-radius:6px;cursor:pointer;color:var(--next-error-btn-text);background:var(--next-error-btn-bg);border:var(--next-error-btn-border)">Reload</button></form></div></div><!--$--><!--/$--><script src="/_next/static/chunks/webpack-f0285ce91d4ec9ef.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[25020,[],\"\"]\n3:I[81130,[],\"\"]\n4:I[84649,[],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[84649,[],\"ViewportBoundary\"]\na:I[84649,[],\"MetadataBoundary\"]\nc:I[45336,[],\"default\",1]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_global-error\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"_global-error\",{\"children\":[\"__PAGE__\",{}]}]}],[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[\"$\",\"html\",null,{\"id\":\"__next_error__\",\"children\":[[\"$\",\"head\",null,{\"children\":[[\"$\",\"title\",null,{\"children\":\"500: This page couldn’t load\"}],[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\":root {--next-error-bg: #fff;--next-error-text: #171717;--next-error-title: #171717;--next-error-message: #171717;--next-error-digest: #666666;--next-error-btn-text: #fff;--next-error-btn-bg: #171717;--next-error-btn-border: none;--next-error-btn-secondary-text: #171717;--next-error-btn-secondary-bg: transparent;--next-error-btn-secondary-border: 1px solid rgba(0,0,0,0.08);}@media (prefers-color-scheme: dark) {:root {--next-error-bg: #0a0a0a;--next-error-text: #ededed;--next-error-title: #ededed;--next-error-message: #ededed;--next-error-digest: #a0a0a0;--next-error-btn-text: #0a0a0a;--next-error-btn-bg: #ededed;--next-error-btn-border: none;--next-error-btn-secondary-text: #ededed;--next-error-btn-secondary-bg: transparent;--next-error-btn-secondary-border: 1px solid rgba(255,255,255,0.14);}}body { margin: 0; color: var(--next-error-text); background: var(--next-error-bg); }\"}}]]}],[\"$\",\"body\",null,{\"children\":[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"display\":\"flex\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"style\":{\"marginTop\":\"-32px\",\"maxWidth\":\"325px\",\"padding\":\"32px 28px\",\"textAlign\":\"left\"},\"children\":[[\"$\",\"svg\",null,{\"width\":\"32\",\"height\":\"32\",\"viewBox\":\"-0.2 -1.5 32 32\",\"fill\":\"none\",\"style\":{\"marginBottom\":\"24px\"},\"children\":[\"$\",\"path\",null,{\"d\":\"M16.9328 0C18.0839 0.000116771 19.1334 0.658832 19.634 1.69531L31.4299 26.1309C32.0708 27.4588 31.1036 28.9999 29.6291 29H2.00215C0.527541 29 -0.439628 27.4588 0.201371 26.1309L11.9973 1.69531C12.4979 0.658823 13.5474 7.75066e-05 14.6984 0H16.9328ZM3.59493 26H28.0363L16.9328 3H14.6984L3.59493 26ZM15.8156 19C16.9202 19.0001 17.8156 19.8955 17.8156 21C17.8156 22.1045 16.9202 22.9999 15.8156 23C14.7111 23 13.8156 22.1046 13.8156 21C13.8156 19.8954 14.7111 19 15.8156 19ZM17.3156 16.5H14.3156V8.5H17.3156V16.5Z\",\"fill\":\"var(--next-error-title)\"}]}],[\"$\",\"h1\",null,{\"style\":{\"fontSize\":\"24px\",\"fontWeight\":500,\"letterSpacing\":\"-0.02em\",\"lineHeight\":\"32px\",\"margin\":\"0 0 12px 0\",\"color\":\"var(--next-error-title)\"},\"children\":\"This page couldn’t load\"}],[\"$\",\"p\",null,{\"style\":{\"fontSize\":\"14px\",\"fontWeight\":400,\"lineHeight\":\"21px\",\"margin\":\"0 0 20px 0\",\"color\":\"var(--next-error-message)\"},\"children\":\"A server error occurred. Reload to try again.\"}],[\"$\",\"form\",null,{\"style\":{\"margin\":0},\"children\":[\"$\",\"button\",null,{\"type\":\"submit\",\"style\":{\"display\":\"inline-flex\",\"alignItems\":\"center\",\"justifyContent\":\"center\",\"height\":\"32px\",\"padding\":\"0 12px\",\"fontSize\":\"14px\",\"fontWeight\":500,\"lineHeight\":\"20px\",\"borderRadius\":\"6px\",\"cursor\":\"pointer\",\"color\":\"var(--next-error-btn-text)\",\"background\":\"var(--next-error-btn-bg)\",\"border\":\"var(--next-error-btn-border)\"},\"children\":\"Reload\"}]}]]}]}]}]]}],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,\"$@7\"],[\"$\",\"$1\",\"h\",{\"children\":[null,[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"xyMkEaICFHJoa98VgJyzY\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[]\n"])</script></body></html>
@@ -1 +1 @@
1
- {"node":{},"edge":{},"encryptionKey":"Qlf90zxyCzzYzaoKppTmBuDpgjEdOwtSN9RL3zxLhbg="}
1
+ {"node":{},"edge":{},"encryptionKey":"8jTeJntsWjrjOUPv04qpNTFNaw6kh9pHiBcscCa/Kr8="}
@@ -7,4 +7,4 @@ Context: knowledge \xb7 history \xb7 undo \xb7 discuss
7
7
  Settings: model \xb7 prefs \xb7 config \xb7 hooks \xb7 mode \xb7 steer
8
8
  Advanced: report \xb7 export \xb7 cleanup \xb7 run-hook \xb7 migrate \xb7 remote
9
9
 
10
- Type /gsd <subcommand> to run. Use /gsd help for this message.`;function u(e){return e.isStreaming?"follow_up":"prompt"}function m(e,t={}){let s=e.trim(),r=function(e){if(!e.startsWith("/"))return null;let t=e.slice(1).trim();if(!t)return null;let s=t.search(/\s/);return -1===s?{name:t,args:""}:{name:t.slice(0,s),args:t.slice(s+1).trim()}}(s);if("/clear"===s)return{kind:"local",input:s,commandName:"clear",action:"clear_terminal"};if("/refresh"===s)return{kind:"local",input:s,commandName:"refresh",action:"refresh_workspace"};if("/state"===s)return{kind:"rpc",input:s,commandName:"state",command:{type:"get_state"}};if("/new-session"===s)return{kind:"rpc",input:s,commandName:"new",command:{type:"new_session"}};if(!r)return{kind:"prompt",input:s,slashCommandName:null,command:{type:u(t),message:s}};if("new"===r.name)return{kind:"rpc",input:s,commandName:"new",command:{type:"new_session"}};if("gsd"===r.name)return function(e,t,s){let r=t.trim(),a=r.search(/\s/),n=-1===a?r:r.slice(0,a),i=-1===a?"":r.slice(a+1).trim();if(!n)return{kind:"prompt",input:e,slashCommandName:"gsd",command:{type:u(s),message:e}};if("help"===n)return{kind:"local",input:e,commandName:"gsd",action:"gsd_help"};if("status"===n||"visualize"===n)return{kind:"view-navigate",input:e,commandName:"gsd",view:"visualize"};let o=l.get(n);return o?{kind:"surface",input:e,commandName:"gsd",surface:o,args:i}:(d.has(n),{kind:"prompt",input:e,slashCommandName:"gsd",command:{type:u(s),message:e}})}(s,r.args,t);let a=o.get(r.name);if(a)return{kind:"surface",input:s,commandName:r.name,surface:a,args:r.args};if(i.has(r.name)){var c,h;let e;return h=c=r.name,e=n.get(h)??"Browser handling is reserved for this built-in command.",{kind:"reject",input:s,commandName:c,reason:`/${c} is a built-in pi command (${e}) that is not available in the browser yet.`,guidance:"It was blocked instead of falling through to the model."}}return{kind:"prompt",input:s,slashCommandName:r.name,command:{type:u(t),message:s}}}function h(e){switch(e.kind){case"surface":return{type:"system",message:`/${e.commandName} is reserved for browser-native handling and was not sent to the model.`};case"reject":return{type:"error",message:`${e.reason} ${e.guidance}`.trim()};default:return null}}var x=s(37144);class p{constructor(e,t=e=>new EventSource(e)){this.eventSource=null,this.lastConnectionState="idle",this.handlers=e,this.createEventSource=t}isOpen(){return null!==this.eventSource}ensure(){if(this.eventSource||!this.handlers.canConnect())return;let e=this.createEventSource(this.handlers.streamUrl());this.eventSource=e,e.onopen=()=>{let e=this.lastConnectionState;this.lastConnectionState="connected",this.handlers.onOpen({previousState:e,wasDisconnected:"reconnecting"===e||"disconnected"===e||"error"===e})},e.onmessage=e=>{this.handlers.onMessage(e.data)},e.onerror=()=>{let e="connected"===this.lastConnectionState?"reconnecting":"error",t=e!==this.lastConnectionState;this.lastConnectionState=e,this.handlers.onError({nextConnectionState:e,changed:t})}}close(){this.eventSource?.close(),this.eventSource=null}}function g(e,t){return{id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,type:e,content:t,timestamp:function(e=new Date){return e.toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}()}}function f(e,t){return[...e,t].slice(-250)}var b=s(83890);let v=new Set(["ls","ll","la","pwd","cd","dir","cat","head","tail","wc","file","which","whoami","echo","date","tree","find","grep","rg","clear","env","df","du","uname","hostname","mkdir","rm","cp","mv","touch","chmod","less","more","sort","uniq","sed","awk","curl","wget","tar","zip","unzip","git","docker","npm","npx","yarn","pnpm","node","python","python3","pip","pip3","make","cargo","go","ruby","brew"]);function j(e){let t=e.trimStart(),s=t.search(/\s/);return(-1===s?t:t.slice(0,s)).toLowerCase()}let y=[{id:"shell-command-prefix",maxShows:2,evaluate(e){let t;if(!(!((t=e.input.trimStart()).startsWith("!")||t.startsWith("/")||t.includes("\n")||t.length>120)&&v.has(j(t))))return null;let s=j(e.input);return`Tip: "${s}" looks like a shell command. Prefix with ! to run locally, or !! to run without using tokens.`}},{id:"large-paste",maxShows:2,evaluate:e=>e.input.length<2e3||e.input.trimStart().startsWith("/")||e.input.trimStart().startsWith("!")?null:"Tip: Large inputs consume many tokens. Consider saving to a file and asking the agent to read it."},{id:"thinking-level-high",maxShows:1,evaluate(e){let t=e.thinkingLevel?.toLowerCase();if("high"!==t&&"xhigh"!==t)return null;let s=e.input.trim();return s.length>80||s.includes("\n")||s.startsWith("/")||s.startsWith("!")?null:`Tip: Thinking is set to ${t}. Use Ctrl+T to lower it for simple questions — saves tokens.`}},{id:"double-bang-reminder",maxShows:2,evaluate(e){if(e.bashIncludedCount<3)return null;let t=e.input.trimStart();return!t.startsWith("!")||t.startsWith("!!")?null:"Tip: Use !! instead of ! to keep command output out of agent context and save tokens."}},{id:"compaction-nudge",maxShows:1,evaluate(e){if(void 0===e.contextPercent||e.contextPercent<70)return null;let t=e.input.trimStart();return t.startsWith("/")||t.startsWith("!")?null:"Tip: Context is getting full. Use /compact to summarize the conversation and free up space."}}];class w{recordBashIncluded(){this._bashIncludedCount++}get bashIncludedCount(){return this._bashIncludedCount}evaluate(e){let t={...e,bashIncludedCount:this._bashIncludedCount};for(let e of y){let s=this.showCounts.get(e.id)??0;if(s>=e.maxShows)continue;let r=e.evaluate(t);if(r)return this.showCounts.set(e.id,s+1),r}return null}reset(){this.showCounts.clear(),this._bashIncludedCount=0}constructor(){this.showCounts=new Map,this._bashIncludedCount=0}}function N(){return{status:"idle",stale:!1,reloadCount:0,lastRequestedAt:null,lastSuccessAt:null,lastFailureAt:null,lastFailure:null,invalidatedAt:null,invalidationReason:null,invalidationSource:null}}function S(){return{visible:!1,tone:"healthy",label:"Recovery summary pending",detail:"Waiting for the first live workspace snapshot.",validationCount:0,retryInProgress:!1,retryAttempt:0,autoRetryEnabled:!1,isCompacting:!1,currentUnitId:null,freshness:"idle",entrypointLabel:"Inspect recovery",lastError:null}}function k(e){return{...e,status:"refreshing",lastRequestedAt:new Date().toISOString(),lastFailure:null}}function C(e,t,s){return{...e,status:e.lastSuccessAt?"stale":e.status,stale:!0,invalidatedAt:new Date().toISOString(),invalidationReason:t,invalidationSource:s}}function A(e){return{...e,status:"fresh",stale:!1,reloadCount:e.reloadCount+1,lastSuccessAt:new Date().toISOString(),lastFailureAt:null,lastFailure:null}}function R(e,t){return{...e,status:"error",stale:!0,lastFailureAt:new Date().toISOString(),lastFailure:t}}function T(e){return e.live.workspace??e.boot?.workspace??null}function E(e){return e.live.auto??e.boot?.auto??null}function P(e){return e.live.resumableSessions.length>0?e.live.resumableSessions:e.boot?.resumableSessions??[]}function _(e){let t=e.boot?.bridge??null,s=T(e),r=E(e),a=s?.validationIssues.length??0,n=!!t?.sessionState?.retryInProgress,i=t?.sessionState?.retryAttempt??0,o=!!t?.sessionState?.autoRetryEnabled,l=!!t?.sessionState?.isCompacting,d=e.live.freshness.recovery,c="error"===d.status?"error":d.stale?"stale":d.lastSuccessAt?"fresh":"idle",u=t?.lastError?{message:t.lastError.message,phase:t.lastError.phase,at:t.lastError.at}:null,m="healthy",h="Recovery summary healthy",x="No retry, compaction, bridge, or validation recovery signals are active.";return s||r||t?(u||"error"===c?(m="danger",h="Recovery attention required",x=u?.message??d.lastFailure??"A targeted live refresh failed."):a>0?(m="warning",h=`Recovery summary: ${a} validation issue${1===a?"":"s"}`,x="Workspace validation surfaced issues that may need doctor or audit follow-up."):n?(m="warning",h=`Recovery retry active (attempt ${Math.max(1,i)})`,x="The live bridge is retrying the current unit after a transient failure."):l?(m="warning",h="Recovery compaction active",x="The live session is compacting context before continuing."):"stale"===c&&(m="warning",h="Recovery summary stale",x=d.invalidationReason?`Waiting for a targeted refresh after ${d.invalidationReason.replaceAll("_"," ")}.`:"Waiting for the next targeted refresh."),{visible:!0,tone:m,label:h,detail:x,validationCount:a,retryInProgress:n,retryAttempt:i,autoRetryEnabled:o,isCompacting:l,currentUnitId:r?.currentUnit?.id??null,freshness:c,entrypointLabel:"danger"===m||"warning"===m?"Inspect recovery":"Review recovery",lastError:u}):S()}let I=new Set(["settings","model","thinking","git","resume","name","fork","compact","login","logout","session","export","gsd-visualize","gsd-forensics","gsd-doctor","gsd-skill-health","gsd-knowledge","gsd-capture","gsd-triage","gsd-quick","gsd-history","gsd-undo","gsd-inspect","gsd-prefs","gsd-config","gsd-hooks","gsd-mode","gsd-steer","gsd-report","gsd-export","gsd-cleanup","gsd-queue"]);function F(e){return!!(e?.activeSessionId||e?.sessionState?.sessionId)}function $(e){return e instanceof Error?e.message:String(e)}function L(e){if("failed"===e.phase)return{type:"error",message:`Bridge failed${e.lastError?.message?` — ${e.lastError.message}`:""}`};if("starting"===e.phase)return{type:"system",message:"Bridge starting for the current project…"};if("ready"===e.phase){let t=X(e);return{type:"success",message:t?`Live bridge ready — attached to ${t}`:"Live bridge ready — session attachment pending"}}return{type:"system",message:"Bridge idle"}}let D=new Set(["running","awaiting_browser_auth","awaiting_input"]),M=new Set(["succeeded","failed","cancelled"]);function q(e,t){return e.required.providers.find(e=>e.id===t)?.label??t}function B(e,t){if(!e)return null;let s={...e,bridge:t};return{...s,resumableSessions:ei(s.resumableSessions,s)}}function O(e,t){return e?.bridge.sessionState?B(e,{...e.bridge,sessionState:{...e.bridge.sessionState,...t}}):e}function U(e,t){return e?{...e,onboarding:t,onboardingNeeded:t.locked}:null}function z(e){return"failed"===e.bridgeAuthRefresh.phase?{type:"error",message:e.bridgeAuthRefresh.error?`Bridge auth refresh failed — ${e.bridgeAuthRefresh.error}`:"Bridge auth refresh failed after setup"}:"pending"===e.bridgeAuthRefresh.phase?{type:"system",message:"Credentials saved — refreshing bridge auth before the workspace unlocks…"}:e.lastValidation?.status==="failed"?{type:"error",message:`Credential validation failed — ${e.lastValidation.message}`}:e.locked||e.lastValidation?.status!=="succeeded"?e.activeFlow?.status==="awaiting_browser_auth"?{type:"system",message:`${e.activeFlow.providerLabel} sign-in is waiting for browser confirmation`}:e.activeFlow?.status==="awaiting_input"?{type:"system",message:`${e.activeFlow.providerLabel} sign-in needs one more input step`}:e.activeFlow?.status==="cancelled"?{type:"system",message:`${e.activeFlow.providerLabel} sign-in was cancelled`}:e.activeFlow?.status==="failed"?{type:"error",message:e.activeFlow.error?`${e.activeFlow.providerLabel} sign-in failed — ${e.activeFlow.error}`:`${e.activeFlow.providerLabel} sign-in failed`}:"required_setup"===e.lockReason?{type:"system",message:"Onboarding is still required before model-backed prompts will run"}:null:{type:"success",message:`${q(e,e.lastValidation.providerId)} is ready — workspace unlocked`}}function G(e){let t=[g("system",`GSD web workspace attached to ${e.project.cwd}`),g("system",`Workspace scope: ${J(e.workspace)}`)],s=L(e.bridge);t.push(g(s.type,s.message)),e.bridge.lastError&&t.push(g("error",`Bridge error: ${e.bridge.lastError.message}`));let r=z(e.onboarding);return r&&t.push(g(r.type,r.message)),t}function W(e,t=3){if(!e)return"—";let s=e.split(/[\\/]/).filter(Boolean);if(s.length<=t)return e.startsWith("/")?`/${s.join("/")}`:s.join("/");let r=s.slice(-t).join("/");return`…/${r}`}function K(e){return e?e.split(/[\\/]/).filter(Boolean).at(-1)||e:"Current project"}function V(e){if(!e||e<1e3)return"0m";let t=Math.floor(e/6e4),s=Math.floor(t/60),r=t%60;return s>0?`${s}h ${r}m`:`${r}m`}function H(e){return!Number.isFinite(e)||e<=0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(Math.round(e))}function Y(e){return!Number.isFinite(e)||e<=0?"$0.00":`$${e.toFixed(2)}`}function J(e){if(!e)return"Project scope pending";let t=[e.active.milestoneId,e.active.sliceId,e.active.taskId].filter(Boolean).join("/");return t?`${t} — ${e.active.phase}`:`project — ${e.active.phase}`}function Q(e){if(!e?.active.milestoneId||!e.active.sliceId)return null;let t=e.milestones.find(t=>t.id===e.active.milestoneId),s=t?.slices.find(t=>t.id===e.active.sliceId);return s?.branch??null}function Z(e){if(!e?.active.milestoneId||!e.active.sliceId)return null;let t=e.milestones.find(t=>t.id===e.active.milestoneId);return t?.slices.find(t=>t.id===e.active.sliceId)??null}function X(e){if(!e?.sessionState&&!e?.activeSessionId)return null;let t=e.sessionState?.sessionName?.trim();return t||(e.activeSessionId?`session ${e.activeSessionId}`:e.sessionState?.sessionId??null)}function ee(e){let t=e?.sessionState?.model;return t&&(t.id||t.providerId||t.provider)||"model pending"}function et(e){let t=e?.sessionState?.model;return t?{provider:t.provider??t.providerId,modelId:t.id}:null}function es(e){if(!e)return null;if(e.required.satisfiedBy?.providerId)return e.required.satisfiedBy.providerId;let t=e.required.providers.find(e=>!e.configured&&e.recommended);if(t)return t.id;let s=e.required.providers.find(e=>!e.configured);return s?s.id:e.required.providers[0]?.id??null}function er(e,t){return{...e,pending:!1,loaded:!1,error:t}}function ea(e,t){return{...e,phase:"error",pending:!1,stale:!0,error:t,lastFailureAt:new Date().toISOString()}}function en(e){return e?.bridge.activeSessionFile??e?.bridge.sessionState?.sessionFile??null}function ei(e,t){let s=en(t),r=t?.bridge.sessionState?.sessionName?.trim()||void 0;return e.map(e=>{let t=s?e.path===s:e.isActive;return{...e,isActive:t,...t&&r?{name:r}:{}}})}function eo(e,t){return{...e,activeSessionPath:en(t),sessions:ei(e.sessions,t)}}function el(e,t,s){return{...e,activeSessionPath:s.isActive?t:e.activeSessionPath,sessions:e.sessions.map(e=>e.path===t?{...e,...s}:s.isActive?{...e,isActive:!1}:e)}}function ed(e){let t=e.boot?.onboarding;return t?.bridgeAuthRefresh.phase==="failed"&&t.bridgeAuthRefresh.error?t.bridgeAuthRefresh.error:t?.lastValidation?.status==="failed"?t.lastValidation.message:e.lastBridgeError?.message??e.lastClientError}function ec(e){if("loading"===e.bootStatus)return{label:"Loading workspace",tone:"info"};if("error"===e.bootStatus)return{label:"Boot failed",tone:"danger"};let t=function(e){if("loading"===e.bootStatus||!e.boot)return{phase:"loading",label:"Loading setup state",detail:"Resolving the current project, bridge, and onboarding contract…",tone:"info"};let t=e.boot.onboarding;return t.activeFlow?.status==="awaiting_browser_auth"?{phase:"awaiting_browser_auth",label:"Continue sign-in in your browser",detail:`${t.activeFlow.providerLabel} is waiting for browser confirmation before the workspace can unlock.`,tone:"info"}:t.activeFlow?.status==="awaiting_input"?{phase:"awaiting_input",label:"One more sign-in step is required",detail:t.activeFlow.prompt?.message??`${t.activeFlow.providerLabel} needs one more input step.`,tone:"info"}:"bridge_refresh_pending"===t.lockReason?{phase:"refreshing",label:"Refreshing bridge auth",detail:"Credentials validated. The live bridge is restarting onto the new auth view before the shell unlocks.",tone:"info"}:"bridge_refresh_failed"===t.lockReason?{phase:"failure",label:"Setup completed, but the shell is still locked",detail:t.bridgeAuthRefresh.error??"The bridge could not reload auth after setup.",tone:"danger"}:t.lastValidation?.status==="failed"?{phase:"failure",label:"Credential validation failed",detail:t.lastValidation.message,tone:"danger"}:"saving_api_key"===e.onboardingRequestState?{phase:"validating",label:"Validating credentials",detail:"Checking the provider key and saving it only if validation succeeds.",tone:"info"}:"starting_provider_flow"===e.onboardingRequestState||"submitting_provider_flow_input"===e.onboardingRequestState?{phase:"running_flow",label:"Advancing provider sign-in",detail:"The onboarding flow is running and will update here as soon as the next step is ready.",tone:"info"}:t.locked?{phase:"locked",label:"Required setup needed",detail:"Choose a required provider, validate it here, and the workspace will unlock without restarting the host.",tone:"warning"}:{phase:"ready",label:"Workspace unlocked",detail:t.lastValidation?.status==="succeeded"?`${q(t,t.lastValidation.providerId)} is ready and the workspace is live.`:"Required setup is satisfied and the shell is ready for live commands.",tone:"success"}}(e);if("ready"!==t.phase)return{label:t.label,tone:t.tone};if(e.boot?.bridge.phase==="failed")return{label:"Bridge failed",tone:"danger"};switch(e.connectionState){case"connected":return{label:"Bridge connected",tone:"success"};case"connecting":return{label:"Connecting stream",tone:"info"};case"reconnecting":return{label:"Reconnecting stream",tone:"warning"};case"disconnected":return{label:"Stream disconnected",tone:"warning"};case"error":return{label:"Stream error",tone:"danger"};default:return{label:"Workspace idle",tone:"muted"}}}function eu(e,t){if(!t)return e;let s=new URL(e,"http://localhost");return s.searchParams.set("project",t),s.pathname+s.search}class em{constructor(e){this.projectCwd=e,this.state={bootStatus:"idle",connectionState:"idle",boot:null,live:{auto:null,workspace:null,resumableSessions:[],recoverySummary:S(),freshness:{auto:N(),workspace:N(),recovery:N(),resumableSessions:N(),gitSummary:N(),sessionBrowser:N(),sessionStats:N()},softBootRefreshCount:0,targetedRefreshCount:0},terminalLines:[g("system","Preparing the live GSD workspace…")],lastClientError:null,lastBridgeError:null,sessionAttached:!1,lastEventType:null,commandInFlight:null,lastSlashCommandOutcome:null,commandSurface:(0,x.iE)(),onboardingRequestState:"idle",onboardingRequestProviderId:null,pendingUiRequests:[],streamingAssistantText:"",streamingThinkingText:"",liveTranscript:[],liveThinkingTranscript:[],completedToolExecutions:[],activeToolExecution:null,currentTurnSegments:[],completedTurnSegments:[],chatUserMessages:[],statusTexts:{},widgetContents:{},titleOverride:null,editorTextBuffer:null},this.listeners=new Set,this.contextualTips=new w,this.eventStream=new p({canConnect:()=>!this.disposed&&!this.state.boot?.onboarding.locked,streamUrl:()=>(0,b.QT)(this.buildUrl("/api/session/events")),onOpen:({wasDisconnected:e})=>this.handleEventStreamOpen(e),onMessage:e=>this.handleEventStreamMessage(e),onError:({nextConnectionState:e,changed:t})=>this.handleEventStreamError(e,t)}),this.bootPromise=null,this.onboardingPollTimer=null,this.started=!1,this.disposed=!1,this.lastBridgeDigest=null,this.commandTimeoutTimer=null,this.lastBootRefreshAt=0,this.visibilityHandler=null,this.subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}),this.getSnapshot=()=>this.state,this.start=()=>{this.started||this.disposed||(this.started=!0,"u">typeof document&&(this.visibilityHandler=()=>{"visible"===document.visibilityState&&Date.now()-this.lastBootRefreshAt>=3e4&&this.refreshBoot({soft:!0})},document.addEventListener("visibilitychange",this.visibilityHandler)),this.refreshBoot())},this.dispose=()=>{this.disposed=!0,this.started=!1,this.stopOnboardingPoller(),this.closeEventStream(),this.clearCommandTimeout(),this.visibilityHandler&&"u">typeof document&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null)},this.disconnectSSE=()=>{this.closeEventStream()},this.reconnectSSE=()=>{this.disposed||(this.ensureEventStream(),this.refreshBoot({soft:!0}))},this.clearTerminalLines=()=>{let e=this.state.boot?G(this.state.boot):[g("system","Terminal cleared")];this.patchState({terminalLines:e})},this.consumeEditorTextBuffer=()=>{let e=this.state.editorTextBuffer;return null!==e&&this.patchState({editorTextBuffer:null}),e},this.openCommandSurface=(e,t={})=>{let s=P(this.state);this.patchState({commandSurface:(0,x.Q8)(this.state.commandSurface,{surface:e,source:t.source??"surface",args:t.args??"",selectedTarget:t.selectedTarget,onboardingLocked:this.state.boot?.onboarding.locked,currentModel:et(this.state.boot?.bridge),currentThinkingLevel:this.state.boot?.bridge.sessionState?.thinkingLevel??null,preferredProviderId:es(this.state.boot?.onboarding),resumableSessions:s.map(e=>({id:e.id,path:e.path,name:e.name,isActive:e.isActive})),currentSessionPath:this.state.boot?.bridge.activeSessionFile??this.state.boot?.bridge.sessionState?.sessionFile??null,currentSessionName:this.state.boot?.bridge.sessionState?.sessionName??null,projectCwd:this.state.boot?.project.cwd??null,projectSessionsDir:this.state.boot?.project.sessionsDir??null})})},this.closeCommandSurface=()=>{this.patchState({commandSurface:(0,x.Qx)(this.state.commandSurface)})},this.setCommandSurfaceSection=e=>{let t=P(this.state);this.patchState({commandSurface:(0,x.c0)(this.state.commandSurface,e,{onboardingLocked:this.state.boot?.onboarding.locked,currentModel:et(this.state.boot?.bridge),currentThinkingLevel:this.state.boot?.bridge.sessionState?.thinkingLevel??null,preferredProviderId:es(this.state.boot?.onboarding),resumableSessions:t.map(e=>({id:e.id,path:e.path,name:e.name,isActive:e.isActive})),currentSessionPath:this.state.boot?.bridge.activeSessionFile??this.state.boot?.bridge.sessionState?.sessionFile??null,currentSessionName:this.state.boot?.bridge.sessionState?.sessionName??null,projectCwd:this.state.boot?.project.cwd??null,projectSessionsDir:this.state.boot?.project.sessionsDir??null})})},this.selectCommandSurfaceTarget=e=>{this.patchState({commandSurface:(0,x.nU)(this.state.commandSurface,e)})},this.loadGitSummary=async()=>{let e={...this.state.commandSurface.gitSummary,pending:!0,error:null},t={...this.state.live,freshness:{...this.state.live.freshness,gitSummary:k(this.state.live.freshness.gitSummary)}};this.patchState({live:{...t,recoverySummary:_({boot:this.state.boot,live:t})},commandSurface:(0,x.Yc)({...this.state.commandSurface,gitSummary:e},"load_git_summary")});try{let t=await (0,b.tm)(this.buildUrl("/api/git"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),s=await t.json().catch(()=>null),r=s&&"object"==typeof s&&("repo"===s.kind||"not_repo"===s.kind)&&s.project&&"object"==typeof s.project&&"current_project"===s.project.scope&&"string"==typeof s.project.cwd&&("not_repo"===s.kind?"string"==typeof s.message:"string"==typeof s.project?.repoRoot&&"boolean"==typeof s.hasChanges&&"boolean"==typeof s.hasConflicts&&!!s.counts&&"object"==typeof s.counts&&!!Array.isArray(s.changedFiles)&&"number"==typeof s.truncatedFileCount&&"number"==typeof s.counts.changed&&"number"==typeof s.counts.staged&&"number"==typeof s.counts.dirty&&"number"==typeof s.counts.untracked&&"number"==typeof s.counts.conflicts)?s:null;if(!t.ok||!r){let r=s&&"object"==typeof s&&"error"in s&&"string"==typeof s.error?s.error:`Current-project git summary failed with ${t.status}`,a=er(e,r),n={...this.state.live,freshness:{...this.state.live.freshness,gitSummary:R(this.state.live.freshness.gitSummary,r)}};return this.patchState({live:{...n,recoverySummary:_({boot:this.state.boot,live:n})},commandSurface:(0,x.yC)({...this.state.commandSurface,gitSummary:a},{action:"load_git_summary",success:!1,message:r,gitSummary:a})}),null}let a={...this.state.live,freshness:{...this.state.live.freshness,gitSummary:A(this.state.live.freshness.gitSummary)}};return this.patchState({live:{...a,recoverySummary:_({boot:this.state.boot,live:a})},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"load_git_summary",success:!0,message:"",gitSummary:{pending:!1,loaded:!0,result:r,error:null}})}),r}catch(a){let t=$(a),s=er(e,t),r={...this.state.live,freshness:{...this.state.live.freshness,gitSummary:R(this.state.live.freshness.gitSummary,t)}};return this.patchState({live:{...r,recoverySummary:_({boot:this.state.boot,live:r})},commandSurface:(0,x.yC)({...this.state.commandSurface,gitSummary:s},{action:"load_git_summary",success:!1,message:t,gitSummary:s})}),null}},this.loadRecoveryDiagnostics=async()=>{var e;let t={...e=this.state.commandSurface.recovery,pending:!0,error:null,phase:e.loaded?e.phase:"loading"},s={...this.state.live,freshness:{...this.state.live.freshness,recovery:k(this.state.live.freshness.recovery)}};this.patchState({live:{...s,recoverySummary:_({boot:this.state.boot,live:s})},commandSurface:(0,x.Yc)({...this.state.commandSurface,recovery:t},"load_recovery_diagnostics")});try{let e=await (0,b.tm)(this.buildUrl("/api/recovery"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),s=await e.json().catch(()=>null),r=s&&"object"==typeof s&&("ready"===s.status||"unavailable"===s.status)&&"string"==typeof s.loadedAt&&s.project&&"string"==typeof s.project.cwd&&s.summary&&"string"==typeof s.summary.label&&"string"==typeof s.summary.detail&&s.bridge&&"string"==typeof s.bridge.phase&&s.validation&&"number"==typeof s.validation.total&&s.doctor&&"number"==typeof s.doctor.total&&s.interruptedRun&&"boolean"==typeof s.interruptedRun.available&&s.actions&&Array.isArray(s.actions.browser)&&Array.isArray(s.actions.commands)?s:null;if(!e.ok||!r){let r=s&&"object"==typeof s&&"error"in s&&"string"==typeof s.error?s.error:`Recovery diagnostics failed with ${e.status}`,a=ea(t,r),n={...this.state.live,freshness:{...this.state.live.freshness,recovery:R(this.state.live.freshness.recovery,r)}};return this.patchState({lastClientError:r,live:{...n,recoverySummary:_({boot:this.state.boot,live:n})},commandSurface:(0,x.yC)({...this.state.commandSurface,recovery:a},{action:"load_recovery_diagnostics",success:!1,message:r,recovery:a})}),null}let a={...{phase:"ready"===r.status?"ready":"unavailable",pending:!1,loaded:!0,stale:!1,diagnostics:r,error:null,lastLoadedAt:r.loadedAt,lastInvalidatedAt:null,lastFailureAt:null},lastInvalidatedAt:this.state.commandSurface.recovery.lastInvalidatedAt},n={...this.state.live,freshness:{...this.state.live.freshness,recovery:A(this.state.live.freshness.recovery)}};return this.patchState({lastClientError:null,live:{...n,recoverySummary:_({boot:this.state.boot,live:n})},commandSurface:(0,x.yC)({...this.state.commandSurface,recovery:a},{action:"load_recovery_diagnostics",success:!0,message:"ready"===r.status?"Recovery diagnostics refreshed":"Recovery diagnostics are currently unavailable",recovery:a})}),r}catch(a){let e=$(a),s=ea(t,e),r={...this.state.live,freshness:{...this.state.live.freshness,recovery:R(this.state.live.freshness.recovery,e)}};return this.patchState({lastClientError:e,live:{...r,recoverySummary:_({boot:this.state.boot,live:r})},commandSurface:(0,x.yC)({...this.state.commandSurface,recovery:s},{action:"load_recovery_diagnostics",success:!1,message:e,recovery:s})}),null}},this.loadForensicsDiagnostics=async()=>{this.patchDiagnosticsPhaseState("forensics",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/forensics"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Forensics request failed with ${e.status}`;return this.patchDiagnosticsPhaseState("forensics",{phase:"error",error:s}),null}return this.patchDiagnosticsPhaseState("forensics",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchDiagnosticsPhaseState("forensics",{phase:"error",error:e}),null}},this.loadDoctorDiagnostics=async e=>{this.patchDoctorState({phase:"loading",error:null});try{let t=e?`/api/doctor?scope=${encodeURIComponent(e)}`:"/api/doctor",s=await (0,b.tm)(t,{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),r=await s.json().catch(()=>null);if(!s.ok||!r){let e=r?.error??`Doctor request failed with ${s.status}`;return this.patchDoctorState({phase:"error",error:e}),null}return this.patchDoctorState({phase:"loaded",data:r,lastLoadedAt:new Date().toISOString()}),r}catch(t){let e=$(t);return this.patchDoctorState({phase:"error",error:e}),null}},this.applyDoctorFixes=async e=>{this.patchDoctorState({fixPending:!0,lastFixError:null,lastFixResult:null});try{let t=await (0,b.tm)(this.buildUrl("/api/doctor"),{method:"POST",cache:"no-store",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e?{scope:e}:{})}),s=await t.json().catch(()=>null);if(!t.ok||!s){let e=s?.error??`Doctor fix request failed with ${t.status}`;return this.patchDoctorState({fixPending:!1,lastFixError:e}),null}return this.patchDoctorState({fixPending:!1,lastFixResult:s}),this.loadDoctorDiagnostics(e),s}catch(t){let e=$(t);return this.patchDoctorState({fixPending:!1,lastFixError:e}),null}},this.loadSkillHealthDiagnostics=async()=>{this.patchDiagnosticsPhaseState("skillHealth",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/skill-health"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Skill health request failed with ${e.status}`;return this.patchDiagnosticsPhaseState("skillHealth",{phase:"error",error:s}),null}return this.patchDiagnosticsPhaseState("skillHealth",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchDiagnosticsPhaseState("skillHealth",{phase:"error",error:e}),null}},this.loadKnowledgeData=async()=>{this.patchKnowledgeCapturesPhaseState("knowledge",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/knowledge"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Knowledge request failed with ${e.status}`;return this.patchKnowledgeCapturesPhaseState("knowledge",{phase:"error",error:s}),null}return this.patchKnowledgeCapturesPhaseState("knowledge",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchKnowledgeCapturesPhaseState("knowledge",{phase:"error",error:e}),null}},this.loadCapturesData=async()=>{this.patchKnowledgeCapturesPhaseState("captures",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/captures"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Captures request failed with ${e.status}`;return this.patchKnowledgeCapturesPhaseState("captures",{phase:"error",error:s}),null}return this.patchKnowledgeCapturesPhaseState("captures",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchKnowledgeCapturesPhaseState("captures",{phase:"error",error:e}),null}},this.loadSettingsData=async()=>{this.patchSettingsPhaseState({phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/settings-data"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Settings request failed with ${e.status}`;return this.patchSettingsPhaseState({phase:"error",error:s}),null}return this.patchSettingsPhaseState({phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchSettingsPhaseState({phase:"error",error:e}),null}},this.loadHistoryData=async()=>{this.patchRemainingCommandsPhaseState("history",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/history"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`History request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("history",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("history",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchRemainingCommandsPhaseState("history",{phase:"error",error:e}),null}},this.loadInspectData=async()=>{this.patchRemainingCommandsPhaseState("inspect",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/inspect"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Inspect request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("inspect",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("inspect",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchRemainingCommandsPhaseState("inspect",{phase:"error",error:e}),null}},this.loadHooksData=async()=>{this.patchRemainingCommandsPhaseState("hooks",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/hooks"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Hooks request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("hooks",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("hooks",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchRemainingCommandsPhaseState("hooks",{phase:"error",error:e}),null}},this.loadExportData=async e=>{this.patchRemainingCommandsPhaseState("exportData",{phase:"loading",error:null});try{let t=e?`/api/export-data?format=${encodeURIComponent(e)}`:"/api/export-data",s=await (0,b.tm)(t,{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),r=await s.json().catch(()=>null);if(!s.ok||!r){let e=r?.error??`Export request failed with ${s.status}`;return this.patchRemainingCommandsPhaseState("exportData",{phase:"error",error:e}),null}return this.patchRemainingCommandsPhaseState("exportData",{phase:"loaded",data:r,lastLoadedAt:new Date().toISOString()}),r}catch(t){let e=$(t);return this.patchRemainingCommandsPhaseState("exportData",{phase:"error",error:e}),null}},this.loadUndoInfo=async()=>{this.patchRemainingCommandsPhaseState("undo",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/undo"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Undo info request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("undo",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("undo",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchRemainingCommandsPhaseState("undo",{phase:"error",error:e}),null}},this.loadCleanupData=async()=>{this.patchRemainingCommandsPhaseState("cleanup",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/cleanup"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Cleanup data request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("cleanup",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("cleanup",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchRemainingCommandsPhaseState("cleanup",{phase:"error",error:e}),null}},this.loadSteerData=async()=>{this.patchRemainingCommandsPhaseState("steer",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/steer"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Steer data request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("steer",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("steer",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchRemainingCommandsPhaseState("steer",{phase:"error",error:e}),null}},this.executeUndoAction=async()=>{try{let e=await (0,b.tm)(this.buildUrl("/api/undo"),{method:"POST",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Undo action failed with ${e.status}`;return{success:!1,message:s}}return this.loadUndoInfo(),t}catch(e){return{success:!1,message:$(e)}}},this.executeCleanupAction=async(e,t)=>{try{let s=await (0,b.tm)(this.buildUrl("/api/cleanup"),{method:"POST",cache:"no-store",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({branches:e,snapshots:t})}),r=await s.json().catch(()=>null);if(!s.ok||!r){let e=r?.error??`Cleanup action failed with ${s.status}`;return{deletedBranches:0,prunedSnapshots:0,message:e}}return this.loadCleanupData(),r}catch(e){return{deletedBranches:0,prunedSnapshots:0,message:$(e)}}},this.resolveCaptureAction=async e=>{this.patchKnowledgeCapturesState({resolveRequest:{pending:!0,lastError:null,lastResult:null}});try{let t=await (0,b.tm)(this.buildUrl("/api/captures"),{method:"POST",cache:"no-store",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>null);if(!t.ok||!s){let e=s?.error??`Capture resolve failed with ${t.status}`;return this.patchKnowledgeCapturesState({resolveRequest:{pending:!1,lastError:e,lastResult:null}}),null}return this.patchKnowledgeCapturesState({resolveRequest:{pending:!1,lastError:null,lastResult:s}}),this.loadCapturesData(),s}catch(t){let e=$(t);return this.patchKnowledgeCapturesState({resolveRequest:{pending:!1,lastError:e,lastResult:null}}),null}},this.updateSessionBrowserState=e=>{this.patchState({commandSurface:{...this.state.commandSurface,sessionBrowser:{...this.state.commandSurface.sessionBrowser,...e,error:null},lastError:null,lastResult:null}})},this.loadSessionBrowser=async(e={})=>{let t={...this.state.commandSurface.sessionBrowser,...e,error:null},s={...this.state.live,freshness:{...this.state.live.freshness,sessionBrowser:k(this.state.live.freshness.sessionBrowser)}};this.patchState({live:{...s,recoverySummary:_({boot:this.state.boot,live:s})},commandSurface:(0,x.Yc)({...this.state.commandSurface,sessionBrowser:t},"load_session_browser")});let r=new URLSearchParams;t.query.trim()&&r.set("query",t.query.trim()),r.set("sortMode",t.sortMode),r.set("nameFilter",t.nameFilter);try{let e=await (0,b.tm)(this.buildUrl(`/api/session/browser?${r.toString()}`),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),s=await e.json().catch(()=>null),a=function(e){if(!e||"object"!=typeof e)return null;let t=e.project,s=e.query;if(!t||!s||!Array.isArray(e.sessions)||"current_project"!==t.scope||"string"!=typeof t.cwd||"string"!=typeof t.sessionsDir||"string"!=typeof s.query||"string"!=typeof s.sortMode||"string"!=typeof s.nameFilter)return null;let r=e.sessions.filter(e=>"string"==typeof e?.id&&"string"==typeof e?.path&&"string"==typeof e?.cwd&&"string"==typeof e?.createdAt&&"string"==typeof e?.modifiedAt&&"number"==typeof e?.messageCount&&"string"==typeof e?.firstMessage&&"boolean"==typeof e?.isActive&&"number"==typeof e?.depth&&"boolean"==typeof e?.isLastInThread&&Array.isArray(e?.ancestorHasNextSibling));return{scope:t.scope,projectCwd:t.cwd,projectSessionsDir:t.sessionsDir,activeSessionPath:"string"==typeof t.activeSessionPath?t.activeSessionPath:null,query:s.query,sortMode:s.sortMode,nameFilter:s.nameFilter,totalSessions:Number(e.totalSessions??r.length),returnedSessions:Number(e.returnedSessions??r.length),sessions:r,loaded:!0,error:null}}(s);if(!e.ok||!a){let r=s&&"object"==typeof s&&"error"in s&&"string"==typeof s.error?s.error:`Current-project session browser failed with ${e.status}`,a={...t,error:r},n={...this.state.live,freshness:{...this.state.live.freshness,sessionBrowser:R(this.state.live.freshness.sessionBrowser,r)}};return this.patchState({live:{...n,recoverySummary:_({boot:this.state.boot,live:n})},commandSurface:(0,x.yC)({...this.state.commandSurface,sessionBrowser:a},{action:"load_session_browser",success:!1,message:r,sessionBrowser:a})}),null}let n=eo(a,this.state.boot),i=this.state.commandSurface.selectedTarget,o=n.sessions.find(e=>!e.isActive)?.path??n.sessions[0]?.path,l=n.sessions.find(e=>e.path===n.activeSessionPath)??n.sessions[0],d=i;if(i?.kind==="resume"||"resume"===this.state.commandSurface.section){let e=i?.kind==="resume"&&i.sessionPath&&n.sessions.some(e=>e.path===i.sessionPath)?i.sessionPath:o;d={kind:"resume",sessionPath:e}}else if(i?.kind==="name"||"name"===this.state.commandSurface.section){let e=i?.kind==="name"&&i.sessionPath?n.sessions.find(e=>e.path===i.sessionPath)??l:l;d={kind:"name",sessionPath:e?.path,name:i?.kind==="name"&&i.sessionPath===e?.path?i.name:e?.name??""}}let c={...this.state.live,freshness:{...this.state.live.freshness,sessionBrowser:A(this.state.live.freshness.sessionBrowser)}};return this.patchState({live:{...c,recoverySummary:_({boot:this.state.boot,live:c})},commandSurface:(0,x.yC)({...this.state.commandSurface,sessionBrowser:n},{action:"load_session_browser",success:!0,message:"",selectedTarget:d,sessionBrowser:n})}),n}catch(a){let e=$(a),s={...t,error:e},r={...this.state.live,freshness:{...this.state.live.freshness,sessionBrowser:R(this.state.live.freshness.sessionBrowser,e)}};return this.patchState({live:{...r,recoverySummary:_({boot:this.state.boot,live:r})},commandSurface:(0,x.yC)({...this.state.commandSurface,sessionBrowser:s},{action:"load_session_browser",success:!1,message:e,sessionBrowser:s})}),null}},this.renameSessionFromSurface=async(e,t)=>{let s=this.state.commandSurface.selectedTarget,r=t??(s?.kind==="name"?s.name:""),a=r.trim(),n={kind:"name",sessionPath:e,name:r};if(!a)return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"rename_session",success:!1,message:"Session name cannot be empty",selectedTarget:n})}),null;this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"rename_session",n)});try{let t=await (0,b.tm)(this.buildUrl("/api/session/manage"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({action:"rename",sessionPath:e,name:a})}),s=await t.json().catch(()=>null);if(!t.ok||!s||"object"!=typeof s||!0!==s.success){let e=s&&"object"==typeof s&&"error"in s&&"string"==typeof s.error?s.error:`Session rename failed with ${t.status}`;return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"rename_session",success:!1,message:e,selectedTarget:n})}),null}let r=function(e,t,s){if(!e)return null;let r=en(e)===t&&e.bridge.sessionState?{...e.bridge,sessionState:{...e.bridge.sessionState,sessionName:s}}:e.bridge,a={...e,bridge:r};return{...a,resumableSessions:ei(a.resumableSessions.map(e=>e.path===t?{...e,name:s}:e),a)}}(this.state.boot,s.sessionPath,s.name),i=eo(el(this.state.commandSurface.sessionBrowser,s.sessionPath,{name:s.name,...s.isActiveSession?{isActive:!0}:{}}),r),o={kind:"name",sessionPath:s.sessionPath,name:s.name},l={...this.state.live,resumableSessions:ei(P(this.state).map(e=>e.path===s.sessionPath?{...e,name:s.name}:e),r)};return this.patchState({...r?{boot:r}:{},live:{...l,recoverySummary:_({boot:r,live:l})},commandSurface:(0,x.yC)({...this.state.commandSurface,sessionBrowser:i},{action:"rename_session",success:!0,message:`Session name set: ${s.name}`,selectedTarget:o,sessionBrowser:i})}),s}catch(t){let e=$(t);return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"rename_session",success:!1,message:e,selectedTarget:n})}),null}},this.loadAvailableModels=async()=>{this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"loading_models")});let e=await this.sendCommand({type:"get_available_models"},{appendInputLine:!1,appendResponseLine:!1});if(!e||!1===e.success){let t=e?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"loading_models",success:!1,message:`Couldn't load models — ${t}`})}),[]}let t=function(e,t){let s=e&&"object"==typeof e&&"models"in e&&Array.isArray(e.models)?e.models:[],r=[];for(let e of s){let s="string"==typeof e.provider?e.provider:"string"==typeof e.providerId?e.providerId:void 0,a="string"==typeof e.id?e.id:void 0;s&&a&&r.push({provider:s,modelId:a,name:"string"==typeof e.name?e.name:void 0,reasoning:!!e.reasoning,isCurrent:s===t?.provider&&a===t?.modelId})}return r.sort((e,t)=>Number(t.isCurrent)-Number(e.isCurrent)||e.provider.localeCompare(t.provider)||e.modelId.localeCompare(t.modelId))}(e.data,et(this.state.boot?.bridge)),s=this.state.commandSurface.selectedTarget,r=s?.kind==="model"?s:t[0]?{kind:"model",provider:t[0].provider,modelId:t[0].modelId}:s;return this.patchState({commandSurface:{...this.state.commandSurface,pendingAction:null,lastError:null,availableModels:t,selectedTarget:r??null}}),t},this.applyModelSelection=async(e,t)=>{let s={kind:"model",provider:e,modelId:t};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"set_model",s)});let r=await this.sendCommand({type:"set_model",provider:e,modelId:t},{appendInputLine:!1,appendResponseLine:!1});if(!r||!1===r.success){let e=r?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_model",success:!1,message:e,selectedTarget:s})}),r}let a=this.state.boot?.bridge.sessionState?{...this.state.boot.bridge,sessionState:{...this.state.boot.bridge.sessionState,model:r.data}}:null,n=this.state.commandSurface.availableModels.map(s=>({...s,isCurrent:s.provider===e&&s.modelId===t}));return this.patchState({...a&&this.state.boot?{boot:B(this.state.boot,a)}:{},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_model",success:!0,message:`Model set to ${e}/${t}`,selectedTarget:s,availableModels:n})}),r},this.applyThinkingLevel=async e=>{let t={kind:"thinking",level:e};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"set_thinking_level",t)});let s=await this.sendCommand({type:"set_thinking_level",level:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_thinking_level",success:!1,message:e,selectedTarget:t})}),s}let r=this.state.boot?.bridge.sessionState?{...this.state.boot.bridge,sessionState:{...this.state.boot.bridge.sessionState,thinkingLevel:e}}:null;return this.patchState({...r&&this.state.boot?{boot:B(this.state.boot,r)}:{},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_thinking_level",success:!0,message:`Thinking level set to ${e}`,selectedTarget:t})}),s},this.setSteeringModeFromSurface=async e=>{let t=this.state.commandSurface.selectedTarget;this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"set_steering_mode",t)});let s=await this.sendCommand({type:"set_steering_mode",mode:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_steering_mode",success:!1,message:e,selectedTarget:t})}),s}let r=O(this.state.boot,{steeringMode:e});return this.patchState({...r?{boot:r}:{},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_steering_mode",success:!0,message:`Steering mode set to ${e}`,selectedTarget:t})}),s},this.setFollowUpModeFromSurface=async e=>{let t=this.state.commandSurface.selectedTarget;this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"set_follow_up_mode",t)});let s=await this.sendCommand({type:"set_follow_up_mode",mode:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_follow_up_mode",success:!1,message:e,selectedTarget:t})}),s}let r=O(this.state.boot,{followUpMode:e});return this.patchState({...r?{boot:r}:{},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_follow_up_mode",success:!0,message:`Follow-up mode set to ${e}`,selectedTarget:t})}),s},this.setAutoCompactionFromSurface=async e=>{let t=this.state.commandSurface.selectedTarget;this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"set_auto_compaction",t)});let s=await this.sendCommand({type:"set_auto_compaction",enabled:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_auto_compaction",success:!1,message:e,selectedTarget:t})}),s}let r=O(this.state.boot,{autoCompactionEnabled:e});return this.patchState({...r?{boot:r}:{},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_auto_compaction",success:!0,message:`Auto-compaction ${e?"enabled":"disabled"}`,selectedTarget:t})}),s},this.setAutoRetryFromSurface=async e=>{let t=this.state.commandSurface.selectedTarget;this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"set_auto_retry",t)});let s=await this.sendCommand({type:"set_auto_retry",enabled:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_auto_retry",success:!1,message:e,selectedTarget:t})}),s}let r=O(this.state.boot,{autoRetryEnabled:e});return this.patchState({...r?{boot:r}:{},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_auto_retry",success:!0,message:`Auto-retry ${e?"enabled":"disabled"}`,selectedTarget:t})}),s},this.abortRetryFromSurface=async()=>{let e=this.state.commandSurface.selectedTarget;this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"abort_retry",e)});let t=await this.sendCommand({type:"abort_retry"},{appendInputLine:!1,appendResponseLine:!1});if(!t||!1===t.success){let s=t?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"abort_retry",success:!1,message:s,selectedTarget:e})}),t}return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"abort_retry",success:!0,message:"Retry cancellation requested. Live retry state will update when the bridge confirms the abort.",selectedTarget:e})}),t},this.switchSessionFromSurface=async e=>{var t;let s,r={kind:"resume",sessionPath:e};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"switch_session",r)});let a=await this.sendCommand({type:"switch_session",sessionPath:e},{appendInputLine:!1,appendResponseLine:!1});if(!a||!1===a.success){let e=a?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"switch_session",success:!1,message:e,selectedTarget:r})}),a}if(a.data&&"object"==typeof a.data&&"cancelled"in a.data&&a.data.cancelled)return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"switch_session",success:!1,message:"Session switch was cancelled before the browser changed sessions.",selectedTarget:r})}),a;let n=this.state.commandSurface.sessionBrowser.sessions.find(t=>t.path===e)?.name??this.state.boot?.resumableSessions.find(t=>t.path===e)?.name,i=function(e,t,s){if(!e)return null;let r=e.resumableSessions.find(e=>e.path===t),a={...e.bridge,activeSessionFile:t,activeSessionId:r?.id??e.bridge.activeSessionId,sessionState:e.bridge.sessionState?{...e.bridge.sessionState,sessionFile:t,sessionId:r?.id??e.bridge.sessionState.sessionId,sessionName:s??r?.name??e.bridge.sessionState.sessionName}:e.bridge.sessionState},n={...e,bridge:a};return{...n,resumableSessions:ei(n.resumableSessions.map(e=>({...e,isActive:e.path===t})),n)}}(this.state.boot,e,n),o=eo(el(this.state.commandSurface.sessionBrowser,e,{isActive:!0,...n?{name:n}:{}}),i),l={...this.state.live,resumableSessions:ei(P(this.state).map(t=>({...t,isActive:t.path===e,...t.path===e&&n?{name:n}:{}})),i)};return this.patchState({...i?{boot:i}:{},live:{...l,recoverySummary:_({boot:i,live:l})},commandSurface:(0,x.yC)({...this.state.commandSurface,sessionBrowser:o},{action:"switch_session",success:!0,message:`Switched to ${(t=i??this.state.boot,s=t?.resumableSessions.find(t=>t.path===e),s?.name?.trim()?s.name.trim():s?.id?s.id:W(e))}`,selectedTarget:r,sessionBrowser:o})}),a},this.loadSessionStats=async()=>{var e;let t={...this.state.live,freshness:{...this.state.live.freshness,sessionStats:k(this.state.live.freshness.sessionStats)}};this.patchState({live:{...t,recoverySummary:_({boot:this.state.boot,live:t})},commandSurface:(0,x.Yc)(this.state.commandSurface,"load_session_stats")});let s=await this.sendCommand({type:"get_session_stats"},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error",t={...this.state.live,freshness:{...this.state.live.freshness,sessionStats:R(this.state.live.freshness.sessionStats,e)}};return this.patchState({live:{...t,recoverySummary:_({boot:this.state.boot,live:t})},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"load_session_stats",success:!1,message:`Couldn't load session details — ${e}`,sessionStats:null})}),null}let r=(e=s.data)&&"object"==typeof e?"string"!=typeof e.sessionId?null:{sessionFile:"string"==typeof e.sessionFile?e.sessionFile:void 0,sessionId:e.sessionId,userMessages:Number(e.userMessages??0),assistantMessages:Number(e.assistantMessages??0),toolCalls:Number(e.toolCalls??0),toolResults:Number(e.toolResults??0),totalMessages:Number(e.totalMessages??0),tokens:{input:Number(e.tokens?.input??0),output:Number(e.tokens?.output??0),cacheRead:Number(e.tokens?.cacheRead??0),cacheWrite:Number(e.tokens?.cacheWrite??0),total:Number(e.tokens?.total??0)},cost:Number(e.cost??0)}:null;if(!r){let e="Session details response was missing the expected fields.",t={...this.state.live,freshness:{...this.state.live.freshness,sessionStats:R(this.state.live.freshness.sessionStats,e)}};return this.patchState({live:{...t,recoverySummary:_({boot:this.state.boot,live:t})},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"load_session_stats",success:!1,message:e,sessionStats:null})}),null}let a={...this.state.live,freshness:{...this.state.live.freshness,sessionStats:A(this.state.live.freshness.sessionStats)}};return this.patchState({live:{...a,recoverySummary:_({boot:this.state.boot,live:a})},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"load_session_stats",success:!0,message:`Loaded session details for ${r.sessionId}`,sessionStats:r})}),r},this.exportSessionFromSurface=async e=>{let t=e?.trim()||void 0,s={kind:"session",outputPath:t};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"export_html",s)});let r=await this.sendCommand(t?{type:"export_html",outputPath:t}:{type:"export_html"},{appendInputLine:!1,appendResponseLine:!1});if(!r||!1===r.success){let e=r?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"export_html",success:!1,message:`Couldn't export this session — ${e}`,selectedTarget:s})}),r}let a=r.data&&"object"==typeof r.data&&"path"in r.data&&"string"==typeof r.data.path?r.data.path:"the generated file";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"export_html",success:!0,message:`Session exported to ${a}`,selectedTarget:s})}),r},this.loadForkMessages=async()=>{var e;this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"load_fork_messages")});let t=await this.sendCommand({type:"get_fork_messages"},{appendInputLine:!1,appendResponseLine:!1});if(!t||!1===t.success){let e=t?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"load_fork_messages",success:!1,message:`Couldn't load fork points — ${e}`,forkMessages:[]})}),[]}let s=((e=t.data)&&"object"==typeof e&&"messages"in e&&Array.isArray(e.messages)?e.messages:[]).map(e=>{let t="string"==typeof e.entryId?e.entryId:void 0,s="string"==typeof e.text?e.text:void 0;return t&&s?{entryId:t,text:s}:null}).filter(e=>null!==e),r=this.state.commandSurface.selectedTarget,a=r?.kind==="fork"&&r.entryId?r:s[0]?{kind:"fork",entryId:s[0].entryId}:r;return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"load_fork_messages",success:!0,message:s.length>0?`Loaded ${s.length} fork points.`:"No fork points are available yet.",selectedTarget:a??null,forkMessages:s})}),s},this.forkSessionFromSurface=async e=>{let t={kind:"fork",entryId:e};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"fork_session",t)});let s=await this.sendCommand({type:"fork",entryId:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"fork_session",success:!1,message:`Couldn't create a fork — ${e}`,selectedTarget:t})}),s}if(s.data&&"object"==typeof s.data&&"cancelled"in s.data&&s.data.cancelled)return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"fork_session",success:!1,message:"Fork creation was cancelled before a new session was created.",selectedTarget:t})}),s;let r=s.data&&"object"==typeof s.data&&"text"in s.data&&"string"==typeof s.data.text?s.data.text.trim():"";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"fork_session",success:!0,message:r?`Forked from “${r.slice(0,120)}${r.length>120?"…":""}”`:"Created a forked session.",selectedTarget:t})}),s},this.compactSessionFromSurface=async e=>{var t;let s=e?.trim()??"",r={kind:"compact",customInstructions:s};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"compact_session",r)});let a=await this.sendCommand(s?{type:"compact",customInstructions:s}:{type:"compact"},{appendInputLine:!1,appendResponseLine:!1});if(!a||!1===a.success){let e=a?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"compact_session",success:!1,message:`Couldn't compact the session — ${e}`,selectedTarget:r,lastCompaction:null})}),a}let n=(t=a.data)&&"object"==typeof t?"string"!=typeof t.summary||"string"!=typeof t.firstKeptEntryId?null:{summary:t.summary,firstKeptEntryId:t.firstKeptEntryId,tokensBefore:Number(t.tokensBefore??0),details:t.details}:null;return n?this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"compact_session",success:!0,message:`Compacted ${n.tokensBefore.toLocaleString()} tokens into a fresh summary${s?" with custom instructions":""}.`,selectedTarget:r,lastCompaction:n})}):this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"compact_session",success:!1,message:"Compaction finished but the browser could not read the compaction result.",selectedTarget:r,lastCompaction:null})}),a},this.saveApiKeyFromSurface=async(e,t)=>{let s={kind:"auth",providerId:e,intent:"manage"};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"save_api_key",s)});let r=await this.saveApiKey(e,t),a=r?q(r,e):e;return r?(r.lastValidation?.status==="failed"?this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"save_api_key",success:!1,message:r.lastValidation.message,selectedTarget:s})}):"failed"===r.bridgeAuthRefresh.phase?this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"save_api_key",success:!1,message:r.bridgeAuthRefresh.error??`${a} credentials validated but bridge auth refresh failed`,selectedTarget:s})}):this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"save_api_key",success:!0,message:`${a} credentials validated and saved.`,selectedTarget:s})}),r):(this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"save_api_key",success:!1,message:this.state.lastClientError??`${a} setup failed`,selectedTarget:s})}),null)},this.startProviderFlowFromSurface=async e=>{let t={kind:"auth",providerId:e,intent:"login"};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"start_provider_flow",t)});let s=await this.startProviderFlow(e),r=s?q(s,e):e;return s?(this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"start_provider_flow",success:!0,message:`${r} sign-in started. Continue in the auth section.`,selectedTarget:t})}),s):(this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"start_provider_flow",success:!1,message:this.state.lastClientError??`${r} sign-in failed to start`,selectedTarget:t})}),null)},this.submitProviderFlowInputFromSurface=async(e,t)=>{let s=this.state.boot?.onboarding.activeFlow?.providerId??void 0,r={kind:"auth",providerId:s,intent:"login"};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"submit_provider_flow_input",r)});let a=await this.submitProviderFlowInput(e,t),n=a?.activeFlow?.providerLabel??(s&&a?q(a,s):s)??"Provider";if(!a)return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"submit_provider_flow_input",success:!1,message:this.state.lastClientError??`${n} sign-in failed`,selectedTarget:r})}),null;if(a.activeFlow?.status==="failed")return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"submit_provider_flow_input",success:!1,message:a.activeFlow.error??`${n} sign-in failed`,selectedTarget:r})}),a;if("failed"===a.bridgeAuthRefresh.phase)return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"submit_provider_flow_input",success:!1,message:a.bridgeAuthRefresh.error??`${n} sign-in completed but bridge auth refresh failed`,selectedTarget:r})}),a;let i=a.activeFlow&&["running","awaiting_browser_auth","awaiting_input"].includes(a.activeFlow.status)?`${n} sign-in advanced. Complete the remaining step in this panel.`:`${n} sign-in complete.`;return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"submit_provider_flow_input",success:!0,message:i,selectedTarget:r})}),a},this.cancelProviderFlowFromSurface=async e=>{let t=this.state.boot?.onboarding.activeFlow?.providerId??void 0,s={kind:"auth",providerId:t,intent:"login"};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"cancel_provider_flow",s)});let r=await this.cancelProviderFlow(e),a=r?.activeFlow?.providerLabel??(t&&r?q(r,t):t)??"Provider";return r?(this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"cancel_provider_flow",success:!0,message:`${a} sign-in cancelled.`,selectedTarget:s})}),r):(this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"cancel_provider_flow",success:!1,message:this.state.lastClientError??`${a} sign-in cancellation failed`,selectedTarget:s})}),null)},this.logoutProviderFromSurface=async e=>{let t={kind:"auth",providerId:e,intent:"logout"};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"logout_provider",t)});let s=await this.logoutProvider(e),r=s?q(s,e):e;if(!s)return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"logout_provider",success:!1,message:this.state.lastClientError??`${r} logout failed`,selectedTarget:t})}),null;if("failed"===s.bridgeAuthRefresh.phase)return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"logout_provider",success:!1,message:s.bridgeAuthRefresh.error??`${r} logout completed but bridge auth refresh failed`,selectedTarget:t})}),s;let a=s.required.providers.find(t=>t.id===e),n=a?.configured?`${r} saved credentials were removed, but ${a.configuredVia} auth still keeps the provider available.`:s.locked?`${r} logged out — required setup is needed again.`:`${r} logged out.`;return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"logout_provider",success:!0,message:n,selectedTarget:t})}),s},this.respondToUiRequest=async(e,t)=>{this.patchState({commandInFlight:"extension_ui_response"});try{let s=await (0,b.tm)(this.buildUrl("/api/session/command"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({type:"extension_ui_response",id:e,...t})});if(!s.ok){let e=await s.json().catch(()=>({error:`HTTP ${s.status}`}));throw Error(e.error??`extension_ui_response failed with ${s.status}`)}this.patchState({pendingUiRequests:this.state.pendingUiRequests.filter(t=>t.id!==e)})}catch(t){let e=$(t);this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`UI response failed — ${e}`))})}finally{this.patchState({commandInFlight:null})}},this.dismissUiRequest=async e=>{this.patchState({commandInFlight:"extension_ui_response"});try{let t=await (0,b.tm)(this.buildUrl("/api/session/command"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({type:"extension_ui_response",id:e,cancelled:!0})});if(!t.ok){let e=await t.json().catch(()=>({error:`HTTP ${t.status}`}));throw Error(e.error??`extension_ui_response cancel failed with ${t.status}`)}this.patchState({pendingUiRequests:this.state.pendingUiRequests.filter(t=>t.id!==e)})}catch(t){let e=$(t);this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`UI dismiss failed — ${e}`))})}finally{this.patchState({commandInFlight:null})}},this.sendSteer=async e=>{await this.sendCommand({type:"steer",message:e})},this.sendAbort=async()=>{await this.sendCommand({type:"abort"})},this.pushChatUserMessage=e=>{this.patchState({chatUserMessages:[...this.state.chatUserMessages,e]})},this.submitInput=async(e,t)=>{let s=e.trim();if(!s)return null;let r=m(s,{isStreaming:this.state.boot?.bridge.sessionState?.isStreaming});if(this.patchState({lastSlashCommandOutcome:s.startsWith("/")?r:null}),"prompt"===r.kind){let e=this.state.boot?.bridge.sessionState,t=this.contextualTips.evaluate({input:s,isStreaming:!!e?.isStreaming,thinkingLevel:e?.thinkingLevel,contextPercent:void 0});t&&this.patchState({terminalLines:f(this.state.terminalLines,g("system",`💡 ${t}`))})}switch(r.kind){case"prompt":case"rpc":{let e=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),a=e&&e.length>0?{...r.command,images:e}:r.command;return await this.sendCommand(a,{displayInput:s}),r}case"local":if("clear_terminal"===r.action)return this.clearTerminalLines(),r;if("refresh_workspace"===r.action)return await this.refreshBoot(),r;return"gsd_help"===r.action&&this.patchState({terminalLines:f(f(this.state.terminalLines,g("input",s)),g("system",c))}),r;case"surface":{if(I.has(r.surface))return this.patchState({terminalLines:f(this.state.terminalLines,g("input",s))}),this.openCommandSurface(r.surface,{source:"slash",args:r.args}),r;let e=h(r),t=f(this.state.terminalLines,g("input",s));return e&&(t=f(t,g(e.type,e.message))),this.patchState({terminalLines:t}),r}case"reject":{let e=h(r),t=f(this.state.terminalLines,g("input",s));return e&&(t=f(t,g(e.type,e.message))),this.patchState({terminalLines:t}),r}case"view-navigate":return this.patchState({terminalLines:f(this.state.terminalLines,g("system",`Navigating to ${r.view} view`))}),window.dispatchEvent(new CustomEvent("gsd:navigate-view",{detail:{view:r.view}})),r}},this.refreshBoot=async(e={})=>{if(this.bootPromise)return await this.bootPromise;this.lastBootRefreshAt=Date.now();let t=!!(e.soft&&this.state.boot);this.bootPromise=(async()=>{t?this.patchState({lastClientError:null}):this.patchState({bootStatus:"loading",connectionState:"connected"===this.state.connectionState?"connected":"connecting",lastClientError:null});try{let e=await (0,b.tm)(this.buildUrl("/api/boot"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}});if(!e.ok){if(401===e.status)return void this.patchState({bootStatus:"unauthenticated",connectionState:"error"});throw Error(`Boot request failed with ${e.status}`)}let s=await e.json(),r=B(s,s.bridge)??s,a=function(e,t,s={}){let r={...e,auto:t.auto,workspace:t.workspace,resumableSessions:t.resumableSessions,freshness:{...e.freshness,auto:A(e.freshness.auto),workspace:A(e.freshness.workspace),recovery:A(e.freshness.recovery),resumableSessions:A(e.freshness.resumableSessions)},softBootRefreshCount:e.softBootRefreshCount+ +!!s.soft};return r.recoverySummary=_({boot:t,live:r}),r}(this.state.live,r,{soft:t});this.lastBridgeDigest=null,this.lastBridgeDigest=[r.bridge.phase,r.bridge.activeSessionId,r.bridge.lastError?.at,r.bridge.lastError?.message].join("::"),this.patchState({bootStatus:"ready",boot:r,live:a,connectionState:r.onboarding.locked?"idle":this.eventStream.isOpen()?this.state.connectionState:"connecting",lastBridgeError:r.bridge.lastError,sessionAttached:F(r.bridge),lastClientError:null,...t?{}:{terminalLines:G(r)}}),r.onboarding.locked?this.closeEventStream():this.ensureEventStream()}catch(s){let e=$(s);if(t)return void this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Workspace refresh failed — ${e}`))});this.patchState({bootStatus:"error",connectionState:"error",lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Boot failed — ${e}`))})}})().finally(()=>{this.bootPromise=null}),await this.bootPromise},this.refreshOnboarding=async()=>{this.patchState({onboardingRequestState:"refreshing",onboardingRequestProviderId:null,lastClientError:null});try{return await this.fetchOnboardingState()}catch(t){let e=$(t);return this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Onboarding refresh failed — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.saveApiKey=async(e,t)=>{this.patchState({onboardingRequestState:"saving_api_key",onboardingRequestProviderId:e,lastClientError:null});try{let s=await this.postOnboardingAction({action:"save_api_key",providerId:e,apiKey:t});return await this.syncAfterOnboardingMutation(s),s}catch(t){let e=$(t);return this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Credential setup failed — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.startProviderFlow=async e=>{this.patchState({onboardingRequestState:"starting_provider_flow",onboardingRequestProviderId:e,lastClientError:null});try{let t=await this.postOnboardingAction({action:"start_provider_flow",providerId:e});return await this.syncAfterOnboardingMutation(t),t}catch(t){let e=$(t);return this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Provider sign-in failed to start — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.submitProviderFlowInput=async(e,t)=>{this.patchState({onboardingRequestState:"submitting_provider_flow_input",onboardingRequestProviderId:this.state.boot?.onboarding.activeFlow?.providerId??null,lastClientError:null});try{let s=await this.postOnboardingAction({action:"continue_provider_flow",flowId:e,input:t});return await this.syncAfterOnboardingMutation(s),s}catch(t){let e=$(t);return this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Provider sign-in input failed — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.cancelProviderFlow=async e=>{this.patchState({onboardingRequestState:"cancelling_provider_flow",onboardingRequestProviderId:this.state.boot?.onboarding.activeFlow?.providerId??null,lastClientError:null});try{let t=await this.postOnboardingAction({action:"cancel_provider_flow",flowId:e});return await this.syncAfterOnboardingMutation(t),t}catch(t){let e=$(t);return this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Provider sign-in cancellation failed — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.logoutProvider=async e=>{this.patchState({onboardingRequestState:"logging_out_provider",onboardingRequestProviderId:e,lastClientError:null});try{let t=await this.postOnboardingAction({action:"logout_provider",providerId:e});return await this.syncAfterOnboardingMutation(t),t}catch(t){let e=$(t);return this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Provider logout failed — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.sendCommand=async(e,t={})=>{this.clearCommandTimeout();let s={commandInFlight:e.type};!1!==t.appendInputLine&&(s.terminalLines=f(this.state.terminalLines,g("input",t.displayInput??("string"==typeof e.message?e.message:`/${e.type}`)))),this.patchState(s),this.commandTimeoutTimer=setTimeout(()=>{this.state.commandInFlight&&this.patchState({commandInFlight:null,lastClientError:"Command timed out — controls re-enabled",terminalLines:f(this.state.terminalLines,g("error","Command timed out — controls re-enabled"))})},9e4);try{let s=await (0,b.tm)(this.buildUrl("/api/session/command"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),r=await s.json();if("ok"in r)return null;if("get_state"===r.command&&r.success&&this.state.boot){let e={...this.state.boot.bridge,sessionState:r.data,activeSessionId:r.data.sessionId,activeSessionFile:r.data.sessionFile??this.state.boot.bridge.activeSessionFile,lastCommandType:"get_state",updatedAt:new Date().toISOString()};this.patchState({boot:B(this.state.boot,e),lastBridgeError:e.lastError,sessionAttached:F(e)})}return"new_session"===r.command&&r.success&&this.contextualTips.reset(),"onboarding_locked"===r.code&&r.details?.onboarding&&this.state.boot&&this.patchState({boot:function(e,t){var s;return e?U(e,(s=e.onboarding,{...s,...t,required:{...s.required,...t.required??{},providers:t.required?.providers??s.required.providers},optional:{...s.optional,...t.optional??{},sections:t.optional?.sections??s.optional.sections},bridgeAuthRefresh:{...s.bridgeAuthRefresh,...t.bridgeAuthRefresh??{}}})):null}(this.state.boot,r.details.onboarding)}),this.patchState({...!1===t.appendResponseLine?{}:{terminalLines:f(this.state.terminalLines,function(e){if(!e.success)return g("error",`Command failed (${e.command}) — ${e.error??"unknown error"}`);switch(e.command){case"get_state":return g("success","Session state refreshed");case"new_session":return g("success","Started a new session");case"prompt":return g("success","Prompt accepted by the live bridge");case"follow_up":return g("success","Follow-up queued on the live bridge");default:return g("success",`Command accepted (${e.command})`)}}(r))},lastBridgeError:r.success?this.state.lastBridgeError:this.state.boot?.bridge.lastError??this.state.lastBridgeError}),r}catch(s){let t=$(s);return this.patchState({lastClientError:t,terminalLines:f(this.state.terminalLines,g("error",`Command failed (${e.type}) — ${t}`))}),{type:"response",command:e.type,success:!1,error:t}}finally{this.clearCommandTimeout(),this.patchState({commandInFlight:null})}}}buildUrl(e){return eu(e,this.projectCwd)}patchDiagnosticsPhaseState(e,t){this.patchState({commandSurface:{...this.state.commandSurface,diagnostics:{...this.state.commandSurface.diagnostics,[e]:{...this.state.commandSurface.diagnostics[e],...t}}}})}patchDoctorState(e){this.patchState({commandSurface:{...this.state.commandSurface,diagnostics:{...this.state.commandSurface.diagnostics,doctor:{...this.state.commandSurface.diagnostics.doctor,...e}}}})}patchKnowledgeCapturesState(e){this.patchState({commandSurface:{...this.state.commandSurface,knowledgeCaptures:{...this.state.commandSurface.knowledgeCaptures,...e}}})}patchKnowledgeCapturesPhaseState(e,t){this.patchState({commandSurface:{...this.state.commandSurface,knowledgeCaptures:{...this.state.commandSurface.knowledgeCaptures,[e]:{...this.state.commandSurface.knowledgeCaptures[e],...t}}}})}patchSettingsPhaseState(e){this.patchState({commandSurface:{...this.state.commandSurface,settingsData:{...this.state.commandSurface.settingsData,...e}}})}patchRemainingCommandsPhaseState(e,t){this.patchState({commandSurface:{...this.state.commandSurface,remainingCommands:{...this.state.commandSurface.remainingCommands,[e]:{...this.state.commandSurface.remainingCommands[e],...t}}}})}async refreshBootAfterCurrentSettles(e={}){if(this.bootPromise)try{await this.bootPromise}catch{}await this.refreshBoot(e)}invalidateLiveFreshness(e,t,s){let r={...this.state.live.freshness};e.includes("auto")&&(r.auto=C(r.auto,t,s)),e.includes("workspace")&&(r.workspace=C(r.workspace,t,s),r.gitSummary=C(r.gitSummary,t,s)),e.includes("recovery")&&(r.recovery=C(r.recovery,t,s),r.sessionStats=C(r.sessionStats,t,s)),e.includes("resumable_sessions")&&(r.resumableSessions=C(r.resumableSessions,t,s),r.sessionBrowser=C(r.sessionBrowser,t,s),r.sessionStats=C(r.sessionStats,t,s));let a={...this.state.live,freshness:r};return{...a,recoverySummary:_({boot:this.state.boot,live:a})}}refreshOpenCommandSurfacesForInvalidation(e){if(e.domains.includes("workspace")&&this.state.commandSurface.open&&"git"===this.state.commandSurface.section&&"load_git_summary"!==this.state.commandSurface.pendingAction&&this.loadGitSummary(),e.domains.includes("recovery")&&this.state.commandSurface.open&&"recovery"===this.state.commandSurface.section&&"load_recovery_diagnostics"!==this.state.commandSurface.pendingAction&&this.loadRecoveryDiagnostics(),e.domains.includes("resumable_sessions")&&(this.state.commandSurface.open&&("resume"===this.state.commandSurface.section||"name"===this.state.commandSurface.section)&&"load_session_browser"!==this.state.commandSurface.pendingAction&&this.loadSessionBrowser(),this.state.commandSurface.open&&"session"===this.state.commandSurface.section)){let e=this.state.boot?.bridge.activeSessionFile??this.state.boot?.bridge.sessionState?.sessionFile??null;this.patchState({commandSurface:{...this.state.commandSurface,sessionStats:this.state.commandSurface.sessionStats&&this.state.commandSurface.sessionStats.sessionFile===e?this.state.commandSurface.sessionStats:null}}),"load_session_stats"!==this.state.commandSurface.pendingAction&&this.loadSessionStats()}}async reloadLiveState(e,t){let s=e.filter(e=>"auto"===e||"workspace"===e||"resumable_sessions"===e);if(0===s.length){let e={...this.state.live,freshness:{...this.state.live.freshness,recovery:A(this.state.live.freshness.recovery)}};this.patchState({live:{...e,recoverySummary:_({boot:this.state.boot,live:e})}});return}let r={...this.state.live.freshness};s.includes("auto")&&(r.auto=k(r.auto)),s.includes("workspace")&&(r.workspace=k(r.workspace)),s.includes("resumable_sessions")&&(r.resumableSessions=k(r.resumableSessions)),r.recovery=k(r.recovery);let a={...this.state.live,freshness:r,targetedRefreshCount:this.state.live.targetedRefreshCount+1};this.patchState({live:{...a,recoverySummary:_({boot:this.state.boot,live:a})}});let n=new URLSearchParams;for(let e of s)n.append("domain",e);try{let e=await (0,b.tm)(this.buildUrl(`/api/live-state?${n.toString()}`),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t)throw Error(t?.error??`Live state request failed with ${e.status}`);let r=this.state.boot,a={...this.state.live,freshness:{...this.state.live.freshness}};if(s.includes("auto")&&t.auto&&(a.auto=t.auto,a.freshness.auto=A(a.freshness.auto),r=r?{...r,auto:t.auto}:r),s.includes("workspace")&&t.workspace&&(a.workspace=t.workspace,a.freshness.workspace=A(a.freshness.workspace),r=r?{...r,workspace:t.workspace}:r),s.includes("resumable_sessions")&&t.resumableSessions){let e=ei(t.resumableSessions,r);a.resumableSessions=e,a.freshness.resumableSessions=A(a.freshness.resumableSessions),r=r?{...r,resumableSessions:e}:r}a.freshness.recovery=A(a.freshness.recovery),a.recoverySummary=_({boot:r,live:a}),this.patchState({...r?{boot:r}:{},live:a})}catch(a){let e=$(a),r={...this.state.live,freshness:{...this.state.live.freshness,auto:s.includes("auto")?R(this.state.live.freshness.auto,e):this.state.live.freshness.auto,workspace:s.includes("workspace")?R(this.state.live.freshness.workspace,e):this.state.live.freshness.workspace,resumableSessions:s.includes("resumable_sessions")?R(this.state.live.freshness.resumableSessions,e):this.state.live.freshness.resumableSessions,recovery:R(this.state.live.freshness.recovery,e)}};this.patchState({lastClientError:e,live:{...r,recoverySummary:_({boot:this.state.boot,live:r})},terminalLines:f(this.state.terminalLines,g("error",`Live refresh failed (${t}) — ${e}`))})}}handleLiveStateInvalidation(e){var t;this.patchState({live:this.invalidateLiveFreshness(e.domains,e.reason,e.source),commandSurface:e.domains.includes("recovery")?{...this.state.commandSurface,recovery:(t=this.state.commandSurface.recovery).loaded||t.error?{...t,stale:!0,lastInvalidatedAt:new Date().toISOString()}:t}:this.state.commandSurface}),this.refreshOpenCommandSurfacesForInvalidation(e),this.reloadLiveState(e.domains,e.reason)}clearCommandTimeout(){this.commandTimeoutTimer&&(clearTimeout(this.commandTimeoutTimer),this.commandTimeoutTimer=null)}async fetchOnboardingState(e=!1){let t=this.state.boot?.onboarding.activeFlow?.status??null,s=await (0,b.tm)(this.buildUrl("/api/onboarding"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),r=await s.json();if(!s.ok||!r.onboarding)throw Error(r.error??`Onboarding request failed with ${s.status}`);return this.applyOnboardingState(r.onboarding),t&&D.has(t)&&r.onboarding.activeFlow&&M.has(r.onboarding.activeFlow.status)?await this.syncAfterOnboardingMutation(r.onboarding):e||this.appendOnboardingSummaryLine(r.onboarding),r.onboarding}async postOnboardingAction(e){let t=await (0,b.tm)(this.buildUrl("/api/onboarding"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),s=await t.json();if(!t.ok)throw s.onboarding&&this.applyOnboardingState(s.onboarding),Error(s.error??`Onboarding action failed with ${t.status}`);if(!s.onboarding)throw Error(`Onboarding action returned no state (${t.status})`);return this.applyOnboardingState(s.onboarding),s.onboarding}applyOnboardingState(e){this.state.boot&&this.patchState({boot:U(this.state.boot,e)})}async syncAfterOnboardingMutation(e){this.applyOnboardingState(e),this.appendOnboardingSummaryLine(e),(e.lastValidation?.status==="succeeded"||"idle"!==e.bridgeAuthRefresh.phase)&&this.refreshBootAfterCurrentSettles({soft:!0})}appendOnboardingSummaryLine(e){let t=z(e);if(!t)return;let s=this.state.terminalLines.at(-1);(s?.type!==t.type||s.content!==t.message)&&this.patchState({terminalLines:f(this.state.terminalLines,g(t.type,t.message))})}emit(){for(let e of this.listeners)e()}patchState(e){this.state={...this.state,...e},this.syncOnboardingPoller(),this.emit()}syncOnboardingPoller(){if(this.disposed)return void this.stopOnboardingPoller();let e=this.state.boot?.onboarding.activeFlow?.status,t=!!(e&&D.has(e));if(t&&!this.onboardingPollTimer){this.onboardingPollTimer=setInterval(()=>{"idle"===this.state.onboardingRequestState&&this.fetchOnboardingState(!0).catch(e=>{let t=$(e);this.patchState({lastClientError:t})})},1500);return}t||this.stopOnboardingPoller()}stopOnboardingPoller(){this.onboardingPollTimer&&(clearInterval(this.onboardingPollTimer),this.onboardingPollTimer=null)}ensureEventStream(){this.eventStream.ensure()}closeEventStream(){this.eventStream.close()}handleEventStreamOpen(e){e&&this.patchState({terminalLines:f(this.state.terminalLines,g("success","Live event stream reconnected"))}),this.patchState({connectionState:"connected",lastClientError:null}),e&&this.refreshBoot({soft:!0})}handleEventStreamMessage(e){try{let t=JSON.parse(e);if(null===t||"object"!=typeof t||"string"!=typeof t.type)return void this.patchState({lastClientError:"Malformed event received from stream",terminalLines:f(this.state.terminalLines,g("error","Malformed event received from stream"))});this.handleEvent(t)}catch(t){let e=$(t);this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Failed to parse stream event — ${e}`))})}}handleEventStreamError(e,t){t?this.patchState({connectionState:e,terminalLines:f(this.state.terminalLines,g("reconnecting"===e?"system":"error","reconnecting"===e?"Live event stream disconnected — retrying…":"Live event stream failed before connection was established"))}):this.patchState({connectionState:e})}handleEvent(e){if(this.patchState({lastEventType:e.type}),"bridge_status"===e.type)return void this.recordBridgeStatus(e.bridge);"live_state_invalidation"===e.type&&this.handleLiveStateInvalidation(e),this.routeLiveInteractionEvent(e);let t=function(e){switch(e.type){case"bridge_status":return L(e.bridge);case"live_state_invalidation":return{type:"system",message:`[Live] Refreshing ${Array.isArray(e.domains)?e.domains.join(", "):"state"} after ${String(e.reason).replaceAll("_"," ")}`};case"agent_start":return{type:"system",message:"[Agent] Run started"};case"agent_end":return{type:"success",message:"[Agent] Run finished"};case"turn_start":return{type:"system",message:"[Agent] Turn started"};case"turn_end":return{type:"success",message:"[Agent] Turn complete"};case"tool_execution_start":return{type:"output",message:`[Tool] ${"string"==typeof e.toolName?e.toolName:"tool"} started`};case"tool_execution_update":default:return null;case"tool_execution_end":return{type:e.isError?"error":"success",message:`[Tool] ${"string"==typeof e.toolName?e.toolName:"tool"} ${e.isError?"failed":"completed"}`};case"auto_compaction_start":return{type:"system",message:"[Auto] Compaction started"};case"auto_compaction_end":return{type:e.aborted?"error":"success",message:e.aborted?"[Auto] Compaction aborted":"[Auto] Compaction finished"};case"auto_retry_start":return{type:"system",message:`[Auto] Retry ${String(e.attempt)}/${String(e.maxAttempts)} scheduled`};case"auto_retry_end":return{type:e.success?"success":"error",message:e.success?"[Auto] Retry recovered the run":"[Auto] Retry exhausted"};case"extension_ui_request":{let t="title"in e&&"string"==typeof e.title&&e.title.trim().length>0?e.title:"message"in e&&"string"==typeof e.message&&e.message.trim().length>0?e.message:e.method;return{type:"notifyType"in e&&"error"===e.notifyType?"error":"system",message:`[UI] ${t}`}}case"extension_error":return{type:"error",message:`[Extension] ${e.error}`}}}(e);t&&this.patchState({terminalLines:f(this.state.terminalLines,g(t.type,t.message))})}routeLiveInteractionEvent(e){switch(e.type){case"extension_ui_request":this.handleExtensionUiRequest(e);break;case"message_update":this.handleMessageUpdate(e);break;case"agent_end":case"turn_end":this.handleTurnBoundary();break;case"tool_execution_start":this.handleToolExecutionStart(e);break;case"tool_execution_update":this.handleToolExecutionUpdate(e);break;case"tool_execution_end":this.handleToolExecutionEnd(e)}}handleExtensionUiRequest(e){switch(e.method){case"select":case"confirm":case"input":case"editor":this.patchState({pendingUiRequests:[...this.state.pendingUiRequests,e]});break;case"notify":break;case"setStatus":if("setStatus"===e.method){let t={...this.state.statusTexts};void 0===e.statusText?delete t[e.statusKey]:t[e.statusKey]=e.statusText,this.patchState({statusTexts:t})}break;case"setWidget":if("setWidget"===e.method){let t={...this.state.widgetContents};void 0===e.widgetLines?delete t[e.widgetKey]:t[e.widgetKey]={lines:e.widgetLines,placement:e.widgetPlacement},this.patchState({widgetContents:t})}break;case"setTitle":if("setTitle"===e.method){let t=e.title.trim();this.patchState({titleOverride:t||null})}break;case"set_editor_text":"set_editor_text"===e.method&&this.patchState({editorTextBuffer:e.text})}}handleMessageUpdate(e){let t=e.assistantMessageEvent;t&&("text_delta"===t.type&&"string"==typeof t.delta?(this.state.streamingThinkingText.length>0&&this.patchState({currentTurnSegments:[...this.state.currentTurnSegments,{kind:"thinking",content:this.state.streamingThinkingText}],streamingThinkingText:""}),this.patchState({streamingAssistantText:this.state.streamingAssistantText+t.delta})):"thinking_delta"===t.type&&"string"==typeof t.delta?(this.state.streamingAssistantText.length>0&&this.patchState({currentTurnSegments:[...this.state.currentTurnSegments,{kind:"text",content:this.state.streamingAssistantText}],streamingAssistantText:""}),this.patchState({streamingThinkingText:this.state.streamingThinkingText+t.delta})):"thinking_end"===t.type&&this.state.streamingThinkingText.length>0&&this.patchState({currentTurnSegments:[...this.state.currentTurnSegments,{kind:"thinking",content:this.state.streamingThinkingText}],streamingThinkingText:""}))}handleTurnBoundary(){let e=[];this.state.streamingThinkingText.length>0&&e.push({kind:"thinking",content:this.state.streamingThinkingText}),this.state.streamingAssistantText.length>0&&e.push({kind:"text",content:this.state.streamingAssistantText});let t=e.length>0?[...this.state.currentTurnSegments,...e]:this.state.currentTurnSegments,s=t.filter(e=>"text"===e.kind).map(e=>e.content).join("");if(s.length>0||t.length>0){let e=[...this.state.liveTranscript,s],r=[...this.state.liveThinkingTranscript,""],a=[...this.state.completedTurnSegments,t],n=e.length>100?e.length-100:0,i=n>0?this.state.chatUserMessages.slice(n):void 0;this.patchState({liveTranscript:n>0?e.slice(n):e,liveThinkingTranscript:n>0?r.slice(n):r,completedTurnSegments:n>0?a.slice(n):a,...void 0!==i?{chatUserMessages:i}:{},streamingAssistantText:"",streamingThinkingText:"",currentTurnSegments:[],completedToolExecutions:[]})}else this.state.streamingThinkingText.length>0?this.patchState({streamingThinkingText:"",currentTurnSegments:[],completedToolExecutions:[]}):this.patchState({currentTurnSegments:[],completedToolExecutions:[]})}handleToolExecutionStart(e){this.patchState({activeToolExecution:{id:e.toolCallId,name:e.toolName,args:e.args},streamingAssistantText:"",streamingThinkingText:""})}handleToolExecutionUpdate(e){let t=this.state.activeToolExecution;t&&t.id===e.toolCallId&&this.patchState({activeToolExecution:{...t,result:e.partialResult?{content:e.partialResult.content,details:e.partialResult.details,isError:!!e.partialResult.isError}:t.result}})}handleToolExecutionEnd(e){let t=this.state.activeToolExecution;if(t){let s={id:t.id,name:t.name,args:t.args??{},result:{content:e.result?.content,details:e.result?.details,isError:e.isError}},r=[...this.state.completedToolExecutions,s];this.patchState({activeToolExecution:null,completedToolExecutions:r.length>50?r.slice(r.length-50):r,currentTurnSegments:[...this.state.currentTurnSegments,{kind:"tool",tool:s}]})}else this.patchState({activeToolExecution:null})}recordBridgeStatus(e){let t=[e.phase,e.activeSessionId,e.lastError?.at,e.lastError?.message].join("::"),s=t!==this.lastBridgeDigest;this.lastBridgeDigest=t;let r=B(this.state.boot,e),a={...this.state.live,resumableSessions:ei(this.state.live.resumableSessions,r)},n={...a,recoverySummary:_({boot:r,live:a})},i={boot:r,live:n,lastBridgeError:e.lastError,sessionAttached:F(e),commandSurface:{...this.state.commandSurface,sessionBrowser:eo(this.state.commandSurface.sessionBrowser,r)}};if(s){let t=L(e);i.terminalLines=f(this.state.terminalLines,g(t.type,t.message))}this.patchState(i)}}let eh=(0,a.createContext)(null);function ex({children:e,store:t}){let[s]=(0,a.useState)(()=>new em),n=t??s;return(0,a.useEffect)(()=>{if(!t)return n.start(),()=>n.dispose()},[n,t]),(0,r.jsx)(eh.Provider,{value:n,children:e})}function ep(){let e=(0,a.useContext)(eh);if(!e)throw Error("useWorkspaceStore must be used within GSDWorkspaceProvider");return e}function eg(){let e=ep();return(0,a.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getSnapshot)}function ef(){let e=ep();return{sendCommand:e.sendCommand,submitInput:e.submitInput,clearTerminalLines:e.clearTerminalLines,consumeEditorTextBuffer:e.consumeEditorTextBuffer,refreshBoot:e.refreshBoot,refreshOnboarding:e.refreshOnboarding,openCommandSurface:e.openCommandSurface,closeCommandSurface:e.closeCommandSurface,setCommandSurfaceSection:e.setCommandSurfaceSection,selectCommandSurfaceTarget:e.selectCommandSurfaceTarget,loadGitSummary:e.loadGitSummary,loadRecoveryDiagnostics:e.loadRecoveryDiagnostics,loadForensicsDiagnostics:e.loadForensicsDiagnostics,loadDoctorDiagnostics:e.loadDoctorDiagnostics,applyDoctorFixes:e.applyDoctorFixes,loadSkillHealthDiagnostics:e.loadSkillHealthDiagnostics,loadKnowledgeData:e.loadKnowledgeData,loadCapturesData:e.loadCapturesData,loadSettingsData:e.loadSettingsData,loadHistoryData:e.loadHistoryData,loadInspectData:e.loadInspectData,loadHooksData:e.loadHooksData,loadExportData:e.loadExportData,loadUndoInfo:e.loadUndoInfo,loadCleanupData:e.loadCleanupData,loadSteerData:e.loadSteerData,executeUndoAction:e.executeUndoAction,executeCleanupAction:e.executeCleanupAction,resolveCaptureAction:e.resolveCaptureAction,updateSessionBrowserState:e.updateSessionBrowserState,loadSessionBrowser:e.loadSessionBrowser,renameSessionFromSurface:e.renameSessionFromSurface,loadAvailableModels:e.loadAvailableModels,applyModelSelection:e.applyModelSelection,applyThinkingLevel:e.applyThinkingLevel,setSteeringModeFromSurface:e.setSteeringModeFromSurface,setFollowUpModeFromSurface:e.setFollowUpModeFromSurface,setAutoCompactionFromSurface:e.setAutoCompactionFromSurface,setAutoRetryFromSurface:e.setAutoRetryFromSurface,abortRetryFromSurface:e.abortRetryFromSurface,switchSessionFromSurface:e.switchSessionFromSurface,loadSessionStats:e.loadSessionStats,exportSessionFromSurface:e.exportSessionFromSurface,loadForkMessages:e.loadForkMessages,forkSessionFromSurface:e.forkSessionFromSurface,compactSessionFromSurface:e.compactSessionFromSurface,saveApiKey:e.saveApiKey,saveApiKeyFromSurface:e.saveApiKeyFromSurface,startProviderFlow:e.startProviderFlow,startProviderFlowFromSurface:e.startProviderFlowFromSurface,submitProviderFlowInput:e.submitProviderFlowInput,submitProviderFlowInputFromSurface:e.submitProviderFlowInputFromSurface,cancelProviderFlow:e.cancelProviderFlow,cancelProviderFlowFromSurface:e.cancelProviderFlowFromSurface,logoutProvider:e.logoutProvider,logoutProviderFromSurface:e.logoutProviderFromSurface,respondToUiRequest:e.respondToUiRequest,dismissUiRequest:e.dismissUiRequest,sendSteer:e.sendSteer,sendAbort:e.sendAbort,pushChatUserMessage:e.pushChatUserMessage}}function eb(e,t){let s=m(e,{isStreaming:t?.sessionState?.isStreaming});if("prompt"===s.kind||"rpc"===s.kind)return s.command;throw Error(`buildPromptCommand cannot serialize ${s.input||e} because browser dispatch resolved it to ${s.kind}; use submitInput() instead.`)}},94002:(e,t,s)=>{function r(e,t){return t<=0?-1:Math.max(0,Math.min(t-1,e))}function a(e,t,s){if(s<=0)return{type:"none"};let a=function(e,t){if(!/^[1-9]$/.test(e))return null;let s=Number(e)-1;return s<t?s:null}(e,s);return null!==a?{type:"select",index:a}:"ArrowUp"===e?{type:"select",index:r(t-1,s)}:"ArrowDown"===e?{type:"select",index:r(t+1,s)}:"Home"===e?{type:"select",index:0}:"End"===e?{type:"select",index:s-1}:"Enter"===e||" "===e?{type:"submit",index:r(t,s)}:{type:"none"}}s.d(t,{cZ:()=>a,cv:()=>r})},97019:(e,t,s)=>{s.d(t,{Bc:()=>i,ZI:()=>d,k$:()=>l,m_:()=>o});var r=s(18870);s(45110);var a=s(37250),n=s(18833);function i({delayDuration:e=0,...t}){return(0,r.jsx)(a.Kq,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function o({...e}){return(0,r.jsx)(i,{children:(0,r.jsx)(a.bL,{"data-slot":"tooltip",...e})})}function l({...e}){return(0,r.jsx)(a.l9,{"data-slot":"tooltip-trigger",...e})}function d({className:e,sideOffset:t=0,children:s,...i}){return(0,r.jsx)(a.ZL,{children:(0,r.jsxs)(a.UC,{"data-slot":"tooltip-content",sideOffset:t,className:(0,n.cn)("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...i,children:[s,(0,r.jsx)(a.i3,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}}}]);
10
+ Type /gsd <subcommand> to run. Use /gsd help for this message.`;function u(e){return e.isStreaming?"follow_up":"prompt"}function m(e,t={}){let s=e.trim(),r=function(e){let t=e.trim();if(!t.startsWith("!"))return null;let s=t.startsWith("!!"),r=s?t.slice(2).trim():t.slice(1).trim();return r?{command:r,excludeFromContext:s}:null}(s);if(r)return{kind:"bash",input:s,command:{type:"bash",command:r.command,...r.excludeFromContext?{excludeFromContext:!0}:{}}};let a=function(e){if(!e.startsWith("/"))return null;let t=e.slice(1).trim();if(!t)return null;let s=t.search(/\s/);return -1===s?{name:t,args:""}:{name:t.slice(0,s),args:t.slice(s+1).trim()}}(s);if("/clear"===s)return{kind:"local",input:s,commandName:"clear",action:"clear_terminal"};if("/refresh"===s)return{kind:"local",input:s,commandName:"refresh",action:"refresh_workspace"};if("/state"===s)return{kind:"rpc",input:s,commandName:"state",command:{type:"get_state"}};if("/new-session"===s)return{kind:"rpc",input:s,commandName:"new",command:{type:"new_session"}};if(!a)return{kind:"prompt",input:s,slashCommandName:null,command:{type:u(t),message:s}};if("new"===a.name)return{kind:"rpc",input:s,commandName:"new",command:{type:"new_session"}};if("gsd"===a.name)return function(e,t,s){let r=t.trim(),a=r.search(/\s/),n=-1===a?r:r.slice(0,a),i=-1===a?"":r.slice(a+1).trim();if(!n)return{kind:"prompt",input:e,slashCommandName:"gsd",command:{type:u(s),message:e}};if("help"===n)return{kind:"local",input:e,commandName:"gsd",action:"gsd_help"};if("status"===n||"visualize"===n)return{kind:"view-navigate",input:e,commandName:"gsd",view:"visualize"};let o=l.get(n);return o?{kind:"surface",input:e,commandName:"gsd",surface:o,args:i}:(d.has(n),{kind:"prompt",input:e,slashCommandName:"gsd",command:{type:u(s),message:e}})}(s,a.args,t);let c=o.get(a.name);if(c)return{kind:"surface",input:s,commandName:a.name,surface:c,args:a.args};if(i.has(a.name)){var h,x;let e;return x=h=a.name,e=n.get(x)??"Browser handling is reserved for this built-in command.",{kind:"reject",input:s,commandName:h,reason:`/${h} is a built-in pi command (${e}) that is not available in the browser yet.`,guidance:"It was blocked instead of falling through to the model."}}return{kind:"prompt",input:s,slashCommandName:a.name,command:{type:u(t),message:s}}}function h(e){switch(e.kind){case"surface":return{type:"system",message:`/${e.commandName} is reserved for browser-native handling and was not sent to the model.`};case"reject":return{type:"error",message:`${e.reason} ${e.guidance}`.trim()};default:return null}}var x=s(37144);class p{constructor(e,t=e=>new EventSource(e)){this.eventSource=null,this.lastConnectionState="idle",this.handlers=e,this.createEventSource=t}isOpen(){return null!==this.eventSource}ensure(){if(this.eventSource||!this.handlers.canConnect())return;let e=this.createEventSource(this.handlers.streamUrl());this.eventSource=e,e.onopen=()=>{let e=this.lastConnectionState;this.lastConnectionState="connected",this.handlers.onOpen({previousState:e,wasDisconnected:"reconnecting"===e||"disconnected"===e||"error"===e})},e.onmessage=e=>{this.handlers.onMessage(e.data)},e.onerror=()=>{let e="connected"===this.lastConnectionState?"reconnecting":"error",t=e!==this.lastConnectionState;this.lastConnectionState=e,this.handlers.onError({nextConnectionState:e,changed:t})}}close(){this.eventSource?.close(),this.eventSource=null}}function g(e,t){return{id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,type:e,content:t,timestamp:function(e=new Date){return e.toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}()}}function f(e,t){return[...e,t].slice(-250)}var b=s(83890);let v=new Set(["ls","ll","la","pwd","cd","dir","cat","head","tail","wc","file","which","whoami","echo","date","tree","find","grep","rg","clear","env","df","du","uname","hostname","mkdir","rm","cp","mv","touch","chmod","less","more","sort","uniq","sed","awk","curl","wget","tar","zip","unzip","git","docker","npm","npx","yarn","pnpm","node","python","python3","pip","pip3","make","cargo","go","ruby","brew"]);function j(e){let t=e.trimStart(),s=t.search(/\s/);return(-1===s?t:t.slice(0,s)).toLowerCase()}let y=[{id:"shell-command-prefix",maxShows:2,evaluate(e){let t;if(!(!((t=e.input.trimStart()).startsWith("!")||t.startsWith("/")||t.includes("\n")||t.length>120)&&v.has(j(t))))return null;let s=j(e.input);return`Tip: "${s}" looks like a shell command. Prefix with ! to run locally, or !! to run without using tokens.`}},{id:"large-paste",maxShows:2,evaluate:e=>e.input.length<2e3||e.input.trimStart().startsWith("/")||e.input.trimStart().startsWith("!")?null:"Tip: Large inputs consume many tokens. Consider saving to a file and asking the agent to read it."},{id:"thinking-level-high",maxShows:1,evaluate(e){let t=e.thinkingLevel?.toLowerCase();if("high"!==t&&"xhigh"!==t)return null;let s=e.input.trim();return s.length>80||s.includes("\n")||s.startsWith("/")||s.startsWith("!")?null:`Tip: Thinking is set to ${t}. Use Ctrl+T to lower it for simple questions — saves tokens.`}},{id:"double-bang-reminder",maxShows:2,evaluate(e){if(e.bashIncludedCount<3)return null;let t=e.input.trimStart();return!t.startsWith("!")||t.startsWith("!!")?null:"Tip: Use !! instead of ! to keep command output out of agent context and save tokens."}},{id:"compaction-nudge",maxShows:1,evaluate(e){if(void 0===e.contextPercent||e.contextPercent<70)return null;let t=e.input.trimStart();return t.startsWith("/")||t.startsWith("!")?null:"Tip: Context is getting full. Use /compact to summarize the conversation and free up space."}}];class w{recordBashIncluded(){this._bashIncludedCount++}get bashIncludedCount(){return this._bashIncludedCount}evaluate(e){let t={...e,bashIncludedCount:this._bashIncludedCount};for(let e of y){let s=this.showCounts.get(e.id)??0;if(s>=e.maxShows)continue;let r=e.evaluate(t);if(r)return this.showCounts.set(e.id,s+1),r}return null}reset(){this.showCounts.clear(),this._bashIncludedCount=0}constructor(){this.showCounts=new Map,this._bashIncludedCount=0}}function N(){return{status:"idle",stale:!1,reloadCount:0,lastRequestedAt:null,lastSuccessAt:null,lastFailureAt:null,lastFailure:null,invalidatedAt:null,invalidationReason:null,invalidationSource:null}}function S(){return{visible:!1,tone:"healthy",label:"Recovery summary pending",detail:"Waiting for the first live workspace snapshot.",validationCount:0,retryInProgress:!1,retryAttempt:0,autoRetryEnabled:!1,isCompacting:!1,currentUnitId:null,freshness:"idle",entrypointLabel:"Inspect recovery",lastError:null}}function k(e){return{...e,status:"refreshing",lastRequestedAt:new Date().toISOString(),lastFailure:null}}function C(e,t,s){return{...e,status:e.lastSuccessAt?"stale":e.status,stale:!0,invalidatedAt:new Date().toISOString(),invalidationReason:t,invalidationSource:s}}function A(e){return{...e,status:"fresh",stale:!1,reloadCount:e.reloadCount+1,lastSuccessAt:new Date().toISOString(),lastFailureAt:null,lastFailure:null}}function R(e,t){return{...e,status:"error",stale:!0,lastFailureAt:new Date().toISOString(),lastFailure:t}}function T(e){return e.live.workspace??e.boot?.workspace??null}function E(e){return e.live.auto??e.boot?.auto??null}function P(e){return e.live.resumableSessions.length>0?e.live.resumableSessions:e.boot?.resumableSessions??[]}function _(e){let t=e.boot?.bridge??null,s=T(e),r=E(e),a=s?.validationIssues.length??0,n=!!t?.sessionState?.retryInProgress,i=t?.sessionState?.retryAttempt??0,o=!!t?.sessionState?.autoRetryEnabled,l=!!t?.sessionState?.isCompacting,d=e.live.freshness.recovery,c="error"===d.status?"error":d.stale?"stale":d.lastSuccessAt?"fresh":"idle",u=t?.lastError?{message:t.lastError.message,phase:t.lastError.phase,at:t.lastError.at}:null,m="healthy",h="Recovery summary healthy",x="No retry, compaction, bridge, or validation recovery signals are active.";return s||r||t?(u||"error"===c?(m="danger",h="Recovery attention required",x=u?.message??d.lastFailure??"A targeted live refresh failed."):a>0?(m="warning",h=`Recovery summary: ${a} validation issue${1===a?"":"s"}`,x="Workspace validation surfaced issues that may need doctor or audit follow-up."):n?(m="warning",h=`Recovery retry active (attempt ${Math.max(1,i)})`,x="The live bridge is retrying the current unit after a transient failure."):l?(m="warning",h="Recovery compaction active",x="The live session is compacting context before continuing."):"stale"===c&&(m="warning",h="Recovery summary stale",x=d.invalidationReason?`Waiting for a targeted refresh after ${d.invalidationReason.replaceAll("_"," ")}.`:"Waiting for the next targeted refresh."),{visible:!0,tone:m,label:h,detail:x,validationCount:a,retryInProgress:n,retryAttempt:i,autoRetryEnabled:o,isCompacting:l,currentUnitId:r?.currentUnit?.id??null,freshness:c,entrypointLabel:"danger"===m||"warning"===m?"Inspect recovery":"Review recovery",lastError:u}):S()}let I=new Set(["settings","model","thinking","git","resume","name","fork","compact","login","logout","session","export","gsd-visualize","gsd-forensics","gsd-doctor","gsd-skill-health","gsd-knowledge","gsd-capture","gsd-triage","gsd-quick","gsd-history","gsd-undo","gsd-inspect","gsd-prefs","gsd-config","gsd-hooks","gsd-mode","gsd-steer","gsd-report","gsd-export","gsd-cleanup","gsd-queue"]);function F(e){return!!(e?.activeSessionId||e?.sessionState?.sessionId)}function $(e){return e instanceof Error?e.message:String(e)}function L(e){if("failed"===e.phase)return{type:"error",message:`Bridge failed${e.lastError?.message?` — ${e.lastError.message}`:""}`};if("starting"===e.phase)return{type:"system",message:"Bridge starting for the current project…"};if("ready"===e.phase){let t=X(e);return{type:"success",message:t?`Live bridge ready — attached to ${t}`:"Live bridge ready — session attachment pending"}}return{type:"system",message:"Bridge idle"}}let D=new Set(["running","awaiting_browser_auth","awaiting_input"]),M=new Set(["succeeded","failed","cancelled"]);function q(e,t){return e.required.providers.find(e=>e.id===t)?.label??t}function B(e,t){if(!e)return null;let s={...e,bridge:t};return{...s,resumableSessions:ei(s.resumableSessions,s)}}function O(e,t){return e?.bridge.sessionState?B(e,{...e.bridge,sessionState:{...e.bridge.sessionState,...t}}):e}function U(e,t){return e?{...e,onboarding:t,onboardingNeeded:t.locked}:null}function z(e){return"failed"===e.bridgeAuthRefresh.phase?{type:"error",message:e.bridgeAuthRefresh.error?`Bridge auth refresh failed — ${e.bridgeAuthRefresh.error}`:"Bridge auth refresh failed after setup"}:"pending"===e.bridgeAuthRefresh.phase?{type:"system",message:"Credentials saved — refreshing bridge auth before the workspace unlocks…"}:e.lastValidation?.status==="failed"?{type:"error",message:`Credential validation failed — ${e.lastValidation.message}`}:e.locked||e.lastValidation?.status!=="succeeded"?e.activeFlow?.status==="awaiting_browser_auth"?{type:"system",message:`${e.activeFlow.providerLabel} sign-in is waiting for browser confirmation`}:e.activeFlow?.status==="awaiting_input"?{type:"system",message:`${e.activeFlow.providerLabel} sign-in needs one more input step`}:e.activeFlow?.status==="cancelled"?{type:"system",message:`${e.activeFlow.providerLabel} sign-in was cancelled`}:e.activeFlow?.status==="failed"?{type:"error",message:e.activeFlow.error?`${e.activeFlow.providerLabel} sign-in failed — ${e.activeFlow.error}`:`${e.activeFlow.providerLabel} sign-in failed`}:"required_setup"===e.lockReason?{type:"system",message:"Onboarding is still required before model-backed prompts will run"}:null:{type:"success",message:`${q(e,e.lastValidation.providerId)} is ready — workspace unlocked`}}function G(e){let t=[g("system",`GSD web workspace attached to ${e.project.cwd}`),g("system",`Workspace scope: ${J(e.workspace)}`)],s=L(e.bridge);t.push(g(s.type,s.message)),e.bridge.lastError&&t.push(g("error",`Bridge error: ${e.bridge.lastError.message}`));let r=z(e.onboarding);return r&&t.push(g(r.type,r.message)),t}function W(e,t=3){if(!e)return"—";let s=e.split(/[\\/]/).filter(Boolean);if(s.length<=t)return e.startsWith("/")?`/${s.join("/")}`:s.join("/");let r=s.slice(-t).join("/");return`…/${r}`}function K(e){return e?e.split(/[\\/]/).filter(Boolean).at(-1)||e:"Current project"}function V(e){if(!e||e<1e3)return"0m";let t=Math.floor(e/6e4),s=Math.floor(t/60),r=t%60;return s>0?`${s}h ${r}m`:`${r}m`}function H(e){return!Number.isFinite(e)||e<=0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(Math.round(e))}function Y(e){return!Number.isFinite(e)||e<=0?"$0.00":`$${e.toFixed(2)}`}function J(e){if(!e)return"Project scope pending";let t=[e.active.milestoneId,e.active.sliceId,e.active.taskId].filter(Boolean).join("/");return t?`${t} — ${e.active.phase}`:`project — ${e.active.phase}`}function Q(e){if(!e?.active.milestoneId||!e.active.sliceId)return null;let t=e.milestones.find(t=>t.id===e.active.milestoneId),s=t?.slices.find(t=>t.id===e.active.sliceId);return s?.branch??null}function Z(e){if(!e?.active.milestoneId||!e.active.sliceId)return null;let t=e.milestones.find(t=>t.id===e.active.milestoneId);return t?.slices.find(t=>t.id===e.active.sliceId)??null}function X(e){if(!e?.sessionState&&!e?.activeSessionId)return null;let t=e.sessionState?.sessionName?.trim();return t||(e.activeSessionId?`session ${e.activeSessionId}`:e.sessionState?.sessionId??null)}function ee(e){let t=e?.sessionState?.model;return t&&(t.id||t.providerId||t.provider)||"model pending"}function et(e){let t=e?.sessionState?.model;return t?{provider:t.provider??t.providerId,modelId:t.id}:null}function es(e){if(!e)return null;if(e.required.satisfiedBy?.providerId)return e.required.satisfiedBy.providerId;let t=e.required.providers.find(e=>!e.configured&&e.recommended);if(t)return t.id;let s=e.required.providers.find(e=>!e.configured);return s?s.id:e.required.providers[0]?.id??null}function er(e,t){return{...e,pending:!1,loaded:!1,error:t}}function ea(e,t){return{...e,phase:"error",pending:!1,stale:!0,error:t,lastFailureAt:new Date().toISOString()}}function en(e){return e?.bridge.activeSessionFile??e?.bridge.sessionState?.sessionFile??null}function ei(e,t){let s=en(t),r=t?.bridge.sessionState?.sessionName?.trim()||void 0;return e.map(e=>{let t=s?e.path===s:e.isActive;return{...e,isActive:t,...t&&r?{name:r}:{}}})}function eo(e,t){return{...e,activeSessionPath:en(t),sessions:ei(e.sessions,t)}}function el(e,t,s){return{...e,activeSessionPath:s.isActive?t:e.activeSessionPath,sessions:e.sessions.map(e=>e.path===t?{...e,...s}:s.isActive?{...e,isActive:!1}:e)}}function ed(e){let t=e.boot?.onboarding;return t?.bridgeAuthRefresh.phase==="failed"&&t.bridgeAuthRefresh.error?t.bridgeAuthRefresh.error:t?.lastValidation?.status==="failed"?t.lastValidation.message:e.lastBridgeError?.message??e.lastClientError}function ec(e){if("loading"===e.bootStatus)return{label:"Loading workspace",tone:"info"};if("error"===e.bootStatus)return{label:"Boot failed",tone:"danger"};let t=function(e){if("loading"===e.bootStatus||!e.boot)return{phase:"loading",label:"Loading setup state",detail:"Resolving the current project, bridge, and onboarding contract…",tone:"info"};let t=e.boot.onboarding;return t.activeFlow?.status==="awaiting_browser_auth"?{phase:"awaiting_browser_auth",label:"Continue sign-in in your browser",detail:`${t.activeFlow.providerLabel} is waiting for browser confirmation before the workspace can unlock.`,tone:"info"}:t.activeFlow?.status==="awaiting_input"?{phase:"awaiting_input",label:"One more sign-in step is required",detail:t.activeFlow.prompt?.message??`${t.activeFlow.providerLabel} needs one more input step.`,tone:"info"}:"bridge_refresh_pending"===t.lockReason?{phase:"refreshing",label:"Refreshing bridge auth",detail:"Credentials validated. The live bridge is restarting onto the new auth view before the shell unlocks.",tone:"info"}:"bridge_refresh_failed"===t.lockReason?{phase:"failure",label:"Setup completed, but the shell is still locked",detail:t.bridgeAuthRefresh.error??"The bridge could not reload auth after setup.",tone:"danger"}:t.lastValidation?.status==="failed"?{phase:"failure",label:"Credential validation failed",detail:t.lastValidation.message,tone:"danger"}:"saving_api_key"===e.onboardingRequestState?{phase:"validating",label:"Validating credentials",detail:"Checking the provider key and saving it only if validation succeeds.",tone:"info"}:"starting_provider_flow"===e.onboardingRequestState||"submitting_provider_flow_input"===e.onboardingRequestState?{phase:"running_flow",label:"Advancing provider sign-in",detail:"The onboarding flow is running and will update here as soon as the next step is ready.",tone:"info"}:t.locked?{phase:"locked",label:"Required setup needed",detail:"Choose a required provider, validate it here, and the workspace will unlock without restarting the host.",tone:"warning"}:{phase:"ready",label:"Workspace unlocked",detail:t.lastValidation?.status==="succeeded"?`${q(t,t.lastValidation.providerId)} is ready and the workspace is live.`:"Required setup is satisfied and the shell is ready for live commands.",tone:"success"}}(e);if("ready"!==t.phase)return{label:t.label,tone:t.tone};if(e.boot?.bridge.phase==="failed")return{label:"Bridge failed",tone:"danger"};switch(e.connectionState){case"connected":return{label:"Bridge connected",tone:"success"};case"connecting":return{label:"Connecting stream",tone:"info"};case"reconnecting":return{label:"Reconnecting stream",tone:"warning"};case"disconnected":return{label:"Stream disconnected",tone:"warning"};case"error":return{label:"Stream error",tone:"danger"};default:return{label:"Workspace idle",tone:"muted"}}}function eu(e,t){if(!t)return e;let s=new URL(e,"http://localhost");return s.searchParams.set("project",t),s.pathname+s.search}class em{constructor(e){this.projectCwd=e,this.state={bootStatus:"idle",connectionState:"idle",boot:null,live:{auto:null,workspace:null,resumableSessions:[],recoverySummary:S(),freshness:{auto:N(),workspace:N(),recovery:N(),resumableSessions:N(),gitSummary:N(),sessionBrowser:N(),sessionStats:N()},softBootRefreshCount:0,targetedRefreshCount:0},terminalLines:[g("system","Preparing the live GSD workspace…")],lastClientError:null,lastBridgeError:null,sessionAttached:!1,lastEventType:null,commandInFlight:null,lastSlashCommandOutcome:null,commandSurface:(0,x.iE)(),onboardingRequestState:"idle",onboardingRequestProviderId:null,pendingUiRequests:[],streamingAssistantText:"",streamingThinkingText:"",liveTranscript:[],liveThinkingTranscript:[],completedToolExecutions:[],activeToolExecution:null,currentTurnSegments:[],completedTurnSegments:[],chatUserMessages:[],statusTexts:{},widgetContents:{},titleOverride:null,editorTextBuffer:null},this.listeners=new Set,this.contextualTips=new w,this.eventStream=new p({canConnect:()=>!this.disposed&&!this.state.boot?.onboarding.locked,streamUrl:()=>(0,b.QT)(this.buildUrl("/api/session/events")),onOpen:({wasDisconnected:e})=>this.handleEventStreamOpen(e),onMessage:e=>this.handleEventStreamMessage(e),onError:({nextConnectionState:e,changed:t})=>this.handleEventStreamError(e,t)}),this.bootPromise=null,this.onboardingPollTimer=null,this.started=!1,this.disposed=!1,this.lastBridgeDigest=null,this.commandTimeoutTimer=null,this.lastBootRefreshAt=0,this.visibilityHandler=null,this.subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}),this.getSnapshot=()=>this.state,this.start=()=>{this.started||this.disposed||(this.started=!0,"u">typeof document&&(this.visibilityHandler=()=>{"visible"===document.visibilityState&&Date.now()-this.lastBootRefreshAt>=3e4&&this.refreshBoot({soft:!0})},document.addEventListener("visibilitychange",this.visibilityHandler)),this.refreshBoot())},this.dispose=()=>{this.disposed=!0,this.started=!1,this.stopOnboardingPoller(),this.closeEventStream(),this.clearCommandTimeout(),this.visibilityHandler&&"u">typeof document&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null)},this.disconnectSSE=()=>{this.closeEventStream()},this.reconnectSSE=()=>{this.disposed||(this.ensureEventStream(),this.refreshBoot({soft:!0}))},this.clearTerminalLines=()=>{let e=this.state.boot?G(this.state.boot):[g("system","Terminal cleared")];this.patchState({terminalLines:e})},this.consumeEditorTextBuffer=()=>{let e=this.state.editorTextBuffer;return null!==e&&this.patchState({editorTextBuffer:null}),e},this.openCommandSurface=(e,t={})=>{let s=P(this.state);this.patchState({commandSurface:(0,x.Q8)(this.state.commandSurface,{surface:e,source:t.source??"surface",args:t.args??"",selectedTarget:t.selectedTarget,onboardingLocked:this.state.boot?.onboarding.locked,currentModel:et(this.state.boot?.bridge),currentThinkingLevel:this.state.boot?.bridge.sessionState?.thinkingLevel??null,preferredProviderId:es(this.state.boot?.onboarding),resumableSessions:s.map(e=>({id:e.id,path:e.path,name:e.name,isActive:e.isActive})),currentSessionPath:this.state.boot?.bridge.activeSessionFile??this.state.boot?.bridge.sessionState?.sessionFile??null,currentSessionName:this.state.boot?.bridge.sessionState?.sessionName??null,projectCwd:this.state.boot?.project.cwd??null,projectSessionsDir:this.state.boot?.project.sessionsDir??null})})},this.closeCommandSurface=()=>{this.patchState({commandSurface:(0,x.Qx)(this.state.commandSurface)})},this.setCommandSurfaceSection=e=>{let t=P(this.state);this.patchState({commandSurface:(0,x.c0)(this.state.commandSurface,e,{onboardingLocked:this.state.boot?.onboarding.locked,currentModel:et(this.state.boot?.bridge),currentThinkingLevel:this.state.boot?.bridge.sessionState?.thinkingLevel??null,preferredProviderId:es(this.state.boot?.onboarding),resumableSessions:t.map(e=>({id:e.id,path:e.path,name:e.name,isActive:e.isActive})),currentSessionPath:this.state.boot?.bridge.activeSessionFile??this.state.boot?.bridge.sessionState?.sessionFile??null,currentSessionName:this.state.boot?.bridge.sessionState?.sessionName??null,projectCwd:this.state.boot?.project.cwd??null,projectSessionsDir:this.state.boot?.project.sessionsDir??null})})},this.selectCommandSurfaceTarget=e=>{this.patchState({commandSurface:(0,x.nU)(this.state.commandSurface,e)})},this.loadGitSummary=async()=>{let e={...this.state.commandSurface.gitSummary,pending:!0,error:null},t={...this.state.live,freshness:{...this.state.live.freshness,gitSummary:k(this.state.live.freshness.gitSummary)}};this.patchState({live:{...t,recoverySummary:_({boot:this.state.boot,live:t})},commandSurface:(0,x.Yc)({...this.state.commandSurface,gitSummary:e},"load_git_summary")});try{let t=await (0,b.tm)(this.buildUrl("/api/git"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),s=await t.json().catch(()=>null),r=s&&"object"==typeof s&&("repo"===s.kind||"not_repo"===s.kind)&&s.project&&"object"==typeof s.project&&"current_project"===s.project.scope&&"string"==typeof s.project.cwd&&("not_repo"===s.kind?"string"==typeof s.message:"string"==typeof s.project?.repoRoot&&"boolean"==typeof s.hasChanges&&"boolean"==typeof s.hasConflicts&&!!s.counts&&"object"==typeof s.counts&&!!Array.isArray(s.changedFiles)&&"number"==typeof s.truncatedFileCount&&"number"==typeof s.counts.changed&&"number"==typeof s.counts.staged&&"number"==typeof s.counts.dirty&&"number"==typeof s.counts.untracked&&"number"==typeof s.counts.conflicts)?s:null;if(!t.ok||!r){let r=s&&"object"==typeof s&&"error"in s&&"string"==typeof s.error?s.error:`Current-project git summary failed with ${t.status}`,a=er(e,r),n={...this.state.live,freshness:{...this.state.live.freshness,gitSummary:R(this.state.live.freshness.gitSummary,r)}};return this.patchState({live:{...n,recoverySummary:_({boot:this.state.boot,live:n})},commandSurface:(0,x.yC)({...this.state.commandSurface,gitSummary:a},{action:"load_git_summary",success:!1,message:r,gitSummary:a})}),null}let a={...this.state.live,freshness:{...this.state.live.freshness,gitSummary:A(this.state.live.freshness.gitSummary)}};return this.patchState({live:{...a,recoverySummary:_({boot:this.state.boot,live:a})},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"load_git_summary",success:!0,message:"",gitSummary:{pending:!1,loaded:!0,result:r,error:null}})}),r}catch(a){let t=$(a),s=er(e,t),r={...this.state.live,freshness:{...this.state.live.freshness,gitSummary:R(this.state.live.freshness.gitSummary,t)}};return this.patchState({live:{...r,recoverySummary:_({boot:this.state.boot,live:r})},commandSurface:(0,x.yC)({...this.state.commandSurface,gitSummary:s},{action:"load_git_summary",success:!1,message:t,gitSummary:s})}),null}},this.loadRecoveryDiagnostics=async()=>{var e;let t={...e=this.state.commandSurface.recovery,pending:!0,error:null,phase:e.loaded?e.phase:"loading"},s={...this.state.live,freshness:{...this.state.live.freshness,recovery:k(this.state.live.freshness.recovery)}};this.patchState({live:{...s,recoverySummary:_({boot:this.state.boot,live:s})},commandSurface:(0,x.Yc)({...this.state.commandSurface,recovery:t},"load_recovery_diagnostics")});try{let e=await (0,b.tm)(this.buildUrl("/api/recovery"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),s=await e.json().catch(()=>null),r=s&&"object"==typeof s&&("ready"===s.status||"unavailable"===s.status)&&"string"==typeof s.loadedAt&&s.project&&"string"==typeof s.project.cwd&&s.summary&&"string"==typeof s.summary.label&&"string"==typeof s.summary.detail&&s.bridge&&"string"==typeof s.bridge.phase&&s.validation&&"number"==typeof s.validation.total&&s.doctor&&"number"==typeof s.doctor.total&&s.interruptedRun&&"boolean"==typeof s.interruptedRun.available&&s.actions&&Array.isArray(s.actions.browser)&&Array.isArray(s.actions.commands)?s:null;if(!e.ok||!r){let r=s&&"object"==typeof s&&"error"in s&&"string"==typeof s.error?s.error:`Recovery diagnostics failed with ${e.status}`,a=ea(t,r),n={...this.state.live,freshness:{...this.state.live.freshness,recovery:R(this.state.live.freshness.recovery,r)}};return this.patchState({lastClientError:r,live:{...n,recoverySummary:_({boot:this.state.boot,live:n})},commandSurface:(0,x.yC)({...this.state.commandSurface,recovery:a},{action:"load_recovery_diagnostics",success:!1,message:r,recovery:a})}),null}let a={...{phase:"ready"===r.status?"ready":"unavailable",pending:!1,loaded:!0,stale:!1,diagnostics:r,error:null,lastLoadedAt:r.loadedAt,lastInvalidatedAt:null,lastFailureAt:null},lastInvalidatedAt:this.state.commandSurface.recovery.lastInvalidatedAt},n={...this.state.live,freshness:{...this.state.live.freshness,recovery:A(this.state.live.freshness.recovery)}};return this.patchState({lastClientError:null,live:{...n,recoverySummary:_({boot:this.state.boot,live:n})},commandSurface:(0,x.yC)({...this.state.commandSurface,recovery:a},{action:"load_recovery_diagnostics",success:!0,message:"ready"===r.status?"Recovery diagnostics refreshed":"Recovery diagnostics are currently unavailable",recovery:a})}),r}catch(a){let e=$(a),s=ea(t,e),r={...this.state.live,freshness:{...this.state.live.freshness,recovery:R(this.state.live.freshness.recovery,e)}};return this.patchState({lastClientError:e,live:{...r,recoverySummary:_({boot:this.state.boot,live:r})},commandSurface:(0,x.yC)({...this.state.commandSurface,recovery:s},{action:"load_recovery_diagnostics",success:!1,message:e,recovery:s})}),null}},this.loadForensicsDiagnostics=async()=>{this.patchDiagnosticsPhaseState("forensics",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/forensics"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Forensics request failed with ${e.status}`;return this.patchDiagnosticsPhaseState("forensics",{phase:"error",error:s}),null}return this.patchDiagnosticsPhaseState("forensics",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchDiagnosticsPhaseState("forensics",{phase:"error",error:e}),null}},this.loadDoctorDiagnostics=async e=>{this.patchDoctorState({phase:"loading",error:null});try{let t=e?`/api/doctor?scope=${encodeURIComponent(e)}`:"/api/doctor",s=await (0,b.tm)(t,{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),r=await s.json().catch(()=>null);if(!s.ok||!r){let e=r?.error??`Doctor request failed with ${s.status}`;return this.patchDoctorState({phase:"error",error:e}),null}return this.patchDoctorState({phase:"loaded",data:r,lastLoadedAt:new Date().toISOString()}),r}catch(t){let e=$(t);return this.patchDoctorState({phase:"error",error:e}),null}},this.applyDoctorFixes=async e=>{this.patchDoctorState({fixPending:!0,lastFixError:null,lastFixResult:null});try{let t=await (0,b.tm)(this.buildUrl("/api/doctor"),{method:"POST",cache:"no-store",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e?{scope:e}:{})}),s=await t.json().catch(()=>null);if(!t.ok||!s){let e=s?.error??`Doctor fix request failed with ${t.status}`;return this.patchDoctorState({fixPending:!1,lastFixError:e}),null}return this.patchDoctorState({fixPending:!1,lastFixResult:s}),this.loadDoctorDiagnostics(e),s}catch(t){let e=$(t);return this.patchDoctorState({fixPending:!1,lastFixError:e}),null}},this.loadSkillHealthDiagnostics=async()=>{this.patchDiagnosticsPhaseState("skillHealth",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/skill-health"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Skill health request failed with ${e.status}`;return this.patchDiagnosticsPhaseState("skillHealth",{phase:"error",error:s}),null}return this.patchDiagnosticsPhaseState("skillHealth",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchDiagnosticsPhaseState("skillHealth",{phase:"error",error:e}),null}},this.loadKnowledgeData=async()=>{this.patchKnowledgeCapturesPhaseState("knowledge",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/knowledge"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Knowledge request failed with ${e.status}`;return this.patchKnowledgeCapturesPhaseState("knowledge",{phase:"error",error:s}),null}return this.patchKnowledgeCapturesPhaseState("knowledge",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchKnowledgeCapturesPhaseState("knowledge",{phase:"error",error:e}),null}},this.loadCapturesData=async()=>{this.patchKnowledgeCapturesPhaseState("captures",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/captures"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Captures request failed with ${e.status}`;return this.patchKnowledgeCapturesPhaseState("captures",{phase:"error",error:s}),null}return this.patchKnowledgeCapturesPhaseState("captures",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchKnowledgeCapturesPhaseState("captures",{phase:"error",error:e}),null}},this.loadSettingsData=async()=>{this.patchSettingsPhaseState({phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/settings-data"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Settings request failed with ${e.status}`;return this.patchSettingsPhaseState({phase:"error",error:s}),null}return this.patchSettingsPhaseState({phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchSettingsPhaseState({phase:"error",error:e}),null}},this.loadHistoryData=async()=>{this.patchRemainingCommandsPhaseState("history",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/history"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`History request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("history",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("history",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchRemainingCommandsPhaseState("history",{phase:"error",error:e}),null}},this.loadInspectData=async()=>{this.patchRemainingCommandsPhaseState("inspect",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/inspect"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Inspect request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("inspect",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("inspect",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchRemainingCommandsPhaseState("inspect",{phase:"error",error:e}),null}},this.loadHooksData=async()=>{this.patchRemainingCommandsPhaseState("hooks",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/hooks"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Hooks request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("hooks",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("hooks",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchRemainingCommandsPhaseState("hooks",{phase:"error",error:e}),null}},this.loadExportData=async e=>{this.patchRemainingCommandsPhaseState("exportData",{phase:"loading",error:null});try{let t=e?`/api/export-data?format=${encodeURIComponent(e)}`:"/api/export-data",s=await (0,b.tm)(t,{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),r=await s.json().catch(()=>null);if(!s.ok||!r){let e=r?.error??`Export request failed with ${s.status}`;return this.patchRemainingCommandsPhaseState("exportData",{phase:"error",error:e}),null}return this.patchRemainingCommandsPhaseState("exportData",{phase:"loaded",data:r,lastLoadedAt:new Date().toISOString()}),r}catch(t){let e=$(t);return this.patchRemainingCommandsPhaseState("exportData",{phase:"error",error:e}),null}},this.loadUndoInfo=async()=>{this.patchRemainingCommandsPhaseState("undo",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/undo"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Undo info request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("undo",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("undo",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchRemainingCommandsPhaseState("undo",{phase:"error",error:e}),null}},this.loadCleanupData=async()=>{this.patchRemainingCommandsPhaseState("cleanup",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/cleanup"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Cleanup data request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("cleanup",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("cleanup",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchRemainingCommandsPhaseState("cleanup",{phase:"error",error:e}),null}},this.loadSteerData=async()=>{this.patchRemainingCommandsPhaseState("steer",{phase:"loading",error:null});try{let e=await (0,b.tm)(this.buildUrl("/api/steer"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Steer data request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("steer",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("steer",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=$(t);return this.patchRemainingCommandsPhaseState("steer",{phase:"error",error:e}),null}},this.executeUndoAction=async()=>{try{let e=await (0,b.tm)(this.buildUrl("/api/undo"),{method:"POST",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Undo action failed with ${e.status}`;return{success:!1,message:s}}return this.loadUndoInfo(),t}catch(e){return{success:!1,message:$(e)}}},this.executeCleanupAction=async(e,t)=>{try{let s=await (0,b.tm)(this.buildUrl("/api/cleanup"),{method:"POST",cache:"no-store",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({branches:e,snapshots:t})}),r=await s.json().catch(()=>null);if(!s.ok||!r){let e=r?.error??`Cleanup action failed with ${s.status}`;return{deletedBranches:0,prunedSnapshots:0,message:e}}return this.loadCleanupData(),r}catch(e){return{deletedBranches:0,prunedSnapshots:0,message:$(e)}}},this.resolveCaptureAction=async e=>{this.patchKnowledgeCapturesState({resolveRequest:{pending:!0,lastError:null,lastResult:null}});try{let t=await (0,b.tm)(this.buildUrl("/api/captures"),{method:"POST",cache:"no-store",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>null);if(!t.ok||!s){let e=s?.error??`Capture resolve failed with ${t.status}`;return this.patchKnowledgeCapturesState({resolveRequest:{pending:!1,lastError:e,lastResult:null}}),null}return this.patchKnowledgeCapturesState({resolveRequest:{pending:!1,lastError:null,lastResult:s}}),this.loadCapturesData(),s}catch(t){let e=$(t);return this.patchKnowledgeCapturesState({resolveRequest:{pending:!1,lastError:e,lastResult:null}}),null}},this.updateSessionBrowserState=e=>{this.patchState({commandSurface:{...this.state.commandSurface,sessionBrowser:{...this.state.commandSurface.sessionBrowser,...e,error:null},lastError:null,lastResult:null}})},this.loadSessionBrowser=async(e={})=>{let t={...this.state.commandSurface.sessionBrowser,...e,error:null},s={...this.state.live,freshness:{...this.state.live.freshness,sessionBrowser:k(this.state.live.freshness.sessionBrowser)}};this.patchState({live:{...s,recoverySummary:_({boot:this.state.boot,live:s})},commandSurface:(0,x.Yc)({...this.state.commandSurface,sessionBrowser:t},"load_session_browser")});let r=new URLSearchParams;t.query.trim()&&r.set("query",t.query.trim()),r.set("sortMode",t.sortMode),r.set("nameFilter",t.nameFilter);try{let e=await (0,b.tm)(this.buildUrl(`/api/session/browser?${r.toString()}`),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),s=await e.json().catch(()=>null),a=function(e){if(!e||"object"!=typeof e)return null;let t=e.project,s=e.query;if(!t||!s||!Array.isArray(e.sessions)||"current_project"!==t.scope||"string"!=typeof t.cwd||"string"!=typeof t.sessionsDir||"string"!=typeof s.query||"string"!=typeof s.sortMode||"string"!=typeof s.nameFilter)return null;let r=e.sessions.filter(e=>"string"==typeof e?.id&&"string"==typeof e?.path&&"string"==typeof e?.cwd&&"string"==typeof e?.createdAt&&"string"==typeof e?.modifiedAt&&"number"==typeof e?.messageCount&&"string"==typeof e?.firstMessage&&"boolean"==typeof e?.isActive&&"number"==typeof e?.depth&&"boolean"==typeof e?.isLastInThread&&Array.isArray(e?.ancestorHasNextSibling));return{scope:t.scope,projectCwd:t.cwd,projectSessionsDir:t.sessionsDir,activeSessionPath:"string"==typeof t.activeSessionPath?t.activeSessionPath:null,query:s.query,sortMode:s.sortMode,nameFilter:s.nameFilter,totalSessions:Number(e.totalSessions??r.length),returnedSessions:Number(e.returnedSessions??r.length),sessions:r,loaded:!0,error:null}}(s);if(!e.ok||!a){let r=s&&"object"==typeof s&&"error"in s&&"string"==typeof s.error?s.error:`Current-project session browser failed with ${e.status}`,a={...t,error:r},n={...this.state.live,freshness:{...this.state.live.freshness,sessionBrowser:R(this.state.live.freshness.sessionBrowser,r)}};return this.patchState({live:{...n,recoverySummary:_({boot:this.state.boot,live:n})},commandSurface:(0,x.yC)({...this.state.commandSurface,sessionBrowser:a},{action:"load_session_browser",success:!1,message:r,sessionBrowser:a})}),null}let n=eo(a,this.state.boot),i=this.state.commandSurface.selectedTarget,o=n.sessions.find(e=>!e.isActive)?.path??n.sessions[0]?.path,l=n.sessions.find(e=>e.path===n.activeSessionPath)??n.sessions[0],d=i;if(i?.kind==="resume"||"resume"===this.state.commandSurface.section){let e=i?.kind==="resume"&&i.sessionPath&&n.sessions.some(e=>e.path===i.sessionPath)?i.sessionPath:o;d={kind:"resume",sessionPath:e}}else if(i?.kind==="name"||"name"===this.state.commandSurface.section){let e=i?.kind==="name"&&i.sessionPath?n.sessions.find(e=>e.path===i.sessionPath)??l:l;d={kind:"name",sessionPath:e?.path,name:i?.kind==="name"&&i.sessionPath===e?.path?i.name:e?.name??""}}let c={...this.state.live,freshness:{...this.state.live.freshness,sessionBrowser:A(this.state.live.freshness.sessionBrowser)}};return this.patchState({live:{...c,recoverySummary:_({boot:this.state.boot,live:c})},commandSurface:(0,x.yC)({...this.state.commandSurface,sessionBrowser:n},{action:"load_session_browser",success:!0,message:"",selectedTarget:d,sessionBrowser:n})}),n}catch(a){let e=$(a),s={...t,error:e},r={...this.state.live,freshness:{...this.state.live.freshness,sessionBrowser:R(this.state.live.freshness.sessionBrowser,e)}};return this.patchState({live:{...r,recoverySummary:_({boot:this.state.boot,live:r})},commandSurface:(0,x.yC)({...this.state.commandSurface,sessionBrowser:s},{action:"load_session_browser",success:!1,message:e,sessionBrowser:s})}),null}},this.renameSessionFromSurface=async(e,t)=>{let s=this.state.commandSurface.selectedTarget,r=t??(s?.kind==="name"?s.name:""),a=r.trim(),n={kind:"name",sessionPath:e,name:r};if(!a)return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"rename_session",success:!1,message:"Session name cannot be empty",selectedTarget:n})}),null;this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"rename_session",n)});try{let t=await (0,b.tm)(this.buildUrl("/api/session/manage"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({action:"rename",sessionPath:e,name:a})}),s=await t.json().catch(()=>null);if(!t.ok||!s||"object"!=typeof s||!0!==s.success){let e=s&&"object"==typeof s&&"error"in s&&"string"==typeof s.error?s.error:`Session rename failed with ${t.status}`;return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"rename_session",success:!1,message:e,selectedTarget:n})}),null}let r=function(e,t,s){if(!e)return null;let r=en(e)===t&&e.bridge.sessionState?{...e.bridge,sessionState:{...e.bridge.sessionState,sessionName:s}}:e.bridge,a={...e,bridge:r};return{...a,resumableSessions:ei(a.resumableSessions.map(e=>e.path===t?{...e,name:s}:e),a)}}(this.state.boot,s.sessionPath,s.name),i=eo(el(this.state.commandSurface.sessionBrowser,s.sessionPath,{name:s.name,...s.isActiveSession?{isActive:!0}:{}}),r),o={kind:"name",sessionPath:s.sessionPath,name:s.name},l={...this.state.live,resumableSessions:ei(P(this.state).map(e=>e.path===s.sessionPath?{...e,name:s.name}:e),r)};return this.patchState({...r?{boot:r}:{},live:{...l,recoverySummary:_({boot:r,live:l})},commandSurface:(0,x.yC)({...this.state.commandSurface,sessionBrowser:i},{action:"rename_session",success:!0,message:`Session name set: ${s.name}`,selectedTarget:o,sessionBrowser:i})}),s}catch(t){let e=$(t);return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"rename_session",success:!1,message:e,selectedTarget:n})}),null}},this.loadAvailableModels=async()=>{this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"loading_models")});let e=await this.sendCommand({type:"get_available_models"},{appendInputLine:!1,appendResponseLine:!1});if(!e||!1===e.success){let t=e?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"loading_models",success:!1,message:`Couldn't load models — ${t}`})}),[]}let t=function(e,t){let s=e&&"object"==typeof e&&"models"in e&&Array.isArray(e.models)?e.models:[],r=[];for(let e of s){let s="string"==typeof e.provider?e.provider:"string"==typeof e.providerId?e.providerId:void 0,a="string"==typeof e.id?e.id:void 0;s&&a&&r.push({provider:s,modelId:a,name:"string"==typeof e.name?e.name:void 0,reasoning:!!e.reasoning,isCurrent:s===t?.provider&&a===t?.modelId})}return r.sort((e,t)=>Number(t.isCurrent)-Number(e.isCurrent)||e.provider.localeCompare(t.provider)||e.modelId.localeCompare(t.modelId))}(e.data,et(this.state.boot?.bridge)),s=this.state.commandSurface.selectedTarget,r=s?.kind==="model"?s:t[0]?{kind:"model",provider:t[0].provider,modelId:t[0].modelId}:s;return this.patchState({commandSurface:{...this.state.commandSurface,pendingAction:null,lastError:null,availableModels:t,selectedTarget:r??null}}),t},this.applyModelSelection=async(e,t)=>{let s={kind:"model",provider:e,modelId:t};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"set_model",s)});let r=await this.sendCommand({type:"set_model",provider:e,modelId:t},{appendInputLine:!1,appendResponseLine:!1});if(!r||!1===r.success){let e=r?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_model",success:!1,message:e,selectedTarget:s})}),r}let a=this.state.boot?.bridge.sessionState?{...this.state.boot.bridge,sessionState:{...this.state.boot.bridge.sessionState,model:r.data}}:null,n=this.state.commandSurface.availableModels.map(s=>({...s,isCurrent:s.provider===e&&s.modelId===t}));return this.patchState({...a&&this.state.boot?{boot:B(this.state.boot,a)}:{},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_model",success:!0,message:`Model set to ${e}/${t}`,selectedTarget:s,availableModels:n})}),r},this.applyThinkingLevel=async e=>{let t={kind:"thinking",level:e};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"set_thinking_level",t)});let s=await this.sendCommand({type:"set_thinking_level",level:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_thinking_level",success:!1,message:e,selectedTarget:t})}),s}let r=this.state.boot?.bridge.sessionState?{...this.state.boot.bridge,sessionState:{...this.state.boot.bridge.sessionState,thinkingLevel:e}}:null;return this.patchState({...r&&this.state.boot?{boot:B(this.state.boot,r)}:{},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_thinking_level",success:!0,message:`Thinking level set to ${e}`,selectedTarget:t})}),s},this.setSteeringModeFromSurface=async e=>{let t=this.state.commandSurface.selectedTarget;this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"set_steering_mode",t)});let s=await this.sendCommand({type:"set_steering_mode",mode:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_steering_mode",success:!1,message:e,selectedTarget:t})}),s}let r=O(this.state.boot,{steeringMode:e});return this.patchState({...r?{boot:r}:{},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_steering_mode",success:!0,message:`Steering mode set to ${e}`,selectedTarget:t})}),s},this.setFollowUpModeFromSurface=async e=>{let t=this.state.commandSurface.selectedTarget;this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"set_follow_up_mode",t)});let s=await this.sendCommand({type:"set_follow_up_mode",mode:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_follow_up_mode",success:!1,message:e,selectedTarget:t})}),s}let r=O(this.state.boot,{followUpMode:e});return this.patchState({...r?{boot:r}:{},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_follow_up_mode",success:!0,message:`Follow-up mode set to ${e}`,selectedTarget:t})}),s},this.setAutoCompactionFromSurface=async e=>{let t=this.state.commandSurface.selectedTarget;this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"set_auto_compaction",t)});let s=await this.sendCommand({type:"set_auto_compaction",enabled:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_auto_compaction",success:!1,message:e,selectedTarget:t})}),s}let r=O(this.state.boot,{autoCompactionEnabled:e});return this.patchState({...r?{boot:r}:{},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_auto_compaction",success:!0,message:`Auto-compaction ${e?"enabled":"disabled"}`,selectedTarget:t})}),s},this.setAutoRetryFromSurface=async e=>{let t=this.state.commandSurface.selectedTarget;this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"set_auto_retry",t)});let s=await this.sendCommand({type:"set_auto_retry",enabled:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_auto_retry",success:!1,message:e,selectedTarget:t})}),s}let r=O(this.state.boot,{autoRetryEnabled:e});return this.patchState({...r?{boot:r}:{},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"set_auto_retry",success:!0,message:`Auto-retry ${e?"enabled":"disabled"}`,selectedTarget:t})}),s},this.abortRetryFromSurface=async()=>{let e=this.state.commandSurface.selectedTarget;this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"abort_retry",e)});let t=await this.sendCommand({type:"abort_retry"},{appendInputLine:!1,appendResponseLine:!1});if(!t||!1===t.success){let s=t?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"abort_retry",success:!1,message:s,selectedTarget:e})}),t}return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"abort_retry",success:!0,message:"Retry cancellation requested. Live retry state will update when the bridge confirms the abort.",selectedTarget:e})}),t},this.switchSessionFromSurface=async e=>{var t;let s,r={kind:"resume",sessionPath:e};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"switch_session",r)});let a=await this.sendCommand({type:"switch_session",sessionPath:e},{appendInputLine:!1,appendResponseLine:!1});if(!a||!1===a.success){let e=a?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"switch_session",success:!1,message:e,selectedTarget:r})}),a}if(a.data&&"object"==typeof a.data&&"cancelled"in a.data&&a.data.cancelled)return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"switch_session",success:!1,message:"Session switch was cancelled before the browser changed sessions.",selectedTarget:r})}),a;let n=this.state.commandSurface.sessionBrowser.sessions.find(t=>t.path===e)?.name??this.state.boot?.resumableSessions.find(t=>t.path===e)?.name,i=function(e,t,s){if(!e)return null;let r=e.resumableSessions.find(e=>e.path===t),a={...e.bridge,activeSessionFile:t,activeSessionId:r?.id??e.bridge.activeSessionId,sessionState:e.bridge.sessionState?{...e.bridge.sessionState,sessionFile:t,sessionId:r?.id??e.bridge.sessionState.sessionId,sessionName:s??r?.name??e.bridge.sessionState.sessionName}:e.bridge.sessionState},n={...e,bridge:a};return{...n,resumableSessions:ei(n.resumableSessions.map(e=>({...e,isActive:e.path===t})),n)}}(this.state.boot,e,n),o=eo(el(this.state.commandSurface.sessionBrowser,e,{isActive:!0,...n?{name:n}:{}}),i),l={...this.state.live,resumableSessions:ei(P(this.state).map(t=>({...t,isActive:t.path===e,...t.path===e&&n?{name:n}:{}})),i)};return this.patchState({...i?{boot:i}:{},live:{...l,recoverySummary:_({boot:i,live:l})},commandSurface:(0,x.yC)({...this.state.commandSurface,sessionBrowser:o},{action:"switch_session",success:!0,message:`Switched to ${(t=i??this.state.boot,s=t?.resumableSessions.find(t=>t.path===e),s?.name?.trim()?s.name.trim():s?.id?s.id:W(e))}`,selectedTarget:r,sessionBrowser:o})}),a},this.loadSessionStats=async()=>{var e;let t={...this.state.live,freshness:{...this.state.live.freshness,sessionStats:k(this.state.live.freshness.sessionStats)}};this.patchState({live:{...t,recoverySummary:_({boot:this.state.boot,live:t})},commandSurface:(0,x.Yc)(this.state.commandSurface,"load_session_stats")});let s=await this.sendCommand({type:"get_session_stats"},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error",t={...this.state.live,freshness:{...this.state.live.freshness,sessionStats:R(this.state.live.freshness.sessionStats,e)}};return this.patchState({live:{...t,recoverySummary:_({boot:this.state.boot,live:t})},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"load_session_stats",success:!1,message:`Couldn't load session details — ${e}`,sessionStats:null})}),null}let r=(e=s.data)&&"object"==typeof e?"string"!=typeof e.sessionId?null:{sessionFile:"string"==typeof e.sessionFile?e.sessionFile:void 0,sessionId:e.sessionId,userMessages:Number(e.userMessages??0),assistantMessages:Number(e.assistantMessages??0),toolCalls:Number(e.toolCalls??0),toolResults:Number(e.toolResults??0),totalMessages:Number(e.totalMessages??0),tokens:{input:Number(e.tokens?.input??0),output:Number(e.tokens?.output??0),cacheRead:Number(e.tokens?.cacheRead??0),cacheWrite:Number(e.tokens?.cacheWrite??0),total:Number(e.tokens?.total??0)},cost:Number(e.cost??0)}:null;if(!r){let e="Session details response was missing the expected fields.",t={...this.state.live,freshness:{...this.state.live.freshness,sessionStats:R(this.state.live.freshness.sessionStats,e)}};return this.patchState({live:{...t,recoverySummary:_({boot:this.state.boot,live:t})},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"load_session_stats",success:!1,message:e,sessionStats:null})}),null}let a={...this.state.live,freshness:{...this.state.live.freshness,sessionStats:A(this.state.live.freshness.sessionStats)}};return this.patchState({live:{...a,recoverySummary:_({boot:this.state.boot,live:a})},commandSurface:(0,x.yC)(this.state.commandSurface,{action:"load_session_stats",success:!0,message:`Loaded session details for ${r.sessionId}`,sessionStats:r})}),r},this.exportSessionFromSurface=async e=>{let t=e?.trim()||void 0,s={kind:"session",outputPath:t};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"export_html",s)});let r=await this.sendCommand(t?{type:"export_html",outputPath:t}:{type:"export_html"},{appendInputLine:!1,appendResponseLine:!1});if(!r||!1===r.success){let e=r?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"export_html",success:!1,message:`Couldn't export this session — ${e}`,selectedTarget:s})}),r}let a=r.data&&"object"==typeof r.data&&"path"in r.data&&"string"==typeof r.data.path?r.data.path:"the generated file";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"export_html",success:!0,message:`Session exported to ${a}`,selectedTarget:s})}),r},this.loadForkMessages=async()=>{var e;this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"load_fork_messages")});let t=await this.sendCommand({type:"get_fork_messages"},{appendInputLine:!1,appendResponseLine:!1});if(!t||!1===t.success){let e=t?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"load_fork_messages",success:!1,message:`Couldn't load fork points — ${e}`,forkMessages:[]})}),[]}let s=((e=t.data)&&"object"==typeof e&&"messages"in e&&Array.isArray(e.messages)?e.messages:[]).map(e=>{let t="string"==typeof e.entryId?e.entryId:void 0,s="string"==typeof e.text?e.text:void 0;return t&&s?{entryId:t,text:s}:null}).filter(e=>null!==e),r=this.state.commandSurface.selectedTarget,a=r?.kind==="fork"&&r.entryId?r:s[0]?{kind:"fork",entryId:s[0].entryId}:r;return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"load_fork_messages",success:!0,message:s.length>0?`Loaded ${s.length} fork points.`:"No fork points are available yet.",selectedTarget:a??null,forkMessages:s})}),s},this.forkSessionFromSurface=async e=>{let t={kind:"fork",entryId:e};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"fork_session",t)});let s=await this.sendCommand({type:"fork",entryId:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"fork_session",success:!1,message:`Couldn't create a fork — ${e}`,selectedTarget:t})}),s}if(s.data&&"object"==typeof s.data&&"cancelled"in s.data&&s.data.cancelled)return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"fork_session",success:!1,message:"Fork creation was cancelled before a new session was created.",selectedTarget:t})}),s;let r=s.data&&"object"==typeof s.data&&"text"in s.data&&"string"==typeof s.data.text?s.data.text.trim():"";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"fork_session",success:!0,message:r?`Forked from “${r.slice(0,120)}${r.length>120?"…":""}”`:"Created a forked session.",selectedTarget:t})}),s},this.compactSessionFromSurface=async e=>{var t;let s=e?.trim()??"",r={kind:"compact",customInstructions:s};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"compact_session",r)});let a=await this.sendCommand(s?{type:"compact",customInstructions:s}:{type:"compact"},{appendInputLine:!1,appendResponseLine:!1});if(!a||!1===a.success){let e=a?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"compact_session",success:!1,message:`Couldn't compact the session — ${e}`,selectedTarget:r,lastCompaction:null})}),a}let n=(t=a.data)&&"object"==typeof t?"string"!=typeof t.summary||"string"!=typeof t.firstKeptEntryId?null:{summary:t.summary,firstKeptEntryId:t.firstKeptEntryId,tokensBefore:Number(t.tokensBefore??0),details:t.details}:null;return n?this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"compact_session",success:!0,message:`Compacted ${n.tokensBefore.toLocaleString()} tokens into a fresh summary${s?" with custom instructions":""}.`,selectedTarget:r,lastCompaction:n})}):this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"compact_session",success:!1,message:"Compaction finished but the browser could not read the compaction result.",selectedTarget:r,lastCompaction:null})}),a},this.saveApiKeyFromSurface=async(e,t)=>{let s={kind:"auth",providerId:e,intent:"manage"};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"save_api_key",s)});let r=await this.saveApiKey(e,t),a=r?q(r,e):e;return r?(r.lastValidation?.status==="failed"?this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"save_api_key",success:!1,message:r.lastValidation.message,selectedTarget:s})}):"failed"===r.bridgeAuthRefresh.phase?this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"save_api_key",success:!1,message:r.bridgeAuthRefresh.error??`${a} credentials validated but bridge auth refresh failed`,selectedTarget:s})}):this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"save_api_key",success:!0,message:`${a} credentials validated and saved.`,selectedTarget:s})}),r):(this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"save_api_key",success:!1,message:this.state.lastClientError??`${a} setup failed`,selectedTarget:s})}),null)},this.startProviderFlowFromSurface=async e=>{let t={kind:"auth",providerId:e,intent:"login"};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"start_provider_flow",t)});let s=await this.startProviderFlow(e),r=s?q(s,e):e;return s?(this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"start_provider_flow",success:!0,message:`${r} sign-in started. Continue in the auth section.`,selectedTarget:t})}),s):(this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"start_provider_flow",success:!1,message:this.state.lastClientError??`${r} sign-in failed to start`,selectedTarget:t})}),null)},this.submitProviderFlowInputFromSurface=async(e,t)=>{let s=this.state.boot?.onboarding.activeFlow?.providerId??void 0,r={kind:"auth",providerId:s,intent:"login"};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"submit_provider_flow_input",r)});let a=await this.submitProviderFlowInput(e,t),n=a?.activeFlow?.providerLabel??(s&&a?q(a,s):s)??"Provider";if(!a)return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"submit_provider_flow_input",success:!1,message:this.state.lastClientError??`${n} sign-in failed`,selectedTarget:r})}),null;if(a.activeFlow?.status==="failed")return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"submit_provider_flow_input",success:!1,message:a.activeFlow.error??`${n} sign-in failed`,selectedTarget:r})}),a;if("failed"===a.bridgeAuthRefresh.phase)return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"submit_provider_flow_input",success:!1,message:a.bridgeAuthRefresh.error??`${n} sign-in completed but bridge auth refresh failed`,selectedTarget:r})}),a;let i=a.activeFlow&&["running","awaiting_browser_auth","awaiting_input"].includes(a.activeFlow.status)?`${n} sign-in advanced. Complete the remaining step in this panel.`:`${n} sign-in complete.`;return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"submit_provider_flow_input",success:!0,message:i,selectedTarget:r})}),a},this.cancelProviderFlowFromSurface=async e=>{let t=this.state.boot?.onboarding.activeFlow?.providerId??void 0,s={kind:"auth",providerId:t,intent:"login"};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"cancel_provider_flow",s)});let r=await this.cancelProviderFlow(e),a=r?.activeFlow?.providerLabel??(t&&r?q(r,t):t)??"Provider";return r?(this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"cancel_provider_flow",success:!0,message:`${a} sign-in cancelled.`,selectedTarget:s})}),r):(this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"cancel_provider_flow",success:!1,message:this.state.lastClientError??`${a} sign-in cancellation failed`,selectedTarget:s})}),null)},this.logoutProviderFromSurface=async e=>{let t={kind:"auth",providerId:e,intent:"logout"};this.patchState({commandSurface:(0,x.Yc)(this.state.commandSurface,"logout_provider",t)});let s=await this.logoutProvider(e),r=s?q(s,e):e;if(!s)return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"logout_provider",success:!1,message:this.state.lastClientError??`${r} logout failed`,selectedTarget:t})}),null;if("failed"===s.bridgeAuthRefresh.phase)return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"logout_provider",success:!1,message:s.bridgeAuthRefresh.error??`${r} logout completed but bridge auth refresh failed`,selectedTarget:t})}),s;let a=s.required.providers.find(t=>t.id===e),n=a?.configured?`${r} saved credentials were removed, but ${a.configuredVia} auth still keeps the provider available.`:s.locked?`${r} logged out — required setup is needed again.`:`${r} logged out.`;return this.patchState({commandSurface:(0,x.yC)(this.state.commandSurface,{action:"logout_provider",success:!0,message:n,selectedTarget:t})}),s},this.respondToUiRequest=async(e,t)=>{this.patchState({commandInFlight:"extension_ui_response"});try{let s=await (0,b.tm)(this.buildUrl("/api/session/command"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({type:"extension_ui_response",id:e,...t})});if(!s.ok){let e=await s.json().catch(()=>({error:`HTTP ${s.status}`}));throw Error(e.error??`extension_ui_response failed with ${s.status}`)}this.patchState({pendingUiRequests:this.state.pendingUiRequests.filter(t=>t.id!==e)})}catch(t){let e=$(t);this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`UI response failed — ${e}`))})}finally{this.patchState({commandInFlight:null})}},this.dismissUiRequest=async e=>{this.patchState({commandInFlight:"extension_ui_response"});try{let t=await (0,b.tm)(this.buildUrl("/api/session/command"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({type:"extension_ui_response",id:e,cancelled:!0})});if(!t.ok){let e=await t.json().catch(()=>({error:`HTTP ${t.status}`}));throw Error(e.error??`extension_ui_response cancel failed with ${t.status}`)}this.patchState({pendingUiRequests:this.state.pendingUiRequests.filter(t=>t.id!==e)})}catch(t){let e=$(t);this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`UI dismiss failed — ${e}`))})}finally{this.patchState({commandInFlight:null})}},this.sendSteer=async e=>{await this.sendCommand({type:"steer",message:e})},this.sendAbort=async()=>{await this.sendCommand({type:"abort"})},this.pushChatUserMessage=e=>{this.patchState({chatUserMessages:[...this.state.chatUserMessages,e]})},this.submitInput=async(e,t)=>{let s=e.trim();if(!s)return null;let r=m(s,{isStreaming:this.state.boot?.bridge.sessionState?.isStreaming});if(this.patchState({lastSlashCommandOutcome:s.startsWith("/")?r:null}),"prompt"===r.kind){let e=this.state.boot?.bridge.sessionState,t=this.contextualTips.evaluate({input:s,isStreaming:!!e?.isStreaming,thinkingLevel:e?.thinkingLevel,contextPercent:void 0});t&&this.patchState({terminalLines:f(this.state.terminalLines,g("system",`💡 ${t}`))})}switch(r.kind){case"bash":return await this.sendCommand(r.command,{displayInput:s}),r;case"prompt":case"rpc":{let e=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),a=e&&e.length>0?{...r.command,images:e}:r.command;return await this.sendCommand(a,{displayInput:s}),r}case"local":if("clear_terminal"===r.action)return this.clearTerminalLines(),r;if("refresh_workspace"===r.action)return await this.refreshBoot(),r;return"gsd_help"===r.action&&this.patchState({terminalLines:f(f(this.state.terminalLines,g("input",s)),g("system",c))}),r;case"surface":{if(I.has(r.surface))return this.patchState({terminalLines:f(this.state.terminalLines,g("input",s))}),this.openCommandSurface(r.surface,{source:"slash",args:r.args}),r;let e=h(r),t=f(this.state.terminalLines,g("input",s));return e&&(t=f(t,g(e.type,e.message))),this.patchState({terminalLines:t}),r}case"reject":{let e=h(r),t=f(this.state.terminalLines,g("input",s));return e&&(t=f(t,g(e.type,e.message))),this.patchState({terminalLines:t}),r}case"view-navigate":return this.patchState({terminalLines:f(this.state.terminalLines,g("system",`Navigating to ${r.view} view`))}),window.dispatchEvent(new CustomEvent("gsd:navigate-view",{detail:{view:r.view}})),r}},this.refreshBoot=async(e={})=>{if(this.bootPromise)return await this.bootPromise;this.lastBootRefreshAt=Date.now();let t=!!(e.soft&&this.state.boot);this.bootPromise=(async()=>{t?this.patchState({lastClientError:null}):this.patchState({bootStatus:"loading",connectionState:"connected"===this.state.connectionState?"connected":"connecting",lastClientError:null});try{let e=await (0,b.tm)(this.buildUrl("/api/boot"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}});if(!e.ok){if(401===e.status)return void this.patchState({bootStatus:"unauthenticated",connectionState:"error"});throw Error(`Boot request failed with ${e.status}`)}let s=await e.json(),r=B(s,s.bridge)??s,a=function(e,t,s={}){let r={...e,auto:t.auto,workspace:t.workspace,resumableSessions:t.resumableSessions,freshness:{...e.freshness,auto:A(e.freshness.auto),workspace:A(e.freshness.workspace),recovery:A(e.freshness.recovery),resumableSessions:A(e.freshness.resumableSessions)},softBootRefreshCount:e.softBootRefreshCount+ +!!s.soft};return r.recoverySummary=_({boot:t,live:r}),r}(this.state.live,r,{soft:t});this.lastBridgeDigest=null,this.lastBridgeDigest=[r.bridge.phase,r.bridge.activeSessionId,r.bridge.lastError?.at,r.bridge.lastError?.message].join("::"),this.patchState({bootStatus:"ready",boot:r,live:a,connectionState:r.onboarding.locked?"idle":this.eventStream.isOpen()?this.state.connectionState:"connecting",lastBridgeError:r.bridge.lastError,sessionAttached:F(r.bridge),lastClientError:null,...t?{}:{terminalLines:G(r)}}),r.onboarding.locked?this.closeEventStream():this.ensureEventStream()}catch(s){let e=$(s);if(t)return void this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Workspace refresh failed — ${e}`))});this.patchState({bootStatus:"error",connectionState:"error",lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Boot failed — ${e}`))})}})().finally(()=>{this.bootPromise=null}),await this.bootPromise},this.refreshOnboarding=async()=>{this.patchState({onboardingRequestState:"refreshing",onboardingRequestProviderId:null,lastClientError:null});try{return await this.fetchOnboardingState()}catch(t){let e=$(t);return this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Onboarding refresh failed — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.saveApiKey=async(e,t)=>{this.patchState({onboardingRequestState:"saving_api_key",onboardingRequestProviderId:e,lastClientError:null});try{let s=await this.postOnboardingAction({action:"save_api_key",providerId:e,apiKey:t});return await this.syncAfterOnboardingMutation(s),s}catch(t){let e=$(t);return this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Credential setup failed — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.startProviderFlow=async e=>{this.patchState({onboardingRequestState:"starting_provider_flow",onboardingRequestProviderId:e,lastClientError:null});try{let t=await this.postOnboardingAction({action:"start_provider_flow",providerId:e});return await this.syncAfterOnboardingMutation(t),t}catch(t){let e=$(t);return this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Provider sign-in failed to start — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.submitProviderFlowInput=async(e,t)=>{this.patchState({onboardingRequestState:"submitting_provider_flow_input",onboardingRequestProviderId:this.state.boot?.onboarding.activeFlow?.providerId??null,lastClientError:null});try{let s=await this.postOnboardingAction({action:"continue_provider_flow",flowId:e,input:t});return await this.syncAfterOnboardingMutation(s),s}catch(t){let e=$(t);return this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Provider sign-in input failed — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.cancelProviderFlow=async e=>{this.patchState({onboardingRequestState:"cancelling_provider_flow",onboardingRequestProviderId:this.state.boot?.onboarding.activeFlow?.providerId??null,lastClientError:null});try{let t=await this.postOnboardingAction({action:"cancel_provider_flow",flowId:e});return await this.syncAfterOnboardingMutation(t),t}catch(t){let e=$(t);return this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Provider sign-in cancellation failed — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.logoutProvider=async e=>{this.patchState({onboardingRequestState:"logging_out_provider",onboardingRequestProviderId:e,lastClientError:null});try{let t=await this.postOnboardingAction({action:"logout_provider",providerId:e});return await this.syncAfterOnboardingMutation(t),t}catch(t){let e=$(t);return this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Provider logout failed — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.sendCommand=async(e,t={})=>{this.clearCommandTimeout();let s={commandInFlight:e.type};!1!==t.appendInputLine&&(s.terminalLines=f(this.state.terminalLines,g("input",t.displayInput??("string"==typeof e.message?e.message:`/${e.type}`)))),this.patchState(s),this.commandTimeoutTimer=setTimeout(()=>{this.state.commandInFlight&&this.patchState({commandInFlight:null,lastClientError:"Command timed out — controls re-enabled",terminalLines:f(this.state.terminalLines,g("error","Command timed out — controls re-enabled"))})},9e4);try{let s=await (0,b.tm)(this.buildUrl("/api/session/command"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),r=await s.json();if("ok"in r)return null;if("get_state"===r.command&&r.success&&this.state.boot){let e={...this.state.boot.bridge,sessionState:r.data,activeSessionId:r.data.sessionId,activeSessionFile:r.data.sessionFile??this.state.boot.bridge.activeSessionFile,lastCommandType:"get_state",updatedAt:new Date().toISOString()};this.patchState({boot:B(this.state.boot,e),lastBridgeError:e.lastError,sessionAttached:F(e)})}return"new_session"===r.command&&r.success&&this.contextualTips.reset(),"onboarding_locked"===r.code&&r.details?.onboarding&&this.state.boot&&this.patchState({boot:function(e,t){var s;return e?U(e,(s=e.onboarding,{...s,...t,required:{...s.required,...t.required??{},providers:t.required?.providers??s.required.providers},optional:{...s.optional,...t.optional??{},sections:t.optional?.sections??s.optional.sections},bridgeAuthRefresh:{...s.bridgeAuthRefresh,...t.bridgeAuthRefresh??{}}})):null}(this.state.boot,r.details.onboarding)}),this.patchState({...!1===t.appendResponseLine?{}:{terminalLines:f(this.state.terminalLines,function(e){if(!e.success)return g("error",`Command failed (${e.command}) — ${e.error??"unknown error"}`);switch(e.command){case"get_state":return g("success","Session state refreshed");case"new_session":return g("success","Started a new session");case"prompt":return g("success","Prompt accepted by the live bridge");case"follow_up":return g("success","Follow-up queued on the live bridge");case"bash":{let t=e.data;if(t?.output?.trim())return g("output",t.output.trimEnd());if(t?.cancelled)return g("system","Bash command cancelled");let s=t?.exitCode??0;return g(0===s?"success":"error",0===s?"Bash command completed":`Bash command exited with code ${s}`)}default:return g("success",`Command accepted (${e.command})`)}}(r))},lastBridgeError:r.success?this.state.lastBridgeError:this.state.boot?.bridge.lastError??this.state.lastBridgeError}),r}catch(s){let t=$(s);return this.patchState({lastClientError:t,terminalLines:f(this.state.terminalLines,g("error",`Command failed (${e.type}) — ${t}`))}),{type:"response",command:e.type,success:!1,error:t}}finally{this.clearCommandTimeout(),this.patchState({commandInFlight:null})}}}buildUrl(e){return eu(e,this.projectCwd)}patchDiagnosticsPhaseState(e,t){this.patchState({commandSurface:{...this.state.commandSurface,diagnostics:{...this.state.commandSurface.diagnostics,[e]:{...this.state.commandSurface.diagnostics[e],...t}}}})}patchDoctorState(e){this.patchState({commandSurface:{...this.state.commandSurface,diagnostics:{...this.state.commandSurface.diagnostics,doctor:{...this.state.commandSurface.diagnostics.doctor,...e}}}})}patchKnowledgeCapturesState(e){this.patchState({commandSurface:{...this.state.commandSurface,knowledgeCaptures:{...this.state.commandSurface.knowledgeCaptures,...e}}})}patchKnowledgeCapturesPhaseState(e,t){this.patchState({commandSurface:{...this.state.commandSurface,knowledgeCaptures:{...this.state.commandSurface.knowledgeCaptures,[e]:{...this.state.commandSurface.knowledgeCaptures[e],...t}}}})}patchSettingsPhaseState(e){this.patchState({commandSurface:{...this.state.commandSurface,settingsData:{...this.state.commandSurface.settingsData,...e}}})}patchRemainingCommandsPhaseState(e,t){this.patchState({commandSurface:{...this.state.commandSurface,remainingCommands:{...this.state.commandSurface.remainingCommands,[e]:{...this.state.commandSurface.remainingCommands[e],...t}}}})}async refreshBootAfterCurrentSettles(e={}){if(this.bootPromise)try{await this.bootPromise}catch{}await this.refreshBoot(e)}invalidateLiveFreshness(e,t,s){let r={...this.state.live.freshness};e.includes("auto")&&(r.auto=C(r.auto,t,s)),e.includes("workspace")&&(r.workspace=C(r.workspace,t,s),r.gitSummary=C(r.gitSummary,t,s)),e.includes("recovery")&&(r.recovery=C(r.recovery,t,s),r.sessionStats=C(r.sessionStats,t,s)),e.includes("resumable_sessions")&&(r.resumableSessions=C(r.resumableSessions,t,s),r.sessionBrowser=C(r.sessionBrowser,t,s),r.sessionStats=C(r.sessionStats,t,s));let a={...this.state.live,freshness:r};return{...a,recoverySummary:_({boot:this.state.boot,live:a})}}refreshOpenCommandSurfacesForInvalidation(e){if(e.domains.includes("workspace")&&this.state.commandSurface.open&&"git"===this.state.commandSurface.section&&"load_git_summary"!==this.state.commandSurface.pendingAction&&this.loadGitSummary(),e.domains.includes("recovery")&&this.state.commandSurface.open&&"recovery"===this.state.commandSurface.section&&"load_recovery_diagnostics"!==this.state.commandSurface.pendingAction&&this.loadRecoveryDiagnostics(),e.domains.includes("resumable_sessions")&&(this.state.commandSurface.open&&("resume"===this.state.commandSurface.section||"name"===this.state.commandSurface.section)&&"load_session_browser"!==this.state.commandSurface.pendingAction&&this.loadSessionBrowser(),this.state.commandSurface.open&&"session"===this.state.commandSurface.section)){let e=this.state.boot?.bridge.activeSessionFile??this.state.boot?.bridge.sessionState?.sessionFile??null;this.patchState({commandSurface:{...this.state.commandSurface,sessionStats:this.state.commandSurface.sessionStats&&this.state.commandSurface.sessionStats.sessionFile===e?this.state.commandSurface.sessionStats:null}}),"load_session_stats"!==this.state.commandSurface.pendingAction&&this.loadSessionStats()}}async reloadLiveState(e,t){let s=e.filter(e=>"auto"===e||"workspace"===e||"resumable_sessions"===e);if(0===s.length){let e={...this.state.live,freshness:{...this.state.live.freshness,recovery:A(this.state.live.freshness.recovery)}};this.patchState({live:{...e,recoverySummary:_({boot:this.state.boot,live:e})}});return}let r={...this.state.live.freshness};s.includes("auto")&&(r.auto=k(r.auto)),s.includes("workspace")&&(r.workspace=k(r.workspace)),s.includes("resumable_sessions")&&(r.resumableSessions=k(r.resumableSessions)),r.recovery=k(r.recovery);let a={...this.state.live,freshness:r,targetedRefreshCount:this.state.live.targetedRefreshCount+1};this.patchState({live:{...a,recoverySummary:_({boot:this.state.boot,live:a})}});let n=new URLSearchParams;for(let e of s)n.append("domain",e);try{let e=await (0,b.tm)(this.buildUrl(`/api/live-state?${n.toString()}`),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t)throw Error(t?.error??`Live state request failed with ${e.status}`);let r=this.state.boot,a={...this.state.live,freshness:{...this.state.live.freshness}};if(s.includes("auto")&&t.auto&&(a.auto=t.auto,a.freshness.auto=A(a.freshness.auto),r=r?{...r,auto:t.auto}:r),s.includes("workspace")&&t.workspace&&(a.workspace=t.workspace,a.freshness.workspace=A(a.freshness.workspace),r=r?{...r,workspace:t.workspace}:r),s.includes("resumable_sessions")&&t.resumableSessions){let e=ei(t.resumableSessions,r);a.resumableSessions=e,a.freshness.resumableSessions=A(a.freshness.resumableSessions),r=r?{...r,resumableSessions:e}:r}a.freshness.recovery=A(a.freshness.recovery),a.recoverySummary=_({boot:r,live:a}),this.patchState({...r?{boot:r}:{},live:a})}catch(a){let e=$(a),r={...this.state.live,freshness:{...this.state.live.freshness,auto:s.includes("auto")?R(this.state.live.freshness.auto,e):this.state.live.freshness.auto,workspace:s.includes("workspace")?R(this.state.live.freshness.workspace,e):this.state.live.freshness.workspace,resumableSessions:s.includes("resumable_sessions")?R(this.state.live.freshness.resumableSessions,e):this.state.live.freshness.resumableSessions,recovery:R(this.state.live.freshness.recovery,e)}};this.patchState({lastClientError:e,live:{...r,recoverySummary:_({boot:this.state.boot,live:r})},terminalLines:f(this.state.terminalLines,g("error",`Live refresh failed (${t}) — ${e}`))})}}handleLiveStateInvalidation(e){var t;this.patchState({live:this.invalidateLiveFreshness(e.domains,e.reason,e.source),commandSurface:e.domains.includes("recovery")?{...this.state.commandSurface,recovery:(t=this.state.commandSurface.recovery).loaded||t.error?{...t,stale:!0,lastInvalidatedAt:new Date().toISOString()}:t}:this.state.commandSurface}),this.refreshOpenCommandSurfacesForInvalidation(e),this.reloadLiveState(e.domains,e.reason)}clearCommandTimeout(){this.commandTimeoutTimer&&(clearTimeout(this.commandTimeoutTimer),this.commandTimeoutTimer=null)}async fetchOnboardingState(e=!1){let t=this.state.boot?.onboarding.activeFlow?.status??null,s=await (0,b.tm)(this.buildUrl("/api/onboarding"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),r=await s.json();if(!s.ok||!r.onboarding)throw Error(r.error??`Onboarding request failed with ${s.status}`);return this.applyOnboardingState(r.onboarding),t&&D.has(t)&&r.onboarding.activeFlow&&M.has(r.onboarding.activeFlow.status)?await this.syncAfterOnboardingMutation(r.onboarding):e||this.appendOnboardingSummaryLine(r.onboarding),r.onboarding}async postOnboardingAction(e){let t=await (0,b.tm)(this.buildUrl("/api/onboarding"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),s=await t.json();if(!t.ok)throw s.onboarding&&this.applyOnboardingState(s.onboarding),Error(s.error??`Onboarding action failed with ${t.status}`);if(!s.onboarding)throw Error(`Onboarding action returned no state (${t.status})`);return this.applyOnboardingState(s.onboarding),s.onboarding}applyOnboardingState(e){this.state.boot&&this.patchState({boot:U(this.state.boot,e)})}async syncAfterOnboardingMutation(e){this.applyOnboardingState(e),this.appendOnboardingSummaryLine(e),(e.lastValidation?.status==="succeeded"||"idle"!==e.bridgeAuthRefresh.phase)&&this.refreshBootAfterCurrentSettles({soft:!0})}appendOnboardingSummaryLine(e){let t=z(e);if(!t)return;let s=this.state.terminalLines.at(-1);(s?.type!==t.type||s.content!==t.message)&&this.patchState({terminalLines:f(this.state.terminalLines,g(t.type,t.message))})}emit(){for(let e of this.listeners)e()}patchState(e){this.state={...this.state,...e},this.syncOnboardingPoller(),this.emit()}syncOnboardingPoller(){if(this.disposed)return void this.stopOnboardingPoller();let e=this.state.boot?.onboarding.activeFlow?.status,t=!!(e&&D.has(e));if(t&&!this.onboardingPollTimer){this.onboardingPollTimer=setInterval(()=>{"idle"===this.state.onboardingRequestState&&this.fetchOnboardingState(!0).catch(e=>{let t=$(e);this.patchState({lastClientError:t})})},1500);return}t||this.stopOnboardingPoller()}stopOnboardingPoller(){this.onboardingPollTimer&&(clearInterval(this.onboardingPollTimer),this.onboardingPollTimer=null)}ensureEventStream(){this.eventStream.ensure()}closeEventStream(){this.eventStream.close()}handleEventStreamOpen(e){e&&this.patchState({terminalLines:f(this.state.terminalLines,g("success","Live event stream reconnected"))}),this.patchState({connectionState:"connected",lastClientError:null}),e&&this.refreshBoot({soft:!0})}handleEventStreamMessage(e){try{let t=JSON.parse(e);if(null===t||"object"!=typeof t||"string"!=typeof t.type)return void this.patchState({lastClientError:"Malformed event received from stream",terminalLines:f(this.state.terminalLines,g("error","Malformed event received from stream"))});this.handleEvent(t)}catch(t){let e=$(t);this.patchState({lastClientError:e,terminalLines:f(this.state.terminalLines,g("error",`Failed to parse stream event — ${e}`))})}}handleEventStreamError(e,t){t?this.patchState({connectionState:e,terminalLines:f(this.state.terminalLines,g("reconnecting"===e?"system":"error","reconnecting"===e?"Live event stream disconnected — retrying…":"Live event stream failed before connection was established"))}):this.patchState({connectionState:e})}handleEvent(e){if(this.patchState({lastEventType:e.type}),"bridge_status"===e.type)return void this.recordBridgeStatus(e.bridge);"live_state_invalidation"===e.type&&this.handleLiveStateInvalidation(e),this.routeLiveInteractionEvent(e);let t=function(e){switch(e.type){case"bridge_status":return L(e.bridge);case"live_state_invalidation":return{type:"system",message:`[Live] Refreshing ${Array.isArray(e.domains)?e.domains.join(", "):"state"} after ${String(e.reason).replaceAll("_"," ")}`};case"agent_start":return{type:"system",message:"[Agent] Run started"};case"agent_end":return{type:"success",message:"[Agent] Run finished"};case"turn_start":return{type:"system",message:"[Agent] Turn started"};case"turn_end":return{type:"success",message:"[Agent] Turn complete"};case"tool_execution_start":return{type:"output",message:`[Tool] ${"string"==typeof e.toolName?e.toolName:"tool"} started`};case"tool_execution_update":default:return null;case"tool_execution_end":return{type:e.isError?"error":"success",message:`[Tool] ${"string"==typeof e.toolName?e.toolName:"tool"} ${e.isError?"failed":"completed"}`};case"auto_compaction_start":return{type:"system",message:"[Auto] Compaction started"};case"auto_compaction_end":return{type:e.aborted?"error":"success",message:e.aborted?"[Auto] Compaction aborted":"[Auto] Compaction finished"};case"auto_retry_start":return{type:"system",message:`[Auto] Retry ${String(e.attempt)}/${String(e.maxAttempts)} scheduled`};case"auto_retry_end":return{type:e.success?"success":"error",message:e.success?"[Auto] Retry recovered the run":"[Auto] Retry exhausted"};case"extension_ui_request":{let t="title"in e&&"string"==typeof e.title&&e.title.trim().length>0?e.title:"message"in e&&"string"==typeof e.message&&e.message.trim().length>0?e.message:e.method;return{type:"notifyType"in e&&"error"===e.notifyType?"error":"system",message:`[UI] ${t}`}}case"extension_error":return{type:"error",message:`[Extension] ${e.error}`}}}(e);t&&this.patchState({terminalLines:f(this.state.terminalLines,g(t.type,t.message))})}routeLiveInteractionEvent(e){switch(e.type){case"extension_ui_request":this.handleExtensionUiRequest(e);break;case"message_update":this.handleMessageUpdate(e);break;case"agent_end":case"turn_end":this.handleTurnBoundary();break;case"tool_execution_start":this.handleToolExecutionStart(e);break;case"tool_execution_update":this.handleToolExecutionUpdate(e);break;case"tool_execution_end":this.handleToolExecutionEnd(e)}}handleExtensionUiRequest(e){switch(e.method){case"select":case"confirm":case"input":case"editor":this.patchState({pendingUiRequests:[...this.state.pendingUiRequests,e]});break;case"notify":break;case"setStatus":if("setStatus"===e.method){let t={...this.state.statusTexts};void 0===e.statusText?delete t[e.statusKey]:t[e.statusKey]=e.statusText,this.patchState({statusTexts:t})}break;case"setWidget":if("setWidget"===e.method){let t={...this.state.widgetContents};void 0===e.widgetLines?delete t[e.widgetKey]:t[e.widgetKey]={lines:e.widgetLines,placement:e.widgetPlacement},this.patchState({widgetContents:t})}break;case"setTitle":if("setTitle"===e.method){let t=e.title.trim();this.patchState({titleOverride:t||null})}break;case"set_editor_text":"set_editor_text"===e.method&&this.patchState({editorTextBuffer:e.text})}}handleMessageUpdate(e){let t=e.assistantMessageEvent;t&&("text_delta"===t.type&&"string"==typeof t.delta?(this.state.streamingThinkingText.length>0&&this.patchState({currentTurnSegments:[...this.state.currentTurnSegments,{kind:"thinking",content:this.state.streamingThinkingText}],streamingThinkingText:""}),this.patchState({streamingAssistantText:this.state.streamingAssistantText+t.delta})):"thinking_delta"===t.type&&"string"==typeof t.delta?(this.state.streamingAssistantText.length>0&&this.patchState({currentTurnSegments:[...this.state.currentTurnSegments,{kind:"text",content:this.state.streamingAssistantText}],streamingAssistantText:""}),this.patchState({streamingThinkingText:this.state.streamingThinkingText+t.delta})):"thinking_end"===t.type&&this.state.streamingThinkingText.length>0&&this.patchState({currentTurnSegments:[...this.state.currentTurnSegments,{kind:"thinking",content:this.state.streamingThinkingText}],streamingThinkingText:""}))}handleTurnBoundary(){let e=[];this.state.streamingThinkingText.length>0&&e.push({kind:"thinking",content:this.state.streamingThinkingText}),this.state.streamingAssistantText.length>0&&e.push({kind:"text",content:this.state.streamingAssistantText});let t=e.length>0?[...this.state.currentTurnSegments,...e]:this.state.currentTurnSegments,s=t.filter(e=>"text"===e.kind).map(e=>e.content).join("");if(s.length>0||t.length>0){let e=[...this.state.liveTranscript,s],r=[...this.state.liveThinkingTranscript,""],a=[...this.state.completedTurnSegments,t],n=e.length>100?e.length-100:0,i=n>0?this.state.chatUserMessages.slice(n):void 0;this.patchState({liveTranscript:n>0?e.slice(n):e,liveThinkingTranscript:n>0?r.slice(n):r,completedTurnSegments:n>0?a.slice(n):a,...void 0!==i?{chatUserMessages:i}:{},streamingAssistantText:"",streamingThinkingText:"",currentTurnSegments:[],completedToolExecutions:[]})}else this.state.streamingThinkingText.length>0?this.patchState({streamingThinkingText:"",currentTurnSegments:[],completedToolExecutions:[]}):this.patchState({currentTurnSegments:[],completedToolExecutions:[]})}handleToolExecutionStart(e){this.patchState({activeToolExecution:{id:e.toolCallId,name:e.toolName,args:e.args},streamingAssistantText:"",streamingThinkingText:""})}handleToolExecutionUpdate(e){let t=this.state.activeToolExecution;t&&t.id===e.toolCallId&&this.patchState({activeToolExecution:{...t,result:e.partialResult?{content:e.partialResult.content,details:e.partialResult.details,isError:!!e.partialResult.isError}:t.result}})}handleToolExecutionEnd(e){let t=this.state.activeToolExecution;if(t){let s={id:t.id,name:t.name,args:t.args??{},result:{content:e.result?.content,details:e.result?.details,isError:e.isError}},r=[...this.state.completedToolExecutions,s];this.patchState({activeToolExecution:null,completedToolExecutions:r.length>50?r.slice(r.length-50):r,currentTurnSegments:[...this.state.currentTurnSegments,{kind:"tool",tool:s}]})}else this.patchState({activeToolExecution:null})}recordBridgeStatus(e){let t=[e.phase,e.activeSessionId,e.lastError?.at,e.lastError?.message].join("::"),s=t!==this.lastBridgeDigest;this.lastBridgeDigest=t;let r=B(this.state.boot,e),a={...this.state.live,resumableSessions:ei(this.state.live.resumableSessions,r)},n={...a,recoverySummary:_({boot:r,live:a})},i={boot:r,live:n,lastBridgeError:e.lastError,sessionAttached:F(e),commandSurface:{...this.state.commandSurface,sessionBrowser:eo(this.state.commandSurface.sessionBrowser,r)}};if(s){let t=L(e);i.terminalLines=f(this.state.terminalLines,g(t.type,t.message))}this.patchState(i)}}let eh=(0,a.createContext)(null);function ex({children:e,store:t}){let[s]=(0,a.useState)(()=>new em),n=t??s;return(0,a.useEffect)(()=>{if(!t)return n.start(),()=>n.dispose()},[n,t]),(0,r.jsx)(eh.Provider,{value:n,children:e})}function ep(){let e=(0,a.useContext)(eh);if(!e)throw Error("useWorkspaceStore must be used within GSDWorkspaceProvider");return e}function eg(){let e=ep();return(0,a.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getSnapshot)}function ef(){let e=ep();return{sendCommand:e.sendCommand,submitInput:e.submitInput,clearTerminalLines:e.clearTerminalLines,consumeEditorTextBuffer:e.consumeEditorTextBuffer,refreshBoot:e.refreshBoot,refreshOnboarding:e.refreshOnboarding,openCommandSurface:e.openCommandSurface,closeCommandSurface:e.closeCommandSurface,setCommandSurfaceSection:e.setCommandSurfaceSection,selectCommandSurfaceTarget:e.selectCommandSurfaceTarget,loadGitSummary:e.loadGitSummary,loadRecoveryDiagnostics:e.loadRecoveryDiagnostics,loadForensicsDiagnostics:e.loadForensicsDiagnostics,loadDoctorDiagnostics:e.loadDoctorDiagnostics,applyDoctorFixes:e.applyDoctorFixes,loadSkillHealthDiagnostics:e.loadSkillHealthDiagnostics,loadKnowledgeData:e.loadKnowledgeData,loadCapturesData:e.loadCapturesData,loadSettingsData:e.loadSettingsData,loadHistoryData:e.loadHistoryData,loadInspectData:e.loadInspectData,loadHooksData:e.loadHooksData,loadExportData:e.loadExportData,loadUndoInfo:e.loadUndoInfo,loadCleanupData:e.loadCleanupData,loadSteerData:e.loadSteerData,executeUndoAction:e.executeUndoAction,executeCleanupAction:e.executeCleanupAction,resolveCaptureAction:e.resolveCaptureAction,updateSessionBrowserState:e.updateSessionBrowserState,loadSessionBrowser:e.loadSessionBrowser,renameSessionFromSurface:e.renameSessionFromSurface,loadAvailableModels:e.loadAvailableModels,applyModelSelection:e.applyModelSelection,applyThinkingLevel:e.applyThinkingLevel,setSteeringModeFromSurface:e.setSteeringModeFromSurface,setFollowUpModeFromSurface:e.setFollowUpModeFromSurface,setAutoCompactionFromSurface:e.setAutoCompactionFromSurface,setAutoRetryFromSurface:e.setAutoRetryFromSurface,abortRetryFromSurface:e.abortRetryFromSurface,switchSessionFromSurface:e.switchSessionFromSurface,loadSessionStats:e.loadSessionStats,exportSessionFromSurface:e.exportSessionFromSurface,loadForkMessages:e.loadForkMessages,forkSessionFromSurface:e.forkSessionFromSurface,compactSessionFromSurface:e.compactSessionFromSurface,saveApiKey:e.saveApiKey,saveApiKeyFromSurface:e.saveApiKeyFromSurface,startProviderFlow:e.startProviderFlow,startProviderFlowFromSurface:e.startProviderFlowFromSurface,submitProviderFlowInput:e.submitProviderFlowInput,submitProviderFlowInputFromSurface:e.submitProviderFlowInputFromSurface,cancelProviderFlow:e.cancelProviderFlow,cancelProviderFlowFromSurface:e.cancelProviderFlowFromSurface,logoutProvider:e.logoutProvider,logoutProviderFromSurface:e.logoutProviderFromSurface,respondToUiRequest:e.respondToUiRequest,dismissUiRequest:e.dismissUiRequest,sendSteer:e.sendSteer,sendAbort:e.sendAbort,pushChatUserMessage:e.pushChatUserMessage}}function eb(e,t){let s=m(e,{isStreaming:t?.sessionState?.isStreaming});if("prompt"===s.kind||"rpc"===s.kind)return s.command;throw Error(`buildPromptCommand cannot serialize ${s.input||e} because browser dispatch resolved it to ${s.kind}; use submitInput() instead.`)}},94002:(e,t,s)=>{function r(e,t){return t<=0?-1:Math.max(0,Math.min(t-1,e))}function a(e,t,s){if(s<=0)return{type:"none"};let a=function(e,t){if(!/^[1-9]$/.test(e))return null;let s=Number(e)-1;return s<t?s:null}(e,s);return null!==a?{type:"select",index:a}:"ArrowUp"===e?{type:"select",index:r(t-1,s)}:"ArrowDown"===e?{type:"select",index:r(t+1,s)}:"Home"===e?{type:"select",index:0}:"End"===e?{type:"select",index:s-1}:"Enter"===e||" "===e?{type:"submit",index:r(t,s)}:{type:"none"}}s.d(t,{cZ:()=>a,cv:()=>r})},97019:(e,t,s)=>{s.d(t,{Bc:()=>i,ZI:()=>d,k$:()=>l,m_:()=>o});var r=s(18870);s(45110);var a=s(37250),n=s(18833);function i({delayDuration:e=0,...t}){return(0,r.jsx)(a.Kq,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function o({...e}){return(0,r.jsx)(i,{children:(0,r.jsx)(a.bL,{"data-slot":"tooltip",...e})})}function l({...e}){return(0,r.jsx)(a.l9,{"data-slot":"tooltip-trigger",...e})}function d({className:e,sideOffset:t=0,children:s,...i}){return(0,r.jsx)(a.ZL,{children:(0,r.jsxs)(a.UC,{"data-slot":"tooltip-content",sideOffset:t,className:(0,n.cn)("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...i,children:[s,(0,r.jsx)(a.i3,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}}}]);