@agenthippo-ai/agenthippo 1.110.11 → 1.110.19

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 (534) hide show
  1. package/out/agentpack/types.js +2 -5
  2. package/out/analytics/dashboard/artifactManager.js +2 -439
  3. package/out/analytics/dashboard/fleetDisplayUtils.js +2 -162
  4. package/out/analytics/dashboard/fleetOrchestrator.js +3 -142
  5. package/out/analytics/dashboard/fleetRegistry.js +2 -79
  6. package/out/analytics/dashboard/fleetRowDefaults.js +2 -87
  7. package/out/analytics/dashboard/fleetScriptAdapter.js +2 -146
  8. package/out/analytics/dashboard/fleetTypes.js +2 -29
  9. package/out/analytics/dashboard/index.js +2 -17
  10. package/out/analytics/dashboard/indexingService.js +2 -422
  11. package/out/analytics/dashboard/localFleetAdapter.js +2 -302
  12. package/out/analytics/dashboard/performanceMonitor.js +5 -76
  13. package/out/analytics/dashboard/processManager.js +2 -209
  14. package/out/analytics/dashboard/provider.js +38 -3817
  15. package/out/analytics/dashboard/queryRunner.js +62 -750
  16. package/out/analytics/dashboard/scheduledFleetStorage.js +2 -241
  17. package/out/analytics/dashboard/sessionJsonlFleet.js +3 -204
  18. package/out/analytics/dashboard/teamViewDiscovery.js +2 -106
  19. package/out/analytics/dashboard/webview/panel.js +34 -2318
  20. package/out/analytics/dashboard/webview/runtime-bridge.js +2 -82
  21. package/out/analytics/lifecycle.js +2 -43
  22. package/out/analytics/service.js +8 -1283
  23. package/out/auth/authBaseUrl.js +2 -59
  24. package/out/auth/bootstrapApply.js +2 -71
  25. package/out/auth/brokerClient.js +2 -160
  26. package/out/auth/callbackUri.js +2 -59
  27. package/out/auth/githubStoreGate.js +2 -70
  28. package/out/auth/loopbackAuthServer.js +4 -159
  29. package/out/auth/onboardingPrompt.js +2 -112
  30. package/out/auth/pkce.js +2 -9
  31. package/out/auth/provider.js +2 -226
  32. package/out/auth/sessionStore.js +2 -156
  33. package/out/auth/signInFlow.js +2 -183
  34. package/out/cli/index.js +617 -564
  35. package/out/cli/run-custom-engine-runner.js +3 -318
  36. package/out/cli/vscode-shim.js +2 -86
  37. package/out/engines/factory.js +2 -45
  38. package/out/engines/types.js +2 -17
  39. package/out/examples/run-headless-repl.js +6 -286
  40. package/out/examples/run-headless.js +2 -187
  41. package/out/extension.js +32 -4473
  42. package/out/gateway/gatewayRouteIndex.js +6 -371
  43. package/out/gateway/gatewaySessionStore.js +3 -243
  44. package/out/gateway/index.js +2 -31
  45. package/out/gateway/resetMappings.js +2 -52
  46. package/out/gateway/service.js +5 -1249
  47. package/out/mcp/publish.js +2 -143
  48. package/out/remote/handleRemoteChat.js +2 -169
  49. package/out/remote/remotePackStatusBar.js +3 -103
  50. package/out/remote/remoteTrust.js +6 -277
  51. package/out/remote/serveClient.js +4 -277
  52. package/out/remoteSkills.js +3 -191
  53. package/out/runtime/index.js +2 -32
  54. package/out/runtime/vscode/index.js +2 -20
  55. package/out/runtime/vscode/vscode-config-provider.js +2 -77
  56. package/out/runtime/vscode/vscode-edit-tracker.js +2 -122
  57. package/out/runtime/vscode/vscode-logger.js +2 -30
  58. package/out/runtime/vscode/vscode-permission-handler.js +2 -72
  59. package/out/scripts/agentide-litellm.sh +0 -1
  60. package/out/scripts/agentide_litellm_hooks_v1.py +127 -459
  61. package/out/scripts/analytics/agent-fleet-widget.js +18 -257
  62. package/out/scripts/analytics/agentide-litellm-otel.config.yaml +0 -4
  63. package/out/scripts/analytics/duckdbLocator.js +2 -28
  64. package/out/scripts/analytics/generate-default-charts.py +43 -323
  65. package/out/scripts/analytics/hotspot-analysis-widget.js +4 -430
  66. package/out/scripts/analytics/index-traces.py +78 -1036
  67. package/out/scripts/analytics/session-comparison-widget.js +26 -472
  68. package/out/scripts/analytics/session-timeline-widget.js +25 -846
  69. package/out/scripts/analytics/token-cost-flamegraph-widget.js +4 -461
  70. package/out/scripts/analytics/token-cost-trend-widget.js +4 -534
  71. package/out/scripts/analytics/workflows-collector.cjs +4 -314
  72. package/out/scripts/analytics/workflows-daemon.mjs +9 -185
  73. package/out/scripts/analytics/workflows-widget.cjs +15 -159
  74. package/out/scripts/analytics/wow-model-widget.js +10 -120
  75. package/out/scripts/vendor-tools.mjs +2 -233
  76. package/out/skills/publish.js +3 -178
  77. package/out/store/github/setup.js +7 -212
  78. package/out/store/oramaIndex.js +2 -884
  79. package/out/sync.js +26 -1829
  80. package/out/terminalLogger.js +5 -358
  81. package/out/utils/pathSafety.js +2 -60
  82. package/out/utils/pythonRunner.js +4 -258
  83. package/out/utils/toolPath.js +2 -83
  84. package/out/workspaceFolders.js +2 -59
  85. package/package.json +1 -1
  86. package/out/agentpack/github.js +0 -547
  87. package/out/agentpack/index.js +0 -69
  88. package/out/agentpack/install.js +0 -297
  89. package/out/agentpack/manager.js +0 -441
  90. package/out/agentpack/manifest.js +0 -135
  91. package/out/agentpack/paths.js +0 -521
  92. package/out/agentpack/publish.js +0 -248
  93. package/out/agentpack/stores.js +0 -554
  94. package/out/analytics/dashboard/fleetStatusUtils.js +0 -30
  95. package/out/analytics/dashboard/fleetTitleUtils.js +0 -68
  96. package/out/analytics/dashboard/refreshPolicy.js +0 -16
  97. package/out/analytics/dashboard/scheduledFleetFingerprint.js +0 -22
  98. package/out/analytics/dashboard/scheduledFleetUtils.js +0 -22
  99. package/out/analytics/dashboard/sessionEventFleetStats.js +0 -118
  100. package/out/analytics/dashboard/viewsConfigMerge.js +0 -221
  101. package/out/analytics/dashboard/webview/codicon.ttf +0 -0
  102. package/out/analytics/identity.js +0 -0
  103. package/out/analytics/sessionEvents.js +0 -324
  104. package/out/auth/callbackUriParse.js +0 -59
  105. package/out/auth/types.js +0 -12
  106. package/out/auth-broker/config.js +0 -112
  107. package/out/auth-broker/jwt.js +0 -105
  108. package/out/auth-broker/pkce.js +0 -59
  109. package/out/auth-broker/server.js +0 -681
  110. package/out/auth-broker/store.js +0 -275
  111. package/out/authority/warrant.js +0 -206
  112. package/out/base-prompts/mcp-servers/.mcp.json +0 -13
  113. package/out/base-prompts/mcp-servers/langfuse-analytics/README.md +0 -142
  114. package/out/base-prompts/mcp-servers/langfuse-analytics/mcp.json +0 -13
  115. package/out/base-prompts/mcp-servers/langfuse-analytics/package-lock.json +0 -1192
  116. package/out/base-prompts/mcp-servers/langfuse-analytics/package.json +0 -23
  117. package/out/base-prompts/mcp-servers/langfuse-analytics/scripts/run-with-env.sh +0 -12
  118. package/out/base-prompts/mcp-servers/langfuse-analytics/scripts/sdk-test.js +0 -102
  119. package/out/base-prompts/mcp-servers/langfuse-analytics/scripts/simple-test.js +0 -137
  120. package/out/base-prompts/mcp-servers/langfuse-analytics/scripts/test-client.js +0 -118
  121. package/out/base-prompts/mcp-servers/langfuse-analytics/scripts/test-server.js +0 -209
  122. package/out/base-prompts/mcp-servers/langfuse-analytics/src/client.ts +0 -431
  123. package/out/base-prompts/mcp-servers/langfuse-analytics/src/index.ts +0 -270
  124. package/out/base-prompts/mcp-servers/langfuse-analytics/tsconfig.json +0 -18
  125. package/out/base-prompts/rules/AGENTS.md +0 -204
  126. package/out/base-prompts/skills/agent-browser/SKILL.md +0 -102
  127. package/out/base-prompts/skills/agent-builder/SKILL.md +0 -73
  128. package/out/base-prompts/skills/agent-builder/references/agent-pack.md +0 -63
  129. package/out/base-prompts/skills/agent-builder/references/crewai.md +0 -66
  130. package/out/base-prompts/skills/agent-builder/references/langchain.md +0 -60
  131. package/out/base-prompts/skills/agent-builder/references/raw-sdk.md +0 -73
  132. package/out/base-prompts/skills/agent-engine-creator/SKILL.md +0 -586
  133. package/out/base-prompts/skills/agent-engine-installer/SKILL.md +0 -106
  134. package/out/base-prompts/skills/agent-engine-installer/scripts/install-engine.mjs +0 -259
  135. package/out/base-prompts/skills/agent-engine-installer/scripts/install-engine.ps1 +0 -189
  136. package/out/base-prompts/skills/agenthippo-cli/SKILL.md +0 -69
  137. package/out/base-prompts/skills/agenthippo-cli/scripts/install.sh +0 -63
  138. package/out/base-prompts/skills/agentpack-creator/SKILL.md +0 -375
  139. package/out/base-prompts/skills/agentpack-creator/references/agent-templates.md +0 -261
  140. package/out/base-prompts/skills/agentpack-creator/references/agents-md-guide.md +0 -195
  141. package/out/base-prompts/skills/agentpack-creator/scripts/init_pack.py +0 -391
  142. package/out/base-prompts/skills/agentpack-creator/scripts/init_pack_test.py +0 -294
  143. package/out/base-prompts/skills/agentpack-testbench/SKILL.md +0 -135
  144. package/out/base-prompts/skills/algorithmic-art/LICENSE.txt +0 -202
  145. package/out/base-prompts/skills/algorithmic-art/SKILL.md +0 -405
  146. package/out/base-prompts/skills/algorithmic-art/templates/generator_template.js +0 -223
  147. package/out/base-prompts/skills/algorithmic-art/templates/viewer.html +0 -599
  148. package/out/base-prompts/skills/debug-agent/SKILL.md +0 -83
  149. package/out/base-prompts/skills/desktop-automation/SKILL.md +0 -166
  150. package/out/base-prompts/skills/desktop-automation/references/agenthippo-ui-recipes.md +0 -441
  151. package/out/base-prompts/skills/desktop-automation/scripts/windows-desktop-uia.psm1 +0 -280
  152. package/out/base-prompts/skills/docx/LICENSE.txt +0 -30
  153. package/out/base-prompts/skills/docx/SKILL.md +0 -197
  154. package/out/base-prompts/skills/docx/docx-js.md +0 -350
  155. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +0 -1499
  156. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +0 -146
  157. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +0 -1085
  158. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +0 -11
  159. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-main.xsd +0 -3081
  160. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +0 -23
  161. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +0 -185
  162. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +0 -287
  163. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/pml.xsd +0 -1676
  164. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +0 -28
  165. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +0 -144
  166. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +0 -174
  167. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +0 -25
  168. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +0 -18
  169. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +0 -59
  170. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +0 -56
  171. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +0 -195
  172. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-math.xsd +0 -582
  173. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +0 -25
  174. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/sml.xsd +0 -4439
  175. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/vml-main.xsd +0 -570
  176. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +0 -509
  177. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +0 -12
  178. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +0 -108
  179. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +0 -96
  180. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/wml.xsd +0 -3646
  181. package/out/base-prompts/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/xml.xsd +0 -116
  182. package/out/base-prompts/skills/docx/ooxml/schemas/ecma/fouth-edition/opc-contentTypes.xsd +0 -42
  183. package/out/base-prompts/skills/docx/ooxml/schemas/ecma/fouth-edition/opc-coreProperties.xsd +0 -50
  184. package/out/base-prompts/skills/docx/ooxml/schemas/ecma/fouth-edition/opc-digSig.xsd +0 -49
  185. package/out/base-prompts/skills/docx/ooxml/schemas/ecma/fouth-edition/opc-relationships.xsd +0 -33
  186. package/out/base-prompts/skills/docx/ooxml/schemas/mce/mc.xsd +0 -75
  187. package/out/base-prompts/skills/docx/ooxml/schemas/microsoft/wml-2010.xsd +0 -560
  188. package/out/base-prompts/skills/docx/ooxml/schemas/microsoft/wml-2012.xsd +0 -67
  189. package/out/base-prompts/skills/docx/ooxml/schemas/microsoft/wml-2018.xsd +0 -14
  190. package/out/base-prompts/skills/docx/ooxml/schemas/microsoft/wml-cex-2018.xsd +0 -20
  191. package/out/base-prompts/skills/docx/ooxml/schemas/microsoft/wml-cid-2016.xsd +0 -13
  192. package/out/base-prompts/skills/docx/ooxml/schemas/microsoft/wml-sdtdatahash-2020.xsd +0 -4
  193. package/out/base-prompts/skills/docx/ooxml/schemas/microsoft/wml-symex-2015.xsd +0 -8
  194. package/out/base-prompts/skills/docx/ooxml/scripts/pack.py +0 -159
  195. package/out/base-prompts/skills/docx/ooxml/scripts/unpack.py +0 -29
  196. package/out/base-prompts/skills/docx/ooxml/scripts/validate.py +0 -69
  197. package/out/base-prompts/skills/docx/ooxml/scripts/validation/__init__.py +0 -15
  198. package/out/base-prompts/skills/docx/ooxml/scripts/validation/base.py +0 -951
  199. package/out/base-prompts/skills/docx/ooxml/scripts/validation/docx.py +0 -274
  200. package/out/base-prompts/skills/docx/ooxml/scripts/validation/pptx.py +0 -315
  201. package/out/base-prompts/skills/docx/ooxml/scripts/validation/redlining.py +0 -279
  202. package/out/base-prompts/skills/docx/ooxml.md +0 -610
  203. package/out/base-prompts/skills/docx/scripts/__init__.py +0 -1
  204. package/out/base-prompts/skills/docx/scripts/document.py +0 -1276
  205. package/out/base-prompts/skills/docx/scripts/templates/comments.xml +0 -3
  206. package/out/base-prompts/skills/docx/scripts/templates/commentsExtended.xml +0 -3
  207. package/out/base-prompts/skills/docx/scripts/templates/commentsExtensible.xml +0 -3
  208. package/out/base-prompts/skills/docx/scripts/templates/commentsIds.xml +0 -3
  209. package/out/base-prompts/skills/docx/scripts/templates/people.xml +0 -3
  210. package/out/base-prompts/skills/docx/scripts/utilities.py +0 -374
  211. package/out/base-prompts/skills/gateway-outbound/SKILL.md +0 -136
  212. package/out/base-prompts/skills/mcp-builder/LICENSE.txt +0 -202
  213. package/out/base-prompts/skills/mcp-builder/SKILL.md +0 -328
  214. package/out/base-prompts/skills/mcp-builder/reference/evaluation.md +0 -602
  215. package/out/base-prompts/skills/mcp-builder/reference/mcp_best_practices.md +0 -249
  216. package/out/base-prompts/skills/mcp-builder/reference/node_mcp_server.md +0 -970
  217. package/out/base-prompts/skills/mcp-builder/reference/python_mcp_server.md +0 -719
  218. package/out/base-prompts/skills/mcp-builder/scripts/connections.py +0 -151
  219. package/out/base-prompts/skills/mcp-builder/scripts/evaluation.py +0 -373
  220. package/out/base-prompts/skills/mcp-builder/scripts/example_evaluation.xml +0 -22
  221. package/out/base-prompts/skills/mcp-builder/scripts/requirements.txt +0 -2
  222. package/out/base-prompts/skills/openclaw/SKILL.md +0 -406
  223. package/out/base-prompts/skills/openclaw/scripts/run-smoke.sh +0 -61
  224. package/out/base-prompts/skills/pdf/LICENSE.txt +0 -30
  225. package/out/base-prompts/skills/pdf/SKILL.md +0 -294
  226. package/out/base-prompts/skills/pdf/forms.md +0 -205
  227. package/out/base-prompts/skills/pdf/reference.md +0 -612
  228. package/out/base-prompts/skills/pdf/scripts/check_bounding_boxes.py +0 -70
  229. package/out/base-prompts/skills/pdf/scripts/check_bounding_boxes_test.py +0 -226
  230. package/out/base-prompts/skills/pdf/scripts/check_fillable_fields.py +0 -12
  231. package/out/base-prompts/skills/pdf/scripts/convert_pdf_to_images.py +0 -35
  232. package/out/base-prompts/skills/pdf/scripts/create_validation_image.py +0 -41
  233. package/out/base-prompts/skills/pdf/scripts/extract_form_field_info.py +0 -152
  234. package/out/base-prompts/skills/pdf/scripts/fill_fillable_fields.py +0 -114
  235. package/out/base-prompts/skills/pdf/scripts/fill_pdf_form_with_annotations.py +0 -108
  236. package/out/base-prompts/skills/pptx/LICENSE.txt +0 -30
  237. package/out/base-prompts/skills/pptx/SKILL.md +0 -484
  238. package/out/base-prompts/skills/pptx/html2pptx.md +0 -625
  239. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +0 -1499
  240. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +0 -146
  241. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +0 -1085
  242. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +0 -11
  243. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-main.xsd +0 -3081
  244. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +0 -23
  245. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +0 -185
  246. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +0 -287
  247. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/pml.xsd +0 -1676
  248. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +0 -28
  249. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +0 -144
  250. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +0 -174
  251. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +0 -25
  252. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +0 -18
  253. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +0 -59
  254. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +0 -56
  255. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +0 -195
  256. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-math.xsd +0 -582
  257. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +0 -25
  258. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/sml.xsd +0 -4439
  259. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/vml-main.xsd +0 -570
  260. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +0 -509
  261. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +0 -12
  262. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +0 -108
  263. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +0 -96
  264. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/wml.xsd +0 -3646
  265. package/out/base-prompts/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/xml.xsd +0 -116
  266. package/out/base-prompts/skills/pptx/ooxml/schemas/ecma/fouth-edition/opc-contentTypes.xsd +0 -42
  267. package/out/base-prompts/skills/pptx/ooxml/schemas/ecma/fouth-edition/opc-coreProperties.xsd +0 -50
  268. package/out/base-prompts/skills/pptx/ooxml/schemas/ecma/fouth-edition/opc-digSig.xsd +0 -49
  269. package/out/base-prompts/skills/pptx/ooxml/schemas/ecma/fouth-edition/opc-relationships.xsd +0 -33
  270. package/out/base-prompts/skills/pptx/ooxml/schemas/mce/mc.xsd +0 -75
  271. package/out/base-prompts/skills/pptx/ooxml/schemas/microsoft/wml-2010.xsd +0 -560
  272. package/out/base-prompts/skills/pptx/ooxml/schemas/microsoft/wml-2012.xsd +0 -67
  273. package/out/base-prompts/skills/pptx/ooxml/schemas/microsoft/wml-2018.xsd +0 -14
  274. package/out/base-prompts/skills/pptx/ooxml/schemas/microsoft/wml-cex-2018.xsd +0 -20
  275. package/out/base-prompts/skills/pptx/ooxml/schemas/microsoft/wml-cid-2016.xsd +0 -13
  276. package/out/base-prompts/skills/pptx/ooxml/schemas/microsoft/wml-sdtdatahash-2020.xsd +0 -4
  277. package/out/base-prompts/skills/pptx/ooxml/schemas/microsoft/wml-symex-2015.xsd +0 -8
  278. package/out/base-prompts/skills/pptx/ooxml/scripts/pack.py +0 -159
  279. package/out/base-prompts/skills/pptx/ooxml/scripts/unpack.py +0 -29
  280. package/out/base-prompts/skills/pptx/ooxml/scripts/validate.py +0 -69
  281. package/out/base-prompts/skills/pptx/ooxml/scripts/validation/__init__.py +0 -15
  282. package/out/base-prompts/skills/pptx/ooxml/scripts/validation/base.py +0 -951
  283. package/out/base-prompts/skills/pptx/ooxml/scripts/validation/docx.py +0 -274
  284. package/out/base-prompts/skills/pptx/ooxml/scripts/validation/pptx.py +0 -315
  285. package/out/base-prompts/skills/pptx/ooxml/scripts/validation/redlining.py +0 -279
  286. package/out/base-prompts/skills/pptx/ooxml.md +0 -427
  287. package/out/base-prompts/skills/pptx/scripts/html2pptx.js +0 -984
  288. package/out/base-prompts/skills/pptx/scripts/inventory.py +0 -1020
  289. package/out/base-prompts/skills/pptx/scripts/rearrange.py +0 -231
  290. package/out/base-prompts/skills/pptx/scripts/replace.py +0 -385
  291. package/out/base-prompts/skills/pptx/scripts/thumbnail.py +0 -450
  292. package/out/base-prompts/skills/prompt-lab/SKILL.md +0 -149
  293. package/out/base-prompts/skills/prompt-lab/scripts/query-analytics.sh +0 -2551
  294. package/out/base-prompts/skills/skill-creator/LICENSE.txt +0 -202
  295. package/out/base-prompts/skills/skill-creator/SKILL.md +0 -371
  296. package/out/base-prompts/skills/skill-creator/references/output-patterns.md +0 -82
  297. package/out/base-prompts/skills/skill-creator/references/workflows.md +0 -28
  298. package/out/base-prompts/skills/skill-creator/scripts/init_skill.py +0 -303
  299. package/out/base-prompts/skills/skill-creator/scripts/package_skill.py +0 -110
  300. package/out/base-prompts/skills/skill-creator/scripts/quick_validate.py +0 -95
  301. package/out/base-prompts/skills/skill-installer/SKILL.md +0 -251
  302. package/out/base-prompts/skills/skill-installer/references/store-api.md +0 -219
  303. package/out/base-prompts/skills/spotlight-dashboard/SKILL.md +0 -83
  304. package/out/base-prompts/skills/spotlight-insights/SKILL.md +0 -101
  305. package/out/base-prompts/skills/spotlight-optimize/SKILL.md +0 -93
  306. package/out/base-prompts/skills/spotlight-optimize/scripts/query-analytics.sh +0 -2551
  307. package/out/base-prompts/skills/spotlight-query/SKILL.md +0 -314
  308. package/out/base-prompts/skills/spotlight-query/references/otel-schema.md +0 -163
  309. package/out/base-prompts/skills/spotlight-query/scripts/query-analytics.sh +0 -2551
  310. package/out/base-prompts/skills/spotlight-query/scripts/query-analytics.test.sh +0 -744
  311. package/out/base-prompts/skills/spotlight-query/scripts/test-fixtures/analytics/sessions/sess-test-1.jsonl +0 -14
  312. package/out/base-prompts/skills/spotlight-query/scripts/test-fixtures/analytics/traces/.duckdb-index.json +0 -7
  313. package/out/base-prompts/skills/spotlight-query/scripts/test-fixtures/analytics/traces/sample.jsonl +0 -5
  314. package/out/base-prompts/skills/spotlight-report/SKILL.md +0 -86
  315. package/out/base-prompts/skills/spotlight-visualize/SKILL.md +0 -92
  316. package/out/base-prompts/skills/spotlight-visualize/scripts/query-analytics.sh +0 -2551
  317. package/out/base-prompts/skills/xlsx/LICENSE.txt +0 -30
  318. package/out/base-prompts/skills/xlsx/SKILL.md +0 -289
  319. package/out/base-prompts/skills/xlsx/recalc.py +0 -178
  320. package/out/branding.js +0 -49
  321. package/out/cli/commands/anywhere.js +0 -66
  322. package/out/cli/commands/ask.js +0 -246
  323. package/out/cli/commands/auth-broker.js +0 -24
  324. package/out/cli/commands/auth.js +0 -219
  325. package/out/cli/commands/chat.js +0 -357
  326. package/out/cli/commands/conformance.js +0 -249
  327. package/out/cli/commands/data-plane.js +0 -151
  328. package/out/cli/commands/deploy.js +0 -263
  329. package/out/cli/commands/gateway.js +0 -218
  330. package/out/cli/commands/idp.js +0 -85
  331. package/out/cli/commands/pack.js +0 -399
  332. package/out/cli/commands/probe-custom-engine.js +0 -82
  333. package/out/cli/commands/sandbox.js +0 -351
  334. package/out/cli/commands/serve.js +0 -1950
  335. package/out/cli/commands/store.js +0 -927
  336. package/out/cli/credential-context.js +0 -108
  337. package/out/cli/data-plane/broker.js +0 -78
  338. package/out/cli/data-plane/connector-host.js +0 -121
  339. package/out/cli/data-plane/egress.js +0 -189
  340. package/out/cli/data-plane/gateway.js +0 -218
  341. package/out/cli/data-plane/index.js +0 -153
  342. package/out/cli/data-plane/registry.js +0 -89
  343. package/out/cli/data-plane/remote.js +0 -106
  344. package/out/cli/data-plane/sidecar.js +0 -225
  345. package/out/cli/deploy/blueprints/registry.js +0 -84
  346. package/out/cli/deploy/layers/identity.js +0 -175
  347. package/out/cli/deploy-init.js +0 -3023
  348. package/out/cli/deps.js +0 -342
  349. package/out/cli/idp-init.js +0 -338
  350. package/out/cli/pack-install-ref.js +0 -15
  351. package/out/cli/pack-loader.js +0 -418
  352. package/out/cli/pack-runtime.js +0 -61
  353. package/out/cli/runtime.js +0 -450
  354. package/out/cli/serve-hardening.js +0 -776
  355. package/out/cli/state-sync.js +0 -424
  356. package/out/cli/utils.js +0 -231
  357. package/out/engines/base.js +0 -188
  358. package/out/engines/claude.js +0 -1254
  359. package/out/engines/codex.js +0 -862
  360. package/out/engines/custom.js +0 -680
  361. package/out/engines/customEngineIpc.js +0 -95
  362. package/out/engines/customEngineRunnerEmbed.js +0 -107
  363. package/out/engines/customRegistry.js +0 -274
  364. package/out/engines/embeddedCustomEngineRunner.generated.js +0 -9
  365. package/out/engines/engineApiKey.js +0 -138
  366. package/out/engines/install.js +0 -372
  367. package/out/engines/persistentEngineWorker.js +0 -320
  368. package/out/engines/publish.js +0 -341
  369. package/out/evidence/sessionShip.js +0 -643
  370. package/out/gateway/bridge.js +0 -843
  371. package/out/gateway/cli-agent-id.js +0 -36
  372. package/out/gateway/client.js +0 -336
  373. package/out/gateway/client.test.js +0 -395
  374. package/out/gateway/gateway-scope-errors.js +0 -14
  375. package/out/gateway/gatewayBackup.js +0 -76
  376. package/out/gateway/installSource.js +0 -68
  377. package/out/gateway/lifecycle.js +0 -3190
  378. package/out/gateway/openclaw-channel-routing.js +0 -317
  379. package/out/gateway/outboundHandles.js +0 -373
  380. package/out/gateway/outboundPaths.js +0 -75
  381. package/out/gateway/outboundSend.js +0 -254
  382. package/out/gateway/protocol.js +0 -48
  383. package/out/gateway/secretsPreflight.js +0 -90
  384. package/out/gateway/sessionRouting.js +0 -77
  385. package/out/headless/index.js +0 -546
  386. package/out/headless/sync.js +0 -473
  387. package/out/live-e2e/mcp-demo/server.mjs +0 -32
  388. package/out/live-probe/connector.mjs +0 -8
  389. package/out/live-probe/env-report.mjs +0 -8
  390. package/out/mcp.js +0 -654
  391. package/out/pack/caps.js +0 -271
  392. package/out/pack/governor.js +0 -326
  393. package/out/pack/lease-schema.js +0 -273
  394. package/out/pack/lease.js +0 -682
  395. package/out/pack/reconcile.js +0 -217
  396. package/out/pack/signature.js +0 -839
  397. package/out/permissions.js +0 -108
  398. package/out/permissions.mapping.yaml +0 -68
  399. package/out/registry/index.js +0 -332
  400. package/out/runner/host.js +0 -141
  401. package/out/runner/protocol.js +0 -128
  402. package/out/runner/remoteEngine.js +0 -166
  403. package/out/runtime/interfaces/config-provider.js +0 -32
  404. package/out/runtime/interfaces/edit-tracker.js +0 -24
  405. package/out/runtime/interfaces/index.js +0 -29
  406. package/out/runtime/interfaces/logger.js +0 -40
  407. package/out/runtime/interfaces/permission-handler.js +0 -66
  408. package/out/runtime/interfaces/session-store.js +0 -342
  409. package/out/runtime/vscode/vscode-session-store.js +0 -22
  410. package/out/sandbox/containerDriver.js +0 -572
  411. package/out/sandbox/processDriver.js +0 -318
  412. package/out/sandbox/sandboxRunner.js +0 -303
  413. package/out/sandbox/support.js +0 -301
  414. package/out/sandbox/types.js +0 -55
  415. package/out/scripts/analytics/fleet-local-adapter.js +0 -246
  416. package/out/scripts/analytics/live-fleet-4-collector.cjs +0 -315
  417. package/out/scripts/analytics/live-fleet-4-daemon.mjs +0 -134
  418. package/out/scripts/analytics/live-fleet-4-widget.cjs +0 -433
  419. package/out/scripts/gateway/Dockerfile.serve +0 -45
  420. package/out/scripts/gateway/docker-serve.sh +0 -248
  421. package/out/scripts/gateway/setup-gateway-server.ps1 +0 -953
  422. package/out/scripts/gateway/setup-gateway-server.sh +0 -935
  423. package/out/session.js +0 -272
  424. package/out/shared/agentEngines.js +0 -170
  425. package/out/shared/index.js +0 -109
  426. package/out/shared/models.js +0 -136
  427. package/out/shared/providers.js +0 -205
  428. package/out/spotlight/install.js +0 -345
  429. package/out/spotlight/publish.js +0 -544
  430. package/out/spotlight/yaml.js +0 -31
  431. package/out/store/index.js +0 -786
  432. package/out/store/shared.js +0 -241
  433. package/out/test/agentEnvFile.test.js +0 -97
  434. package/out/test/agentYaml.test.js +0 -373
  435. package/out/test/agentpack.test.js +0 -639
  436. package/out/test/analytics-lifecycle.test.js +0 -174
  437. package/out/test/analytics.test.js +0 -756
  438. package/out/test/auth-baseurl.test.js +0 -132
  439. package/out/test/auth-bootstrapApply.test.js +0 -123
  440. package/out/test/auth-broker-hardening.test.js +0 -227
  441. package/out/test/auth-broker.test.js +0 -541
  442. package/out/test/auth-callback.test.js +0 -62
  443. package/out/test/blueprint-registry.test.js +0 -105
  444. package/out/test/branding.test.js +0 -242
  445. package/out/test/caps-governor.test.js +0 -460
  446. package/out/test/cli-agent-id.test.js +0 -55
  447. package/out/test/codex-new-file-survival.test.js +0 -119
  448. package/out/test/configuration-scopes.test.js +0 -131
  449. package/out/test/credential-context.test.js +0 -160
  450. package/out/test/custom-env-layering.test.js +0 -151
  451. package/out/test/customEngineInstall.test.js +0 -100
  452. package/out/test/customRegistry.test.js +0 -122
  453. package/out/test/data-plane-engine-wiring.test.js +0 -282
  454. package/out/test/data-plane.test.js +0 -624
  455. package/out/test/deploy-init.test.js +0 -860
  456. package/out/test/deps-auto-install.test.js +0 -81
  457. package/out/test/egress-broker.test.js +0 -172
  458. package/out/test/engine-integration.test.js +0 -297
  459. package/out/test/enginePaths.test.js +0 -195
  460. package/out/test/enginePublish.test.js +0 -82
  461. package/out/test/fleetDisplayUtils.test.js +0 -100
  462. package/out/test/gateway-client.test.js +0 -409
  463. package/out/test/gateway-install-source.test.js +0 -111
  464. package/out/test/gateway-lifecycle.test.js +0 -608
  465. package/out/test/gateway-outbound.test.js +0 -538
  466. package/out/test/gateway-reset-mappings.test.js +0 -221
  467. package/out/test/gateway-route-index.test.js +0 -235
  468. package/out/test/gateway-secrets-preflight.test.js +0 -127
  469. package/out/test/gateway-session-routing.test.js +0 -65
  470. package/out/test/gateway-session-store.test.js +0 -216
  471. package/out/test/github.test.js +0 -232
  472. package/out/test/governor-hardening.test.js +0 -222
  473. package/out/test/headless-sync.test.js +0 -301
  474. package/out/test/helpers/manifest-fixtures.js +0 -27
  475. package/out/test/idp-init.test.js +0 -151
  476. package/out/test/lease-signature.test.js +0 -357
  477. package/out/test/lease-trust-root.test.js +0 -273
  478. package/out/test/lease-validation.test.js +0 -224
  479. package/out/test/lease.test.js +0 -114
  480. package/out/test/localFleetAdapter.test.js +0 -91
  481. package/out/test/mcp-obo.test.js +0 -107
  482. package/out/test/mcp.test.js +0 -389
  483. package/out/test/model-routing.test.js +0 -133
  484. package/out/test/openclaw-channel-routing.test.js +0 -191
  485. package/out/test/pack-admission.test.js +0 -216
  486. package/out/test/pack-digest-parity.test.js +0 -140
  487. package/out/test/pack-reconcile.test.js +0 -183
  488. package/out/test/pack-signature-artifact.test.js +0 -103
  489. package/out/test/pack-signature.test.js +0 -176
  490. package/out/test/pack-trust-root.test.js +0 -202
  491. package/out/test/pathSafety.test.js +0 -63
  492. package/out/test/permissions.test.js +0 -175
  493. package/out/test/persistent-engine-worker.test.js +0 -220
  494. package/out/test/refreshPolicy.test.js +0 -60
  495. package/out/test/registry.test.js +0 -351
  496. package/out/test/remote-trust.test.js +0 -242
  497. package/out/test/runner-protocol.test.js +0 -249
  498. package/out/test/runtime.test.js +0 -349
  499. package/out/test/sandbox-driver.test.js +0 -553
  500. package/out/test/sandbox-hardening.test.js +0 -406
  501. package/out/test/sandbox-runner.test.js +0 -343
  502. package/out/test/sandbox-scope.test.js +0 -449
  503. package/out/test/scheduledFleetStorage.test.js +0 -72
  504. package/out/test/serve-cron-acceptance.test.js +0 -370
  505. package/out/test/serve-gateway-turn.test.js +0 -389
  506. package/out/test/serve-hardening.test.js +0 -591
  507. package/out/test/serveClient.test.js +0 -209
  508. package/out/test/sessionJsonlFleet.test.js +0 -78
  509. package/out/test/sessionShip.test.js +0 -618
  510. package/out/test/shared.test.js +0 -173
  511. package/out/test/skills-mcp.test.js +0 -299
  512. package/out/test/spotlightPublish.test.js +0 -327
  513. package/out/test/spotlightYaml.test.js +0 -58
  514. package/out/test/state-sync-peer.test.js +0 -156
  515. package/out/test/store-install-safe.test.js +0 -69
  516. package/out/test/store.test.js +0 -331
  517. package/out/test/stores.test.js +0 -504
  518. package/out/test/sync-switch.test.js +0 -251
  519. package/out/test/teamViewDiscovery.test.js +0 -90
  520. package/out/test/tls-bypass.test.js +0 -90
  521. package/out/test/toolPath.test.js +0 -120
  522. package/out/test/utils.test.js +0 -308
  523. package/out/test/viewsConfigMerge.test.js +0 -180
  524. package/out/test/warrant.test.js +0 -138
  525. package/out/test/windows-command-line.test.js +0 -75
  526. package/out/utils/agentEnvFile.js +0 -131
  527. package/out/utils/binary.js +0 -175
  528. package/out/utils/index.js +0 -37
  529. package/out/utils/network.js +0 -74
  530. package/out/utils/paths.js +0 -116
  531. package/out/utils/pid.js +0 -180
  532. package/out/utils/resolveNodeBinary.js +0 -168
  533. package/out/utils/windowsCommandLine.js +0 -29
  534. package/out/utils.js +0 -968
@@ -1,1249 +1,5 @@
1
- "use strict";
2
- /*---------------------------------------------------------------------------------------------
3
- * Copyright (c) AgentHippo.ai. All rights reserved.
4
- *--------------------------------------------------------------------------------------------*/
5
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- var desc = Object.getOwnPropertyDescriptor(m, k);
8
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
- desc = { enumerable: true, get: function() { return m[k]; } };
10
- }
11
- Object.defineProperty(o, k2, desc);
12
- }) : (function(o, m, k, k2) {
13
- if (k2 === undefined) k2 = k;
14
- o[k2] = m[k];
15
- }));
16
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17
- Object.defineProperty(o, "default", { enumerable: true, value: v });
18
- }) : function(o, v) {
19
- o["default"] = v;
20
- });
21
- var __importStar = (this && this.__importStar) || (function () {
22
- var ownKeys = function(o) {
23
- ownKeys = Object.getOwnPropertyNames || function (o) {
24
- var ar = [];
25
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
26
- return ar;
27
- };
28
- return ownKeys(o);
29
- };
30
- return function (mod) {
31
- if (mod && mod.__esModule) return mod;
32
- var result = {};
33
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
34
- __setModuleDefault(result, mod);
35
- return result;
36
- };
37
- })();
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.GatewayService = exports.GatewaySessionBindingError = void 0;
40
- /* eslint-disable local/code-no-unexternalized-strings */
41
- /**
42
- * Gateway Service - Manages connection to OpenClaw Gateway in VS Code
43
- *
44
- * Key concepts:
45
- * - Stable agent IDs: ide-{workspace} or ide-{workspace}-{pack}
46
- * - Session routing: disk-backed route index + per-session gateway-session.json
47
- * - Publish: user connects an existing IDE session to the gateway
48
- */
49
- const crypto_1 = require("crypto");
50
- const os = __importStar(require("os"));
51
- const path = __importStar(require("path"));
52
- const vscode = __importStar(require("vscode"));
53
- const scheduledFleetStorage_js_1 = require("../analytics/dashboard/scheduledFleetStorage.js");
54
- const branding_js_1 = require("../branding.js");
55
- const bridge_js_1 = require("./bridge.js");
56
- const gateway_scope_errors_js_1 = require("./gateway-scope-errors.js");
57
- const gatewayRouteIndex_js_1 = require("./gatewayRouteIndex.js");
58
- const gatewaySessionStore_js_1 = require("./gatewaySessionStore.js");
59
- const lifecycle_js_1 = require("./lifecycle.js");
60
- const openclaw_channel_routing_js_1 = require("./openclaw-channel-routing.js");
61
- const outboundHandles_js_1 = require("./outboundHandles.js");
62
- const outboundPaths_js_1 = require("./outboundPaths.js");
63
- const resetMappings_js_1 = require("./resetMappings.js");
64
- /** Thrown when a gateway-bound chat cannot be opened without creating a new session (B+E fail-closed). */
65
- class GatewaySessionBindingError extends Error {
66
- userMessage;
67
- constructor(sessionId, detail) {
68
- const userMessage = `Agent Anywhere cannot open chat session ${sessionId}. ` +
69
- `Use "Connect Chat to Gateway" on that chat to reconnect.`;
70
- super(detail ? `${userMessage} ${detail}` : userMessage);
71
- this.name = "GatewaySessionBindingError";
72
- this.userMessage = userMessage;
73
- }
74
- }
75
- exports.GatewaySessionBindingError = GatewaySessionBindingError;
76
- // ============================================================================
77
- // GatewayService
78
- // ============================================================================
79
- class GatewayService {
80
- extensionContext;
81
- bridge = null;
82
- outputChannel;
83
- config = {};
84
- disposables = [];
85
- healthCheckTimer = null;
86
- static HEALTH_CHECK_INTERVAL = 30000;
87
- static MAX_SESSIONS = 20;
88
- /** Runtime cache: AgentHippo sessionId -> active VS Code chat binding. */
89
- sessionCache = new Map();
90
- // Gateway emitter correlation (unchanged from before)
91
- static gatewayEmitters = new Map();
92
- static getGatewayEmitter(token) {
93
- const emitter = GatewayService.gatewayEmitters.get(token);
94
- if (emitter) {
95
- GatewayService.gatewayEmitters.delete(token);
96
- }
97
- return emitter;
98
- }
99
- constructor(extensionContext, outputChannel) {
100
- this.extensionContext = extensionContext;
101
- this.outputChannel = outputChannel;
102
- this.registerCommands();
103
- this.disposables.push(vscode.workspace.onDidChangeConfiguration((e) => {
104
- if (e.affectsConfiguration("agentide.gateway")) {
105
- this.loadConfig();
106
- }
107
- }));
108
- this.loadConfig();
109
- }
110
- // ============================================================================
111
- // Config
112
- // ============================================================================
113
- loadConfig() {
114
- const config = vscode.workspace.getConfiguration("agentide.gateway");
115
- this.config = {
116
- url: config.get("url"),
117
- token: config.get("token"),
118
- autoConnect: config.get("autoConnect", false),
119
- autoRegister: config.get("autoRegister", true),
120
- workspaceName: config.get("workspaceName"),
121
- agents: config.get("agents"),
122
- };
123
- if (this.config.autoConnect && this.config.url && !this.isConnected) {
124
- void this.connect({ silent: true });
125
- }
126
- }
127
- // ============================================================================
128
- // Stable Agent IDs
129
- // ============================================================================
130
- /**
131
- * Derive workspace name from VS Code workspace folder or setting.
132
- * E.g., /Users/me/dev/frontend -> "frontend"
133
- */
134
- resolveWorkspaceName() {
135
- const configured = this.config.workspaceName?.trim();
136
- if (configured) {
137
- return this.slugify(configured);
138
- }
139
- const folder = vscode.workspace.workspaceFolders?.[0];
140
- if (folder) {
141
- const folderName = folder.uri.path.split("/").pop() || "workspace";
142
- return this.slugify(folderName);
143
- }
144
- return "workspace";
145
- }
146
- /**
147
- * Build stable agent ID: ide-{workspace} or ide-{workspace}-{pack}
148
- */
149
- resolveAgentId(packName) {
150
- const ws = this.resolveWorkspaceName();
151
- if (!packName || packName === "default" || packName === "Default") {
152
- return `ide-${ws}`;
153
- }
154
- return `ide-${ws}-${this.slugify(packName)}`;
155
- }
156
- slugify(str) {
157
- return str
158
- .toLowerCase()
159
- .replace(/[^a-z0-9-]/g, "-")
160
- .replace(/-+/g, "-")
161
- .replace(/^-|-$/g, "")
162
- .slice(0, 32) || "unnamed";
163
- }
164
- // ============================================================================
165
- // Commands
166
- // ============================================================================
167
- registerCommands() {
168
- this.disposables.push(vscode.commands.registerCommand("agentide.gateway.connect", () => this.connect()), vscode.commands.registerCommand("agentide.gateway.disconnect", () => this.disconnect()), vscode.commands.registerCommand("agentide.gateway.toggle", () => {
169
- return this.isConnected ? this.disconnect() : this.connect();
170
- }), vscode.commands.registerCommand("agentide.gateway.status", () => this.showStatus()), vscode.commands.registerCommand("agentide.gateway.connectSession", () => this.publishCurrentSession()), vscode.commands.registerCommand("agentide.gateway.listSessions", () => this.showSessionMap()), vscode.commands.registerCommand("agentide.gateway.resetMappings", () => this.resetMappings()));
171
- }
172
- // ============================================================================
173
- // Reset mappings (forget learned inbound/outbound routing for an agent)
174
- // ============================================================================
175
- /**
176
- * Forget an agent's learned routing so new Slack/Telegram messages start fresh chats. Backs up
177
- * (never deletes) the route index, default chat, and per-chat outbound stores to `.bk` files.
178
- * Channel bindings and chat history are kept. Works offline — pure local file operations.
179
- */
180
- async resetMappings() {
181
- const workspaceRoot = this.resolveGatewayWorkspaceRoot();
182
- const agentId = await this.resolveResetMappingsAgentId();
183
- if (!agentId) {
184
- vscode.window.showWarningMessage("No agent found to reset. Open a chat or register an agent first.");
185
- return;
186
- }
187
- // Cheap pre-check so we don't pop a modal when there is nothing to forget.
188
- const index = await (0, gatewayRouteIndex_js_1.readGatewayRouteIndex)(workspaceRoot);
189
- const prefix = `${agentId}::`;
190
- const routeCount = Object.keys(index.byRoute).filter((k) => k.startsWith(prefix)).length;
191
- const hasDefault = Boolean(await (0, gatewayRouteIndex_js_1.getDefaultPublishedSessionId)(workspaceRoot, agentId));
192
- if (routeCount === 0 && !hasDefault) {
193
- vscode.window.showInformationMessage(`${agentId}: no mappings to reset.`);
194
- return;
195
- }
196
- const confirm = await vscode.window.showWarningMessage(`Reset mappings for "${agentId}"? New messages will start fresh chats. ` +
197
- `Your channels, chats, and history are kept; old mappings are saved as .bk files.`, { modal: true }, "Reset");
198
- if (confirm !== "Reset") {
199
- return;
200
- }
201
- try {
202
- const result = await (0, resetMappings_js_1.resetAgentMappings)(workspaceRoot, agentId);
203
- // Drop in-memory routes for this agent so the Sessions list reflects reality at once.
204
- for (const [id, entry] of this.sessionCache) {
205
- if (entry.agentId === agentId) {
206
- this.sessionCache.delete(id);
207
- }
208
- }
209
- const parts = [`${result.routes} mapping${result.routes === 1 ? "" : "s"}`];
210
- if (result.sessions > 0) {
211
- parts.push(`${result.sessions} chat${result.sessions === 1 ? "" : "s"}`);
212
- }
213
- if (result.hadDefault) {
214
- parts.push("default chat");
215
- }
216
- vscode.window.showInformationMessage(`Reset ${parts.join(", ")} for ${agentId}. Originals saved as .bk.`);
217
- }
218
- catch (err) {
219
- this.log(`Reset mappings failed: ${err}`);
220
- vscode.window.showErrorMessage(`Failed to reset mappings: ${err instanceof Error ? err.message : String(err)}`);
221
- }
222
- }
223
- /**
224
- * Resolve which agent "Reset mappings" should target: the current chat's agent when a chat is
225
- * focused, otherwise a pick across registered agents (single registered agent is auto-selected).
226
- */
227
- async resolveResetMappingsAgentId() {
228
- try {
229
- const chatState = await this.queryChatState();
230
- if (chatState?.sessionId) {
231
- return this.resolveAgentId(chatState.activePackId || "default");
232
- }
233
- }
234
- catch {
235
- // Fall through to the registered-agent picker.
236
- }
237
- const agents = this.bridge?.registeredAgents ?? [];
238
- if (agents.length === 1) {
239
- return agents[0];
240
- }
241
- if (agents.length === 0) {
242
- return undefined;
243
- }
244
- return vscode.window.showQuickPick(agents, {
245
- title: "Reset mappings for which agent?",
246
- placeHolder: "Select the agent whose learned routing to forget",
247
- });
248
- }
249
- // ============================================================================
250
- // Publish (Connect Existing Session to Gateway) - Phase 3
251
- // ============================================================================
252
- /**
253
- * Publish the current VS Code chat session to the gateway.
254
- * Shows a picker to choose who this session is for:
255
- * - A specific known peer (e.g., @x via telegram)
256
- * - Default fallback (web UI and unmatched inbound routes — not every channel/thread)
257
- */
258
- async publishCurrentSession(retryAttempt = 0) {
259
- if (!this.isConnected) {
260
- // Route through the lifecycle command so it owns the status-bar bookkeeping
261
- // (setBridgeConnected + setStatus("running")). connectBridge() delegates back to
262
- // this.connect() via _bridgeRef, so a direct call here would connect the bridge
263
- // but leave the Agent Anywhere status bar stuck on "Disconnected".
264
- await vscode.commands.executeCommand("agentide.anywhere.connect");
265
- }
266
- if (!this.bridge) {
267
- vscode.window.showErrorMessage("Not connected to Gateway");
268
- return;
269
- }
270
- try {
271
- const chatState = await this.queryChatState();
272
- if (!chatState?.sessionId || !chatState?.sessionResource) {
273
- vscode.window.showErrorMessage("No active chat session found.");
274
- return;
275
- }
276
- const packName = chatState.activePackId || "default";
277
- const agentId = this.resolveAgentId(packName);
278
- const sessionId = chatState.sessionId;
279
- const sessionResource = vscode.Uri.parse(chatState.sessionResource);
280
- const workspaceRoot = this.resolveGatewayWorkspaceRoot();
281
- await this.ensureAgentRegistered(agentId, packName);
282
- const peerItems = [
283
- {
284
- label: "$(globe) Default for new routes",
285
- description: "New Slack/Telegram threads use this chat; existing routes unchanged",
286
- routeKey: undefined,
287
- },
288
- ];
289
- const seenPeers = new Set();
290
- for (const entry of this.sessionCache.values()) {
291
- if (entry.agentId === agentId && entry.peerLabel && !seenPeers.has(entry.peerLabel)) {
292
- seenPeers.add(entry.peerLabel);
293
- peerItems.push({
294
- label: `$(person) ${entry.peerLabel}`,
295
- description: `Bind this chat to ${entry.peerLabel}`,
296
- routeKey: entry.gatewaySessionKey,
297
- });
298
- }
299
- }
300
- let selectedRouteKey;
301
- if (peerItems.length > 1) {
302
- const picked = await vscode.window.showQuickPick(peerItems, {
303
- title: "Connect Chat to Gateway",
304
- placeHolder: "Who should this chat session serve?",
305
- });
306
- if (!picked) {
307
- return;
308
- }
309
- selectedRouteKey = picked.routeKey;
310
- }
311
- let peerRoute;
312
- let seedGatewaySessionKey;
313
- let seedChannel;
314
- if (selectedRouteKey) {
315
- const dmMatch = selectedRouteKey.match(/:dm:(.+)$/i);
316
- const channelMatch = selectedRouteKey.match(/:(channel|thread|group|chat):([^:]+)$/i);
317
- peerRoute = dmMatch?.[1]
318
- ? `dm:${dmMatch[1]}`
319
- : channelMatch
320
- ? `${channelMatch[1].toLowerCase()}:${channelMatch[2]}`
321
- : selectedRouteKey;
322
- seedGatewaySessionKey = selectedRouteKey;
323
- const cached = [...this.sessionCache.values()].find((e) => e.gatewaySessionKey === selectedRouteKey);
324
- seedChannel = cached?.channel;
325
- }
326
- const sessionTitleTrim = chatState.sessionTitle?.trim();
327
- const bindLabel = !peerRoute && sessionTitleTrim && sessionTitleTrim.length > 0
328
- ? (0, gatewaySessionStore_js_1.normalizeInboundBindLabel)(sessionTitleTrim)
329
- : undefined;
330
- const publishedMode = peerRoute ? "peer" : "default";
331
- const existingRecord = await (0, gatewaySessionStore_js_1.readGatewaySessionRecord)(workspaceRoot, sessionId);
332
- // Guard (a) — double-connect: this chat is already bound to a route/default.
333
- // Confirm, then clear its prior mappings so we reconnect cleanly (per spec: "clear our
334
- // connected session and reconnect this session anew").
335
- if (existingRecord?.published) {
336
- const prior = this.describePublishedTarget(existingRecord.published);
337
- const choice = await vscode.window.showWarningMessage(`This chat is already connected to Agent Anywhere (${prior}). Clear that connection and reconnect this chat anew?`, "Clear & Reconnect");
338
- if (choice !== "Clear & Reconnect") {
339
- return;
340
- }
341
- const removedRoutes = await (0, gatewayRouteIndex_js_1.removeRouteSessionMappingsForSession)(workspaceRoot, agentId, sessionId);
342
- await (0, gatewayRouteIndex_js_1.clearDefaultPublishedSessionId)(workspaceRoot, agentId, sessionId);
343
- this.log(`Cleared prior gateway mapping for chat ${sessionId} (routes: ${removedRoutes.join(", ") || "none"})`);
344
- }
345
- // Guard (b) — clobber: the route/default we're about to claim is already served by a
346
- // different chat. Confirm reassignment before stealing it, and remember the previous
347
- // owner(s) so we can scrub their now-stale binding after the new mapping is written.
348
- let reassignedDefaultOwner;
349
- const reassignedRouteOwners = new Map();
350
- if (publishedMode === "default") {
351
- const currentDefault = await (0, gatewayRouteIndex_js_1.getDefaultPublishedSessionId)(workspaceRoot, agentId);
352
- if (currentDefault && currentDefault !== sessionId) {
353
- if (!(await this.confirmRouteReassignment(workspaceRoot, "Default for new inbound routes", currentDefault))) {
354
- return;
355
- }
356
- reassignedDefaultOwner = currentDefault;
357
- }
358
- }
359
- else {
360
- const claimKeys = [...new Set([selectedRouteKey, peerRoute].filter((k) => !!k))];
361
- for (const key of claimKeys) {
362
- const owner = await (0, gatewayRouteIndex_js_1.getRouteSessionMapping)(workspaceRoot, agentId, key);
363
- if (owner && owner !== sessionId) {
364
- if (!(await this.confirmRouteReassignment(workspaceRoot, `Route "${key}"`, owner))) {
365
- return;
366
- }
367
- const keys = reassignedRouteOwners.get(owner) ?? new Set();
368
- keys.add(key);
369
- reassignedRouteOwners.set(owner, keys);
370
- }
371
- }
372
- }
373
- const gatewaySessionKeys = (0, gatewaySessionStore_js_1.mergeGatewaySessionKeyList)(existingRecord?.gatewaySessionKeys ?? [], seedGatewaySessionKey);
374
- await (0, gatewaySessionStore_js_1.writeGatewaySessionRecord)(workspaceRoot, {
375
- version: 1,
376
- sessionId,
377
- agentId,
378
- packName,
379
- vscodeSessionResource: sessionResource.toString(),
380
- chatMode: chatState.mode,
381
- published: {
382
- mode: publishedMode,
383
- peerRoute,
384
- bindLabel: bindLabel && bindLabel.length > 0 ? bindLabel : undefined,
385
- at: new Date().toISOString(),
386
- },
387
- gatewaySessionKeys,
388
- updatedAt: new Date().toISOString(),
389
- });
390
- if ((0, gatewaySessionStore_js_1.shouldUpdateAgentDefaultOnGatewayPublish)(publishedMode)) {
391
- await (0, gatewayRouteIndex_js_1.setDefaultPublishedSessionId)(workspaceRoot, agentId, sessionId);
392
- }
393
- if (selectedRouteKey) {
394
- await (0, gatewayRouteIndex_js_1.setRouteSessionMapping)(workspaceRoot, agentId, selectedRouteKey, sessionId);
395
- }
396
- if (peerRoute) {
397
- await (0, gatewayRouteIndex_js_1.setRouteSessionMapping)(workspaceRoot, agentId, peerRoute, sessionId);
398
- }
399
- // New mappings are in place — scrub the reassigned binding from its previous owner so a
400
- // stale leading sessionKey can't misroute that chat's outbound and its `published` no
401
- // longer claims a route it lost. Delete the record only if fully orphaned (see § clobber).
402
- if (reassignedDefaultOwner) {
403
- const scrubbed = await (0, gatewaySessionStore_js_1.clearGatewaySessionPublishedDefault)(workspaceRoot, reassignedDefaultOwner);
404
- await this.deleteOrphanedGatewayRecord(workspaceRoot, agentId, reassignedDefaultOwner, scrubbed);
405
- }
406
- for (const [owner, keys] of reassignedRouteOwners) {
407
- const scrubbed = await (0, gatewaySessionStore_js_1.detachGatewaySessionRoutes)(workspaceRoot, owner, [...keys]);
408
- await this.deleteOrphanedGatewayRecord(workspaceRoot, agentId, owner, scrubbed);
409
- }
410
- const entry = {
411
- gatewaySessionKey: seedGatewaySessionKey ?? `__published__:${agentId}`,
412
- agentId,
413
- packName,
414
- vscodeSessionResource: sessionResource,
415
- chatSessionId: sessionId,
416
- chatMode: chatState.mode,
417
- lastActiveAt: Date.now(),
418
- channel: seedChannel,
419
- };
420
- this.sessionCache.set(sessionId, entry);
421
- const boundChannels = await this.bindPublishedGatewayChannels(agentId, seedChannel);
422
- if (seedGatewaySessionKey) {
423
- this.seedPublishedGatewayOutbound(packName, agentId, sessionId, seedGatewaySessionKey, seedChannel);
424
- }
425
- this.updateStatusBar("connected");
426
- const displayName = bindLabel ?? (sessionTitleTrim && sessionTitleTrim.length > 0 ? sessionTitleTrim : undefined);
427
- const chatDesc = displayName ? `Chat "${displayName}"` : "New chat";
428
- const target = peerRoute
429
- ? `route "${peerRoute}"`
430
- : "default for new inbound routes";
431
- this.log(`Published ${chatDesc} (${sessionId}) as ${agentId} for ${target}`);
432
- const bindHint = bindLabel && bindLabel.length > 0
433
- ? ` Use hippoclaw agent --session-id "${bindLabel}" to reach this chat.`
434
- : "";
435
- const channelHint = boundChannels.length > 0
436
- ? ` Reachable from: ${boundChannels.join(", ")}.`
437
- : "";
438
- vscode.window.showInformationMessage(`${chatDesc} connected to Gateway for ${target}.${channelHint}${bindHint}`);
439
- }
440
- catch (err) {
441
- const message = err instanceof Error ? err.message : String(err);
442
- // The gateway may require a reconnect if the extension connected with stale auth/scopes.
443
- const shouldRetry = retryAttempt < 1 &&
444
- ((0, gateway_scope_errors_js_1.isGatewayScopeAuthError)(message) || message.toLowerCase().includes("connection closed"));
445
- if (shouldRetry) {
446
- this.log(`publishCurrentSession failed (${message}); reconnecting and retrying...`);
447
- try {
448
- await this.disconnect();
449
- await this.connect();
450
- return await this.publishCurrentSession(retryAttempt + 1);
451
- }
452
- catch {
453
- // Fall through to error message
454
- }
455
- }
456
- vscode.window.showErrorMessage(`Failed to publish session: ${message}`);
457
- }
458
- }
459
- // ============================================================================
460
- // Session Resolution - Phase 2
461
- // ============================================================================
462
- /**
463
- * Build a human-readable label for a peer from their info.
464
- */
465
- /** Human-readable description of what a chat's existing publish points at (for the reconnect prompt). */
466
- describePublishedTarget(published) {
467
- if (published.mode === "peer" && published.peerRoute) {
468
- return `route "${published.peerRoute}"`;
469
- }
470
- if (published.bindLabel) {
471
- return `CLI label "${published.bindLabel}"`;
472
- }
473
- return "default for new inbound routes";
474
- }
475
- /**
476
- * Confirm reassigning a route/default that another chat currently owns. Returns true to proceed.
477
- * Dismissing the toast (no choice) cancels — we never silently clobber an existing binding.
478
- */
479
- async confirmRouteReassignment(workspaceRoot, targetDesc, ownerSessionId) {
480
- const ownerRecord = await (0, gatewaySessionStore_js_1.readGatewaySessionRecord)(workspaceRoot, ownerSessionId);
481
- const ownerLabel = ownerRecord?.published?.bindLabel?.trim() ||
482
- ownerRecord?.published?.peerRoute?.trim() ||
483
- ownerSessionId;
484
- const choice = await vscode.window.showWarningMessage(`${targetDesc} is currently served by another chat ("${ownerLabel}"). Reassign it to this chat? The other chat will stop receiving those messages.`, "Reassign");
485
- return choice === "Reassign";
486
- }
487
- /** Remove a scrubbed owner's binding record once it holds no routes/published and is not the agent default. */
488
- async deleteOrphanedGatewayRecord(workspaceRoot, agentId, ownerSessionId, scrubbed) {
489
- if (!scrubbed || !(0, gatewaySessionStore_js_1.isGatewaySessionRecordOrphaned)(scrubbed)) {
490
- return;
491
- }
492
- const currentDefault = await (0, gatewayRouteIndex_js_1.getDefaultPublishedSessionId)(workspaceRoot, agentId);
493
- if (currentDefault === ownerSessionId) {
494
- return; // Still the agent default (published cleared but pointer remains) — keep the record.
495
- }
496
- await (0, gatewaySessionStore_js_1.deleteGatewaySessionRecord)(workspaceRoot, ownerSessionId);
497
- this.log(`Removed orphaned gateway record for chat ${ownerSessionId}`);
498
- }
499
- buildPeerLabel(peerInfo) {
500
- if (!peerInfo) {
501
- return undefined;
502
- }
503
- const name = peerInfo.senderUsername || peerInfo.senderName || peerInfo.senderId;
504
- if (!name) {
505
- return undefined;
506
- }
507
- const channel = peerInfo.channel ? ` via ${peerInfo.channel}` : "";
508
- return `${name}${channel}`;
509
- }
510
- async resolveOrCreateSession(agentId, sessionKey, packName, peerInfo, gatewayWireSessionId) {
511
- const workspaceRoot = this.resolveGatewayWorkspaceRoot();
512
- const routeKey = sessionKey;
513
- const resolution = await (0, gatewayRouteIndex_js_1.resolveInboundSessionId)({
514
- workspaceRoot,
515
- agentId,
516
- routeKey,
517
- gatewaySessionKey: sessionKey,
518
- gatewayWireSessionId,
519
- });
520
- // The default published session is a one-shot catch for the first unmatched inbound. Claim it
521
- // atomically so a burst of messages from *different* channels (e.g. a Slack backlog flushed on
522
- // reconnect) can't all collapse onto it — only the first winner keeps the default chat and
523
- // persists its route mapping; the rest fall through to their own per-channel chat below.
524
- let sessionId = resolution.sessionId;
525
- if (resolution.source === "defaultPublished") {
526
- sessionId = await (0, gatewayRouteIndex_js_1.tryClaimDefaultPublishedSessionId)(workspaceRoot, agentId);
527
- }
528
- if (resolution.source === "new" || !sessionId) {
529
- const peerLabel = this.buildPeerLabel(peerInfo);
530
- this.log(`Creating new VS Code session for peer: ${peerLabel ?? sessionKey ?? "unknown"}, agent=${agentId}`);
531
- return this.createNewGatewaySession(agentId, sessionKey, packName, peerInfo, resolution.persistRouteKey);
532
- }
533
- let entry = this.sessionCache.get(sessionId);
534
- if (!entry) {
535
- entry = await this.hydrateSessionEntryFromDisk(workspaceRoot, sessionId, agentId, packName);
536
- }
537
- if (!entry) {
538
- this.log(`Session record missing for ${sessionId}; creating new chat and remapping route`);
539
- const created = await this.createNewGatewaySession(agentId, sessionKey, packName, peerInfo, resolution.persistRouteKey);
540
- if (resolution.persistRouteKey) {
541
- await (0, gatewayRouteIndex_js_1.setRouteSessionMapping)(workspaceRoot, agentId, resolution.persistRouteKey, created.chatSessionId);
542
- }
543
- return created;
544
- }
545
- entry.lastActiveAt = Date.now();
546
- entry.gatewaySessionKey = sessionKey ?? entry.gatewaySessionKey;
547
- const peerLabel = this.buildPeerLabel(peerInfo);
548
- if (peerLabel && !entry.peerLabel) {
549
- entry.peerLabel = peerLabel;
550
- }
551
- if (peerInfo?.channel) {
552
- entry.channel = peerInfo.channel;
553
- }
554
- await this.ensureChatSessionOpen(entry, workspaceRoot);
555
- if (resolution.persistRouteKey) {
556
- await (0, gatewayRouteIndex_js_1.setRouteSessionMapping)(workspaceRoot, agentId, resolution.persistRouteKey, sessionId);
557
- await (0, gatewaySessionStore_js_1.appendGatewaySessionKey)(workspaceRoot, sessionId, resolution.persistRouteKey);
558
- }
559
- this.sessionCache.set(sessionId, entry);
560
- this.evictStaleSessionCache();
561
- return entry;
562
- }
563
- async hydrateSessionEntryFromDisk(workspaceRoot, sessionId, agentId, packName) {
564
- const record = await (0, gatewaySessionStore_js_1.readGatewaySessionRecord)(workspaceRoot, sessionId);
565
- if (!record) {
566
- return undefined;
567
- }
568
- return {
569
- gatewaySessionKey: record.gatewaySessionKeys[0] ?? `__published__:${agentId}`,
570
- agentId: record.agentId,
571
- packName: record.packName || packName,
572
- vscodeSessionResource: vscode.Uri.parse(record.vscodeSessionResource),
573
- chatSessionId: record.sessionId,
574
- chatMode: record.chatMode,
575
- lastActiveAt: Date.now(),
576
- };
577
- }
578
- /**
579
- * Open the gateway-bound VS Code chat (B: workbench restore only; E: fail closed, no newChat).
580
- * Session folder id remains {@link GatewaySessionEntry.chatSessionId}.
581
- */
582
- async ensureChatSessionOpen(entry, workspaceRoot) {
583
- const sessionId = entry.chatSessionId;
584
- const candidates = [];
585
- const stored = entry.vscodeSessionResource.toString();
586
- if (stored) {
587
- candidates.push(stored);
588
- }
589
- const canonical = (0, scheduledFleetStorage_js_1.buildChatSessionResourceFromSessionId)(sessionId);
590
- if (canonical && !candidates.includes(canonical)) {
591
- candidates.push(canonical);
592
- }
593
- const failures = [];
594
- for (const sessionResource of candidates) {
595
- const result = await vscode.commands.executeCommand("agentide.openChatSession", { sessionId, sessionResource });
596
- if (result?.success) {
597
- const openedResource = result.sessionResource;
598
- if (openedResource && openedResource !== stored) {
599
- entry.vscodeSessionResource = vscode.Uri.parse(openedResource);
600
- await (0, gatewaySessionStore_js_1.updateGatewaySessionResource)(workspaceRoot, sessionId, openedResource, entry.chatMode);
601
- }
602
- return;
603
- }
604
- const reason = result && !result.success ? result.reason : "command_unavailable";
605
- failures.push(`${sessionResource}: ${reason}`);
606
- }
607
- this.log(`Gateway could not open chat session ${sessionId} (${failures.join("; ")})`);
608
- throw new GatewaySessionBindingError(sessionId);
609
- }
610
- async createNewGatewaySession(agentId, sessionKey, packName, peerInfo, persistRouteKey) {
611
- const workspaceRoot = this.resolveGatewayWorkspaceRoot();
612
- await vscode.commands.executeCommand("workbench.action.chat.newChat");
613
- await new Promise((resolve) => setTimeout(resolve, 500));
614
- const chatState = await this.queryChatState();
615
- if (!chatState?.sessionId || !chatState?.sessionResource) {
616
- throw new Error("Failed to create new chat session");
617
- }
618
- const sessionId = chatState.sessionId;
619
- const sessionResource = vscode.Uri.parse(chatState.sessionResource);
620
- const gatewaySessionKey = sessionKey ?? `__created__:${agentId}:${sessionId}`;
621
- await (0, gatewaySessionStore_js_1.writeGatewaySessionRecord)(workspaceRoot, {
622
- version: 1,
623
- sessionId,
624
- agentId,
625
- packName,
626
- vscodeSessionResource: sessionResource.toString(),
627
- chatMode: chatState.mode,
628
- gatewaySessionKeys: gatewaySessionKey ? [gatewaySessionKey] : [],
629
- updatedAt: new Date().toISOString(),
630
- });
631
- if (persistRouteKey) {
632
- await (0, gatewayRouteIndex_js_1.setRouteSessionMapping)(workspaceRoot, agentId, persistRouteKey, sessionId);
633
- }
634
- const entry = {
635
- gatewaySessionKey,
636
- agentId,
637
- packName,
638
- vscodeSessionResource: sessionResource,
639
- chatSessionId: sessionId,
640
- chatMode: chatState.mode,
641
- peerLabel: this.buildPeerLabel(peerInfo),
642
- channel: peerInfo?.channel,
643
- lastActiveAt: Date.now(),
644
- };
645
- this.sessionCache.set(sessionId, entry);
646
- this.evictStaleSessionCache();
647
- return entry;
648
- }
649
- evictStaleSessionCache() {
650
- while (this.sessionCache.size > GatewayService.MAX_SESSIONS) {
651
- let oldestId;
652
- let oldestTime = Infinity;
653
- for (const [id, entry] of this.sessionCache) {
654
- if (entry.lastActiveAt < oldestTime) {
655
- oldestTime = entry.lastActiveAt;
656
- oldestId = id;
657
- }
658
- }
659
- if (oldestId) {
660
- this.log(`Evicting stale session cache: ${oldestId}`);
661
- this.sessionCache.delete(oldestId);
662
- }
663
- else {
664
- break;
665
- }
666
- }
667
- }
668
- // ============================================================================
669
- // Chat UI Handler (session-aware)
670
- // ============================================================================
671
- resolveGatewayWorkspaceRoot() {
672
- const folder = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
673
- if (folder) {
674
- return folder;
675
- }
676
- const dirName = vscode.workspace.getConfiguration("agentide").get("fallbackDirectory") || ".agent-hippo";
677
- return path.join(os.homedir(), dirName);
678
- }
679
- async bindPublishedGatewayChannels(agentId, preferredChannel) {
680
- if (!this.bridge?.isConnected) {
681
- return [];
682
- }
683
- const request = this.bridge.request.bind(this.bridge);
684
- const { rows, statusPayload } = await (0, openclaw_channel_routing_js_1.fetchMeetAgentChannelContext)(request);
685
- const selectedChannels = (0, openclaw_channel_routing_js_1.resolvePublishedGatewayChannelIds)(rows, preferredChannel);
686
- if (selectedChannels.length === 0) {
687
- return [];
688
- }
689
- const patched = await (0, openclaw_channel_routing_js_1.applyAgentChannelBindingsViaConfigPatch)(request, {
690
- agentId,
691
- selectedChannelIds: selectedChannels,
692
- statusPayload,
693
- });
694
- this.log(patched
695
- ? `Bound ${agentId} to gateway channels: ${selectedChannels.join(", ")}`
696
- : `${agentId} gateway channel bindings already current: ${selectedChannels.join(", ")}`);
697
- // A real binding patch can bounce the affected channel; wait for the channels that were live
698
- // before the patch to come back before we report success, otherwise an inbound message in the
699
- // restart window is dropped or routed to the gateway's embedded agent (the "publish didn't
700
- // take the first time, worked on the second click" symptom). Only wait on channels that were
701
- // actually live pre-patch — a configured-but-offline channel (e.g. stalled Telegram polling)
702
- // must not block publish. No patch ⇒ nothing restarted ⇒ skip the wait.
703
- if (patched) {
704
- const liveBefore = new Set(rows.filter((r) => r.connected).map((r) => r.id.trim().toLowerCase()));
705
- const awaitable = selectedChannels.filter((id) => liveBefore.has(id.trim().toLowerCase()));
706
- if (awaitable.length > 0) {
707
- const settle = await (0, openclaw_channel_routing_js_1.waitForChannelsLive)(request, awaitable);
708
- this.log(settle.ready
709
- ? `Gateway channels live after bind: ${settle.live.join(", ")}`
710
- : `Gateway channels not confirmed live after bind (timed out after ${settle.polls} poll(s)); pending: ${settle.pending.join(", ")}`);
711
- }
712
- }
713
- return selectedChannels;
714
- }
715
- persistIdeGatewayOutbound(agentId, gatewayAgentId, sessionEntry, runContext) {
716
- if (!runContext) {
717
- return;
718
- }
719
- const workspaceRoot = this.resolveGatewayWorkspaceRoot();
720
- const chatSessionId = sessionEntry.chatSessionId ||
721
- (0, scheduledFleetStorage_js_1.parseSessionIdFromChatResource)(sessionEntry.vscodeSessionResource.toString());
722
- if (!chatSessionId) {
723
- return;
724
- }
725
- const storePath = (0, outboundPaths_js_1.getGatewayOutboundFilePath)(workspaceRoot, chatSessionId);
726
- void (0, outboundHandles_js_1.upsertGatewayOutboundHandle)(storePath, agentId, runContext.params, runContext.runId, {
727
- gatewayAgentId,
728
- })
729
- .then((handle) => {
730
- if (handle) {
731
- this.log(`Gateway outbound routes: ${storePath}`);
732
- }
733
- })
734
- .catch((err) => {
735
- this.log(`Failed to persist outbound handle: ${err instanceof Error ? err.message : String(err)}`);
736
- });
737
- }
738
- seedPublishedGatewayOutbound(agentId, gatewayAgentId, chatSessionId, gatewaySessionKey, channel) {
739
- const sourceSessionDirId = (0, outboundPaths_js_1.resolveGatewaySessionDirId)({ gatewaySessionKey });
740
- if (!sourceSessionDirId) {
741
- return;
742
- }
743
- const workspaceRoot = this.resolveGatewayWorkspaceRoot();
744
- const sourceStorePath = (0, outboundPaths_js_1.getGatewayOutboundFilePath)(workspaceRoot, sourceSessionDirId);
745
- const targetStorePath = (0, outboundPaths_js_1.getGatewayOutboundFilePath)(workspaceRoot, chatSessionId);
746
- void (0, outboundHandles_js_1.mergeGatewayOutboundHandles)(sourceStorePath, targetStorePath, agentId)
747
- .then(async (merged) => {
748
- if (merged > 0) {
749
- this.log(`Gateway outbound routes: ${targetStorePath} (seeded from ${sourceStorePath})`);
750
- return;
751
- }
752
- const handle = await (0, outboundHandles_js_1.upsertGatewayOutboundHandle)(targetStorePath, agentId, {
753
- message: "",
754
- channel,
755
- sessionKey: gatewaySessionKey,
756
- idempotencyKey: `publish:${Date.now()}`,
757
- }, undefined, {
758
- gatewayAgentId,
759
- });
760
- if (handle) {
761
- this.log(`Gateway outbound routes: ${targetStorePath}`);
762
- }
763
- })
764
- .catch((err) => {
765
- this.log(`Failed to seed outbound handle: ${err instanceof Error ? err.message : String(err)}`);
766
- });
767
- }
768
- /**
769
- * Create a session-aware Chat UI handler.
770
- * Uses sessionKey + peerInfo to resolve the correct VS Code session.
771
- */
772
- createSessionAwareChatUIHandler(agentId, packName) {
773
- return async (message, sessionKey, peerInfo, emitter, runContext) => {
774
- // Unguessable: this token is a bearer capability for the run's output stream, and
775
- // `getGatewayEmitter` is a destructive first-reader-wins read. A predictable value
776
- // lets any chat message beginning with `[gw:...]` steal or drop another run's stream.
777
- const gatewayRequestToken = `gw-${(0, crypto_1.randomUUID)()}`;
778
- GatewayService.gatewayEmitters.set(gatewayRequestToken, emitter);
779
- const markedMessage = `[gw:${gatewayRequestToken}]${message}`;
780
- try {
781
- const sessionEntry = await this.resolveOrCreateSession(agentId, sessionKey, packName, peerInfo, runContext?.params.sessionId);
782
- const sessionResource = sessionEntry.vscodeSessionResource;
783
- this.persistIdeGatewayOutbound(packName, agentId, sessionEntry, runContext);
784
- const peerLabel = this.buildPeerLabel(peerInfo);
785
- const sessionInfo = `session=${sessionResource.toString()}, peer=${peerLabel ?? "unknown"}, sessionKey=${sessionKey ?? "none"}`;
786
- this.log(`Routing gateway message to Chat UI (${sessionInfo}): ${message.slice(0, 50)}...`);
787
- const commandParams = {
788
- query: markedMessage,
789
- blockOnResponse: true,
790
- sessionResource: sessionResource.toString(),
791
- };
792
- commandParams.mode = sessionEntry.chatMode?.trim() || "agent";
793
- const result = await vscode.commands.executeCommand("workbench.action.chat.open", commandParams);
794
- if (result?.errorDetails?.message) {
795
- return `[Error: ${result.errorDetails.message}]`;
796
- }
797
- return result?.responseText || "[Chat response completed]";
798
- }
799
- catch (err) {
800
- if (err instanceof GatewaySessionBindingError) {
801
- this.log(`Gateway session binding lost: ${err.message}`);
802
- void vscode.window.showWarningMessage(err.userMessage);
803
- await emitter.error(err.userMessage);
804
- return `[Error: ${err.userMessage}]`;
805
- }
806
- const errorMsg = err instanceof Error ? err.message : String(err);
807
- this.log(`Chat UI handler error: ${errorMsg}`);
808
- await emitter.error(errorMsg);
809
- throw err;
810
- }
811
- finally {
812
- GatewayService.gatewayEmitters.delete(gatewayRequestToken);
813
- }
814
- };
815
- }
816
- // ============================================================================
817
- // Agent Registration
818
- // ============================================================================
819
- /**
820
- * Ensure an agent is registered with the gateway.
821
- * Idempotent: re-registering with the same ID is a no-op.
822
- */
823
- async ensureAgentRegistered(agentId, packName, scopeRetryDepth = 0) {
824
- if (!this.bridge) {
825
- return;
826
- }
827
- // Check if already registered
828
- if (this.bridge.registeredAgents.includes(agentId)) {
829
- return;
830
- }
831
- const chatUIHandler = this.createSessionAwareChatUIHandler(agentId, packName);
832
- const agent = {
833
- id: agentId,
834
- agentId: packName,
835
- name: `${packName} (${this.resolveWorkspaceName()})`,
836
- workspace: this.resolveGatewayWorkspaceRoot(),
837
- useChatUI: true,
838
- chatUIHandler,
839
- };
840
- try {
841
- await this.bridge.registerAgent(agent);
842
- }
843
- catch (err) {
844
- const message = err instanceof Error ? err.message : String(err);
845
- if (scopeRetryDepth >= 1 || !(0, gateway_scope_errors_js_1.isGatewayScopeAuthError)(message)) {
846
- throw err;
847
- }
848
- // Scopes are fixed at WebSocket handshake time. A connection opened before the
849
- // extension sent operator scopes will keep failing agents.register until we reconnect.
850
- // Use bridge.reconnect() (not service.disconnect) so the session map stays intact.
851
- this.log("Gateway denied RPC (missing operator scope); reconnecting with a fresh handshake...");
852
- await this.bridge.reconnect();
853
- await this.registerConfiguredAgents();
854
- await this.ensureAgentRegistered(agentId, packName, scopeRetryDepth + 1);
855
- return;
856
- }
857
- this.log(`Registered agent: ${agentId}`);
858
- }
859
- /**
860
- * Register agents from settings on connect.
861
- */
862
- async registerConfiguredAgents() {
863
- if (!this.bridge) {
864
- return;
865
- }
866
- // Auto-register active pack
867
- if (this.config.autoRegister) {
868
- try {
869
- const chatState = await this.queryChatState();
870
- const packName = chatState?.activePackId || "default";
871
- const agentId = this.resolveAgentId(packName);
872
- await this.ensureAgentRegistered(agentId, packName);
873
- }
874
- catch (err) {
875
- this.log(`Failed to auto-register active pack: ${err}`);
876
- }
877
- }
878
- // Register explicitly configured packs
879
- if (this.config.agents?.length) {
880
- for (const agentConfig of this.config.agents) {
881
- try {
882
- const agentId = this.resolveAgentId(agentConfig.pack);
883
- await this.ensureAgentRegistered(agentId, agentConfig.pack);
884
- }
885
- catch (err) {
886
- this.log(`Failed to register pack ${agentConfig.pack}: ${err}`);
887
- }
888
- }
889
- }
890
- }
891
- // ============================================================================
892
- // Session New (from Gateway) - Phase 4
893
- // ============================================================================
894
- async handleSessionNewRequest(request) {
895
- const { requestId, params } = request;
896
- this.log(`Creating new session from Gateway (requestedBy=${params.requestedBy}, sessionKey=${params.sessionKey})`);
897
- try {
898
- await vscode.commands.executeCommand("workbench.action.chat.newChat");
899
- await new Promise((resolve) => setTimeout(resolve, 500));
900
- const chatState = await this.queryChatState();
901
- if (!chatState?.sessionId || !chatState?.sessionResource) {
902
- this.bridge?.respondSessionNew(requestId, {
903
- success: false,
904
- error: "Failed to create chat session",
905
- });
906
- return;
907
- }
908
- const sessionResource = vscode.Uri.parse(chatState.sessionResource);
909
- const packName = chatState.activePackId || "default";
910
- const agentId = this.resolveAgentId(packName);
911
- // Ensure agent is registered
912
- await this.ensureAgentRegistered(agentId, packName);
913
- const workspaceRoot = this.resolveGatewayWorkspaceRoot();
914
- const sessionId = chatState.sessionId;
915
- const newTitleTrim = chatState.sessionTitle?.trim();
916
- const bindLabel = newTitleTrim && newTitleTrim.length > 0 ? (0, gatewaySessionStore_js_1.normalizeInboundBindLabel)(newTitleTrim) : undefined;
917
- const existingRecord = await (0, gatewaySessionStore_js_1.readGatewaySessionRecord)(workspaceRoot, sessionId);
918
- await (0, gatewaySessionStore_js_1.writeGatewaySessionRecord)(workspaceRoot, {
919
- version: 1,
920
- sessionId,
921
- agentId,
922
- packName,
923
- vscodeSessionResource: sessionResource.toString(),
924
- chatMode: chatState.mode,
925
- published: bindLabel
926
- ? {
927
- mode: "default",
928
- bindLabel,
929
- at: new Date().toISOString(),
930
- }
931
- : undefined,
932
- gatewaySessionKeys: (0, gatewaySessionStore_js_1.mergeGatewaySessionKeyList)(existingRecord?.gatewaySessionKeys ?? [], params.sessionKey),
933
- updatedAt: new Date().toISOString(),
934
- });
935
- await (0, gatewayRouteIndex_js_1.setDefaultPublishedSessionId)(workspaceRoot, agentId, sessionId);
936
- if (params.sessionKey) {
937
- await (0, gatewayRouteIndex_js_1.setRouteSessionMapping)(workspaceRoot, agentId, params.sessionKey, sessionId);
938
- }
939
- for (const [id, entry] of this.sessionCache) {
940
- if (entry.agentId === agentId) {
941
- this.sessionCache.delete(id);
942
- }
943
- }
944
- this.sessionCache.set(sessionId, {
945
- gatewaySessionKey: params.sessionKey ?? `__published__:${agentId}`,
946
- agentId,
947
- packName,
948
- vscodeSessionResource: sessionResource,
949
- chatSessionId: sessionId,
950
- chatMode: chatState.mode,
951
- lastActiveAt: Date.now(),
952
- });
953
- if (params.sessionKey) {
954
- this.log(`Route index updated: ${params.sessionKey} -> ${sessionId}`);
955
- }
956
- if (params.initialMessage) {
957
- await vscode.commands.executeCommand("workbench.action.chat.open", {
958
- mode: "agent",
959
- query: params.initialMessage,
960
- sessionResource: chatState.sessionResource,
961
- });
962
- }
963
- vscode.window.showInformationMessage(`New chat session created from ${params.requestedBy ?? "Gateway"}`);
964
- this.bridge?.respondSessionNew(requestId, {
965
- success: true,
966
- agentId,
967
- });
968
- }
969
- catch (err) {
970
- const errorMsg = err instanceof Error ? err.message : String(err);
971
- this.log(`Failed to create new session: ${errorMsg}`);
972
- this.bridge?.respondSessionNew(requestId, {
973
- success: false,
974
- error: errorMsg,
975
- });
976
- }
977
- }
978
- // ============================================================================
979
- // Connection Lifecycle
980
- // ============================================================================
981
- async connect(opts) {
982
- const silent = opts?.silent ?? false;
983
- // Read merged settings here — onDidChangeConfiguration can lag behind await
984
- // `getConfiguration().update()` from connectBridge / reset token, which would
985
- // otherwise leave `this.config` stale and connect without a token.
986
- const gwLive = vscode.workspace.getConfiguration("agentide.gateway");
987
- const url = (gwLive.get("url") ?? "").trim() || (this.config.url ?? "").trim();
988
- const tokenRaw = (gwLive.get("token") ?? "").trim() || (this.config.token ?? "").trim();
989
- if (!url) {
990
- if (!silent) {
991
- vscode.window.showWarningMessage(`Gateway URL not configured. Set ${(0, branding_js_1.toSettingsDisplayKey)("agentide.gateway.url")} in settings.`);
992
- }
993
- return;
994
- }
995
- if (this.isConnected) {
996
- if (!silent) {
997
- vscode.window.showInformationMessage("Already connected to Gateway");
998
- }
999
- return;
1000
- }
1001
- try {
1002
- this.updateStatusBar("connecting");
1003
- this.log("Connecting to Gateway...");
1004
- const options = {
1005
- gatewayUrl: url,
1006
- token: tokenRaw || undefined,
1007
- version: this.extensionContext.extension.packageJSON.version,
1008
- outputChannel: this.outputChannel,
1009
- };
1010
- this.bridge = new bridge_js_1.GatewayBridge(options);
1011
- this.bridge.on("connected", () => {
1012
- this.updateStatusBar("connected");
1013
- this.log("Connected to Gateway");
1014
- void this.registerConfiguredAgents();
1015
- });
1016
- this.bridge.on("disconnected", () => {
1017
- const sessionCount = this.sessionCache.size;
1018
- this.sessionCache.clear();
1019
- this.updateStatusBar("disconnected");
1020
- this.log(`Disconnected from Gateway. Cleared ${sessionCount} cached session(s).`);
1021
- });
1022
- this.bridge.on("error", (err) => {
1023
- this.log(`Gateway error: ${err.message}`);
1024
- });
1025
- this.bridge.on("reconnecting", (attempt) => {
1026
- this.updateStatusBar("reconnecting");
1027
- this.log(`Reconnecting... (attempt ${attempt})`);
1028
- });
1029
- this.bridge.on("agent.message", (data) => {
1030
- const rk = data.routeKey ?? data.sessionKey ?? "";
1031
- this.log(`Message for ${data.agentId}${rk ? ` (${rk})` : ""}: ${data.message.slice(0, 100)}...`);
1032
- });
1033
- this.bridge.on("agent.registered", (_agentId, result) => {
1034
- if (result?.needsBinding && this.onNeedsBinding) {
1035
- this.onNeedsBinding(_agentId);
1036
- }
1037
- });
1038
- this.bridge.on("session.new.request", (request) => {
1039
- void this.handleSessionNewRequest(request);
1040
- });
1041
- this.bridge.on("agent.cancel", (params) => {
1042
- this.log(`Cancelling chat generation (agent.cancel: sessionKey=${params?.sessionKey})`);
1043
- const sessionKey = params?.sessionKey;
1044
- const agentId = params?.agentId;
1045
- if (sessionKey && agentId) {
1046
- void this.openSessionForGatewayCancel(agentId, sessionKey);
1047
- return;
1048
- }
1049
- void vscode.commands.executeCommand("workbench.action.chat.cancel");
1050
- });
1051
- await this.bridge.connect();
1052
- this.startHealthCheck();
1053
- }
1054
- catch (err) {
1055
- this.updateStatusBar("error");
1056
- const message = err instanceof Error ? err.message : String(err);
1057
- this.log(`Failed to connect: ${message}`);
1058
- if (!silent) {
1059
- vscode.window.showErrorMessage(`Failed to connect to Gateway: ${message}`);
1060
- }
1061
- }
1062
- }
1063
- async disconnect() {
1064
- this.stopHealthCheck();
1065
- if (!this.bridge) {
1066
- return;
1067
- }
1068
- try {
1069
- await this.bridge.disconnect();
1070
- }
1071
- finally {
1072
- this.sessionCache.clear();
1073
- this.bridge = null;
1074
- this.updateStatusBar("disconnected");
1075
- }
1076
- }
1077
- async openSessionForGatewayCancel(agentId, sessionKey) {
1078
- const routeKey = (0, bridge_js_1.buildIdeSessionRouteKey)(sessionKey, undefined) ?? sessionKey;
1079
- const cached = [...this.sessionCache.values()].find((e) => e.gatewaySessionKey === sessionKey);
1080
- if (cached) {
1081
- await vscode.commands.executeCommand("workbench.action.chat.open", {
1082
- sessionResource: cached.vscodeSessionResource.toString(),
1083
- });
1084
- await vscode.commands.executeCommand("workbench.action.chat.cancel");
1085
- return;
1086
- }
1087
- const workspaceRoot = this.resolveGatewayWorkspaceRoot();
1088
- const sessionId = await (0, gatewayRouteIndex_js_1.resolveInboundSessionId)({
1089
- workspaceRoot,
1090
- agentId,
1091
- routeKey,
1092
- gatewaySessionKey: sessionKey,
1093
- }).then((r) => r.sessionId);
1094
- if (sessionId) {
1095
- const entry = await this.hydrateSessionEntryFromDisk(workspaceRoot, sessionId, agentId, "default");
1096
- if (entry) {
1097
- await vscode.commands.executeCommand("workbench.action.chat.open", {
1098
- sessionResource: entry.vscodeSessionResource.toString(),
1099
- });
1100
- await vscode.commands.executeCommand("workbench.action.chat.cancel");
1101
- return;
1102
- }
1103
- }
1104
- await vscode.commands.executeCommand("workbench.action.chat.cancel");
1105
- }
1106
- // ============================================================================
1107
- // Health Check
1108
- // ============================================================================
1109
- startHealthCheck() {
1110
- this.stopHealthCheck();
1111
- this.healthCheckTimer = setInterval(() => {
1112
- void this.performHealthCheck();
1113
- }, GatewayService.HEALTH_CHECK_INTERVAL);
1114
- }
1115
- stopHealthCheck() {
1116
- if (this.healthCheckTimer) {
1117
- clearInterval(this.healthCheckTimer);
1118
- this.healthCheckTimer = null;
1119
- }
1120
- }
1121
- async performHealthCheck() {
1122
- if (!this.bridge?.isConnected) {
1123
- return;
1124
- }
1125
- try {
1126
- await this.bridge.request("agents.list", {});
1127
- }
1128
- catch {
1129
- this.log("Health check failed, reconnecting...");
1130
- try {
1131
- await this.bridge.reconnect();
1132
- }
1133
- catch (err) {
1134
- this.log(`Reconnect failed: ${err}`);
1135
- }
1136
- }
1137
- }
1138
- // ============================================================================
1139
- // Status UI
1140
- // ============================================================================
1141
- showStatus() {
1142
- const connected = this.isConnected;
1143
- const agents = this.bridge?.registeredAgents ?? [];
1144
- const sessionCount = this.sessionCache.size;
1145
- let message = connected ? "Connected to Gateway" : "Disconnected from Gateway";
1146
- if (connected && agents.length > 0) {
1147
- message += `\nAgents: ${agents.join(", ")}`;
1148
- }
1149
- if (connected) {
1150
- message += `\nSessions: ${sessionCount} active (disk-backed routing)`;
1151
- }
1152
- if (connected && this.bridge?.connId) {
1153
- message += `\nConnection: ${this.bridge.connId}`;
1154
- }
1155
- vscode.window.showInformationMessage(message);
1156
- }
1157
- async showSessionMap() {
1158
- if (!this.isConnected) {
1159
- vscode.window.showInformationMessage("Not connected to Gateway");
1160
- return;
1161
- }
1162
- const items = [];
1163
- const workspaceRoot = this.resolveGatewayWorkspaceRoot();
1164
- const seenDefaults = new Set();
1165
- for (const agentId of this.bridge?.registeredAgents ?? []) {
1166
- const defaultId = await (0, gatewayRouteIndex_js_1.getDefaultPublishedSessionId)(workspaceRoot, agentId);
1167
- if (defaultId && !seenDefaults.has(defaultId)) {
1168
- seenDefaults.add(defaultId);
1169
- const record = await (0, gatewaySessionStore_js_1.readGatewaySessionRecord)(workspaceRoot, defaultId);
1170
- items.push({
1171
- label: `$(pin) ${agentId}`,
1172
- description: "default published session",
1173
- detail: record?.published?.bindLabel
1174
- ? `CLI: ${record.published.bindLabel} | ${defaultId}`
1175
- : defaultId,
1176
- });
1177
- }
1178
- }
1179
- for (const entry of this.sessionCache.values()) {
1180
- const peerDisplay = entry.peerLabel ?? entry.gatewaySessionKey;
1181
- items.push({
1182
- label: `$(broadcast) ${peerDisplay}`,
1183
- description: `${entry.agentId}${entry.channel ? ` (${entry.channel})` : ""}`,
1184
- detail: `Pack: ${entry.packName} | ${entry.chatSessionId} | Active ${this.formatRelativeTime(entry.lastActiveAt)}`,
1185
- });
1186
- }
1187
- if (items.length === 0) {
1188
- vscode.window.showInformationMessage("No sessions mapped. Use 'Connect Chat to Gateway' to publish the current session.");
1189
- return;
1190
- }
1191
- await vscode.window.showQuickPick(items, {
1192
- title: `Gateway Sessions (${items.length})`,
1193
- placeHolder: "Session mappings (published + active routes)",
1194
- });
1195
- }
1196
- // ============================================================================
1197
- // Helpers
1198
- // ============================================================================
1199
- async queryChatState() {
1200
- return vscode.commands.executeCommand("agentide.getChatState");
1201
- }
1202
- formatRelativeTime(timestamp) {
1203
- const seconds = Math.floor((Date.now() - timestamp) / 1000);
1204
- if (seconds < 60) {
1205
- return "just now";
1206
- }
1207
- const minutes = Math.floor(seconds / 60);
1208
- if (minutes < 60) {
1209
- return `${minutes}m ago`;
1210
- }
1211
- const hours = Math.floor(minutes / 60);
1212
- if (hours < 24) {
1213
- return `${hours}h ago`;
1214
- }
1215
- return `${Math.floor(hours / 24)}d ago`;
1216
- }
1217
- /**
1218
- * Status bar is now owned by GatewayLifecycleManager.
1219
- * This is a no-op kept for internal call-site compatibility.
1220
- */
1221
- updateStatusBar(_status) {
1222
- // No-op: lifecycle manager owns the single status bar icon
1223
- }
1224
- log(message) {
1225
- this.outputChannel.appendLine(`[${lifecycle_js_1.AGENT_ANYWHERE_LABEL}] ${message}`);
1226
- }
1227
- /** Callback invoked when a registered agent has no channel bindings. */
1228
- onNeedsBinding;
1229
- get isConnected() {
1230
- return this.bridge?.isConnected ?? false;
1231
- }
1232
- /**
1233
- * Send a gateway method request via the bridge's WebSocket client.
1234
- * Exposed via GatewayBridgeRef so the lifecycle manager can call gateway methods.
1235
- */
1236
- async request(method, params) {
1237
- if (!this.bridge?.isConnected) {
1238
- throw new Error("Not connected to gateway");
1239
- }
1240
- return this.bridge.request(method, params);
1241
- }
1242
- dispose() {
1243
- void this.disconnect();
1244
- for (const d of this.disposables) {
1245
- d.dispose();
1246
- }
1247
- }
1248
- }
1249
- exports.GatewayService = GatewayService;
1
+ /*! Copyright (c) 2026 AgentHippo.ai. All rights reserved. Proprietary; see LICENSE. */
2
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(g,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(g,n,s)}):(function(g,e,t,n){n===void 0&&(n=t),g[n]=e[t]})),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?(function(g,e){Object.defineProperty(g,"default",{enumerable:!0,value:e})}):function(g,e){g.default=e}),__importStar=this&&this.__importStar||(function(){var g=function(e){return g=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},g(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=g(e),s=0;s<n.length;s++)n[s]!=="default"&&__createBinding(t,e,n[s]);return __setModuleDefault(t,e),t}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.GatewayService=exports.GatewaySessionBindingError=void 0;const crypto_1=require("crypto"),os=__importStar(require("os")),path=__importStar(require("path")),vscode=__importStar(require("vscode")),scheduledFleetStorage_js_1=require("../analytics/dashboard/scheduledFleetStorage.js"),branding_js_1=require("../branding.js"),bridge_js_1=require("./bridge.js"),gateway_scope_errors_js_1=require("./gateway-scope-errors.js"),gatewayRouteIndex_js_1=require("./gatewayRouteIndex.js"),gatewaySessionStore_js_1=require("./gatewaySessionStore.js"),lifecycle_js_1=require("./lifecycle.js"),openclaw_channel_routing_js_1=require("./openclaw-channel-routing.js"),outboundHandles_js_1=require("./outboundHandles.js"),outboundPaths_js_1=require("./outboundPaths.js"),resetMappings_js_1=require("./resetMappings.js");class GatewaySessionBindingError extends Error{userMessage;constructor(e,t){const n=`Agent Anywhere cannot open chat session ${e}. Use "Connect Chat to Gateway" on that chat to reconnect.`;super(t?`${n} ${t}`:n),this.name="GatewaySessionBindingError",this.userMessage=n}}exports.GatewaySessionBindingError=GatewaySessionBindingError;class GatewayService{extensionContext;bridge=null;outputChannel;config={};disposables=[];healthCheckTimer=null;static HEALTH_CHECK_INTERVAL=3e4;static MAX_SESSIONS=20;sessionCache=new Map;static gatewayEmitters=new Map;static getGatewayEmitter(e){const t=GatewayService.gatewayEmitters.get(e);return t&&GatewayService.gatewayEmitters.delete(e),t}constructor(e,t){this.extensionContext=e,this.outputChannel=t,this.registerCommands(),this.disposables.push(vscode.workspace.onDidChangeConfiguration(n=>{n.affectsConfiguration("agentide.gateway")&&this.loadConfig()})),this.loadConfig()}loadConfig(){const e=vscode.workspace.getConfiguration("agentide.gateway");this.config={url:e.get("url"),token:e.get("token"),autoConnect:e.get("autoConnect",!1),autoRegister:e.get("autoRegister",!0),workspaceName:e.get("workspaceName"),agents:e.get("agents")},this.config.autoConnect&&this.config.url&&!this.isConnected&&this.connect({silent:!0})}resolveWorkspaceName(){const e=this.config.workspaceName?.trim();if(e)return this.slugify(e);const t=vscode.workspace.workspaceFolders?.[0];if(t){const n=t.uri.path.split("/").pop()||"workspace";return this.slugify(n)}return"workspace"}resolveAgentId(e){const t=this.resolveWorkspaceName();return!e||e==="default"||e==="Default"?`ide-${t}`:`ide-${t}-${this.slugify(e)}`}slugify(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,32)||"unnamed"}registerCommands(){this.disposables.push(vscode.commands.registerCommand("agentide.gateway.connect",()=>this.connect()),vscode.commands.registerCommand("agentide.gateway.disconnect",()=>this.disconnect()),vscode.commands.registerCommand("agentide.gateway.toggle",()=>this.isConnected?this.disconnect():this.connect()),vscode.commands.registerCommand("agentide.gateway.status",()=>this.showStatus()),vscode.commands.registerCommand("agentide.gateway.connectSession",()=>this.publishCurrentSession()),vscode.commands.registerCommand("agentide.gateway.listSessions",()=>this.showSessionMap()),vscode.commands.registerCommand("agentide.gateway.resetMappings",()=>this.resetMappings()))}async resetMappings(){const e=this.resolveGatewayWorkspaceRoot(),t=await this.resolveResetMappingsAgentId();if(!t){vscode.window.showWarningMessage("No agent found to reset. Open a chat or register an agent first.");return}const n=await(0,gatewayRouteIndex_js_1.readGatewayRouteIndex)(e),s=`${t}::`,a=Object.keys(n.byRoute).filter(r=>r.startsWith(s)).length,c=!!await(0,gatewayRouteIndex_js_1.getDefaultPublishedSessionId)(e,t);if(a===0&&!c){vscode.window.showInformationMessage(`${t}: no mappings to reset.`);return}if(await vscode.window.showWarningMessage(`Reset mappings for "${t}"? New messages will start fresh chats. Your channels, chats, and history are kept; old mappings are saved as .bk files.`,{modal:!0},"Reset")==="Reset")try{const r=await(0,resetMappings_js_1.resetAgentMappings)(e,t);for(const[i,h]of this.sessionCache)h.agentId===t&&this.sessionCache.delete(i);const d=[`${r.routes} mapping${r.routes===1?"":"s"}`];r.sessions>0&&d.push(`${r.sessions} chat${r.sessions===1?"":"s"}`),r.hadDefault&&d.push("default chat"),vscode.window.showInformationMessage(`Reset ${d.join(", ")} for ${t}. Originals saved as .bk.`)}catch(r){this.log(`Reset mappings failed: ${r}`),vscode.window.showErrorMessage(`Failed to reset mappings: ${r instanceof Error?r.message:String(r)}`)}}async resolveResetMappingsAgentId(){try{const t=await this.queryChatState();if(t?.sessionId)return this.resolveAgentId(t.activePackId||"default")}catch{}const e=this.bridge?.registeredAgents??[];if(e.length===1)return e[0];if(e.length!==0)return vscode.window.showQuickPick(e,{title:"Reset mappings for which agent?",placeHolder:"Select the agent whose learned routing to forget"})}async publishCurrentSession(e=0){if(this.isConnected||await vscode.commands.executeCommand("agentide.anywhere.connect"),!this.bridge){vscode.window.showErrorMessage("Not connected to Gateway");return}try{const t=await this.queryChatState();if(!t?.sessionId||!t?.sessionResource){vscode.window.showErrorMessage("No active chat session found.");return}const n=t.activePackId||"default",s=this.resolveAgentId(n),a=t.sessionId,c=vscode.Uri.parse(t.sessionResource),o=this.resolveGatewayWorkspaceRoot();await this.ensureAgentRegistered(s,n);const r=[{label:"$(globe) Default for new routes",description:"New Slack/Telegram threads use this chat; existing routes unchanged",routeKey:void 0}],d=new Set;for(const u of this.sessionCache.values())u.agentId===s&&u.peerLabel&&!d.has(u.peerLabel)&&(d.add(u.peerLabel),r.push({label:`$(person) ${u.peerLabel}`,description:`Bind this chat to ${u.peerLabel}`,routeKey:u.gatewaySessionKey}));let i;if(r.length>1){const u=await vscode.window.showQuickPick(r,{title:"Connect Chat to Gateway",placeHolder:"Who should this chat session serve?"});if(!u)return;i=u.routeKey}let h,l,y;if(i){const u=i.match(/:dm:(.+)$/i),w=i.match(/:(channel|thread|group|chat):([^:]+)$/i);h=u?.[1]?`dm:${u[1]}`:w?`${w[1].toLowerCase()}:${w[2]}`:i,l=i,y=[...this.sessionCache.values()].find(S=>S.gatewaySessionKey===i)?.channel}const f=t.sessionTitle?.trim(),p=!h&&f&&f.length>0?(0,gatewaySessionStore_js_1.normalizeInboundBindLabel)(f):void 0,C=h?"peer":"default",R=await(0,gatewaySessionStore_js_1.readGatewaySessionRecord)(o,a);if(R?.published){const u=this.describePublishedTarget(R.published);if(await vscode.window.showWarningMessage(`This chat is already connected to Agent Anywhere (${u}). Clear that connection and reconnect this chat anew?`,"Clear & Reconnect")!=="Clear & Reconnect")return;const m=await(0,gatewayRouteIndex_js_1.removeRouteSessionMappingsForSession)(o,s,a);await(0,gatewayRouteIndex_js_1.clearDefaultPublishedSessionId)(o,s,a),this.log(`Cleared prior gateway mapping for chat ${a} (routes: ${m.join(", ")||"none"})`)}let b;const $=new Map;if(C==="default"){const u=await(0,gatewayRouteIndex_js_1.getDefaultPublishedSessionId)(o,s);if(u&&u!==a){if(!await this.confirmRouteReassignment(o,"Default for new inbound routes",u))return;b=u}}else{const u=[...new Set([i,h].filter(w=>!!w))];for(const w of u){const m=await(0,gatewayRouteIndex_js_1.getRouteSessionMapping)(o,s,w);if(m&&m!==a){if(!await this.confirmRouteReassignment(o,`Route "${w}"`,m))return;const S=$.get(m)??new Set;S.add(w),$.set(m,S)}}}const M=(0,gatewaySessionStore_js_1.mergeGatewaySessionKeyList)(R?.gatewaySessionKeys??[],l);if(await(0,gatewaySessionStore_js_1.writeGatewaySessionRecord)(o,{version:1,sessionId:a,agentId:s,packName:n,vscodeSessionResource:c.toString(),chatMode:t.mode,published:{mode:C,peerRoute:h,bindLabel:p&&p.length>0?p:void 0,at:new Date().toISOString()},gatewaySessionKeys:M,updatedAt:new Date().toISOString()}),(0,gatewaySessionStore_js_1.shouldUpdateAgentDefaultOnGatewayPublish)(C)&&await(0,gatewayRouteIndex_js_1.setDefaultPublishedSessionId)(o,s,a),i&&await(0,gatewayRouteIndex_js_1.setRouteSessionMapping)(o,s,i,a),h&&await(0,gatewayRouteIndex_js_1.setRouteSessionMapping)(o,s,h,a),b){const u=await(0,gatewaySessionStore_js_1.clearGatewaySessionPublishedDefault)(o,b);await this.deleteOrphanedGatewayRecord(o,s,b,u)}for(const[u,w]of $){const m=await(0,gatewaySessionStore_js_1.detachGatewaySessionRoutes)(o,u,[...w]);await this.deleteOrphanedGatewayRecord(o,s,u,m)}const _={gatewaySessionKey:l??`__published__:${s}`,agentId:s,packName:n,vscodeSessionResource:c,chatSessionId:a,chatMode:t.mode,lastActiveAt:Date.now(),channel:y};this.sessionCache.set(a,_);const v=await this.bindPublishedGatewayChannels(s,y);l&&this.seedPublishedGatewayOutbound(n,s,a,l,y),this.updateStatusBar("connected");const k=p??(f&&f.length>0?f:void 0),G=k?`Chat "${k}"`:"New chat",I=h?`route "${h}"`:"default for new inbound routes";this.log(`Published ${G} (${a}) as ${s} for ${I}`);const A=p&&p.length>0?` Use hippoclaw agent --session-id "${p}" to reach this chat.`:"",P=v.length>0?` Reachable from: ${v.join(", ")}.`:"";vscode.window.showInformationMessage(`${G} connected to Gateway for ${I}.${P}${A}`)}catch(t){const n=t instanceof Error?t.message:String(t);if(e<1&&((0,gateway_scope_errors_js_1.isGatewayScopeAuthError)(n)||n.toLowerCase().includes("connection closed"))){this.log(`publishCurrentSession failed (${n}); reconnecting and retrying...`);try{return await this.disconnect(),await this.connect(),await this.publishCurrentSession(e+1)}catch{}}vscode.window.showErrorMessage(`Failed to publish session: ${n}`)}}describePublishedTarget(e){return e.mode==="peer"&&e.peerRoute?`route "${e.peerRoute}"`:e.bindLabel?`CLI label "${e.bindLabel}"`:"default for new inbound routes"}async confirmRouteReassignment(e,t,n){const s=await(0,gatewaySessionStore_js_1.readGatewaySessionRecord)(e,n),a=s?.published?.bindLabel?.trim()||s?.published?.peerRoute?.trim()||n;return await vscode.window.showWarningMessage(`${t} is currently served by another chat ("${a}"). Reassign it to this chat? The other chat will stop receiving those messages.`,"Reassign")==="Reassign"}async deleteOrphanedGatewayRecord(e,t,n,s){!s||!(0,gatewaySessionStore_js_1.isGatewaySessionRecordOrphaned)(s)||await(0,gatewayRouteIndex_js_1.getDefaultPublishedSessionId)(e,t)===n||(await(0,gatewaySessionStore_js_1.deleteGatewaySessionRecord)(e,n),this.log(`Removed orphaned gateway record for chat ${n}`))}buildPeerLabel(e){if(!e)return;const t=e.senderUsername||e.senderName||e.senderId;if(!t)return;const n=e.channel?` via ${e.channel}`:"";return`${t}${n}`}async resolveOrCreateSession(e,t,n,s,a){const c=this.resolveGatewayWorkspaceRoot(),o=t,r=await(0,gatewayRouteIndex_js_1.resolveInboundSessionId)({workspaceRoot:c,agentId:e,routeKey:o,gatewaySessionKey:t,gatewayWireSessionId:a});let d=r.sessionId;if(r.source==="defaultPublished"&&(d=await(0,gatewayRouteIndex_js_1.tryClaimDefaultPublishedSessionId)(c,e)),r.source==="new"||!d){const l=this.buildPeerLabel(s);return this.log(`Creating new VS Code session for peer: ${l??t??"unknown"}, agent=${e}`),this.createNewGatewaySession(e,t,n,s,r.persistRouteKey)}let i=this.sessionCache.get(d);if(i||(i=await this.hydrateSessionEntryFromDisk(c,d,e,n)),!i){this.log(`Session record missing for ${d}; creating new chat and remapping route`);const l=await this.createNewGatewaySession(e,t,n,s,r.persistRouteKey);return r.persistRouteKey&&await(0,gatewayRouteIndex_js_1.setRouteSessionMapping)(c,e,r.persistRouteKey,l.chatSessionId),l}i.lastActiveAt=Date.now(),i.gatewaySessionKey=t??i.gatewaySessionKey;const h=this.buildPeerLabel(s);return h&&!i.peerLabel&&(i.peerLabel=h),s?.channel&&(i.channel=s.channel),await this.ensureChatSessionOpen(i,c),r.persistRouteKey&&(await(0,gatewayRouteIndex_js_1.setRouteSessionMapping)(c,e,r.persistRouteKey,d),await(0,gatewaySessionStore_js_1.appendGatewaySessionKey)(c,d,r.persistRouteKey)),this.sessionCache.set(d,i),this.evictStaleSessionCache(),i}async hydrateSessionEntryFromDisk(e,t,n,s){const a=await(0,gatewaySessionStore_js_1.readGatewaySessionRecord)(e,t);if(a)return{gatewaySessionKey:a.gatewaySessionKeys[0]??`__published__:${n}`,agentId:a.agentId,packName:a.packName||s,vscodeSessionResource:vscode.Uri.parse(a.vscodeSessionResource),chatSessionId:a.sessionId,chatMode:a.chatMode,lastActiveAt:Date.now()}}async ensureChatSessionOpen(e,t){const n=e.chatSessionId,s=[],a=e.vscodeSessionResource.toString();a&&s.push(a);const c=(0,scheduledFleetStorage_js_1.buildChatSessionResourceFromSessionId)(n);c&&!s.includes(c)&&s.push(c);const o=[];for(const r of s){const d=await vscode.commands.executeCommand("agentide.openChatSession",{sessionId:n,sessionResource:r});if(d?.success){const h=d.sessionResource;h&&h!==a&&(e.vscodeSessionResource=vscode.Uri.parse(h),await(0,gatewaySessionStore_js_1.updateGatewaySessionResource)(t,n,h,e.chatMode));return}const i=d&&!d.success?d.reason:"command_unavailable";o.push(`${r}: ${i}`)}throw this.log(`Gateway could not open chat session ${n} (${o.join("; ")})`),new GatewaySessionBindingError(n)}async createNewGatewaySession(e,t,n,s,a){const c=this.resolveGatewayWorkspaceRoot();await vscode.commands.executeCommand("workbench.action.chat.newChat"),await new Promise(l=>setTimeout(l,500));const o=await this.queryChatState();if(!o?.sessionId||!o?.sessionResource)throw new Error("Failed to create new chat session");const r=o.sessionId,d=vscode.Uri.parse(o.sessionResource),i=t??`__created__:${e}:${r}`;await(0,gatewaySessionStore_js_1.writeGatewaySessionRecord)(c,{version:1,sessionId:r,agentId:e,packName:n,vscodeSessionResource:d.toString(),chatMode:o.mode,gatewaySessionKeys:i?[i]:[],updatedAt:new Date().toISOString()}),a&&await(0,gatewayRouteIndex_js_1.setRouteSessionMapping)(c,e,a,r);const h={gatewaySessionKey:i,agentId:e,packName:n,vscodeSessionResource:d,chatSessionId:r,chatMode:o.mode,peerLabel:this.buildPeerLabel(s),channel:s?.channel,lastActiveAt:Date.now()};return this.sessionCache.set(r,h),this.evictStaleSessionCache(),h}evictStaleSessionCache(){for(;this.sessionCache.size>GatewayService.MAX_SESSIONS;){let e,t=1/0;for(const[n,s]of this.sessionCache)s.lastActiveAt<t&&(t=s.lastActiveAt,e=n);if(e)this.log(`Evicting stale session cache: ${e}`),this.sessionCache.delete(e);else break}}resolveGatewayWorkspaceRoot(){const e=vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;if(e)return e;const t=vscode.workspace.getConfiguration("agentide").get("fallbackDirectory")||".agent-hippo";return path.join(os.homedir(),t)}async bindPublishedGatewayChannels(e,t){if(!this.bridge?.isConnected)return[];const n=this.bridge.request.bind(this.bridge),{rows:s,statusPayload:a}=await(0,openclaw_channel_routing_js_1.fetchMeetAgentChannelContext)(n),c=(0,openclaw_channel_routing_js_1.resolvePublishedGatewayChannelIds)(s,t);if(c.length===0)return[];const o=await(0,openclaw_channel_routing_js_1.applyAgentChannelBindingsViaConfigPatch)(n,{agentId:e,selectedChannelIds:c,statusPayload:a});if(this.log(o?`Bound ${e} to gateway channels: ${c.join(", ")}`:`${e} gateway channel bindings already current: ${c.join(", ")}`),o){const r=new Set(s.filter(i=>i.connected).map(i=>i.id.trim().toLowerCase())),d=c.filter(i=>r.has(i.trim().toLowerCase()));if(d.length>0){const i=await(0,openclaw_channel_routing_js_1.waitForChannelsLive)(n,d);this.log(i.ready?`Gateway channels live after bind: ${i.live.join(", ")}`:`Gateway channels not confirmed live after bind (timed out after ${i.polls} poll(s)); pending: ${i.pending.join(", ")}`)}}return c}persistIdeGatewayOutbound(e,t,n,s){if(!s)return;const a=this.resolveGatewayWorkspaceRoot(),c=n.chatSessionId||(0,scheduledFleetStorage_js_1.parseSessionIdFromChatResource)(n.vscodeSessionResource.toString());if(!c)return;const o=(0,outboundPaths_js_1.getGatewayOutboundFilePath)(a,c);(0,outboundHandles_js_1.upsertGatewayOutboundHandle)(o,e,s.params,s.runId,{gatewayAgentId:t}).then(r=>{r&&this.log(`Gateway outbound routes: ${o}`)}).catch(r=>{this.log(`Failed to persist outbound handle: ${r instanceof Error?r.message:String(r)}`)})}seedPublishedGatewayOutbound(e,t,n,s,a){const c=(0,outboundPaths_js_1.resolveGatewaySessionDirId)({gatewaySessionKey:s});if(!c)return;const o=this.resolveGatewayWorkspaceRoot(),r=(0,outboundPaths_js_1.getGatewayOutboundFilePath)(o,c),d=(0,outboundPaths_js_1.getGatewayOutboundFilePath)(o,n);(0,outboundHandles_js_1.mergeGatewayOutboundHandles)(r,d,e).then(async i=>{if(i>0){this.log(`Gateway outbound routes: ${d} (seeded from ${r})`);return}await(0,outboundHandles_js_1.upsertGatewayOutboundHandle)(d,e,{message:"",channel:a,sessionKey:s,idempotencyKey:`publish:${Date.now()}`},void 0,{gatewayAgentId:t})&&this.log(`Gateway outbound routes: ${d}`)}).catch(i=>{this.log(`Failed to seed outbound handle: ${i instanceof Error?i.message:String(i)}`)})}createSessionAwareChatUIHandler(e,t){return async(n,s,a,c,o)=>{const r=`gw-${(0,crypto_1.randomUUID)()}`;GatewayService.gatewayEmitters.set(r,c);const d=`[gw:${r}]${n}`;try{const i=await this.resolveOrCreateSession(e,s,t,a,o?.params.sessionId),h=i.vscodeSessionResource;this.persistIdeGatewayOutbound(t,e,i,o);const l=this.buildPeerLabel(a),y=`session=${h.toString()}, peer=${l??"unknown"}, sessionKey=${s??"none"}`;this.log(`Routing gateway message to Chat UI (${y}): ${n.slice(0,50)}...`);const f={query:d,blockOnResponse:!0,sessionResource:h.toString()};f.mode=i.chatMode?.trim()||"agent";const p=await vscode.commands.executeCommand("workbench.action.chat.open",f);return p?.errorDetails?.message?`[Error: ${p.errorDetails.message}]`:p?.responseText||"[Chat response completed]"}catch(i){if(i instanceof GatewaySessionBindingError)return this.log(`Gateway session binding lost: ${i.message}`),vscode.window.showWarningMessage(i.userMessage),await c.error(i.userMessage),`[Error: ${i.userMessage}]`;const h=i instanceof Error?i.message:String(i);throw this.log(`Chat UI handler error: ${h}`),await c.error(h),i}finally{GatewayService.gatewayEmitters.delete(r)}}}async ensureAgentRegistered(e,t,n=0){if(!this.bridge||this.bridge.registeredAgents.includes(e))return;const s=this.createSessionAwareChatUIHandler(e,t),a={id:e,agentId:t,name:`${t} (${this.resolveWorkspaceName()})`,workspace:this.resolveGatewayWorkspaceRoot(),useChatUI:!0,chatUIHandler:s};try{await this.bridge.registerAgent(a)}catch(c){const o=c instanceof Error?c.message:String(c);if(n>=1||!(0,gateway_scope_errors_js_1.isGatewayScopeAuthError)(o))throw c;this.log("Gateway denied RPC (missing operator scope); reconnecting with a fresh handshake..."),await this.bridge.reconnect(),await this.registerConfiguredAgents(),await this.ensureAgentRegistered(e,t,n+1);return}this.log(`Registered agent: ${e}`)}async registerConfiguredAgents(){if(this.bridge){if(this.config.autoRegister)try{const t=(await this.queryChatState())?.activePackId||"default",n=this.resolveAgentId(t);await this.ensureAgentRegistered(n,t)}catch(e){this.log(`Failed to auto-register active pack: ${e}`)}if(this.config.agents?.length)for(const e of this.config.agents)try{const t=this.resolveAgentId(e.pack);await this.ensureAgentRegistered(t,e.pack)}catch(t){this.log(`Failed to register pack ${e.pack}: ${t}`)}}}async handleSessionNewRequest(e){const{requestId:t,params:n}=e;this.log(`Creating new session from Gateway (requestedBy=${n.requestedBy}, sessionKey=${n.sessionKey})`);try{await vscode.commands.executeCommand("workbench.action.chat.newChat"),await new Promise(y=>setTimeout(y,500));const s=await this.queryChatState();if(!s?.sessionId||!s?.sessionResource){this.bridge?.respondSessionNew(t,{success:!1,error:"Failed to create chat session"});return}const a=vscode.Uri.parse(s.sessionResource),c=s.activePackId||"default",o=this.resolveAgentId(c);await this.ensureAgentRegistered(o,c);const r=this.resolveGatewayWorkspaceRoot(),d=s.sessionId,i=s.sessionTitle?.trim(),h=i&&i.length>0?(0,gatewaySessionStore_js_1.normalizeInboundBindLabel)(i):void 0,l=await(0,gatewaySessionStore_js_1.readGatewaySessionRecord)(r,d);await(0,gatewaySessionStore_js_1.writeGatewaySessionRecord)(r,{version:1,sessionId:d,agentId:o,packName:c,vscodeSessionResource:a.toString(),chatMode:s.mode,published:h?{mode:"default",bindLabel:h,at:new Date().toISOString()}:void 0,gatewaySessionKeys:(0,gatewaySessionStore_js_1.mergeGatewaySessionKeyList)(l?.gatewaySessionKeys??[],n.sessionKey),updatedAt:new Date().toISOString()}),await(0,gatewayRouteIndex_js_1.setDefaultPublishedSessionId)(r,o,d),n.sessionKey&&await(0,gatewayRouteIndex_js_1.setRouteSessionMapping)(r,o,n.sessionKey,d);for(const[y,f]of this.sessionCache)f.agentId===o&&this.sessionCache.delete(y);this.sessionCache.set(d,{gatewaySessionKey:n.sessionKey??`__published__:${o}`,agentId:o,packName:c,vscodeSessionResource:a,chatSessionId:d,chatMode:s.mode,lastActiveAt:Date.now()}),n.sessionKey&&this.log(`Route index updated: ${n.sessionKey} -> ${d}`),n.initialMessage&&await vscode.commands.executeCommand("workbench.action.chat.open",{mode:"agent",query:n.initialMessage,sessionResource:s.sessionResource}),vscode.window.showInformationMessage(`New chat session created from ${n.requestedBy??"Gateway"}`),this.bridge?.respondSessionNew(t,{success:!0,agentId:o})}catch(s){const a=s instanceof Error?s.message:String(s);this.log(`Failed to create new session: ${a}`),this.bridge?.respondSessionNew(t,{success:!1,error:a})}}async connect(e){const t=e?.silent??!1,n=vscode.workspace.getConfiguration("agentide.gateway"),s=(n.get("url")??"").trim()||(this.config.url??"").trim(),a=(n.get("token")??"").trim()||(this.config.token??"").trim();if(!s){t||vscode.window.showWarningMessage(`Gateway URL not configured. Set ${(0,branding_js_1.toSettingsDisplayKey)("agentide.gateway.url")} in settings.`);return}if(this.isConnected){t||vscode.window.showInformationMessage("Already connected to Gateway");return}try{this.updateStatusBar("connecting"),this.log("Connecting to Gateway...");const c={gatewayUrl:s,token:a||void 0,version:this.extensionContext.extension.packageJSON.version,outputChannel:this.outputChannel};this.bridge=new bridge_js_1.GatewayBridge(c),this.bridge.on("connected",()=>{this.updateStatusBar("connected"),this.log("Connected to Gateway"),this.registerConfiguredAgents()}),this.bridge.on("disconnected",()=>{const o=this.sessionCache.size;this.sessionCache.clear(),this.updateStatusBar("disconnected"),this.log(`Disconnected from Gateway. Cleared ${o} cached session(s).`)}),this.bridge.on("error",o=>{this.log(`Gateway error: ${o.message}`)}),this.bridge.on("reconnecting",o=>{this.updateStatusBar("reconnecting"),this.log(`Reconnecting... (attempt ${o})`)}),this.bridge.on("agent.message",o=>{const r=o.routeKey??o.sessionKey??"";this.log(`Message for ${o.agentId}${r?` (${r})`:""}: ${o.message.slice(0,100)}...`)}),this.bridge.on("agent.registered",(o,r)=>{r?.needsBinding&&this.onNeedsBinding&&this.onNeedsBinding(o)}),this.bridge.on("session.new.request",o=>{this.handleSessionNewRequest(o)}),this.bridge.on("agent.cancel",o=>{this.log(`Cancelling chat generation (agent.cancel: sessionKey=${o?.sessionKey})`);const r=o?.sessionKey,d=o?.agentId;if(r&&d){this.openSessionForGatewayCancel(d,r);return}vscode.commands.executeCommand("workbench.action.chat.cancel")}),await this.bridge.connect(),this.startHealthCheck()}catch(c){this.updateStatusBar("error");const o=c instanceof Error?c.message:String(c);this.log(`Failed to connect: ${o}`),t||vscode.window.showErrorMessage(`Failed to connect to Gateway: ${o}`)}}async disconnect(){if(this.stopHealthCheck(),!!this.bridge)try{await this.bridge.disconnect()}finally{this.sessionCache.clear(),this.bridge=null,this.updateStatusBar("disconnected")}}async openSessionForGatewayCancel(e,t){const n=(0,bridge_js_1.buildIdeSessionRouteKey)(t,void 0)??t,s=[...this.sessionCache.values()].find(o=>o.gatewaySessionKey===t);if(s){await vscode.commands.executeCommand("workbench.action.chat.open",{sessionResource:s.vscodeSessionResource.toString()}),await vscode.commands.executeCommand("workbench.action.chat.cancel");return}const a=this.resolveGatewayWorkspaceRoot(),c=await(0,gatewayRouteIndex_js_1.resolveInboundSessionId)({workspaceRoot:a,agentId:e,routeKey:n,gatewaySessionKey:t}).then(o=>o.sessionId);if(c){const o=await this.hydrateSessionEntryFromDisk(a,c,e,"default");if(o){await vscode.commands.executeCommand("workbench.action.chat.open",{sessionResource:o.vscodeSessionResource.toString()}),await vscode.commands.executeCommand("workbench.action.chat.cancel");return}}await vscode.commands.executeCommand("workbench.action.chat.cancel")}startHealthCheck(){this.stopHealthCheck(),this.healthCheckTimer=setInterval(()=>{this.performHealthCheck()},GatewayService.HEALTH_CHECK_INTERVAL)}stopHealthCheck(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null)}async performHealthCheck(){if(this.bridge?.isConnected)try{await this.bridge.request("agents.list",{})}catch{this.log("Health check failed, reconnecting...");try{await this.bridge.reconnect()}catch(e){this.log(`Reconnect failed: ${e}`)}}}showStatus(){const e=this.isConnected,t=this.bridge?.registeredAgents??[],n=this.sessionCache.size;let s=e?"Connected to Gateway":"Disconnected from Gateway";e&&t.length>0&&(s+=`
3
+ Agents: ${t.join(", ")}`),e&&(s+=`
4
+ Sessions: ${n} active (disk-backed routing)`),e&&this.bridge?.connId&&(s+=`
5
+ Connection: ${this.bridge.connId}`),vscode.window.showInformationMessage(s)}async showSessionMap(){if(!this.isConnected){vscode.window.showInformationMessage("Not connected to Gateway");return}const e=[],t=this.resolveGatewayWorkspaceRoot(),n=new Set;for(const s of this.bridge?.registeredAgents??[]){const a=await(0,gatewayRouteIndex_js_1.getDefaultPublishedSessionId)(t,s);if(a&&!n.has(a)){n.add(a);const c=await(0,gatewaySessionStore_js_1.readGatewaySessionRecord)(t,a);e.push({label:`$(pin) ${s}`,description:"default published session",detail:c?.published?.bindLabel?`CLI: ${c.published.bindLabel} | ${a}`:a})}}for(const s of this.sessionCache.values()){const a=s.peerLabel??s.gatewaySessionKey;e.push({label:`$(broadcast) ${a}`,description:`${s.agentId}${s.channel?` (${s.channel})`:""}`,detail:`Pack: ${s.packName} | ${s.chatSessionId} | Active ${this.formatRelativeTime(s.lastActiveAt)}`})}if(e.length===0){vscode.window.showInformationMessage("No sessions mapped. Use 'Connect Chat to Gateway' to publish the current session.");return}await vscode.window.showQuickPick(e,{title:`Gateway Sessions (${e.length})`,placeHolder:"Session mappings (published + active routes)"})}async queryChatState(){return vscode.commands.executeCommand("agentide.getChatState")}formatRelativeTime(e){const t=Math.floor((Date.now()-e)/1e3);if(t<60)return"just now";const n=Math.floor(t/60);if(n<60)return`${n}m ago`;const s=Math.floor(n/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}updateStatusBar(e){}log(e){this.outputChannel.appendLine(`[${lifecycle_js_1.AGENT_ANYWHERE_LABEL}] ${e}`)}onNeedsBinding;get isConnected(){return this.bridge?.isConnected??!1}async request(e,t){if(!this.bridge?.isConnected)throw new Error("Not connected to gateway");return this.bridge.request(e,t)}dispose(){this.disconnect();for(const e of this.disposables)e.dispose()}}exports.GatewayService=GatewayService;