ft-scout 9.5.1 → 9.5.2

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 (299) hide show
  1. package/README.md +12 -18
  2. package/bin/src/commands/agent.d.ts +41 -0
  3. package/bin/src/commands/audit.d.ts +2 -0
  4. package/bin/src/commands/authCommand.d.ts +2 -0
  5. package/bin/src/commands/benchmark.d.ts +2 -0
  6. package/bin/src/commands/brief.d.ts +4 -0
  7. package/bin/src/commands/checkpoint.d.ts +7 -0
  8. package/bin/src/commands/configCommand.d.ts +7 -0
  9. package/bin/src/commands/dashboard.d.ts +5 -0
  10. package/bin/src/commands/history.d.ts +2 -0
  11. package/bin/src/commands/init.d.ts +8 -0
  12. package/bin/src/commands/login.d.ts +10 -0
  13. package/bin/src/commands/logout.d.ts +6 -0
  14. package/bin/src/commands/mcp.d.ts +49 -0
  15. package/bin/src/commands/owners.d.ts +2 -0
  16. package/bin/src/commands/plan.d.ts +2 -0
  17. package/bin/src/commands/pr.d.ts +11 -0
  18. package/bin/src/commands/quota.d.ts +2 -0
  19. package/bin/src/commands/recommend.d.ts +5 -0
  20. package/bin/src/commands/risky.d.ts +10 -0
  21. package/bin/src/commands/setup.d.ts +2 -0
  22. package/bin/src/commands/signup.d.ts +8 -0
  23. package/bin/src/commands/switchCommand.d.ts +3 -0
  24. package/bin/src/commands/undo.d.ts +2 -0
  25. package/bin/src/commands/watch.d.ts +12 -0
  26. package/bin/src/commands/web.d.ts +8 -0
  27. package/bin/src/discovery/config.d.ts +10 -0
  28. package/bin/src/discovery/display.d.ts +3 -0
  29. package/bin/src/discovery/messages.d.ts +4 -0
  30. package/bin/src/discovery/signals.d.ts +16 -0
  31. package/bin/src/engine/actionVerifier.d.ts +69 -0
  32. package/bin/src/engine/agentEngine.d.ts +110 -0
  33. package/bin/src/engine/agentState.d.ts +154 -0
  34. package/bin/src/engine/browser/browserController.d.ts +155 -0
  35. package/bin/src/engine/browser/index.d.ts +2 -0
  36. package/bin/src/engine/checkpoints/checkpointManager.d.ts +48 -0
  37. package/bin/src/engine/computer/computerController.d.ts +130 -0
  38. package/bin/src/engine/computer/computerController.js +8 -0
  39. package/bin/src/engine/computer/computerDiagnostic.d.ts +31 -0
  40. package/bin/src/engine/computer/index.d.ts +4 -0
  41. package/bin/src/engine/computer/mockComputer.d.ts +62 -0
  42. package/bin/src/engine/computer/operatorHud.d.ts +30 -0
  43. package/bin/src/engine/git.d.ts +20 -0
  44. package/bin/src/engine/llm.d.ts +92 -0
  45. package/bin/src/engine/planner.d.ts +21 -0
  46. package/bin/src/engine/runtime/agentRuntime.d.ts +111 -0
  47. package/bin/src/engine/runtime/index.d.ts +2 -0
  48. package/bin/src/engine/safety.d.ts +55 -0
  49. package/bin/src/engine/scanners.d.ts +2 -0
  50. package/bin/src/engine/subagents/subagentManager.d.ts +29 -0
  51. package/bin/src/engine/toolRegistry.d.ts +38 -0
  52. package/bin/src/engine/verifier.d.ts +47 -0
  53. package/bin/src/engine/voiceEngine.d.ts +26 -0
  54. package/bin/src/engine/web.d.ts +22 -0
  55. package/bin/src/engine/workspace/agentWorkspace.d.ts +112 -0
  56. package/bin/src/engine/workspace/index.d.ts +2 -0
  57. package/bin/src/index.d.ts +2 -0
  58. package/bin/src/index.js +4 -4
  59. package/bin/src/mcp/client.d.ts +62 -0
  60. package/bin/src/mcp/client.js +1 -1
  61. package/bin/src/mcp/cloudSync.d.ts +19 -0
  62. package/bin/src/mcp/discovery.d.ts +22 -0
  63. package/bin/src/mcp/health.d.ts +13 -0
  64. package/bin/src/mcp/index.d.ts +16 -0
  65. package/bin/src/mcp/manager.d.ts +113 -0
  66. package/bin/src/mcp/permissions.d.ts +18 -0
  67. package/bin/src/mcp/persistence.d.ts +44 -0
  68. package/bin/src/mcp/persistence.js +8 -1
  69. package/bin/src/mcp/recovery.d.ts +19 -0
  70. package/bin/src/mcp/telemetry.d.ts +15 -0
  71. package/bin/src/mcp/toolRouter.d.ts +23 -0
  72. package/bin/src/mcp/transport.d.ts +60 -0
  73. package/bin/src/mcp/types.d.ts +130 -0
  74. package/bin/src/server/server.d.ts +6 -0
  75. package/bin/src/utils/admin.d.ts +84 -0
  76. package/bin/src/utils/auditLogger.d.ts +18 -0
  77. package/bin/src/utils/auth.d.ts +132 -0
  78. package/bin/src/utils/branding.d.ts +2 -0
  79. package/bin/src/utils/branding.js +1 -1
  80. package/bin/src/utils/claudeUI.d.ts +101 -0
  81. package/bin/src/utils/config.d.ts +46 -0
  82. package/bin/src/utils/email.d.ts +36 -0
  83. package/bin/src/utils/firebaseAuth.d.ts +19 -0
  84. package/bin/src/utils/holoseneAuth.d.ts +18 -0
  85. package/bin/src/utils/interruptHandler.d.ts +32 -0
  86. package/bin/src/utils/language.d.ts +13 -0
  87. package/bin/src/utils/logger.d.ts +2 -0
  88. package/bin/src/utils/markdown.d.ts +19 -0
  89. package/bin/src/utils/payment.d.ts +81 -0
  90. package/bin/src/utils/pricing.d.ts +26 -0
  91. package/bin/src/utils/qrBridge.d.ts +33 -0
  92. package/bin/src/utils/qrBridge.js +1 -1
  93. package/bin/src/utils/razorpay.d.ts +48 -0
  94. package/bin/src/utils/rules.d.ts +24 -0
  95. package/bin/src/utils/session.d.ts +32 -0
  96. package/bin/src/utils/updateCheck.d.ts +3 -0
  97. package/package.json +14 -4
  98. package/.firebase/hosting.d2Vi.cache +0 -16
  99. package/.firebaserc +0 -14
  100. package/.mcp-config.json +0 -19
  101. package/.mft-mcp-config.json +0 -29
  102. package/.scoutrules +0 -13
  103. package/.test-ft/mcp_activity.json +0 -23
  104. package/.test-ft/mcp_credentials.enc +0 -1
  105. package/.test-ft/mcp_servers.json +0 -1
  106. package/bin/src/commands/agent.d.ts.map +0 -1
  107. package/bin/src/commands/agent.js.map +0 -1
  108. package/bin/src/commands/audit.d.ts.map +0 -1
  109. package/bin/src/commands/audit.js.map +0 -1
  110. package/bin/src/commands/authCommand.d.ts.map +0 -1
  111. package/bin/src/commands/authCommand.js.map +0 -1
  112. package/bin/src/commands/benchmark.d.ts.map +0 -1
  113. package/bin/src/commands/benchmark.js.map +0 -1
  114. package/bin/src/commands/brief.d.ts.map +0 -1
  115. package/bin/src/commands/brief.js.map +0 -1
  116. package/bin/src/commands/checkpoint.d.ts.map +0 -1
  117. package/bin/src/commands/checkpoint.js.map +0 -1
  118. package/bin/src/commands/configCommand.d.ts.map +0 -1
  119. package/bin/src/commands/configCommand.js.map +0 -1
  120. package/bin/src/commands/dashboard.d.ts.map +0 -1
  121. package/bin/src/commands/dashboard.js.map +0 -1
  122. package/bin/src/commands/history.d.ts.map +0 -1
  123. package/bin/src/commands/history.js.map +0 -1
  124. package/bin/src/commands/init.d.ts.map +0 -1
  125. package/bin/src/commands/init.js.map +0 -1
  126. package/bin/src/commands/login.d.ts.map +0 -1
  127. package/bin/src/commands/login.js.map +0 -1
  128. package/bin/src/commands/logout.d.ts.map +0 -1
  129. package/bin/src/commands/logout.js.map +0 -1
  130. package/bin/src/commands/mcp.d.ts.map +0 -1
  131. package/bin/src/commands/mcp.js.map +0 -1
  132. package/bin/src/commands/owners.d.ts.map +0 -1
  133. package/bin/src/commands/owners.js.map +0 -1
  134. package/bin/src/commands/plan.d.ts.map +0 -1
  135. package/bin/src/commands/plan.js.map +0 -1
  136. package/bin/src/commands/pr.d.ts.map +0 -1
  137. package/bin/src/commands/pr.js.map +0 -1
  138. package/bin/src/commands/quota.d.ts.map +0 -1
  139. package/bin/src/commands/quota.js.map +0 -1
  140. package/bin/src/commands/recommend.d.ts.map +0 -1
  141. package/bin/src/commands/recommend.js.map +0 -1
  142. package/bin/src/commands/risky.d.ts.map +0 -1
  143. package/bin/src/commands/risky.js.map +0 -1
  144. package/bin/src/commands/setup.d.ts.map +0 -1
  145. package/bin/src/commands/setup.js.map +0 -1
  146. package/bin/src/commands/signup.d.ts.map +0 -1
  147. package/bin/src/commands/signup.js.map +0 -1
  148. package/bin/src/commands/switchCommand.d.ts.map +0 -1
  149. package/bin/src/commands/switchCommand.js.map +0 -1
  150. package/bin/src/commands/undo.d.ts.map +0 -1
  151. package/bin/src/commands/undo.js.map +0 -1
  152. package/bin/src/commands/watch.d.ts.map +0 -1
  153. package/bin/src/commands/watch.js.map +0 -1
  154. package/bin/src/commands/web.d.ts.map +0 -1
  155. package/bin/src/commands/web.js.map +0 -1
  156. package/bin/src/discovery/config.d.ts.map +0 -1
  157. package/bin/src/discovery/config.js.map +0 -1
  158. package/bin/src/discovery/display.d.ts.map +0 -1
  159. package/bin/src/discovery/display.js.map +0 -1
  160. package/bin/src/discovery/messages.d.ts.map +0 -1
  161. package/bin/src/discovery/messages.js.map +0 -1
  162. package/bin/src/discovery/signals.d.ts.map +0 -1
  163. package/bin/src/discovery/signals.js.map +0 -1
  164. package/bin/src/engine/actionVerifier.d.ts.map +0 -1
  165. package/bin/src/engine/actionVerifier.js.map +0 -1
  166. package/bin/src/engine/agentEngine.d.ts.map +0 -1
  167. package/bin/src/engine/agentEngine.js.map +0 -1
  168. package/bin/src/engine/agentState.d.ts.map +0 -1
  169. package/bin/src/engine/agentState.js.map +0 -1
  170. package/bin/src/engine/browser/browserController.d.ts.map +0 -1
  171. package/bin/src/engine/browser/browserController.js.map +0 -1
  172. package/bin/src/engine/browser/index.d.ts.map +0 -1
  173. package/bin/src/engine/browser/index.js.map +0 -1
  174. package/bin/src/engine/checkpoints/checkpointManager.d.ts.map +0 -1
  175. package/bin/src/engine/checkpoints/checkpointManager.js.map +0 -1
  176. package/bin/src/engine/computer/computerController.d.ts.map +0 -1
  177. package/bin/src/engine/computer/computerController.js.map +0 -1
  178. package/bin/src/engine/computer/computerDiagnostic.d.ts.map +0 -1
  179. package/bin/src/engine/computer/computerDiagnostic.js.map +0 -1
  180. package/bin/src/engine/computer/index.d.ts.map +0 -1
  181. package/bin/src/engine/computer/index.js.map +0 -1
  182. package/bin/src/engine/computer/mockComputer.d.ts.map +0 -1
  183. package/bin/src/engine/computer/mockComputer.js.map +0 -1
  184. package/bin/src/engine/computer/operatorHud.d.ts.map +0 -1
  185. package/bin/src/engine/computer/operatorHud.js.map +0 -1
  186. package/bin/src/engine/computer/scout_driver.exe +0 -0
  187. package/bin/src/engine/git.d.ts.map +0 -1
  188. package/bin/src/engine/git.js.map +0 -1
  189. package/bin/src/engine/llm.d.ts.map +0 -1
  190. package/bin/src/engine/llm.js.map +0 -1
  191. package/bin/src/engine/planner.d.ts.map +0 -1
  192. package/bin/src/engine/planner.js.map +0 -1
  193. package/bin/src/engine/runtime/agentRuntime.d.ts.map +0 -1
  194. package/bin/src/engine/runtime/agentRuntime.js.map +0 -1
  195. package/bin/src/engine/runtime/index.d.ts.map +0 -1
  196. package/bin/src/engine/runtime/index.js.map +0 -1
  197. package/bin/src/engine/safety.d.ts.map +0 -1
  198. package/bin/src/engine/safety.js.map +0 -1
  199. package/bin/src/engine/scanners.d.ts.map +0 -1
  200. package/bin/src/engine/scanners.js.map +0 -1
  201. package/bin/src/engine/scoutAudioRecorder.cs +0 -215
  202. package/bin/src/engine/scout_audio_recorder.exe +0 -0
  203. package/bin/src/engine/subagents/subagentManager.d.ts.map +0 -1
  204. package/bin/src/engine/subagents/subagentManager.js.map +0 -1
  205. package/bin/src/engine/toolRegistry.d.ts.map +0 -1
  206. package/bin/src/engine/toolRegistry.js.map +0 -1
  207. package/bin/src/engine/verifier.d.ts.map +0 -1
  208. package/bin/src/engine/verifier.js.map +0 -1
  209. package/bin/src/engine/voiceEngine.d.ts.map +0 -1
  210. package/bin/src/engine/voiceEngine.js.map +0 -1
  211. package/bin/src/engine/web.d.ts.map +0 -1
  212. package/bin/src/engine/web.js.map +0 -1
  213. package/bin/src/engine/workspace/agentWorkspace.d.ts.map +0 -1
  214. package/bin/src/engine/workspace/agentWorkspace.js.map +0 -1
  215. package/bin/src/engine/workspace/index.d.ts.map +0 -1
  216. package/bin/src/engine/workspace/index.js.map +0 -1
  217. package/bin/src/index.d.ts.map +0 -1
  218. package/bin/src/index.js.map +0 -1
  219. package/bin/src/mcp/client.d.ts.map +0 -1
  220. package/bin/src/mcp/client.js.map +0 -1
  221. package/bin/src/mcp/cloudSync.d.ts.map +0 -1
  222. package/bin/src/mcp/cloudSync.js.map +0 -1
  223. package/bin/src/mcp/discovery.d.ts.map +0 -1
  224. package/bin/src/mcp/discovery.js.map +0 -1
  225. package/bin/src/mcp/health.d.ts.map +0 -1
  226. package/bin/src/mcp/health.js.map +0 -1
  227. package/bin/src/mcp/index.d.ts.map +0 -1
  228. package/bin/src/mcp/index.js.map +0 -1
  229. package/bin/src/mcp/manager.d.ts.map +0 -1
  230. package/bin/src/mcp/manager.js.map +0 -1
  231. package/bin/src/mcp/permissions.d.ts.map +0 -1
  232. package/bin/src/mcp/permissions.js.map +0 -1
  233. package/bin/src/mcp/persistence.d.ts.map +0 -1
  234. package/bin/src/mcp/persistence.js.map +0 -1
  235. package/bin/src/mcp/recovery.d.ts.map +0 -1
  236. package/bin/src/mcp/recovery.js.map +0 -1
  237. package/bin/src/mcp/telemetry.d.ts.map +0 -1
  238. package/bin/src/mcp/telemetry.js.map +0 -1
  239. package/bin/src/mcp/toolRouter.d.ts.map +0 -1
  240. package/bin/src/mcp/toolRouter.js.map +0 -1
  241. package/bin/src/mcp/transport.d.ts.map +0 -1
  242. package/bin/src/mcp/transport.js.map +0 -1
  243. package/bin/src/mcp/types.d.ts.map +0 -1
  244. package/bin/src/mcp/types.js.map +0 -1
  245. package/bin/src/server/server.d.ts.map +0 -1
  246. package/bin/src/server/server.js.map +0 -1
  247. package/bin/src/utils/admin.d.ts.map +0 -1
  248. package/bin/src/utils/admin.js.map +0 -1
  249. package/bin/src/utils/auditLogger.d.ts.map +0 -1
  250. package/bin/src/utils/auditLogger.js.map +0 -1
  251. package/bin/src/utils/auth.d.ts.map +0 -1
  252. package/bin/src/utils/auth.js.map +0 -1
  253. package/bin/src/utils/branding.d.ts.map +0 -1
  254. package/bin/src/utils/branding.js.map +0 -1
  255. package/bin/src/utils/claudeUI.d.ts.map +0 -1
  256. package/bin/src/utils/claudeUI.js.map +0 -1
  257. package/bin/src/utils/config.d.ts.map +0 -1
  258. package/bin/src/utils/config.js.map +0 -1
  259. package/bin/src/utils/email.d.ts.map +0 -1
  260. package/bin/src/utils/email.js.map +0 -1
  261. package/bin/src/utils/firebaseAuth.d.ts.map +0 -1
  262. package/bin/src/utils/firebaseAuth.js.map +0 -1
  263. package/bin/src/utils/holoseneAuth.d.ts.map +0 -1
  264. package/bin/src/utils/holoseneAuth.js.map +0 -1
  265. package/bin/src/utils/interruptHandler.d.ts.map +0 -1
  266. package/bin/src/utils/interruptHandler.js.map +0 -1
  267. package/bin/src/utils/language.d.ts.map +0 -1
  268. package/bin/src/utils/language.js.map +0 -1
  269. package/bin/src/utils/logger.d.ts.map +0 -1
  270. package/bin/src/utils/logger.js.map +0 -1
  271. package/bin/src/utils/markdown.d.ts.map +0 -1
  272. package/bin/src/utils/markdown.js.map +0 -1
  273. package/bin/src/utils/payment.d.ts.map +0 -1
  274. package/bin/src/utils/payment.js.map +0 -1
  275. package/bin/src/utils/pricing.d.ts.map +0 -1
  276. package/bin/src/utils/pricing.js.map +0 -1
  277. package/bin/src/utils/qrBridge.d.ts.map +0 -1
  278. package/bin/src/utils/qrBridge.js.map +0 -1
  279. package/bin/src/utils/razorpay.d.ts.map +0 -1
  280. package/bin/src/utils/razorpay.js.map +0 -1
  281. package/bin/src/utils/rules.d.ts.map +0 -1
  282. package/bin/src/utils/rules.js.map +0 -1
  283. package/bin/src/utils/session.d.ts.map +0 -1
  284. package/bin/src/utils/session.js.map +0 -1
  285. package/bin/src/utils/updateCheck.d.ts.map +0 -1
  286. package/bin/src/utils/updateCheck.js.map +0 -1
  287. package/downloads/invoice-2026-03.pdf +0 -1
  288. package/firebase.json +0 -74
  289. package/front-terrain-cli-1.0.0.tgz +0 -0
  290. package/web/ScoutFavicon.png +0 -0
  291. package/web/ScoutOGImage.png +0 -0
  292. package/web/app.js +0 -4510
  293. package/web/ft-logo.png +0 -0
  294. package/web/og-image.png +0 -0
  295. package/web/robots.txt +0 -24
  296. package/web/site.webmanifest +0 -16
  297. package/web/sitemap-tryscout.xml +0 -47
  298. package/web/sitemap.xml +0 -47
  299. package/web/styles.css +0 -3436
package/web/app.js DELETED
@@ -1,4510 +0,0 @@
1
- /* ==========================================================================
2
- FrontTerrain Scout Multi-Page Application Engine v9.5.1
3
- ========================================================================== */
4
-
5
- const FIREBASE_CONFIG = {
6
- apiKey: 'AIzaSyCMVNDgR8EejfXofUy87L7hsKxi3E_C3lg',
7
- projectId: 'frontterrain',
8
- tenantId: 'ft-scout-auth-gc2v5',
9
- baseAuthUrl: 'https://identitytoolkit.googleapis.com/v1/accounts',
10
- };
11
-
12
- // Tier Configuration Details
13
- const TIER_DETAILS = {
14
- free: {
15
- name: 'Developer Free Tier',
16
- badge: 'ACTIVE',
17
- desc: 'Standard access to Scout CLI features & local execution.',
18
- icon: '<i class="fa-solid fa-star text-warning" style="font-size: 28px;"></i>',
19
- },
20
- pro: {
21
- name: 'Pro Developer Tier',
22
- badge: 'PRO ACTIVE',
23
- desc: 'High-power AI co-pilot capabilities, Autonomous Computer & Browser Control, priority quota & 5 active CLI sessions.',
24
- icon: '<i class="fa-solid fa-bolt text-primary" style="font-size: 28px;"></i>',
25
- },
26
- team: {
27
- name: 'Team & Squads Tier',
28
- badge: 'TEAM ACTIVE',
29
- desc: 'Shared Onboarding Knowledge Graph, PR Risk Gatekeeper & multi-seat controls.',
30
- icon: '<i class="fa-solid fa-user-group text-info" style="font-size: 28px;"></i>',
31
- },
32
- enterprise: {
33
- name: 'Enterprise Scale Tier',
34
- badge: 'ENTERPRISE ACTIVE',
35
- desc: 'Organization security, SAML SSO, SOC2 compliance & private VPC LLM gateway.',
36
- icon: '<i class="fa-solid fa-building-shield text-warning" style="font-size: 28px;"></i>',
37
- },
38
- };
39
-
40
- // Global Application State
41
- let state = {
42
- user: null,
43
- token: null,
44
- refreshToken: null,
45
- serverConnected: false,
46
- apiBaseUrl: '',
47
- sessions: [],
48
- currentTier: 'free',
49
- billingCycle: 'monthly',
50
- creditsUsed: 0,
51
- creditsTotal: 100,
52
- renewAt: null,
53
- cancelAtPeriodEnd: false,
54
- pendingDowngrade: null,
55
- paidTier: null,
56
- byokEnabled: false,
57
- customLlmProvider: 'nvidia',
58
- customApiKey: '',
59
- customBaseUrl: '',
60
- razorpayKeyId: '',
61
- pricing: {
62
- free: { monthlyPriceINR: 0, annualPriceINR: 0, monthlyPriceUSD: 0, annualPriceUSD: 0, credits: 100 },
63
- pro: { monthlyPriceINR: 1499, annualPriceINR: 1199, monthlyPriceUSD: 19, annualPriceUSD: 15, credits: 2500 },
64
- team: { monthlyPriceINR: 3999, annualPriceINR: 3199, monthlyPriceUSD: 49, annualPriceUSD: 39, credits: 10000 },
65
- enterprise: { monthlyPriceINR: 7999, annualPriceINR: 6399, monthlyPriceUSD: 99, annualPriceUSD: 79, credits: 30000 },
66
- },
67
- };
68
-
69
- let pendingCheckoutTier = null;
70
- let pendingDowngradeTier = null;
71
-
72
- // Audio Synthesizer via Web Audio API
73
- let audioCtx = null;
74
-
75
- function playRetroBeep(freq = 440, duration = 0.08, type = 'square') {
76
- try {
77
- if (!audioCtx) {
78
- const AudioContext = window.AudioContext || window.webkitAudioContext;
79
- audioCtx = new AudioContext();
80
- }
81
- if (audioCtx.state === 'suspended') audioCtx.resume();
82
-
83
- const osc = audioCtx.createOscillator();
84
- const gain = audioCtx.createGain();
85
- osc.type = type;
86
- osc.frequency.setValueAtTime(freq, audioCtx.currentTime);
87
-
88
- gain.gain.setValueAtTime(0.08, audioCtx.currentTime);
89
- gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + duration);
90
-
91
- osc.connect(gain);
92
- gain.connect(audioCtx.destination);
93
- osc.start();
94
- osc.stop(audioCtx.currentTime + duration);
95
- } catch { }
96
- }
97
-
98
- // DOM Helper Getter
99
- function getEl(id) {
100
- return document.getElementById(id);
101
- }
102
-
103
- // Helper to determine current page basename
104
- function getCurrentPage() {
105
- const path = window.location.pathname.toLowerCase();
106
- if (path.includes('/auth')) return '/auth';
107
- if (path.includes('/plans')) return '/plans';
108
- if (path.includes('/cli')) return '/cli';
109
- return 'index.html';
110
- }
111
-
112
- // Highlight current active nav link in navbar
113
- function highlightActiveNav() {
114
- const currentPage = getCurrentPage();
115
- document.querySelectorAll('.nav-links .nav-btn').forEach((link) => {
116
- const href = link.getAttribute('href');
117
- if (href === currentPage || (currentPage === 'index.html' && (href === 'index.html' || href === './'))) {
118
- link.classList.add('active');
119
- } else {
120
- link.classList.remove('active');
121
- }
122
- });
123
- }
124
-
125
- // Apply plan tier upgrade and update persistent credits & UI
126
- function applyTierUpgrade(tier, transactionId) {
127
- const targetTier = tier && TIER_DETAILS[tier] ? tier : 'pro';
128
- const tierInfo = TIER_DETAILS[targetTier];
129
- const quota = targetTier === 'enterprise' ? 10000 : (targetTier === 'pro' ? 1000 : 100);
130
-
131
- state.currentTier = targetTier;
132
- state.paidTier = targetTier;
133
- state.cancelAtPeriodEnd = false;
134
- state.pendingDowngrade = null;
135
- state.creditsTotal = quota;
136
- state.creditsUsed = 0;
137
- const durationDays = state.billingCycle === 'annual' ? 365 : 30;
138
- state.renewAt = new Date(Date.now() + durationDays * 24 * 60 * 60 * 1000).toISOString();
139
-
140
- saveSessionToStorage();
141
- renderAllDynamicComponents();
142
- updateUserUI();
143
- renderCreditUsageUI();
144
- renderTiersUI();
145
- closeCheckoutModal();
146
-
147
- if (state.serverConnected) {
148
- syncAuthWithServer();
149
- }
150
-
151
- const txMsg = transactionId ? ` (Ref: ${transactionId.slice(-8)})` : '';
152
- showToast(`🎉 Welcome to ${tierInfo.name}! Your ${quota.toLocaleString()} monthly AI credits are active!${txMsg}`, 'success');
153
- }
154
-
155
- // Check for payment redirect callback from PayPal / external gateways
156
- async function checkPaymentRedirectCallback() {
157
- const params = new URLSearchParams(window.location.search);
158
- const orderId = params.get('token') || params.get('session_id') || params.get('orderId');
159
- const isSuccess = params.get('success') === 'true' || Boolean(params.get('token'));
160
- const tier = params.get('tier') || 'pro';
161
-
162
- if (orderId && isSuccess) {
163
- window.history.replaceState({}, document.title, window.location.pathname);
164
- showToast('Activating subscription...', 'info');
165
-
166
- if (state.serverConnected && state.apiBaseUrl) {
167
- try {
168
- const res = await fetch(`${state.apiBaseUrl}/api/payment/verify`, {
169
- method: 'POST',
170
- headers: { 'Content-Type': 'application/json' },
171
- body: JSON.stringify({
172
- orderId,
173
- token: orderId,
174
- sessionId: orderId,
175
- tier,
176
- }),
177
- });
178
- const data = await res.json();
179
- if (data.success) {
180
- applyTierUpgrade(data.tier || tier, data.transactionId || orderId);
181
- return;
182
- }
183
- } catch { }
184
- }
185
-
186
- // Standalone Cloud Web Mode: Instant activation
187
- applyTierUpgrade(tier, orderId);
188
- } else if (params.get('canceled') === 'true') {
189
- window.history.replaceState({}, document.title, window.location.pathname);
190
- showToast('Subscription checkout was canceled.', 'warning');
191
- }
192
- }
193
-
194
- // Dynamic Pricing Loader & Admin Navigation Hook
195
- function loadPricingFromStorage() {
196
- try {
197
- const stored = localStorage.getItem('scout_pricing_config');
198
- if (stored) {
199
- const parsed = JSON.parse(stored);
200
- if (parsed && typeof parsed === 'object' && parsed.pro) {
201
- state.pricing = { ...state.pricing, ...parsed };
202
- }
203
- }
204
- } catch { }
205
- }
206
-
207
- async function loadDynamicPricing() {
208
- // 1. Instantly apply locally saved admin pricing configuration
209
- loadPricingFromStorage();
210
- renderTiersUI();
211
-
212
- // 2. Fetch fresh server pricing if connected
213
- try {
214
- const res = await fetch('/api/pricing');
215
- if (res.ok) {
216
- const contentType = res.headers.get('content-type') || '';
217
- if (contentType.includes('application/json')) {
218
- const data = await res.json();
219
- if (data && data.success && data.pricing) {
220
- state.pricing = data.pricing;
221
- localStorage.setItem('scout_pricing_config', JSON.stringify(data.pricing));
222
- renderTiersUI();
223
- }
224
- }
225
- }
226
- } catch { }
227
-
228
- checkAdminStatus();
229
- }
230
-
231
- // Whitelisted Master Administrator Accounts
232
- const AUTHORIZED_ADMIN_EMAILS = [
233
- 'rishishandilya40@gmail.com',
234
- 'rishi.shandilya@frontterrain.com',
235
- 'company@frontterrain.com'
236
- ];
237
-
238
- function getActiveUserEmail() {
239
- let email = (state.user?.email || '').trim().toLowerCase();
240
- if (!email) {
241
- try {
242
- const stored = localStorage.getItem('scout_auth_user');
243
- if (stored) {
244
- const parsed = JSON.parse(stored);
245
- email = (parsed?.email || '').trim().toLowerCase();
246
- }
247
- } catch { }
248
- }
249
- return email;
250
- }
251
-
252
- function isUserAdmin() {
253
- const email = getActiveUserEmail();
254
- const isWhitelisted = Boolean(email && AUTHORIZED_ADMIN_EMAILS.includes(email));
255
- const hasAdminToken = Boolean(sessionStorage.getItem('scout_admin_token'));
256
- return isWhitelisted || hasAdminToken;
257
- }
258
-
259
- function checkAdminStatus() {
260
- if (isUserAdmin()) {
261
- // Ensure an admin token is primed in sessionStorage so navigation to /admin is instantly unlocked
262
- if (!sessionStorage.getItem('scout_admin_token')) {
263
- sessionStorage.setItem('scout_admin_token', 'scout_admin_session_' + Date.now().toString(36));
264
- }
265
- showAdminNavigationLink();
266
- return true;
267
- } else {
268
- hideAdminNavigationLink();
269
- return false;
270
- }
271
- }
272
-
273
- function showAdminNavigationLink() {
274
- const adminLink = document.getElementById('nav-admin-link');
275
- const adminGroup = document.getElementById('nav-group-admin');
276
- const topbarAdmin = document.getElementById('topbar-admin-link');
277
- const dropdownAdmin = document.getElementById('btn-dropdown-admin');
278
- const settingsAdminBtn = document.getElementById('settings-admin-portal-btn');
279
-
280
- if (adminGroup) adminGroup.style.display = 'block';
281
- if (adminLink) {
282
- adminLink.style.display = 'flex';
283
- adminLink.classList.add('admin-authorized');
284
- }
285
- if (topbarAdmin) topbarAdmin.style.display = 'inline-flex';
286
- if (dropdownAdmin) dropdownAdmin.style.display = 'flex';
287
- if (settingsAdminBtn) settingsAdminBtn.style.display = 'inline-flex';
288
-
289
- // Highlight admin identity in sidebar user footer
290
- const sidebarTier = document.getElementById('sidebar-user-tier');
291
- if (sidebarTier) {
292
- sidebarTier.innerHTML = '<span style="color: #e15b37; font-weight: 700;"><i class="fa-solid fa-shield-halved"></i> Master Admin</span>';
293
- }
294
-
295
- // Maintain backward compatibility with legacy main-nav
296
- const mainNav = getEl('main-nav');
297
- if (mainNav && !document.getElementById('legacy-nav-admin-link')) {
298
- const a = document.createElement('a');
299
- a.id = 'legacy-nav-admin-link';
300
- a.href = '/admin';
301
- a.className = 'nav-btn';
302
- a.style.color = '#f06843';
303
- a.innerHTML = '<i class="fa-solid fa-sliders"></i> Admin';
304
- mainNav.appendChild(a);
305
- }
306
- }
307
-
308
- function hideAdminNavigationLink() {
309
- const adminLink = document.getElementById('nav-admin-link');
310
- const adminGroup = document.getElementById('nav-group-admin');
311
- const topbarAdmin = document.getElementById('topbar-admin-link');
312
- const dropdownAdmin = document.getElementById('btn-dropdown-admin');
313
- const settingsAdminBtn = document.getElementById('settings-admin-portal-btn');
314
-
315
- if (adminGroup) adminGroup.style.display = 'none';
316
- if (adminLink) adminLink.style.display = 'none';
317
- if (topbarAdmin) topbarAdmin.style.display = 'none';
318
- if (dropdownAdmin) dropdownAdmin.style.display = 'none';
319
- if (settingsAdminBtn) settingsAdminBtn.style.display = 'none';
320
- }
321
-
322
- // Initialize Application
323
- document.addEventListener('DOMContentLoaded', async () => {
324
- highlightActiveNav();
325
- loadTierAndCreditsFromStorage();
326
- loadSessionsFromStorage();
327
- initEventListeners();
328
- initFAQAccordions();
329
- initRoiCalculator();
330
- initTerminalSimulator();
331
- renderAllDynamicComponents();
332
- await checkServerStatusAndSession();
333
- await loadDynamicPricing();
334
- await checkPaymentRedirectCallback();
335
-
336
- window.addEventListener('storage', (e) => {
337
- if (e.key === 'scout_pricing_config') {
338
- loadPricingFromStorage();
339
- renderTiersUI();
340
- }
341
- });
342
-
343
- if (getEl('pacman-canvas')) {
344
- initPacmanGame();
345
- }
346
-
347
- initAutonomousAgentMonitor();
348
- initWorkstationRouter();
349
- loadMcpData();
350
- });
351
-
352
- // Time Helper Function for Dynamic Relative Timestamps
353
- function timeAgo(dateInput) {
354
- if (!dateInput) return 'Just now';
355
- const date = new Date(dateInput);
356
- if (isNaN(date.getTime())) return String(dateInput);
357
-
358
- const now = new Date();
359
- const seconds = Math.floor((now - date) / 1000);
360
- if (seconds < 45) return 'Just now';
361
- const minutes = Math.floor(seconds / 60);
362
- if (minutes < 60) return `${minutes}m ago`;
363
- const hours = Math.floor(minutes / 60);
364
- if (hours < 24) return `${hours}h ago`;
365
- const days = Math.floor(hours / 24);
366
- return `${days}d ago`;
367
- }
368
-
369
- // Date and Expiration Helpers
370
- function formatRenewDate(isoDateStr) {
371
- if (!isoDateStr) return 'End of billing period';
372
- try {
373
- const d = new Date(isoDateStr);
374
- if (isNaN(d.getTime())) return 'End of billing period';
375
- return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
376
- } catch {
377
- return 'End of billing period';
378
- }
379
- }
380
-
381
- function isSubscriptionExpired() {
382
- if (!state.renewAt) return true;
383
- const renewDate = new Date(state.renewAt);
384
- if (isNaN(renewDate.getTime())) return true;
385
- return Date.now() >= renewDate.getTime();
386
- }
387
-
388
- function checkSubscriptionExpiration() {
389
- if (!state.renewAt) return;
390
- const renewDate = new Date(state.renewAt);
391
- if (isNaN(renewDate.getTime())) return;
392
-
393
- const now = new Date();
394
- if (now >= renewDate) {
395
- if (state.currentTier !== 'free') {
396
- // Paid plan expired / revoked on its expiration time: automatically shift to Free tier
397
- const previousTierName = (TIER_DETAILS[state.currentTier] || {}).name || state.currentTier.toUpperCase();
398
- state.currentTier = 'free';
399
- state.paidTier = null;
400
- state.cancelAtPeriodEnd = false;
401
- state.pendingDowngrade = null;
402
- state.creditsTotal = 100;
403
- state.creditsUsed = 0;
404
- state.renewAt = new Date(now.getFullYear(), now.getMonth() + 1, 1, 0, 0, 0).toISOString();
405
- saveSessionToStorage();
406
- if (state.serverConnected) syncAuthWithServer();
407
- renderAllDynamicComponents();
408
- showToast(`Your ${previousTierName} subscription has reached its expiration time and your account has automatically shifted to the Free tier.`, 'info');
409
- } else {
410
- // Free tier monthly credits reset
411
- const nextRenewal = new Date(renewDate);
412
- while (nextRenewal <= now) {
413
- nextRenewal.setMonth(nextRenewal.getMonth() + 1);
414
- }
415
- state.renewAt = nextRenewal.toISOString();
416
- state.creditsUsed = 0;
417
- saveSessionToStorage();
418
- if (state.serverConnected) syncAuthWithServer();
419
- renderAllDynamicComponents();
420
- }
421
- }
422
- }
423
-
424
- // Load Subscription Tier & Dynamic Credits from Local Storage
425
- function loadTierAndCreditsFromStorage() {
426
- const savedTier = localStorage.getItem('scout_current_tier');
427
- if (savedTier && TIER_DETAILS[savedTier]) {
428
- state.currentTier = savedTier;
429
- }
430
-
431
- const savedUsed = localStorage.getItem('scout_credits_used');
432
- state.creditsUsed = savedUsed !== null ? parseInt(savedUsed, 10) || 0 : 0;
433
-
434
- const savedTotal = localStorage.getItem('scout_credits_total');
435
- if (savedTotal !== null) {
436
- state.creditsTotal = parseInt(savedTotal, 10) || 100;
437
- } else {
438
- state.creditsTotal = state.currentTier === 'pro' ? 1000 : state.currentTier === 'enterprise' ? 10000 : 100;
439
- }
440
-
441
- const savedRenew = localStorage.getItem('scout_renew_at');
442
- if (savedRenew) {
443
- state.renewAt = savedRenew;
444
- } else {
445
- const now = new Date();
446
- state.renewAt = new Date(now.getFullYear(), now.getMonth() + 1, 1, 0, 0, 0).toISOString();
447
- }
448
-
449
- state.cancelAtPeriodEnd = localStorage.getItem('scout_cancel_at_period_end') === 'true';
450
- state.pendingDowngrade = localStorage.getItem('scout_pending_downgrade') || null;
451
- const savedPaidTier = localStorage.getItem('scout_paid_tier');
452
- state.paidTier = (savedPaidTier && TIER_DETAILS[savedPaidTier]) ? savedPaidTier : (state.currentTier !== 'free' ? state.currentTier : null);
453
-
454
- state.byokEnabled = localStorage.getItem('scout_byok_enabled') === 'true';
455
- state.customLlmProvider = localStorage.getItem('scout_byok_provider') || 'nvidia';
456
- state.customApiKey = localStorage.getItem('scout_byok_key') || '';
457
- state.customBaseUrl = localStorage.getItem('scout_byok_endpoint') || '';
458
-
459
- loadPricingFromStorage();
460
- checkSubscriptionExpiration();
461
- }
462
-
463
- // Render All Dynamic Components
464
- function renderAllDynamicComponents() {
465
- renderSessionsTable();
466
- renderCreditUsageUI();
467
- renderTiersUI();
468
- updateUserUI();
469
- }
470
-
471
- // Open / Close Checkout Modal
472
- function openCheckoutModal(targetTier) {
473
- pendingCheckoutTier = targetTier;
474
- const isAnnual = state.billingCycle === 'annual';
475
- const tierInfo = TIER_DETAILS[targetTier] || TIER_DETAILS.pro;
476
-
477
- const p = state.pricing || {
478
- pro: { monthlyPriceINR: 50, annualPriceINR: 45, credits: 1000 },
479
- enterprise: { monthlyPriceINR: 3999, annualPriceINR: 37990, credits: 10000 },
480
- };
481
-
482
- let price = '0';
483
- let quota = '100 Credits / mo';
484
-
485
- if (targetTier === 'pro') {
486
- const isOffer = p.pro?.offerActive && !isAnnual && p.pro?.offerPriceUSD !== undefined;
487
- const usd = isOffer ? p.pro.offerPriceUSD : (isAnnual ? (p.pro?.annualPriceUSD ?? 0.79) : (p.pro?.monthlyPriceUSD ?? 0.99));
488
- price = usd.toString();
489
- quota = `${(p.pro?.credits || 1000).toLocaleString()} Credits / mo`;
490
- } else if (targetTier === 'enterprise') {
491
- const isOffer = p.enterprise?.offerActive && !isAnnual && p.enterprise?.offerPriceUSD !== undefined;
492
- const usd = isOffer ? p.enterprise.offerPriceUSD : (isAnnual ? (p.enterprise?.annualPriceUSD ?? 39) : (p.enterprise?.monthlyPriceUSD ?? 49));
493
- price = usd.toString();
494
- quota = `${(p.enterprise?.credits || 10000).toLocaleString()} Credits / mo`;
495
- }
496
-
497
- if (getEl('checkout-plan-name')) getEl('checkout-plan-name').innerText = tierInfo.name;
498
- if (getEl('checkout-billing-cycle')) getEl('checkout-billing-cycle').innerText = isAnnual ? 'Billed Annually (Save more)' : 'Billed Monthly';
499
- if (getEl('checkout-plan-price')) getEl('checkout-plan-price').innerText = price;
500
- const checkoutCurrency = document.querySelector('.checkout-price-display .price-currency');
501
- if (checkoutCurrency) checkoutCurrency.innerText = '$';
502
- if (getEl('checkout-price-period')) getEl('checkout-price-period').innerText = isAnnual ? '/ mo (annual)' : '/ mo';
503
- if (getEl('checkout-quota-val')) getEl('checkout-quota-val').innerText = quota;
504
-
505
- const modal = getEl('checkout-modal');
506
- if (modal) {
507
- modal.classList.remove('hidden');
508
- renderRazorpayButton(targetTier);
509
- renderPayPalButtons(targetTier);
510
- }
511
- }
512
-
513
- function closeCheckoutModal() {
514
- pendingCheckoutTier = null;
515
- const modal = getEl('checkout-modal');
516
- if (modal) modal.classList.add('hidden');
517
- const container = getEl('paypal-button-container');
518
- if (container) container.innerHTML = '';
519
- }
520
-
521
- // Downgrade Handlers (Downgrades Disallowed: Auto-shifts to Free on Expiration)
522
- function openDowngradeModal(targetTier = 'free') {
523
- closeDowngradeModal();
524
- const renewDateFormatted = formatRenewDate(state.renewAt);
525
- showToast(`Downgrading paid plans is not allowed. Your plan remains active until ${renewDateFormatted}, after which it will automatically shift to the Free tier.`, 'warning');
526
- }
527
-
528
- function closeDowngradeModal() {
529
- pendingDowngradeTier = null;
530
- const modal = getEl('downgrade-modal');
531
- if (modal) modal.classList.add('hidden');
532
- }
533
-
534
- function confirmScheduleDowngrade() {
535
- closeDowngradeModal();
536
- const renewDateFormatted = formatRenewDate(state.renewAt);
537
- showToast(`Downgrading paid plans is not allowed. Your plan remains active until ${renewDateFormatted}, after which it will automatically shift to the Free tier.`, 'warning');
538
- }
539
-
540
- function confirmImmediateDowngrade() {
541
- closeDowngradeModal();
542
- const renewDateFormatted = formatRenewDate(state.renewAt);
543
- showToast(`Downgrading paid plans is not allowed. Your plan remains active until ${renewDateFormatted}, after which it will automatically shift to the Free tier.`, 'warning');
544
- }
545
-
546
- function resumeSubscription() {
547
- const resumeTier = (state.paidTier && state.paidTier !== 'free' && !isSubscriptionExpired()) ? state.paidTier : (state.currentTier !== 'free' ? state.currentTier : 'pro');
548
- state.currentTier = resumeTier;
549
- state.paidTier = resumeTier;
550
- state.cancelAtPeriodEnd = false;
551
- state.pendingDowngrade = null;
552
- state.creditsTotal = resumeTier === 'pro' ? 1000 : (resumeTier === 'enterprise' ? 10000 : 100);
553
-
554
- saveSessionToStorage();
555
- if (state.serverConnected) syncAuthWithServer();
556
- renderAllDynamicComponents();
557
- showToast(`🎉 Subscription resumed! Your ${TIER_DETAILS[resumeTier].name} is active again with no extra charge.`, 'success');
558
- }
559
-
560
- // Render and initialize Razorpay button UI
561
- function renderRazorpayButton(targetTier) {
562
- const isAnnual = state.billingCycle === 'annual';
563
- const p = state.pricing || {};
564
- const isProOffer = p.pro?.offerActive && !isAnnual && p.pro?.offerPriceINR !== undefined;
565
- const isEntOffer = p.enterprise?.offerActive && !isAnnual && p.enterprise?.offerPriceINR !== undefined;
566
- const inrAmount = targetTier === 'enterprise'
567
- ? (isEntOffer ? p.enterprise.offerPriceINR : (isAnnual ? (p.enterprise?.annualPriceINR ?? 37990) : (p.enterprise?.monthlyPriceINR ?? 3999)))
568
- : (isProOffer ? p.pro.offerPriceINR : (isAnnual ? (p.pro?.annualPriceINR ?? 45) : (p.pro?.monthlyPriceINR ?? 50)));
569
- const btnRzp = getEl('btn-razorpay-checkout');
570
- if (!btnRzp) return;
571
-
572
- btnRzp.disabled = false;
573
- btnRzp.innerHTML = `
574
- <i class="fa-solid fa-bolt text-warning" style="font-size: 18px;"></i>
575
- <span>Pay ₹${inrAmount.toLocaleString('en-IN')} with Razorpay / UPI</span>
576
- `;
577
- }
578
-
579
- // STEP 2: FRONTEND - Razorpay Standard Web Checkout Flow
580
- async function handleRazorpayCheckout() {
581
- const targetTier = pendingCheckoutTier || 'pro';
582
- const isAnnual = state.billingCycle === 'annual';
583
- const p = state.pricing || {};
584
- const isProOffer = p.pro?.offerActive && !isAnnual && p.pro?.offerPriceINR !== undefined;
585
- const isEntOffer = p.enterprise?.offerActive && !isAnnual && p.enterprise?.offerPriceINR !== undefined;
586
- const inrAmount = targetTier === 'enterprise'
587
- ? (isEntOffer ? p.enterprise.offerPriceINR : (isAnnual ? (p.enterprise?.annualPriceINR ?? 37990) : (p.enterprise?.monthlyPriceINR ?? 3999)))
588
- : (isProOffer ? p.pro.offerPriceINR : (isAnnual ? (p.pro?.annualPriceINR ?? 45) : (p.pro?.monthlyPriceINR ?? 50)));
589
- const amountInPaise = inrAmount * 100; // minimum 100 paise
590
-
591
- const btnRzp = getEl('btn-razorpay-checkout');
592
- if (btnRzp) {
593
- btnRzp.disabled = true;
594
- btnRzp.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Connecting to Razorpay...';
595
- }
596
-
597
- try {
598
- // Ensure Razorpay SDK is loaded
599
- if (typeof window.Razorpay !== 'function') {
600
- await new Promise((resolve, reject) => {
601
- const existingScript = document.querySelector('script[src*="checkout.razorpay.com"]');
602
- if (existingScript && window.Razorpay) return resolve();
603
-
604
- const script = document.createElement('script');
605
- script.src = 'https://checkout.razorpay.com/v1/checkout.js';
606
- script.async = true;
607
- script.onload = () => resolve();
608
- script.onerror = () => reject(new Error('Unable to load Razorpay checkout SDK. Please verify your internet connection.'));
609
- document.head.appendChild(script);
610
- });
611
- }
612
-
613
- // Determine safe API base URL for local CLI server if connected
614
- const isHttpsPage = window.location.protocol === 'https:';
615
- let safeApiBase = '';
616
- if (state.serverConnected && state.apiBaseUrl) {
617
- // Prevent mixed content: never request http:// from https://
618
- if (!(isHttpsPage && state.apiBaseUrl.startsWith('http://'))) {
619
- safeApiBase = state.apiBaseUrl;
620
- }
621
- } else if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
622
- safeApiBase = '';
623
- }
624
-
625
- // Fetch Razorpay key ID from backend if available, or use public key
626
- if (!state.razorpayKeyId && safeApiBase) {
627
- try {
628
- const configRes = await fetch(`${safeApiBase}/api/razorpay/config`, { method: 'GET' });
629
- if (configRes.ok) {
630
- const cfg = await configRes.json();
631
- if (cfg && cfg.key_id) {
632
- state.razorpayKeyId = cfg.key_id;
633
- }
634
- }
635
- } catch (err) {
636
- console.warn('Could not fetch razorpay key from server:', err);
637
- }
638
- }
639
-
640
- const keyId = state.razorpayKeyId || (window.RAZORPAY_KEY_ID || 'rzp_live_Tajz48jXVm0H1Y');
641
-
642
- // Attempt server-side order creation if backend server is available
643
- let orderId = null;
644
- if (safeApiBase || (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1')) {
645
- try {
646
- const controller = new AbortController();
647
- const timeoutId = setTimeout(() => controller.abort(), 4000);
648
- const orderRes = await fetch(`${safeApiBase}/api/create-order`, {
649
- method: 'POST',
650
- headers: { 'Content-Type': 'application/json' },
651
- body: JSON.stringify({
652
- amount: amountInPaise,
653
- currency: 'INR',
654
- receipt: `rcpt_${Date.now()}_${Math.floor(Math.random() * 1000)}`,
655
- notes: {
656
- tier: targetTier,
657
- billingCycle: isAnnual ? 'annual' : 'monthly',
658
- userEmail: state.user?.email || '',
659
- },
660
- }),
661
- signal: controller.signal,
662
- });
663
- clearTimeout(timeoutId);
664
-
665
- if (orderRes.ok) {
666
- const orderData = await orderRes.json();
667
- if (orderData && orderData.order_id) {
668
- orderId = orderData.order_id;
669
- }
670
- }
671
- } catch (orderErr) {
672
- console.warn('Server order creation unavailable or skipped, proceeding with direct checkout:', orderErr);
673
- }
674
- }
675
-
676
- if (typeof window.Razorpay !== 'function') {
677
- throw new Error('Razorpay SDK not loaded. Please ensure checkout.js is loaded.');
678
- }
679
-
680
- const options = {
681
- key: keyId,
682
- amount: amountInPaise,
683
- currency: 'INR',
684
- name: 'FrontTerrain Scout',
685
- description: `Scout ${targetTier.toUpperCase()} Plan (${isAnnual ? 'Annual' : 'Monthly'})`,
686
- image: 'https://scout.frontterrain.com/ScoutFavicon.png',
687
- handler: async function (response) {
688
- showToast('Payment successful! Activating subscription...', 'info');
689
-
690
- // If order_id was created and backend server is available, verify payment signature
691
- if (response.razorpay_order_id && response.razorpay_signature && safeApiBase) {
692
- try {
693
- const verifyRes = await fetch(`${safeApiBase}/api/verify-payment`, {
694
- method: 'POST',
695
- headers: { 'Content-Type': 'application/json' },
696
- body: JSON.stringify({
697
- order_id: response.razorpay_order_id,
698
- payment_id: response.razorpay_payment_id,
699
- signature: response.razorpay_signature,
700
- tier: targetTier,
701
- userEmail: state.user?.email || '',
702
- }),
703
- });
704
-
705
- const verifyData = await verifyRes.json();
706
- if (verifyRes.ok && verifyData.success) {
707
- applyTierUpgrade(targetTier, response.razorpay_payment_id);
708
- return;
709
- }
710
- } catch (err) {
711
- console.warn('Signature verification network error, activating client upgrade:', err);
712
- }
713
- }
714
-
715
- // Direct activation (standalone cloud web mode or client-side checkout)
716
- applyTierUpgrade(targetTier, response.razorpay_payment_id);
717
- },
718
- prefill: {
719
- name: state.user?.name || 'Developer',
720
- email: state.user?.email || 'developer@frontterrain.com',
721
- },
722
- notes: {
723
- tier: targetTier,
724
- billingCycle: isAnnual ? 'annual' : 'monthly',
725
- },
726
- theme: {
727
- color: '#175cd3',
728
- },
729
- modal: {
730
- ondismiss: function () {
731
- showToast('payment canceled.', 'warning');
732
- renderRazorpayButton(targetTier);
733
- },
734
- },
735
- };
736
-
737
- if (orderId) {
738
- options.order_id = orderId;
739
- }
740
-
741
- const rzp = new window.Razorpay(options);
742
-
743
- // Handle payment failure event
744
- rzp.on('payment.failed', function (resp) {
745
- console.error('Razorpay payment failed:', resp.error);
746
- showToast(`Payment failed: ${resp.error.description || resp.error.reason || 'Transaction could not be completed'}`, 'error');
747
- renderRazorpayButton(targetTier);
748
- });
749
-
750
- rzp.open();
751
-
752
- } catch (err) {
753
- console.error('Razorpay checkout error:', err);
754
- showToast(err.message || 'Failed to start Razorpay payment.', 'error');
755
- renderRazorpayButton(targetTier);
756
- }
757
- }
758
-
759
- // Render Official PayPal Checkout Smart Buttons inside modal
760
- function renderPayPalButtons(targetTier) {
761
- const container = getEl('paypal-button-container');
762
- if (!container) return;
763
- container.innerHTML = '';
764
-
765
- const isAnnual = state.billingCycle === 'annual';
766
- let unitPrice = targetTier === 'enterprise' ? (isAnnual ? 39 * 12 : 49) : (isAnnual ? 15 * 12 : 19);
767
- const amountStr = unitPrice.toFixed(2);
768
-
769
- if (window.paypal && typeof window.paypal.Buttons === 'function') {
770
- try {
771
- window.paypal.Buttons({
772
- style: {
773
- layout: 'vertical',
774
- color: 'gold',
775
- shape: 'rect',
776
- label: 'paypal',
777
- tagline: false,
778
- height: 44
779
- },
780
- createOrder: function (data, actions) {
781
- return actions.order.create({
782
- purchase_units: [{
783
- description: `FrontTerrain Scout ${targetTier.toUpperCase()} Plan (${isAnnual ? 'Annual' : 'Monthly'})`,
784
- amount: {
785
- currency_code: 'USD',
786
- value: amountStr
787
- }
788
- }]
789
- });
790
- },
791
- onApprove: async function (data, actions) {
792
- showToast('Verifying payment with PayPal...', 'info');
793
- try {
794
- const order = await actions.order.capture();
795
- const captureId = order.purchase_units?.[0]?.payments?.captures?.[0]?.id || order.id || data.orderID;
796
- applyTierUpgrade(targetTier, captureId);
797
- } catch (captureErr) {
798
- applyTierUpgrade(targetTier, data.orderID || 'COMPLETED');
799
- }
800
- },
801
- onCancel: function () {
802
- showToast('PayPal checkout was canceled.', 'warning');
803
- },
804
- onError: function (err) {
805
- console.error('PayPal Buttons Error:', err);
806
- showToast('PayPal checkout error. Please try again.', 'error');
807
- }
808
- }).render('#paypal-button-container');
809
- return;
810
- } catch (e) {
811
- console.error('PayPal Buttons render error:', e);
812
- }
813
- }
814
-
815
- // Fallback if PayPal SDK is blocked or still loading
816
- container.innerHTML = `
817
- <button type="button" class="btn btn-primary btn-lg btn-block" style="background: linear-gradient(135deg, #0079C1 0%, #00457C 100%); border-color: #0079C1; width: 100%; display: flex; align-items: center; justify-content: center; gap: 10px;" id="btn-fallback-paypal">
818
- <i class="fa-brands fa-paypal text-warning" style="font-size: 20px;"></i>
819
- <span>Pay with PayPal ($${amountStr})</span>
820
- </button>
821
- `;
822
- getEl('btn-fallback-paypal')?.addEventListener('click', () => {
823
- const txId = 'PAYID-' + Math.random().toString(36).substring(2, 11).toUpperCase();
824
- applyTierUpgrade(targetTier, txId);
825
- });
826
- }
827
-
828
- // Setup Event Handlers
829
- function initEventListeners() {
830
- // Auth Form Tabs Switcher
831
- getEl('tab-login-btn')?.addEventListener('click', () => switchAuthForm('login'));
832
- getEl('tab-signup-btn')?.addEventListener('click', () => switchAuthForm('signup'));
833
- getEl('tab-sso-btn')?.addEventListener('click', () => switchAuthForm('sso'));
834
-
835
- // Form Submissions
836
- getEl('login-form')?.addEventListener('submit', handleSignIn);
837
- getEl('signup-form')?.addEventListener('submit', handleSignUp);
838
- getEl('btn-demo-mode')?.addEventListener('click', launchDemoSession);
839
-
840
- // SSO & OAuth listeners
841
- getEl('btn-submit-sso')?.addEventListener('click', () => {
842
- const domain = (getEl('sso-domain')?.value || '').trim();
843
- if (!domain) {
844
- showToast('Please enter your company work email or organization domain.', 'warning');
845
- return;
846
- }
847
- showToast(`Routing to Enterprise SSO IdP for ${domain}...`, 'info');
848
- setTimeout(() => {
849
- showToast(`SSO Handshake established with ${domain}. Team seat license verified.`, 'success');
850
- }, 1200);
851
- });
852
-
853
- document.querySelectorAll('.btn-idp-provider').forEach(btn => {
854
- btn.addEventListener('click', (e) => {
855
- const idp = e.currentTarget.getAttribute('data-idp') || 'Okta';
856
- showToast(`Connecting to ${idp.replace('_', ' ').toUpperCase()} Single Sign-On...`, 'info');
857
- });
858
- });
859
-
860
- document.querySelectorAll('.btn-quick-oauth').forEach(btn => {
861
- btn.addEventListener('click', (e) => {
862
- const prov = e.currentTarget.getAttribute('data-provider') || 'OAuth';
863
- showToast(`Authenticating via ${prov.toUpperCase()} developer token...`, 'info');
864
- });
865
- });
866
-
867
- // Password Strength Checker
868
- getEl('signup-password')?.addEventListener('input', (e) => {
869
- const val = e.target.value;
870
- const bar = getEl('pwd-strength-bar');
871
- if (!bar) return;
872
-
873
- let strength = 0;
874
- if (val.length >= 6) strength += 33;
875
- if (/[A-Z]/.test(val) && /[0-9]/.test(val)) strength += 33;
876
- if (/[^A-Za-z0-9]/.test(val) && val.length >= 10) strength += 34;
877
-
878
- bar.style.width = `${strength}%`;
879
- bar.style.backgroundColor = strength < 40 ? '#ef4444' : strength < 80 ? '#eab308' : '#22c55e';
880
- });
881
-
882
- getEl('btn-forgot-pwd')?.addEventListener('click', (e) => {
883
- e.preventDefault();
884
- handleForgotPassword();
885
- });
886
-
887
- // User Dropdown Menu
888
- getEl('user-menu-toggle')?.addEventListener('click', (e) => {
889
- e.stopPropagation();
890
- getEl('user-dropdown')?.classList.toggle('show');
891
- });
892
-
893
- document.addEventListener('click', () => {
894
- getEl('user-dropdown')?.classList.remove('show');
895
- });
896
-
897
- getEl('btn-dropdown-logout')?.addEventListener('click', handleLogout);
898
- getEl('btn-account-logout')?.addEventListener('click', handleLogout);
899
-
900
- // Checkout Modal Events
901
- getEl('btn-close-checkout')?.addEventListener('click', closeCheckoutModal);
902
- getEl('btn-cancel-checkout')?.addEventListener('click', closeCheckoutModal);
903
- getEl('btn-razorpay-checkout')?.addEventListener('click', handleRazorpayCheckout);
904
-
905
- // Downgrade Modal Events
906
- getEl('btn-close-downgrade')?.addEventListener('click', closeDowngradeModal);
907
- getEl('btn-cancel-downgrade-modal')?.addEventListener('click', closeDowngradeModal);
908
- getEl('btn-confirm-schedule-downgrade')?.addEventListener('click', confirmScheduleDowngrade);
909
- getEl('btn-confirm-immediate-downgrade')?.addEventListener('click', confirmImmediateDowngrade);
910
- getEl('btn-banner-resume-plan')?.addEventListener('click', resumeSubscription);
911
-
912
- getEl('btn-confirm-checkout')?.addEventListener('click', async () => {
913
- if (!pendingCheckoutTier) return;
914
-
915
- const targetTier = pendingCheckoutTier;
916
- const tierInfo = TIER_DETAILS[targetTier];
917
- if (!tierInfo) return;
918
-
919
- const btn = getEl('btn-confirm-checkout');
920
- const origBtnHtml = btn ? btn.innerHTML : '';
921
- if (btn) {
922
- btn.disabled = true;
923
- btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Activating Plan...';
924
- }
925
-
926
- try {
927
- if (state.serverConnected && state.apiBaseUrl) {
928
- try {
929
- const res = await fetch(`${state.apiBaseUrl}/api/payment/create-checkout`, {
930
- method: 'POST',
931
- headers: { 'Content-Type': 'application/json' },
932
- body: JSON.stringify({
933
- tier: targetTier,
934
- billingCycle: state.billingCycle || 'monthly',
935
- returnUrl: window.location.origin + '/plans',
936
- email: state.user?.email,
937
- }),
938
- });
939
-
940
- const rawText = await res.text();
941
- const data = JSON.parse(rawText);
942
- if (data && data.success && data.checkoutUrl) {
943
- btn.innerHTML = '<i class="fa-brands fa-paypal"></i> Redirecting to PayPal...';
944
- window.location.href = data.checkoutUrl;
945
- return;
946
- }
947
- } catch { }
948
- }
949
-
950
- // Standalone Cloud Web Mode: Instant activation & upgrade without localhost
951
- setTimeout(() => {
952
- const txId = 'PAYID-' + Math.random().toString(36).substring(2, 11).toUpperCase();
953
- applyTierUpgrade(targetTier, txId);
954
- }, 600);
955
- } catch (err) {
956
- showToast(err.message || 'Payment processing failed.', 'error');
957
- if (btn) {
958
- btn.disabled = false;
959
- btn.innerHTML = origBtnHtml;
960
- }
961
- }
962
- });
963
-
964
- // Password Visibility Toggle Buttons
965
- document.querySelectorAll('.btn-toggle-pwd').forEach((btn) => {
966
- btn.addEventListener('click', () => {
967
- const targetId = btn.getAttribute('data-target');
968
- const input = getEl(targetId);
969
- if (input) {
970
- const isPwd = input.type === 'password';
971
- input.type = isPwd ? 'text' : 'password';
972
- btn.innerHTML = isPwd ? '<i class="fa-solid fa-eye-slash"></i>' : '<i class="fa-solid fa-eye"></i>';
973
- }
974
- });
975
- });
976
-
977
- // Profile Form Submission
978
- getEl('profile-form')?.addEventListener('submit', (e) => {
979
- e.preventDefault();
980
- const inputDisp = getEl('settings-display-name');
981
- const newName = inputDisp ? inputDisp.value.trim() : '';
982
- if (newName && state.user) {
983
- state.user.name = newName;
984
- saveSessionToStorage();
985
- syncAuthWithServer();
986
- updateUserUI();
987
- showToast('Profile display name updated successfully!', 'success');
988
- }
989
- });
990
-
991
- getEl('select-byok-provider')?.addEventListener('change', (e) => {
992
- const provider = e.target.value;
993
- const defaultEndpoints = {
994
- nvidia: 'https://integrate.api.nvidia.com/v1',
995
- gemini: 'https://generativelanguage.googleapis.com/v1beta/openai',
996
- openai: 'https://api.openai.com/v1',
997
- custom: 'http://localhost:11434/v1',
998
- };
999
- const epInput = getEl('input-byok-endpoint');
1000
- if (epInput && defaultEndpoints[provider]) {
1001
- epInput.value = defaultEndpoints[provider];
1002
- }
1003
- });
1004
-
1005
- // BYOK & Custom Proxy Form Submission
1006
- getEl('byok-form')?.addEventListener('submit', (e) => {
1007
- e.preventDefault();
1008
- state.customLlmProvider = getEl('select-byok-provider')?.value || 'nvidia';
1009
- state.customBaseUrl = getEl('input-byok-endpoint')?.value.trim() || '';
1010
- state.customApiKey = getEl('input-byok-key')?.value.trim() || '';
1011
- state.byokEnabled = getEl('checkbox-enable-byok')?.checked || false;
1012
-
1013
- localStorage.setItem('scout_byok_enabled', String(state.byokEnabled));
1014
- localStorage.setItem('scout_byok_provider', state.customLlmProvider);
1015
- localStorage.setItem('scout_byok_key', state.customApiKey);
1016
- localStorage.setItem('scout_byok_endpoint', state.customBaseUrl);
1017
-
1018
- syncAuthWithServer();
1019
- renderCreditUsageUI();
1020
- updateUserUI();
1021
-
1022
- if (state.byokEnabled) {
1023
- showToast('BYOK Mode Active! Requests now route through your custom API key/proxy endpoint (Scout credits bypassed).', 'success');
1024
- } else {
1025
- showToast('Endpoint configuration saved. Using standard Scout key.', 'info');
1026
- }
1027
- });
1028
-
1029
- getEl('checkbox-enable-byok')?.addEventListener('change', (e) => {
1030
- state.byokEnabled = e.target.checked;
1031
- localStorage.setItem('scout_byok_enabled', String(state.byokEnabled));
1032
- syncAuthWithServer();
1033
- renderCreditUsageUI();
1034
- });
1035
-
1036
- // Billing Cycle Toggle Switcher
1037
- getEl('toggle-billing-cycle')?.addEventListener('change', (e) => {
1038
- state.billingCycle = e.target.checked ? 'annual' : 'monthly';
1039
- renderTiersUI();
1040
- });
1041
-
1042
- // Tier Selection Buttons
1043
- document.querySelectorAll('.btn-select-tier').forEach((btn) => {
1044
- btn.addEventListener('click', () => {
1045
- const targetTier = btn.getAttribute('data-tier');
1046
- if (!targetTier || !TIER_DETAILS[targetTier]) return;
1047
-
1048
- const TIER_RANK = { free: 0, pro: 1, enterprise: 2 };
1049
- const currentRank = TIER_RANK[state.currentTier] || 0;
1050
- const targetRank = TIER_RANK[targetTier] || 0;
1051
-
1052
- // 1. Clicked Current Active Tier
1053
- if (targetTier === state.currentTier) {
1054
- showToast(`You are currently subscribed to the ${TIER_DETAILS[targetTier].name}.`, 'info');
1055
- return;
1056
- }
1057
-
1058
- // 2. Disallow Downgrade (from Pro/Enterprise to Free, or Enterprise to Pro)
1059
- if (currentRank > 0 && targetRank < currentRank) {
1060
- const renewFormatted = formatRenewDate(state.renewAt);
1061
- showToast(`Downgrading paid plans is not allowed. Your plan will automatically shift to the Free tier on ${renewFormatted}.`, 'warning');
1062
- return;
1063
- }
1064
-
1065
- // 3. Regular Upgrade via Checkout Modal
1066
- openCheckoutModal(targetTier);
1067
- });
1068
- });
1069
- }
1070
-
1071
- // FAQ Accordion Handler
1072
- function initFAQAccordions() {
1073
- document.querySelectorAll('.faq-question').forEach((btn) => {
1074
- btn.addEventListener('click', () => {
1075
- const item = btn.closest('.faq-item');
1076
- if (item) item.classList.toggle('open');
1077
- });
1078
- });
1079
- }
1080
-
1081
- // Interactive Team ROI & Seat Calculator for $10M MRR Scale
1082
- function initRoiCalculator() {
1083
- const slider = getEl('range-team-size');
1084
- if (!slider) return;
1085
-
1086
- function updateRoi() {
1087
- const teamSize = parseInt(slider.value, 10) || 15;
1088
- const hoursSaved = teamSize * 14; // ~14 hrs/mo per engineer on onboarding + test self-healing
1089
- const dollarsSaved = hoursSaved * 50; // $50/hr blended developer rate
1090
- const teamCost = teamSize * 49; // $49/seat/mo
1091
- const roiMultiplier = teamCost > 0 ? (dollarsSaved / teamCost).toFixed(1) : '14.0';
1092
-
1093
- if (getEl('calc-team-count')) getEl('calc-team-count').innerText = `${teamSize} Engineers`;
1094
- if (getEl('calc-hours-saved')) getEl('calc-hours-saved').innerText = `${hoursSaved.toLocaleString()} hrs`;
1095
- if (getEl('calc-dollars-saved')) getEl('calc-dollars-saved').innerText = `$${dollarsSaved.toLocaleString()}`;
1096
- if (getEl('calc-roi-multiplier')) getEl('calc-roi-multiplier').innerText = `${roiMultiplier}x`;
1097
- }
1098
-
1099
- slider.addEventListener('input', updateRoi);
1100
- updateRoi();
1101
- }
1102
-
1103
- // Interactive Web Terminal Simulator
1104
- function initTerminalSimulator() {
1105
- const form = getEl('cli-terminal-form');
1106
- const input = getEl('terminal-input-field');
1107
- const logs = getEl('terminal-logs');
1108
-
1109
- if (!form || !input || !logs) return;
1110
-
1111
- // Quick Command Chip Click Handlers
1112
- document.querySelectorAll('.btn-cli-chip').forEach((chip) => {
1113
- chip.addEventListener('click', () => {
1114
- const cmd = chip.getAttribute('data-cmd');
1115
- if (cmd) {
1116
- input.value = cmd;
1117
- runTerminalCommand(cmd);
1118
- }
1119
- });
1120
- });
1121
-
1122
- form.addEventListener('submit', (e) => {
1123
- e.preventDefault();
1124
- const cmd = input.value.trim();
1125
- if (cmd) {
1126
- runTerminalCommand(cmd);
1127
- input.value = '';
1128
- }
1129
- });
1130
-
1131
- function runTerminalCommand(cmd) {
1132
- const line = document.createElement('div');
1133
- line.className = 'terminal-line';
1134
- line.innerHTML = `<span class="prompt-user">developer@scout</span>:$ <span class="cmd-text">${escapeHtml(cmd)}</span>`;
1135
- logs.appendChild(line);
1136
-
1137
- const response = document.createElement('div');
1138
- response.style.margin = '4px 0 12px 0';
1139
-
1140
- const lower = cmd.toLowerCase().trim();
1141
- if (lower === 'clear') {
1142
- logs.innerHTML = '';
1143
- return;
1144
- } else if (lower === 'help' || lower === 'scout help' || lower === 'scout --help' || lower === 'scout') {
1145
- response.innerHTML = `
1146
- <span class="term-yellow">Available Scout Commands:</span><br>
1147
- ↳ <code>scout agent</code> - Launch autonomous AI co-pilot agent & reasoning loop<br>
1148
- ↳ <code>scout status</code> - Inspect CLI authentication, active workspace & credit balance<br>
1149
- ↳ <code>scout analyze</code> - Run instant AST codebase teardown and entry point indexing<br>
1150
- ↳ <code>scout teardown</code> - Generate strategic onboarding map & architectural moat report<br>
1151
- ↳ <code>scout byok</code> - Verify custom LLM proxy endpoint connection<br>
1152
- ↳ <code>clear</code> - Clear terminal buffer<br>
1153
- `;
1154
- } else if (lower.includes('agent')) {
1155
- response.innerHTML = `
1156
- <span class="term-bg-purple"> SCOUT AUTONOMOUS CO-PILOT AGENT </span><br>
1157
- <span class="term-green">✔ Agent Orchestrator active (Gemini 2.5 Flash / Deep Reasoning Engine)</span><br>
1158
- <span class="term-cyan">↳ Workspace Vector Memory:</span> 124 files indexed and loaded<br>
1159
- <span class="term-yellow">↳ Pair-Programming Status:</span> Ready for interactive tasks & refactoring loops<br>
1160
- `;
1161
- } else if (lower.includes('status')) {
1162
- response.innerHTML = `
1163
- <span class="term-green">✔ Scout CLI Engine: v9.5.1 Online</span><br>
1164
- ↳ User: <strong>${escapeHtml(state.user ? state.user.name : 'Guest Session')}</strong><br>
1165
- ↳ Active Subscription: <strong>${escapeHtml(TIER_DETAILS[state.currentTier].name)}</strong><br>
1166
- ↳ Credit Quota: <strong>${state.byokEnabled ? 'BYOK Mode (Unlimited)' : `${state.creditsUsed} / ${state.creditsTotal} Credits Used`}</strong><br>
1167
- `;
1168
- } else if (lower.includes('analyze') || lower.includes('teardown')) {
1169
- response.innerHTML = `
1170
- <span class="term-bg-cyan"> FRONTTERRAIN SCOUT AST ENGINE </span><br>
1171
- <span class="term-green">✔ Indexed 124 workspace files in 42ms.</span><br>
1172
- <span class="term-yellow">↳ Primary Entry Point:</span> src/index.ts<br>
1173
- <span class="term-purple">↳ Core Dependencies:</span> TypeScript, Commander, Clack, Express, Firebase SDK<br>
1174
- `;
1175
- } else if (lower.includes('byok')) {
1176
- response.innerHTML = `
1177
- <span class="term-yellow">↳ BYOK Mode Status:</span> ${state.byokEnabled ? '<span class="term-green">ACTIVE (Scout Credits Bypassed)</span>' : '<span class="term-dim">DISABLED (Using Scout Default Key)</span>'}<br>
1178
- ↳ Provider: ${escapeHtml(state.customLlmProvider)}<br>
1179
- ↳ Endpoint: ${escapeHtml(state.customBaseUrl || 'Default Proxy')}<br>
1180
- `;
1181
- } else {
1182
- response.innerHTML = `<span class="term-purple">scout: command not found: '${escapeHtml(cmd)}'. Type 'help' for available commands.</span>`;
1183
- }
1184
-
1185
- logs.appendChild(response);
1186
- logs.scrollTop = logs.scrollHeight;
1187
- }
1188
- }
1189
-
1190
- // Sessions Storage Loader
1191
- function loadSessionsFromStorage() {
1192
- try {
1193
- const stored = localStorage.getItem('scout_cli_sessions');
1194
- if (stored) {
1195
- state.sessions = JSON.parse(stored);
1196
- } else {
1197
- state.sessions = [
1198
- {
1199
- id: 'sess_local_1',
1200
- host: 'Local Workstation (FT-CLI)',
1201
- platform: 'Windows x64 Node.js',
1202
- lastActive: new Date().toISOString(),
1203
- ip: '127.0.2.1',
1204
- active: true,
1205
- },
1206
- ];
1207
- saveSessionsToStorage();
1208
- }
1209
- } catch {
1210
- state.sessions = [];
1211
- }
1212
- }
1213
-
1214
- function saveSessionsToStorage() {
1215
- try {
1216
- localStorage.setItem('scout_cli_sessions', JSON.stringify(state.sessions));
1217
- } catch { }
1218
- }
1219
-
1220
- function renderSessionsTable() {
1221
- const tbody = getEl('session-table-body');
1222
- const slotCounter = getEl('session-slot-counter');
1223
-
1224
- const tier = (state.currentTier || 'free').toLowerCase();
1225
- const maxSlots = tier === 'enterprise' ? 'Unlimited' : (tier === 'pro' ? 5 : 1);
1226
- const sessionCount = state.sessions && state.sessions.length > 0 ? state.sessions.length : 1;
1227
-
1228
- if (slotCounter) {
1229
- slotCounter.innerText = `${sessionCount} / ${maxSlots} Slots Used`;
1230
- if (typeof maxSlots === 'number' && sessionCount >= maxSlots) {
1231
- slotCounter.className = 'badge badge-warning';
1232
- } else {
1233
- slotCounter.className = 'badge badge-primary';
1234
- }
1235
- }
1236
-
1237
- if (!tbody) return;
1238
-
1239
- if (!state.sessions || state.sessions.length === 0) {
1240
- tbody.innerHTML = `
1241
- <tr>
1242
- <td colspan="4" class="empty-table-notice">No active CLI authorization sessions found.</td>
1243
- </tr>
1244
- `;
1245
- return;
1246
- }
1247
-
1248
- tbody.innerHTML = state.sessions
1249
- .map((sess) => {
1250
- return `
1251
- <tr data-id="${escapeHtml(sess.id)}">
1252
- <td>
1253
- <div class="flex-center-gap" style="display: flex; align-items: center; gap: 8px;">
1254
- <i class="fa-solid fa-terminal text-primary"></i>
1255
- <div>
1256
- <strong>${escapeHtml(sess.host)}</strong>
1257
- <small class="block text-muted">${escapeHtml(sess.platform)}</small>
1258
- </div>
1259
- </div>
1260
- </td>
1261
- <td><span class="badge badge-success">${escapeHtml(timeAgo(sess.lastActive))}</span></td>
1262
- <td><code>${escapeHtml(sess.ip)}</code></td>
1263
- <td><button class="btn btn-xs btn-outline text-danger btn-revoke-session" data-session-id="${escapeHtml(sess.id)}" onclick="revokeSession('${escapeHtml(sess.id)}')"><i class="fa-solid fa-trash"></i> Revoke</button></td>
1264
- </tr>
1265
- `;
1266
- })
1267
- .join('');
1268
- }
1269
-
1270
- function revokeSession(sessionId) {
1271
- state.sessions = state.sessions.filter(s => s.id !== sessionId);
1272
- saveSessionsToStorage();
1273
- renderSessionsTable();
1274
- showToast('CLI access session revoked.', 'info');
1275
- }
1276
-
1277
- // Render Dynamic Credit Usage & BYOK Status UI
1278
- function renderCreditUsageUI() {
1279
- const byokStatusBadge = getEl('byok-status-badge');
1280
- const creditStatusBadge = getEl('credit-status-badge');
1281
- const valUsed = getEl('val-credits-used');
1282
- const valRemaining = getEl('val-credits-remaining');
1283
- const valTotal = getEl('val-credits-total');
1284
- const valPct = getEl('val-credits-pct');
1285
- const progressFill = getEl('credit-progress-fill');
1286
- const labelConsumption = getEl('label-credit-consumption');
1287
- const byokNote = getEl('byok-banner-note');
1288
- const valRenew = getEl('val-renew-datetime');
1289
-
1290
- if (state.byokEnabled) {
1291
- if (byokStatusBadge) {
1292
- byokStatusBadge.innerText = 'BYOK Mode Active';
1293
- byokStatusBadge.className = 'badge badge-accent';
1294
- }
1295
- if (creditStatusBadge) {
1296
- creditStatusBadge.innerText = 'Custom Endpoint Active';
1297
- creditStatusBadge.className = 'badge badge-accent';
1298
- }
1299
- if (valUsed) valUsed.innerText = 'Unmonitored';
1300
- if (valRemaining) valRemaining.innerText = 'Unlimited (BYOK)';
1301
- if (valTotal) valTotal.innerText = 'Custom Provider';
1302
- if (valPct) valPct.innerText = 'BYOK';
1303
-
1304
- if (progressFill) {
1305
- progressFill.style.width = '100%';
1306
- progressFill.style.background = 'linear-gradient(90deg, #a855f7 0%, #ec4899 100%)';
1307
- }
1308
-
1309
- if (labelConsumption) {
1310
- labelConsumption.innerText = 'Direct Custom Endpoint Routing (Scout Credits Bypassed)';
1311
- }
1312
-
1313
- if (byokNote) byokNote.classList.remove('hidden');
1314
- } else {
1315
- if (byokStatusBadge) {
1316
- byokStatusBadge.innerText = 'Scout Default';
1317
- byokStatusBadge.className = 'badge';
1318
- }
1319
- if (creditStatusBadge) {
1320
- creditStatusBadge.innerText = 'Quota Active';
1321
- creditStatusBadge.className = 'badge badge-success';
1322
- }
1323
-
1324
- const defaultTotal = state.currentTier === 'pro' ? 1000 : state.currentTier === 'enterprise' ? 10000 : 100;
1325
- const total = state.creditsTotal || defaultTotal;
1326
- const used = state.creditsUsed || 0;
1327
- const remaining = Math.max(0, total - used);
1328
- const pct = Math.min(100, Math.round((used / total) * 100));
1329
-
1330
- if (valUsed) valUsed.innerText = used.toLocaleString();
1331
- if (valRemaining) valRemaining.innerText = remaining.toLocaleString();
1332
- if (valTotal) valTotal.innerText = total.toLocaleString();
1333
- if (valPct) valPct.innerText = `${pct}%`;
1334
-
1335
- if (progressFill) {
1336
- progressFill.style.width = `${pct}%`;
1337
- progressFill.style.background = 'linear-gradient(90deg, #6366f1 0%, #38bdf8 60%, #34d399 100%)';
1338
- }
1339
-
1340
- if (labelConsumption) {
1341
- labelConsumption.innerText = 'Monthly Credit Consumption';
1342
- }
1343
-
1344
- if (byokNote) byokNote.classList.add('hidden');
1345
- }
1346
-
1347
- let renewDateStr = '';
1348
- if (state.renewAt) {
1349
- const d = new Date(state.renewAt);
1350
- if (!isNaN(d.getTime())) {
1351
- renewDateStr = `${d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })} at 00:00:00 UTC`;
1352
- }
1353
- }
1354
- if (!renewDateStr) {
1355
- const now = new Date();
1356
- const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
1357
- renewDateStr = `${nextMonth.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })} at 00:00:00 UTC`;
1358
- }
1359
-
1360
- if (valRenew) {
1361
- if (state.cancelAtPeriodEnd && state.currentTier !== 'free') {
1362
- valRenew.innerHTML = `${renewDateStr} <span style="color: #eab308; font-weight: 600; margin-left: 6px;">(Cancels at period end)</span>`;
1363
- } else {
1364
- valRenew.innerText = renewDateStr;
1365
- }
1366
- }
1367
- }
1368
-
1369
- // Render Paid Tiers UI
1370
- function renderTiersUI() {
1371
- const current = TIER_DETAILS[state.currentTier] || TIER_DETAILS.free;
1372
- const formattedDate = formatRenewDate(state.renewAt);
1373
-
1374
- if (getEl('current-plan-title')) getEl('current-plan-title').innerText = current.name;
1375
- if (getEl('tier-active-icon')) getEl('tier-active-icon').innerHTML = current.icon;
1376
-
1377
- if (getEl('current-plan-badge')) {
1378
- getEl('current-plan-badge').innerText = 'ACTIVE';
1379
- getEl('current-plan-badge').className = 'badge badge-success';
1380
- }
1381
-
1382
- if (getEl('current-plan-desc')) {
1383
- if (state.currentTier !== 'free') {
1384
- getEl('current-plan-desc').innerText = `Your ${current.name} is active until ${formattedDate}. Paid plans cannot be downgraded; upon reaching expiration time, your account will automatically shift to the Free tier.`;
1385
- } else {
1386
- getEl('current-plan-desc').innerText = current.desc;
1387
- }
1388
- }
1389
-
1390
- const bannerResumeBtn = getEl('btn-banner-resume-plan');
1391
- if (bannerResumeBtn) {
1392
- bannerResumeBtn.classList.add('hidden');
1393
- }
1394
-
1395
- const isAnnual = state.billingCycle === 'annual';
1396
- const p = state.pricing || {};
1397
- const isProOffer = p.pro?.offerActive && !isAnnual && p.pro?.offerPriceUSD !== undefined;
1398
- const isTeamOffer = p.team?.offerActive && !isAnnual && p.team?.offerPriceUSD !== undefined;
1399
- const isEntOffer = p.enterprise?.offerActive && !isAnnual && p.enterprise?.offerPriceUSD !== undefined;
1400
-
1401
- const proUSD = isProOffer ? p.pro.offerPriceUSD : (isAnnual ? (p.pro?.annualPriceUSD ?? 15) : (p.pro?.monthlyPriceUSD ?? 19));
1402
- const teamUSD = isTeamOffer ? p.team.offerPriceUSD : (isAnnual ? (p.team?.annualPriceUSD ?? 39) : (p.team?.monthlyPriceUSD ?? 49));
1403
- const entUSD = isEntOffer ? p.enterprise.offerPriceUSD : (isAnnual ? (p.enterprise?.annualPriceUSD ?? 79) : (p.enterprise?.monthlyPriceUSD ?? 99));
1404
-
1405
- if (getEl('price-pro-val')) {
1406
- if (isProOffer && p.pro?.monthlyPriceUSD) {
1407
- getEl('price-pro-val').innerHTML = `<s style="font-size: 0.55em; opacity: 0.55; margin-right: 6px;">$${p.pro.monthlyPriceUSD}</s>$${proUSD}`;
1408
- } else {
1409
- getEl('price-pro-val').innerText = proUSD;
1410
- }
1411
- }
1412
- if (getEl('price-pro-period')) getEl('price-pro-period').innerText = isProOffer ? `/ month (${p.pro?.offerBadge || 'PROMO OFFER'})` : (isAnnual ? '/ month (billed annually)' : '/ month');
1413
- const proCurrency = document.querySelector('#tier-card-pro .price-currency');
1414
- if (proCurrency) proCurrency.innerText = isProOffer ? '' : '$';
1415
-
1416
- if (getEl('price-team-val')) {
1417
- if (isTeamOffer && p.team?.monthlyPriceUSD) {
1418
- getEl('price-team-val').innerHTML = `<s style="font-size: 0.55em; opacity: 0.55; margin-right: 6px;">$${p.team.monthlyPriceUSD}</s>$${teamUSD}`;
1419
- } else {
1420
- getEl('price-team-val').innerText = teamUSD;
1421
- }
1422
- }
1423
- if (getEl('price-team-period')) getEl('price-team-period').innerText = isTeamOffer ? `/ seat / mo (${p.team?.offerBadge || 'TEAM PROMO'})` : (isAnnual ? '/ seat / mo (billed annually)' : '/ seat / mo');
1424
-
1425
- if (getEl('price-ent-val')) {
1426
- if (isEntOffer && p.enterprise?.monthlyPriceUSD) {
1427
- getEl('price-ent-val').innerHTML = `<s style="font-size: 0.55em; opacity: 0.55; margin-right: 6px;">$${p.enterprise.monthlyPriceUSD}</s>$${entUSD}`;
1428
- } else {
1429
- getEl('price-ent-val').innerText = entUSD;
1430
- }
1431
- }
1432
- if (getEl('price-ent-period')) getEl('price-ent-period').innerText = isEntOffer ? `/ seat / mo (${p.enterprise?.offerBadge || 'PROMO OFFER'})` : (isAnnual ? '/ seat / mo (billed annually)' : '/ seat / mo');
1433
- const entCurrency = document.querySelector('#tier-card-enterprise .price-currency');
1434
- if (entCurrency) entCurrency.innerText = isEntOffer ? '' : '$';
1435
-
1436
- const tierRankMap = { free: 0, pro: 1, team: 2, enterprise: 3 };
1437
- const curRank = tierRankMap[state.currentTier] || 0;
1438
-
1439
- ['free', 'pro', 'team', 'enterprise'].forEach((t) => {
1440
- const card = getEl(`tier-card-${t}`);
1441
- const btn = getEl(`btn-tier-${t}`);
1442
- if (!card || !btn) return;
1443
-
1444
- if (t === state.currentTier) {
1445
- card.classList.add('active-tier-card');
1446
- btn.className = (t === 'enterprise' ? 'btn btn-warning' : (t === 'team' ? 'btn btn-info' : (t === 'pro' ? 'btn btn-primary' : 'btn btn-success'))) + ' btn-block btn-select-tier';
1447
- btn.innerText = 'Current Plan';
1448
- btn.disabled = true;
1449
- } else {
1450
- card.classList.remove('active-tier-card');
1451
- const targetRank = tierRankMap[t] || 0;
1452
- if (targetRank < curRank) {
1453
- btn.disabled = true;
1454
- btn.className = 'btn btn-outline btn-block btn-select-tier';
1455
- btn.innerHTML = '<i class="fa-solid fa-lock" style="font-size: 11px; margin-right: 4px;"></i> Downgrades Disabled';
1456
- btn.title = `Paid plans cannot be downgraded during an active billing cycle.`;
1457
- } else {
1458
- btn.disabled = false;
1459
- btn.className = (t === 'team' ? 'btn btn-primary' : 'btn btn-outline') + ' btn-block btn-select-tier';
1460
- btn.innerText = t === 'team' ? 'Upgrade to Team' : `Upgrade to ${t.charAt(0).toUpperCase() + t.slice(1)}`;
1461
- }
1462
- }
1463
- });
1464
- }
1465
-
1466
- // Sync with Local Server CLI Session
1467
- async function checkServerStatusAndSession() {
1468
- let connected = false;
1469
- let data = null;
1470
-
1471
- // Only attempt direct relative path if running locally or via file protocol
1472
- const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' || window.location.protocol === 'file:';
1473
-
1474
- if (isLocalhost) {
1475
- try {
1476
- const res = await fetch('/api/status', { method: 'GET' });
1477
- if (res.ok) {
1478
- data = await res.json();
1479
- if (data && data.status === 'ok') {
1480
- state.apiBaseUrl = '';
1481
- connected = true;
1482
- }
1483
- }
1484
- } catch { }
1485
- }
1486
-
1487
- if (!connected) {
1488
- const candidateHosts = ['http://localhost:9120', 'http://127.0.0.1:9120', 'http://localhost:9121', 'http://localhost:9122'];
1489
- for (const host of candidateHosts) {
1490
- try {
1491
- const controller = new AbortController();
1492
- const timeoutId = setTimeout(() => controller.abort(), 1200);
1493
- const res = await fetch(`${host}/api/status`, { method: 'GET', signal: controller.signal });
1494
- clearTimeout(timeoutId);
1495
- if (res.ok) {
1496
- data = await res.json();
1497
- if (data && data.status === 'ok') {
1498
- state.apiBaseUrl = host;
1499
- connected = true;
1500
- break;
1501
- }
1502
- }
1503
- } catch { }
1504
- }
1505
- }
1506
-
1507
- if (connected && data) {
1508
- state.serverConnected = true;
1509
-
1510
- if (data.isLoggedIn && data.auth?.user) {
1511
- state.user = data.auth.user;
1512
- state.token = data.auth.token;
1513
- state.refreshToken = data.auth.refreshToken;
1514
-
1515
- if (typeof data.auth.creditsUsed === 'number') state.creditsUsed = data.auth.creditsUsed;
1516
- if (typeof data.auth.creditsTotal === 'number') state.creditsTotal = data.auth.creditsTotal;
1517
- if (data.auth.currentTier) state.currentTier = data.auth.currentTier;
1518
- if (data.auth.renewAt) state.renewAt = data.auth.renewAt;
1519
- if (typeof data.auth.cancelAtPeriodEnd === 'boolean') state.cancelAtPeriodEnd = data.auth.cancelAtPeriodEnd;
1520
- if (data.auth.pendingDowngrade !== undefined) state.pendingDowngrade = data.auth.pendingDowngrade;
1521
- if (data.auth.paidTier !== undefined) state.paidTier = data.auth.paidTier;
1522
- if (typeof data.auth.byokEnabled === 'boolean') state.byokEnabled = data.auth.byokEnabled;
1523
- if (data.auth.customLlmProvider) state.customLlmProvider = data.auth.customLlmProvider;
1524
- if (typeof data.auth.customApiKey === 'string') state.customApiKey = data.auth.customApiKey;
1525
- if (typeof data.auth.customBaseUrl === 'string') state.customBaseUrl = data.auth.customBaseUrl;
1526
-
1527
- saveSessionToStorage();
1528
- showDashboard();
1529
- updateUserUI();
1530
- renderCreditUsageUI();
1531
- renderSessionsTable();
1532
- return;
1533
- }
1534
- }
1535
-
1536
- state.serverConnected = false;
1537
- checkLocalStorageSession();
1538
- }
1539
-
1540
- function checkLocalStorageSession() {
1541
- try {
1542
- const storedUser = localStorage.getItem('scout_auth_user');
1543
- const storedToken = localStorage.getItem('scout_auth_token');
1544
-
1545
- if (storedUser && storedToken) {
1546
- state.user = JSON.parse(storedUser);
1547
- state.token = storedToken;
1548
- state.refreshToken = localStorage.getItem('scout_refresh_token') || '';
1549
-
1550
- showDashboard();
1551
- updateUserUI();
1552
- return;
1553
- }
1554
- } catch (err) {
1555
- console.error('Saved session parse error:', err);
1556
- }
1557
-
1558
- showAuthSection();
1559
- }
1560
-
1561
- // Switch Auth View Forms
1562
- function switchAuthForm(mode) {
1563
- const tabLogin = getEl('tab-login-btn');
1564
- const tabSignup = getEl('tab-signup-btn');
1565
- const tabSso = getEl('tab-sso-btn');
1566
- const formLogin = getEl('login-form');
1567
- const formSignup = getEl('signup-form');
1568
- const formSso = getEl('sso-form');
1569
-
1570
- tabLogin?.classList.toggle('active', mode === 'login');
1571
- tabSignup?.classList.toggle('active', mode === 'signup');
1572
- tabSso?.classList.toggle('active', mode === 'sso');
1573
-
1574
- formLogin?.classList.toggle('hidden', mode !== 'login');
1575
- formSignup?.classList.toggle('hidden', mode !== 'signup');
1576
- formSso?.classList.toggle('hidden', mode !== 'sso');
1577
- }
1578
-
1579
- // Handle Sign In Submission
1580
- async function handleSignIn(e) {
1581
- e.preventDefault();
1582
- const email = getEl('login-email')?.value.trim();
1583
- const password = getEl('login-password')?.value;
1584
- const btnSubmit = getEl('btn-submit-login');
1585
-
1586
- if (!email || !password) return;
1587
-
1588
- // Check Master Admin Credentials
1589
- const AUTHORIZED_ADMIN_EMAILS = [
1590
- 'rishishandilya40@gmail.com',
1591
- 'rishi.shandilya@frontterrain.com',
1592
- 'company@frontterrain.com'
1593
- ];
1594
- const isMasterAdminAuth = AUTHORIZED_ADMIN_EMAILS.includes(email.toLowerCase().trim()) && password === 'scout_admin_2026';
1595
- if (isMasterAdminAuth) {
1596
- if (state.serverConnected) {
1597
- try {
1598
- const adminLoginRes = await fetch(`${state.apiBaseUrl}/api/admin/login`, {
1599
- method: 'POST',
1600
- headers: { 'Content-Type': 'application/json' },
1601
- body: JSON.stringify({ email: email.trim(), passkey: password }),
1602
- });
1603
- if (adminLoginRes.ok) {
1604
- const adminData = await adminLoginRes.json();
1605
- if (adminData.success && adminData.token) {
1606
- state.token = adminData.token;
1607
- state.refreshToken = 'rt_' + Date.now().toString(36);
1608
- state.user = {
1609
- id: 'usr_admin_001',
1610
- email: email,
1611
- name: 'Scout Administrator',
1612
- createdAt: new Date().toISOString(),
1613
- };
1614
- state.currentTier = 'pro';
1615
- state.creditsTotal = 1000;
1616
- state.creditsUsed = 0;
1617
- sessionStorage.setItem('scout_admin_token', adminData.token);
1618
- saveSessionToStorage();
1619
- updateUserUI();
1620
- showToast('Authenticated as Scout Administrator! Redirecting to Control Center...', 'success');
1621
- setTimeout(() => { window.location.href = '/admin'; }, 400);
1622
- return;
1623
- }
1624
- }
1625
- } catch { }
1626
- }
1627
-
1628
- // Standalone fallback
1629
- state.token = 'scout_admin_token_' + Date.now().toString(36);
1630
- state.refreshToken = 'rt_' + Date.now().toString(36);
1631
- state.user = {
1632
- id: 'usr_admin_001',
1633
- email: email,
1634
- name: 'Scout Administrator',
1635
- createdAt: new Date().toISOString(),
1636
- };
1637
- state.currentTier = 'pro';
1638
- state.creditsTotal = 1000;
1639
- state.creditsUsed = 0;
1640
- sessionStorage.setItem('scout_admin_token', 'scout_admin_standalone_' + Date.now());
1641
- saveSessionToStorage();
1642
- updateUserUI();
1643
- showToast('Authenticated as Scout Administrator! Redirecting to Control Center...', 'success');
1644
- setTimeout(() => { window.location.href = '/admin'; }, 400);
1645
- return;
1646
- }
1647
-
1648
- if (btnSubmit) {
1649
- btnSubmit.disabled = true;
1650
- btnSubmit.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Authenticating...';
1651
- }
1652
-
1653
- try {
1654
- let authRes;
1655
- if (state.serverConnected) {
1656
- const res = await fetch(`${state.apiBaseUrl}/api/login`, {
1657
- method: 'POST',
1658
- headers: { 'Content-Type': 'application/json' },
1659
- body: JSON.stringify({ email, password }),
1660
- });
1661
- const data = await res.json();
1662
- if (!res.ok || !data.success) {
1663
- throw new Error(data.error || 'Server authentication failed.');
1664
- }
1665
- authRes = data.auth;
1666
- } else {
1667
- authRes = await apiFirebaseSignIn(email, password);
1668
- }
1669
-
1670
- state.token = authRes.token || authRes.idToken;
1671
- state.refreshToken = authRes.refreshToken;
1672
- state.user = authRes.user || {
1673
- id: authRes.localId || 'usr_' + Date.now().toString(36),
1674
- email: authRes.email || email,
1675
- name: authRes.displayName || email.split('@')[0],
1676
- createdAt: new Date().toISOString(),
1677
- };
1678
-
1679
- saveSessionToStorage();
1680
- syncAuthWithServer();
1681
- updateUserUI();
1682
- showToast(`Signed in successfully as ${state.user.name}!`, 'success');
1683
-
1684
- if (getCurrentPage() === '/auth') {
1685
- setTimeout(() => { window.location.href = 'index.html'; }, 400);
1686
- } else {
1687
- showDashboard();
1688
- }
1689
- } catch (error) {
1690
- showToast(error.message || 'Login failed.', 'error');
1691
- } finally {
1692
- if (btnSubmit) {
1693
- btnSubmit.disabled = false;
1694
- btnSubmit.innerHTML = '<span>Sign In to Scout</span><i class="fa-solid fa-arrow-right"></i>';
1695
- }
1696
- }
1697
- }
1698
-
1699
- // Handle Sign Up Submission
1700
- async function handleSignUp(e) {
1701
- e.preventDefault();
1702
- const name = getEl('signup-name')?.value.trim();
1703
- const email = getEl('signup-email')?.value.trim();
1704
- const password = getEl('signup-password')?.value;
1705
- const confirmPassword = getEl('signup-confirm-password')?.value;
1706
- const btnSubmit = getEl('btn-submit-signup');
1707
-
1708
- if (password !== confirmPassword) {
1709
- showToast('Passwords do not match.', 'error');
1710
- return;
1711
- }
1712
-
1713
- if (btnSubmit) {
1714
- btnSubmit.disabled = true;
1715
- btnSubmit.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Creating Account...';
1716
- }
1717
-
1718
- try {
1719
- let authRes;
1720
- if (state.serverConnected) {
1721
- const res = await fetch(`${state.apiBaseUrl}/api/signup`, {
1722
- method: 'POST',
1723
- headers: { 'Content-Type': 'application/json' },
1724
- body: JSON.stringify({ name, email, password }),
1725
- });
1726
- const data = await res.json();
1727
- if (!res.ok || !data.success) {
1728
- throw new Error(data.error || 'Server registration failed.');
1729
- }
1730
- authRes = data.auth;
1731
- } else {
1732
- authRes = await apiFirebaseSignUp(name, email, password);
1733
- }
1734
-
1735
- state.token = authRes.token || authRes.idToken;
1736
- state.refreshToken = authRes.refreshToken;
1737
- state.user = authRes.user || {
1738
- id: authRes.localId || 'usr_' + Date.now().toString(36),
1739
- email: authRes.email || email,
1740
- name: name,
1741
- createdAt: new Date().toISOString(),
1742
- };
1743
-
1744
- saveSessionToStorage();
1745
- syncAuthWithServer();
1746
- updateUserUI();
1747
- showToast(`Account created! Welcome to FrontTerrain, ${name}.`, 'success');
1748
-
1749
- if (getCurrentPage() === '/auth') {
1750
- setTimeout(() => { window.location.href = 'index.html'; }, 400);
1751
- } else {
1752
- showDashboard();
1753
- }
1754
- } catch (error) {
1755
- showToast(error.message || 'Registration failed.', 'error');
1756
- } finally {
1757
- if (btnSubmit) {
1758
- btnSubmit.disabled = false;
1759
- btnSubmit.innerHTML = '<span>Create Scout Account</span><i class="fa-solid fa-user-check"></i>';
1760
- }
1761
- }
1762
- }
1763
-
1764
- function handleForgotPassword() {
1765
- const email = prompt('Enter your registered email address for password reset:');
1766
- if (email && email.includes('@')) {
1767
- showToast(`Password reset link dispatched to ${email}`, 'success');
1768
- } else if (email) {
1769
- showToast('Please enter a valid email address.', 'error');
1770
- }
1771
- }
1772
-
1773
- // Demo Session Launcher
1774
- function launchDemoSession() {
1775
- state.token = 'ft_demo_token_' + Date.now().toString(36);
1776
- state.user = {
1777
- id: 'usr_demo_' + Math.floor(1000 + Math.random() * 9000),
1778
- email: 'developer@frontterrain.com',
1779
- name: 'FrontTerrain Developer',
1780
- createdAt: new Date().toISOString(),
1781
- };
1782
-
1783
- saveSessionToStorage();
1784
- syncAuthWithServer();
1785
- updateUserUI();
1786
- showToast('Demo Developer Session Active!', 'info');
1787
-
1788
- if (getCurrentPage() === '/auth') {
1789
- setTimeout(() => { window.location.href = 'index.html'; }, 300);
1790
- } else {
1791
- showDashboard();
1792
- }
1793
- }
1794
-
1795
- // Firebase Direct REST API
1796
- async function apiFirebaseSignIn(email, password) {
1797
- const url = `${FIREBASE_CONFIG.baseAuthUrl}:signInWithPassword?key=${FIREBASE_CONFIG.apiKey}`;
1798
- const response = await fetch(url, {
1799
- method: 'POST',
1800
- headers: { 'Content-Type': 'application/json' },
1801
- body: JSON.stringify({
1802
- email,
1803
- password,
1804
- returnSecureToken: true,
1805
- tenantId: FIREBASE_CONFIG.tenantId,
1806
- }),
1807
- });
1808
-
1809
- const data = await response.json();
1810
- if (!response.ok) {
1811
- throw new Error(parseFirebaseError(data, 'Firebase sign in failed'));
1812
- }
1813
- return data;
1814
- }
1815
-
1816
- async function apiFirebaseSignUp(name, email, password) {
1817
- const url = `${FIREBASE_CONFIG.baseAuthUrl}:signUp?key=${FIREBASE_CONFIG.apiKey}`;
1818
- const response = await fetch(url, {
1819
- method: 'POST',
1820
- headers: { 'Content-Type': 'application/json' },
1821
- body: JSON.stringify({
1822
- email,
1823
- password,
1824
- returnSecureToken: true,
1825
- tenantId: FIREBASE_CONFIG.tenantId,
1826
- }),
1827
- });
1828
-
1829
- const data = await response.json();
1830
- if (!response.ok) {
1831
- throw new Error(parseFirebaseError(data, 'Firebase sign up failed'));
1832
- }
1833
-
1834
- try {
1835
- const updateUrl = `${FIREBASE_CONFIG.baseAuthUrl}:update?key=${FIREBASE_CONFIG.apiKey}`;
1836
- await fetch(updateUrl, {
1837
- method: 'POST',
1838
- headers: { 'Content-Type': 'application/json' },
1839
- body: JSON.stringify({
1840
- idToken: data.idToken,
1841
- displayName: name,
1842
- tenantId: FIREBASE_CONFIG.tenantId,
1843
- }),
1844
- });
1845
- data.displayName = name;
1846
- } catch { }
1847
-
1848
- return data;
1849
- }
1850
-
1851
- function parseFirebaseError(errData, defaultMsg) {
1852
- const code = errData?.error?.message || errData?.message || '';
1853
- if (code.includes('EMAIL_NOT_FOUND')) return 'No account found with this email.';
1854
- if (code.includes('INVALID_PASSWORD') || code.includes('INVALID_LOGIN_CREDENTIALS')) return 'Invalid password entered.';
1855
- if (code.includes('EMAIL_EXISTS')) return 'An account already exists with this email.';
1856
- if (code.includes('WEAK_PASSWORD')) return 'Password is too weak (min 6 chars).';
1857
- if (code.includes('INVALID_EMAIL')) return 'Invalid email address format.';
1858
- if (code.includes('TOO_MANY_ATTEMPTS_TRY_LATER')) return 'Too many login attempts. Try later.';
1859
- return `${defaultMsg}: ${code || 'Unknown error'}`;
1860
- }
1861
-
1862
- // UI State Renderers
1863
- function showAuthSection() {
1864
- const authSec = getEl('auth-section');
1865
- const dashSec = getEl('dashboard-section');
1866
- const userMenu = getEl('user-menu');
1867
- const btnOpenAuth = getEl('btn-open-auth');
1868
-
1869
- if (authSec) authSec.classList.remove('hidden');
1870
- if (dashSec) dashSec.classList.add('hidden');
1871
- if (userMenu) userMenu.classList.add('hidden');
1872
- if (btnOpenAuth) btnOpenAuth.classList.remove('hidden');
1873
- }
1874
-
1875
- function showDashboard() {
1876
- const authSec = getEl('auth-section');
1877
- const dashSec = getEl('dashboard-section');
1878
- const userMenu = getEl('user-menu');
1879
- const btnOpenAuth = getEl('btn-open-auth');
1880
-
1881
- if (authSec) authSec.classList.add('hidden');
1882
- if (dashSec) dashSec.classList.remove('hidden');
1883
- if (userMenu) userMenu.classList.remove('hidden');
1884
- if (btnOpenAuth) btnOpenAuth.classList.add('hidden');
1885
-
1886
- renderAllDynamicComponents();
1887
- checkAdminStatus();
1888
- }
1889
-
1890
- function updateUserUI() {
1891
- if (!state.user) {
1892
- const userMenu = getEl('user-menu');
1893
- const btnOpenAuth = getEl('btn-open-auth');
1894
- if (userMenu) userMenu.classList.add('hidden');
1895
- if (btnOpenAuth) btnOpenAuth.classList.remove('hidden');
1896
- hideAdminNavigationLink();
1897
- return;
1898
- }
1899
-
1900
- const userMenu = getEl('user-menu');
1901
- const btnOpenAuth = getEl('btn-open-auth');
1902
- if (userMenu) userMenu.classList.remove('hidden');
1903
- if (btnOpenAuth) btnOpenAuth.classList.add('hidden');
1904
-
1905
- const name = state.user.name || 'Developer';
1906
- const initial = name.charAt(0).toUpperCase();
1907
-
1908
- if (getEl('nav-avatar')) getEl('nav-avatar').innerText = initial;
1909
- if (getEl('nav-user-name')) getEl('nav-user-name').innerText = name;
1910
- if (getEl('user-display-name')) getEl('user-display-name').innerText = name;
1911
- if (getEl('dropdown-name')) getEl('dropdown-name').innerText = name;
1912
- if (getEl('dropdown-email')) getEl('dropdown-email').innerText = state.user.email;
1913
-
1914
- if (getEl('sidebar-nav-avatar')) getEl('sidebar-nav-avatar').innerText = initial;
1915
- if (getEl('sidebar-user-name')) getEl('sidebar-user-name').innerText = name;
1916
-
1917
- if (getEl('settings-display-name')) getEl('settings-display-name').value = name;
1918
- if (getEl('settings-email')) getEl('settings-email').value = state.user.email;
1919
- if (getEl('settings-uid')) getEl('settings-uid').value = state.user.id;
1920
-
1921
- const tierInfo = TIER_DETAILS[state.currentTier] || TIER_DETAILS.free;
1922
- if (getEl('settings-active-tier')) getEl('settings-active-tier').value = tierInfo.name;
1923
- if (getEl('sidebar-user-tier')) getEl('sidebar-user-tier').innerText = tierInfo.name;
1924
-
1925
- // Check & display Admin portal link and Master Admin badge
1926
- checkAdminStatus();
1927
-
1928
- if (getEl('select-byok-provider')) getEl('select-byok-provider').value = state.customLlmProvider || 'nvidia';
1929
- if (getEl('input-byok-endpoint')) getEl('input-byok-endpoint').value = state.customBaseUrl || '';
1930
- if (getEl('input-byok-key')) getEl('input-byok-key').value = state.customApiKey || '';
1931
- if (getEl('checkbox-enable-byok')) getEl('checkbox-enable-byok').checked = Boolean(state.byokEnabled);
1932
-
1933
- const inceptionBadge = getEl('nvidia-inception-badge');
1934
- if (inceptionBadge) {
1935
- if (state.currentTier === 'pro' || state.currentTier === 'enterprise') {
1936
- inceptionBadge.style.display = 'inline-flex';
1937
- } else {
1938
- inceptionBadge.style.display = 'none';
1939
- }
1940
- }
1941
-
1942
- // Render multi-account switching list in dropdown
1943
- renderDropdownAccounts();
1944
-
1945
- // Refresh MCP servers scoped to active user
1946
- if (typeof loadMcpData === 'function') {
1947
- loadMcpData();
1948
- }
1949
- }
1950
-
1951
- function getSavedAccountsFromStorage() {
1952
- try {
1953
- const raw = localStorage.getItem('scout_accounts');
1954
- return raw ? JSON.parse(raw) : [];
1955
- } catch {
1956
- return [];
1957
- }
1958
- }
1959
-
1960
- function saveAccountToStorageList(accountState) {
1961
- if (!accountState?.user?.email) return;
1962
- const accounts = getSavedAccountsFromStorage();
1963
- const key = accountState.user.email.toLowerCase();
1964
- const idx = accounts.findIndex(a => a.user?.email?.toLowerCase() === key);
1965
- const item = {
1966
- user: accountState.user,
1967
- token: accountState.token,
1968
- refreshToken: accountState.refreshToken,
1969
- currentTier: accountState.currentTier || 'free',
1970
- creditsUsed: accountState.creditsUsed ?? 0,
1971
- creditsTotal: accountState.creditsTotal ?? 100,
1972
- renewAt: accountState.renewAt,
1973
- paidTier: accountState.paidTier,
1974
- lastActiveAt: new Date().toISOString()
1975
- };
1976
- if (idx >= 0) {
1977
- accounts[idx] = item;
1978
- } else {
1979
- accounts.push(item);
1980
- }
1981
- localStorage.setItem('scout_accounts', JSON.stringify(accounts));
1982
- }
1983
-
1984
- async function renderDropdownAccounts() {
1985
- const dropdown = getEl('user-dropdown');
1986
- if (!dropdown) return;
1987
-
1988
- let container = getEl('dropdown-accounts-container');
1989
- if (!container) {
1990
- container = document.createElement('div');
1991
- container.id = 'dropdown-accounts-container';
1992
- const logoutBtn = getEl('btn-dropdown-logout');
1993
- if (logoutBtn) {
1994
- dropdown.insertBefore(container, logoutBtn);
1995
- } else {
1996
- dropdown.appendChild(container);
1997
- }
1998
- }
1999
-
2000
- let accounts = getSavedAccountsFromStorage();
2001
- if (state.serverConnected) {
2002
- try {
2003
- const res = await fetch(`${state.apiBaseUrl}/api/accounts`);
2004
- const data = await res.json();
2005
- if (data.success && Array.isArray(data.accounts)) {
2006
- accounts = data.accounts;
2007
- localStorage.setItem('scout_accounts', JSON.stringify(accounts));
2008
- }
2009
- } catch { }
2010
- }
2011
-
2012
- const currentEmail = (state.user?.email || '').toLowerCase();
2013
- const otherAccounts = accounts.filter(a => (a.user?.email || '').toLowerCase() !== currentEmail);
2014
-
2015
- let html = '<hr class="dropdown-divider">';
2016
- html += '<div class="dropdown-header" style="font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; opacity: 0.7; padding-bottom: 4px;">Saved Accounts</div>';
2017
-
2018
- if (otherAccounts.length > 0) {
2019
- otherAccounts.forEach(acc => {
2020
- const email = acc.user?.email || 'Unknown';
2021
- const tier = (acc.currentTier || 'free').toUpperCase();
2022
- html += `
2023
- <button type="button" class="dropdown-item btn-switch-account" data-email="${escapeHtml(email)}" style="display: flex; align-items: center; justify-content: space-between; gap: 8px; width: 100%; border: none; background: transparent; cursor: pointer; text-align: left;">
2024
- <span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"><i class="fa-solid fa-circle-user" style="margin-right: 6px;"></i> ${escapeHtml(email)}</span>
2025
- <span class="badge" style="font-size: 9px; padding: 2px 6px; border-radius: 4px; background: rgba(255,255,255,0.1);">${escapeHtml(tier)}</span>
2026
- </button>
2027
- `;
2028
- });
2029
- }
2030
-
2031
- html += `
2032
- <a href="/auth?add_account=true" class="dropdown-item" id="btn-dropdown-add-account" style="color: var(--color-primary, #10b981);">
2033
- <i class="fa-solid fa-user-plus"></i> Add Another Account
2034
- </a>
2035
- `;
2036
-
2037
- container.innerHTML = html;
2038
-
2039
- container.querySelectorAll('.btn-switch-account').forEach(btn => {
2040
- btn.addEventListener('click', (e) => {
2041
- e.stopPropagation();
2042
- const targetEmail = btn.dataset.email;
2043
- if (targetEmail) {
2044
- switchAccountWeb(targetEmail);
2045
- }
2046
- });
2047
- });
2048
- }
2049
-
2050
- async function switchAccountWeb(targetEmail) {
2051
- showToast(`Switching active account to ${targetEmail}...`, 'info');
2052
- if (state.serverConnected) {
2053
- try {
2054
- const res = await fetch(`${state.apiBaseUrl}/api/accounts/switch`, {
2055
- method: 'POST',
2056
- headers: { 'Content-Type': 'application/json' },
2057
- body: JSON.stringify({ email: targetEmail })
2058
- });
2059
- const data = await res.json();
2060
- if (data.success && data.auth) {
2061
- state.user = data.auth.user;
2062
- state.token = data.auth.token;
2063
- state.refreshToken = data.auth.refreshToken || null;
2064
- state.currentTier = data.auth.currentTier || 'free';
2065
- state.creditsUsed = data.auth.creditsUsed ?? 0;
2066
- state.creditsTotal = data.auth.creditsTotal ?? 100;
2067
- state.renewAt = data.auth.renewAt || null;
2068
- state.byokEnabled = Boolean(data.auth.byokEnabled);
2069
- state.customLlmProvider = data.auth.customLlmProvider || 'nvidia';
2070
- state.customApiKey = data.auth.customApiKey || '';
2071
- state.customBaseUrl = data.auth.customBaseUrl || '';
2072
-
2073
- saveSessionToStorage();
2074
- updateUserUI();
2075
- showToast(`Switched active account to ${targetEmail}`, 'success');
2076
- setTimeout(() => { window.location.reload(); }, 300);
2077
- return;
2078
- }
2079
- } catch { }
2080
- }
2081
-
2082
- const accounts = getSavedAccountsFromStorage();
2083
- const target = accounts.find(a => (a.user?.email || '').toLowerCase() === targetEmail.toLowerCase());
2084
- if (target) {
2085
- state.user = target.user;
2086
- state.token = target.token;
2087
- state.refreshToken = target.refreshToken;
2088
- state.currentTier = target.currentTier || 'free';
2089
- state.creditsUsed = target.creditsUsed ?? 0;
2090
- state.creditsTotal = target.creditsTotal ?? 100;
2091
- state.renewAt = target.renewAt;
2092
-
2093
- saveSessionToStorage();
2094
- updateUserUI();
2095
- showToast(`Switched active account to ${targetEmail}`, 'success');
2096
- setTimeout(() => { window.location.reload(); }, 300);
2097
- }
2098
- }
2099
-
2100
- async function handleLogout() {
2101
- const currentEmail = (state.user?.email || '').toLowerCase();
2102
- let accounts = getSavedAccountsFromStorage();
2103
- accounts = accounts.filter(a => (a.user?.email || '').toLowerCase() !== currentEmail);
2104
- localStorage.setItem('scout_accounts', JSON.stringify(accounts));
2105
-
2106
- if (state.serverConnected) {
2107
- try {
2108
- await fetch(`${state.apiBaseUrl}/api/logout`, {
2109
- method: 'POST',
2110
- headers: { 'Content-Type': 'application/json' },
2111
- body: JSON.stringify({ email: currentEmail })
2112
- });
2113
- } catch { }
2114
- }
2115
-
2116
- if (accounts.length > 0) {
2117
- const next = accounts[0];
2118
- switchAccountWeb(next.user.email);
2119
- showToast(`Logged out. Switched to ${next.user.email}.`, 'info');
2120
- return;
2121
- }
2122
-
2123
- state.user = null;
2124
- state.token = null;
2125
- state.refreshToken = null;
2126
-
2127
- sessionStorage.removeItem('scout_admin_token');
2128
- hideAdminNavigationLink();
2129
-
2130
- localStorage.removeItem('scout_auth_user');
2131
- localStorage.removeItem('scout_auth_token');
2132
- localStorage.removeItem('scout_refresh_token');
2133
-
2134
- if (typeof mcpState !== 'undefined') {
2135
- mcpState.servers = [];
2136
- if (typeof renderMcpServersList === 'function') renderMcpServersList();
2137
- }
2138
-
2139
- showToast('Signed out of Scout session.', 'info');
2140
- window.location.href = '/auth';
2141
- }
2142
-
2143
- function saveSessionToStorage() {
2144
- if (state.user) localStorage.setItem('scout_auth_user', JSON.stringify(state.user));
2145
- if (state.token) localStorage.setItem('scout_auth_token', state.token);
2146
- if (state.refreshToken) localStorage.setItem('scout_refresh_token', state.refreshToken);
2147
- localStorage.setItem('scout_current_tier', state.currentTier);
2148
- localStorage.setItem('scout_credits_used', String(state.creditsUsed));
2149
- localStorage.setItem('scout_credits_total', String(state.creditsTotal));
2150
- if (state.renewAt) localStorage.setItem('scout_renew_at', state.renewAt);
2151
- localStorage.setItem('scout_cancel_at_period_end', String(Boolean(state.cancelAtPeriodEnd)));
2152
- localStorage.setItem('scout_pending_downgrade', state.pendingDowngrade || '');
2153
- localStorage.setItem('scout_paid_tier', state.paidTier || '');
2154
- localStorage.setItem('scout_byok_enabled', String(state.byokEnabled));
2155
- localStorage.setItem('scout_byok_provider', state.customLlmProvider);
2156
- localStorage.setItem('scout_byok_key', state.customApiKey);
2157
- localStorage.setItem('scout_byok_endpoint', state.customBaseUrl);
2158
- saveAccountToStorageList(state);
2159
- }
2160
-
2161
- async function syncAuthWithServer() {
2162
- if (state.user) {
2163
- try {
2164
- await fetch(`${state.apiBaseUrl}/api/save-auth`, {
2165
- method: 'POST',
2166
- headers: { 'Content-Type': 'application/json' },
2167
- body: JSON.stringify({
2168
- user: state.user,
2169
- token: state.token,
2170
- refreshToken: state.refreshToken,
2171
- creditsUsed: state.creditsUsed,
2172
- creditsTotal: state.creditsTotal,
2173
- currentTier: state.currentTier,
2174
- renewAt: state.renewAt,
2175
- cancelAtPeriodEnd: state.cancelAtPeriodEnd,
2176
- pendingDowngrade: state.pendingDowngrade,
2177
- paidTier: state.paidTier,
2178
- byokEnabled: state.byokEnabled,
2179
- customLlmProvider: state.customLlmProvider,
2180
- customApiKey: state.customApiKey,
2181
- customBaseUrl: state.customBaseUrl,
2182
- }),
2183
- });
2184
- } catch { }
2185
- }
2186
- }
2187
-
2188
- // Copy Utility
2189
- function copyText(text, successMsg = 'Copied to clipboard!') {
2190
- navigator.clipboard.writeText(text).then(
2191
- () => showToast(successMsg, 'success'),
2192
- () => showToast('Failed to copy to clipboard', 'error')
2193
- );
2194
- }
2195
-
2196
- document.addEventListener('click', (e) => {
2197
- const copyBtn = e.target.closest('#btn-copy-terminal-cmd');
2198
- if (copyBtn) {
2199
- const cmdText = getEl('terminal-cmd-display')?.innerText || 'npx -y ft-scout@latest';
2200
- copyText(cmdText, 'CLI Command copied to clipboard!');
2201
- }
2202
-
2203
- const revokeBtn = e.target.closest('.btn-revoke-session');
2204
- if (revokeBtn) {
2205
- const sessionId = revokeBtn.dataset.sessionId || revokeBtn.closest('tr')?.dataset?.id;
2206
- if (sessionId) revokeSession(sessionId);
2207
- }
2208
- });
2209
-
2210
- // Toast System
2211
- function showToast(message, type = 'info') {
2212
- const container = getEl('toast-container');
2213
- if (!container) return;
2214
-
2215
- const toast = document.createElement('div');
2216
- toast.className = `toast toast-${type}`;
2217
-
2218
- let iconClass = 'fa-circle-info';
2219
- if (type === 'success') iconClass = 'fa-circle-check';
2220
- if (type === 'error') iconClass = 'fa-circle-exclamation';
2221
-
2222
- toast.innerHTML = `<i class="fa-solid ${iconClass}"></i> <span>${escapeHtml(message)}</span>`;
2223
- container.appendChild(toast);
2224
-
2225
- setTimeout(() => {
2226
- toast.style.opacity = '0';
2227
- toast.style.transform = 'translateX(100%)';
2228
- toast.style.transition = 'all 0.3s ease-out';
2229
- setTimeout(() => toast.remove(), 300);
2230
- }, 3500);
2231
- }
2232
-
2233
- function escapeHtml(str) {
2234
- if (!str) return '';
2235
- return String(str)
2236
- .replace(/&/g, '&amp;')
2237
- .replace(/</g, '&lt;')
2238
- .replace(/>/g, '&gt;')
2239
- .replace(/"/g, '&quot;');
2240
- }
2241
-
2242
- /* ==========================================================================
2243
- Interactive 60 FPS Pacman Retro Arcade Game Loop Engine
2244
- ========================================================================== */
2245
- function initPacmanGame() {
2246
- const canvas = getEl('pacman-canvas');
2247
- if (!canvas) return;
2248
-
2249
- const ctx = canvas.getContext('2d');
2250
- const overlay = getEl('arcade-overlay');
2251
- const overlayTitle = getEl('overlay-title');
2252
- const overlaySubtitle = getEl('overlay-subtitle');
2253
- const btnAction = getEl('btn-arcade-action');
2254
- const scoreValEl = getEl('pacman-score');
2255
- const highScoreValEl = getEl('pacman-highscore');
2256
-
2257
- let gameLoopId = null;
2258
- let score = 0;
2259
- let highScore = parseInt(localStorage.getItem('scout_pacman_highscore') || '12400', 10);
2260
- let level = 1;
2261
- let lives = 3;
2262
- let gameState = 'STOPPED'; // STOPPED, PLAYING, PAUSED, GAMEOVER
2263
- let crtEnabled = true;
2264
- let soundEnabled = true;
2265
-
2266
- if (highScoreValEl) highScoreValEl.innerText = String(highScore).padStart(5, '0');
2267
-
2268
- // Classic Grid Map (1: wall, 0: pellet, 2: power pellet, 3: empty)
2269
- const originalGrid = [
2270
- [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
2271
- [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
2272
- [1, 2, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 2, 1],
2273
- [1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1],
2274
- [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
2275
- [1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1],
2276
- [1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
2277
- [1, 1, 1, 1, 0, 1, 1, 1, 3, 1, 3, 1, 1, 1, 0, 1, 1, 1, 1],
2278
- [3, 3, 3, 1, 0, 1, 3, 3, 3, 3, 3, 3, 3, 1, 0, 1, 3, 3, 3],
2279
- [1, 1, 1, 1, 0, 1, 3, 1, 1, 3, 1, 1, 3, 1, 0, 1, 1, 1, 1],
2280
- [3, 3, 3, 3, 0, 3, 3, 1, 3, 3, 3, 1, 3, 3, 0, 3, 3, 3, 3],
2281
- [1, 1, 1, 1, 0, 1, 3, 1, 1, 1, 1, 1, 3, 1, 0, 1, 1, 1, 1],
2282
- [3, 3, 3, 1, 0, 1, 3, 3, 3, 3, 3, 3, 3, 1, 0, 1, 3, 3, 3],
2283
- [1, 1, 1, 1, 0, 1, 3, 1, 1, 1, 1, 1, 3, 1, 0, 1, 1, 1, 1],
2284
- [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
2285
- [1, 2, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 2, 1],
2286
- [1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
2287
- [1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1],
2288
- [1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
2289
- [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
2290
- ];
2291
-
2292
- let grid = JSON.parse(JSON.stringify(originalGrid));
2293
- const tileSize = 22;
2294
- const offsetX = (canvas.width - 19 * tileSize) / 2;
2295
- const offsetY = (canvas.height - 20 * tileSize) / 2;
2296
-
2297
- const pacman = {
2298
- x: 9,
2299
- y: 14,
2300
- px: 9 * tileSize + tileSize / 2,
2301
- py: 14 * tileSize + tileSize / 2,
2302
- dirX: 0,
2303
- dirY: 0,
2304
- nextDirX: 0,
2305
- nextDirY: 0,
2306
- speed: 2,
2307
- mouthAngle: 0.2,
2308
- mouthSpeed: 0.03,
2309
- };
2310
-
2311
- const ghosts = [
2312
- { name: 'Blinky', color: '#ef4444', x: 9, y: 9, px: 9 * tileSize + tileSize / 2, py: 9 * tileSize + tileSize / 2, dirX: 1, dirY: 0, scared: 0 },
2313
- { name: 'Pinky', color: '#ec4899', x: 9, y: 10, px: 9 * tileSize + tileSize / 2, py: 10 * tileSize + tileSize / 2, dirX: -1, dirY: 0, scared: 0 },
2314
- { name: 'Inky', color: '#38bdf8', x: 8, y: 10, px: 8 * tileSize + tileSize / 2, py: 10 * tileSize + tileSize / 2, dirX: 0, dirY: -1, scared: 0 },
2315
- { name: 'Clyde', color: '#fbbf24', x: 10, y: 10, px: 10 * tileSize + tileSize / 2, py: 10 * tileSize + tileSize / 2, dirX: 0, dirY: 1, scared: 0 },
2316
- ];
2317
-
2318
- function resetPositions() {
2319
- pacman.x = 9;
2320
- pacman.y = 14;
2321
- pacman.px = 9 * tileSize + tileSize / 2;
2322
- pacman.py = 14 * tileSize + tileSize / 2;
2323
- pacman.dirX = 0;
2324
- pacman.dirY = 0;
2325
- pacman.nextDirX = 0;
2326
- pacman.nextDirY = 0;
2327
-
2328
- ghosts[0].px = 9 * tileSize + tileSize / 2; ghosts[0].py = 8 * tileSize + tileSize / 2; ghosts[0].dirX = 1; ghosts[0].dirY = 0; ghosts[0].scared = 0;
2329
- ghosts[1].px = 9 * tileSize + tileSize / 2; ghosts[1].py = 10 * tileSize + tileSize / 2; ghosts[1].dirX = -1; ghosts[1].dirY = 0; ghosts[1].scared = 0;
2330
- ghosts[2].px = 8 * tileSize + tileSize / 2; ghosts[2].py = 10 * tileSize + tileSize / 2; ghosts[2].dirX = 0; ghosts[2].dirY = -1; ghosts[2].scared = 0;
2331
- ghosts[3].px = 10 * tileSize + tileSize / 2; ghosts[3].py = 10 * tileSize + tileSize / 2; ghosts[3].dirX = 0; ghosts[3].dirY = 1; ghosts[3].scared = 0;
2332
- }
2333
-
2334
- function startGame() {
2335
- score = 0;
2336
- lives = 3;
2337
- level = 1;
2338
- grid = JSON.parse(JSON.stringify(originalGrid));
2339
- resetPositions();
2340
- gameState = 'PLAYING';
2341
- if (overlay) overlay.classList.add('hidden');
2342
- if (scoreValEl) scoreValEl.innerText = '00000';
2343
- updateLivesUI();
2344
- if (!gameLoopId) loop();
2345
- }
2346
-
2347
- function togglePause() {
2348
- if (gameState === 'PLAYING') {
2349
- gameState = 'PAUSED';
2350
- if (overlayTitle) overlayTitle.innerText = 'PAUSED';
2351
- if (overlaySubtitle) overlaySubtitle.innerText = 'Press SPACE to Resume';
2352
- if (btnAction) btnAction.innerHTML = '<i class="fa-solid fa-play"></i> RESUME';
2353
- if (overlay) overlay.classList.remove('hidden');
2354
- } else if (gameState === 'PAUSED') {
2355
- gameState = 'PLAYING';
2356
- if (overlay) overlay.classList.add('hidden');
2357
- }
2358
- }
2359
-
2360
- function updateLivesUI() {
2361
- const livesEl = getEl('pacman-lives');
2362
- if (livesEl) {
2363
- livesEl.innerHTML = Array(Math.max(0, lives)).fill('<span class="life-pacman">❤️</span>').join('');
2364
- }
2365
- }
2366
-
2367
- function canMoveTo(gx, gy) {
2368
- if (gy < 0 || gy >= grid.length || gx < 0 || gx >= grid[0].length) return false;
2369
- return grid[gy][gx] !== 1;
2370
- }
2371
-
2372
- function update() {
2373
- if (gameState !== 'PLAYING') return;
2374
-
2375
- // Pacman mouth animation
2376
- pacman.mouthAngle += pacman.mouthSpeed;
2377
- if (pacman.mouthAngle > 0.4 || pacman.mouthAngle < 0.05) pacman.mouthSpeed = -pacman.mouthSpeed;
2378
-
2379
- const currentTileX = Math.floor(pacman.px / tileSize);
2380
- const currentTileY = Math.floor(pacman.py / tileSize);
2381
- const centerX = currentTileX * tileSize + tileSize / 2;
2382
- const centerY = currentTileY * tileSize + tileSize / 2;
2383
-
2384
- if (Math.abs(pacman.px - centerX) < pacman.speed && Math.abs(pacman.py - centerY) < pacman.speed) {
2385
- pacman.px = centerX;
2386
- pacman.py = centerY;
2387
-
2388
- if (pacman.nextDirX !== 0 || pacman.nextDirY !== 0) {
2389
- if (canMoveTo(currentTileX + pacman.nextDirX, currentTileY + pacman.nextDirY)) {
2390
- pacman.dirX = pacman.nextDirX;
2391
- pacman.dirY = pacman.nextDirY;
2392
- }
2393
- }
2394
-
2395
- if (!canMoveTo(currentTileX + pacman.dirX, currentTileY + pacman.dirY)) {
2396
- pacman.dirX = 0;
2397
- pacman.dirY = 0;
2398
- }
2399
-
2400
- // Eat Pellets
2401
- if (grid[currentTileY] && grid[currentTileY][currentTileX] === 0) {
2402
- grid[currentTileY][currentTileX] = 3;
2403
- score += 10;
2404
- if (soundEnabled) playRetroBeep(580, 0.04, 'triangle');
2405
- } else if (grid[currentTileY] && grid[currentTileY][currentTileX] === 2) {
2406
- grid[currentTileY][currentTileX] = 3;
2407
- score += 50;
2408
- ghosts.forEach(g => g.scared = 300);
2409
- if (soundEnabled) playRetroBeep(880, 0.12, 'sawtooth');
2410
- }
2411
-
2412
- if (score > highScore) {
2413
- highScore = score;
2414
- localStorage.setItem('scout_pacman_highscore', String(highScore));
2415
- if (highScoreValEl) highScoreValEl.innerText = String(highScore).padStart(5, '0');
2416
- }
2417
-
2418
- if (scoreValEl) scoreValEl.innerText = String(score).padStart(5, '0');
2419
- }
2420
-
2421
- pacman.px += pacman.dirX * pacman.speed;
2422
- pacman.py += pacman.dirY * pacman.speed;
2423
-
2424
- // Ghosts move
2425
- ghosts.forEach((g) => {
2426
- if (g.scared > 0) g.scared--;
2427
- const gSpeed = g.scared > 0 ? 1 : 2;
2428
-
2429
- const gtx = Math.floor(g.px / tileSize);
2430
- const gty = Math.floor(g.py / tileSize);
2431
- const gcx = gtx * tileSize + tileSize / 2;
2432
- const gcy = gty * tileSize + tileSize / 2;
2433
-
2434
- if (Math.abs(g.px - gcx) < gSpeed && Math.abs(g.py - gcy) < gSpeed) {
2435
- g.px = gcx;
2436
- g.py = gcy;
2437
-
2438
- const allDirs = [
2439
- { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }
2440
- ];
2441
- let validDirs = allDirs.filter(d =>
2442
- (d.x !== -g.dirX || d.y !== -g.dirY) && canMoveTo(gtx + d.x, gty + d.y)
2443
- );
2444
- if (validDirs.length === 0) {
2445
- validDirs = allDirs.filter(d => canMoveTo(gtx + d.x, gty + d.y));
2446
- }
2447
-
2448
- if (validDirs.length > 0) {
2449
- const chosen = validDirs[Math.floor(Math.random() * validDirs.length)];
2450
- g.dirX = chosen.x;
2451
- g.dirY = chosen.y;
2452
- }
2453
- }
2454
-
2455
- g.px += g.dirX * gSpeed;
2456
- g.py += g.dirY * gSpeed;
2457
-
2458
- // Collision with Pacman
2459
- const dist = Math.hypot(pacman.px - g.px, pacman.py - g.py);
2460
- if (dist < tileSize * 0.85) {
2461
- if (g.scared > 0) {
2462
- score += 200;
2463
- g.px = 9 * tileSize + tileSize / 2;
2464
- g.py = 8 * tileSize + tileSize / 2;
2465
- g.scared = 0;
2466
- if (soundEnabled) playRetroBeep(1200, 0.15, 'sine');
2467
- } else {
2468
- lives--;
2469
- updateLivesUI();
2470
- if (soundEnabled) playRetroBeep(220, 0.3, 'sawtooth');
2471
- if (lives <= 0) {
2472
- gameState = 'GAMEOVER';
2473
- if (overlayTitle) overlayTitle.innerText = 'GAME OVER';
2474
- if (overlaySubtitle) overlaySubtitle.innerText = `Final Score: ${score}`;
2475
- if (btnAction) btnAction.innerHTML = '<i class="fa-solid fa-rotate-right"></i> PLAY AGAIN';
2476
- if (overlay) overlay.classList.remove('hidden');
2477
- } else {
2478
- resetPositions();
2479
- }
2480
- }
2481
- }
2482
- });
2483
- }
2484
-
2485
- function render() {
2486
- ctx.fillStyle = '#08090c';
2487
- ctx.fillRect(0, 0, canvas.width, canvas.height);
2488
-
2489
- ctx.save();
2490
- ctx.translate(offsetX, offsetY);
2491
-
2492
- // Draw Map Grid
2493
- for (let r = 0; r < grid.length; r++) {
2494
- for (let c = 0; c < grid[r].length; c++) {
2495
- const tile = grid[r][c];
2496
- const x = c * tileSize;
2497
- const y = r * tileSize;
2498
-
2499
- if (tile === 1) {
2500
- ctx.fillStyle = '#1c202d';
2501
- ctx.strokeStyle = '#38bdf8';
2502
- ctx.lineWidth = 1.5;
2503
- ctx.fillRect(x, y, tileSize, tileSize);
2504
- ctx.strokeRect(x + 2, y + 2, tileSize - 4, tileSize - 4);
2505
- } else if (tile === 0) {
2506
- ctx.fillStyle = '#fbbf24';
2507
- ctx.beginPath();
2508
- ctx.arc(x + tileSize / 2, y + tileSize / 2, 3, 0, Math.PI * 2);
2509
- ctx.fill();
2510
- } else if (tile === 2) {
2511
- ctx.fillStyle = '#f8fafc';
2512
- ctx.beginPath();
2513
- ctx.arc(x + tileSize / 2, y + tileSize / 2, 7, 0, Math.PI * 2);
2514
- ctx.fill();
2515
- }
2516
- }
2517
- }
2518
-
2519
- // Draw Pacman
2520
- let startAngle = pacman.mouthAngle;
2521
- let endAngle = Math.PI * 2 - pacman.mouthAngle;
2522
- if (pacman.dirX === -1) { startAngle += Math.PI; endAngle += Math.PI; }
2523
- if (pacman.dirY === 1) { startAngle += Math.PI / 2; endAngle += Math.PI / 2; }
2524
- if (pacman.dirY === -1) { startAngle -= Math.PI / 2; endAngle -= Math.PI / 2; }
2525
-
2526
- ctx.fillStyle = '#facc15';
2527
- ctx.beginPath();
2528
- ctx.arc(pacman.px, pacman.py, tileSize / 2 - 2, startAngle, endAngle);
2529
- ctx.lineTo(pacman.px, pacman.py);
2530
- ctx.fill();
2531
-
2532
- // Draw Ghosts
2533
- ghosts.forEach((g) => {
2534
- ctx.fillStyle = g.scared > 0 ? '#3b82f6' : g.color;
2535
- ctx.beginPath();
2536
- ctx.arc(g.px, g.py, tileSize / 2 - 2, Math.PI, 0, false);
2537
- ctx.lineTo(g.px + tileSize / 2 - 2, g.py + tileSize / 2 - 2);
2538
- ctx.lineTo(g.px - tileSize / 2 + 2, g.py + tileSize / 2 - 2);
2539
- ctx.fill();
2540
-
2541
- // Eyes
2542
- ctx.fillStyle = '#ffffff';
2543
- ctx.beginPath();
2544
- ctx.arc(g.px - 3, g.py - 3, 3, 0, Math.PI * 2);
2545
- ctx.arc(g.px + 3, g.py - 3, 3, 0, Math.PI * 2);
2546
- ctx.fill();
2547
-
2548
- ctx.fillStyle = '#1e1b4b';
2549
- ctx.beginPath();
2550
- ctx.arc(g.px - 3 + g.dirX * 1.5, g.py - 3 + g.dirY * 1.5, 1.5, 0, Math.PI * 2);
2551
- ctx.arc(g.px + 3 + g.dirX * 1.5, g.py - 3 + g.dirY * 1.5, 1.5, 0, Math.PI * 2);
2552
- ctx.fill();
2553
- });
2554
-
2555
- ctx.restore();
2556
- }
2557
-
2558
- function loop() {
2559
- update();
2560
- render();
2561
- gameLoopId = requestAnimationFrame(loop);
2562
- }
2563
-
2564
- // Input Listeners
2565
- window.addEventListener('keydown', (e) => {
2566
- const active = document.activeElement;
2567
- if (active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || active.tagName === 'SELECT' || active.isContentEditable)) {
2568
- return;
2569
- }
2570
-
2571
- if (['ArrowUp', 'KeyW'].includes(e.code)) { pacman.nextDirX = 0; pacman.nextDirY = -1; }
2572
- if (['ArrowDown', 'KeyS'].includes(e.code)) { pacman.nextDirX = 0; pacman.nextDirY = 1; }
2573
- if (['ArrowLeft', 'KeyA'].includes(e.code)) { pacman.nextDirX = -1; pacman.nextDirY = 0; }
2574
- if (['ArrowRight', 'KeyD'].includes(e.code)) { pacman.nextDirX = 1; pacman.nextDirY = 0; }
2575
- if (e.code === 'Space') {
2576
- e.preventDefault();
2577
- if (gameState === 'STOPPED' || gameState === 'GAMEOVER') startGame();
2578
- else togglePause();
2579
- }
2580
- });
2581
-
2582
- btnAction?.addEventListener('click', startGame);
2583
- getEl('btn-pacman-pause')?.addEventListener('click', togglePause);
2584
- getEl('btn-pacman-restart')?.addEventListener('click', startGame);
2585
-
2586
- const handleDir = (dx, dy) => (e) => {
2587
- if (e.type === 'touchstart') e.preventDefault();
2588
- pacman.nextDirX = dx;
2589
- pacman.nextDirY = dy;
2590
- };
2591
-
2592
- ['click', 'pointerdown', 'touchstart'].forEach((evt) => {
2593
- getEl('dpad-up')?.addEventListener(evt, handleDir(0, -1));
2594
- getEl('dpad-down')?.addEventListener(evt, handleDir(0, 1));
2595
- getEl('dpad-left')?.addEventListener(evt, handleDir(-1, 0));
2596
- getEl('dpad-right')?.addEventListener(evt, handleDir(1, 0));
2597
- });
2598
-
2599
- getEl('btn-toggle-crt')?.addEventListener('click', () => {
2600
- const screen = getEl('arcade-screen');
2601
- if (screen) {
2602
- crtEnabled = !crtEnabled;
2603
- screen.classList.toggle('crt-active', crtEnabled);
2604
- showToast(`CRT Filter ${crtEnabled ? 'ENABLED' : 'DISABLED'}`, 'info');
2605
- }
2606
- });
2607
-
2608
- getEl('btn-toggle-sound')?.addEventListener('click', () => {
2609
- soundEnabled = !soundEnabled;
2610
- const btn = getEl('btn-toggle-sound');
2611
- if (btn) {
2612
- btn.innerHTML = soundEnabled
2613
- ? '<i class="fa-solid fa-volume-high text-success"></i> Sound ON'
2614
- : '<i class="fa-solid fa-volume-xmark text-danger"></i> Sound OFF';
2615
- }
2616
- });
2617
-
2618
- render();
2619
- }
2620
-
2621
- /* ==========================================================================
2622
- Autonomous Agent Execution Engine, Workstation Router & Activity Controller
2623
- ========================================================================== */
2624
- let agentMonitorPollTimer = null;
2625
- let currentPendingApprovalId = null;
2626
- let activeSimulationTimer = null;
2627
-
2628
- // Local task history store
2629
- let tasksHistoryStore = [];
2630
-
2631
- function loadTasksHistoryFromStorage() {
2632
- try {
2633
- const stored = localStorage.getItem('scout_tasks_history');
2634
- if (stored) {
2635
- tasksHistoryStore = JSON.parse(stored);
2636
- } else {
2637
- tasksHistoryStore = [];
2638
- }
2639
- } catch {
2640
- tasksHistoryStore = [];
2641
- }
2642
- }
2643
-
2644
- function saveTasksHistoryToStorage() {
2645
- try {
2646
- localStorage.setItem('scout_tasks_history', JSON.stringify(tasksHistoryStore));
2647
- } catch { }
2648
- }
2649
-
2650
- function initAutonomousAgentMonitor() {
2651
- const monitorPanel = getEl('agent-monitor-panel');
2652
- if (!monitorPanel) return;
2653
-
2654
- loadTasksHistoryFromStorage();
2655
-
2656
- const taskForm = getEl('agent-task-form');
2657
- const goalInput = getEl('agent-goal-input');
2658
- const autoApproveToggle = getEl('agent-auto-approve-toggle');
2659
- const btnRefresh = getEl('btn-refresh-agent-state');
2660
- const btnCancel = getEl('btn-cancel-agent-task');
2661
- const btnApprove = getEl('btn-approve-action');
2662
- const btnDeny = getEl('btn-deny-action');
2663
-
2664
- async function fetchAgentState() {
2665
- if (!state.serverConnected) {
2666
- updateDashboardMetrics();
2667
- return;
2668
- }
2669
-
2670
- try {
2671
- const apiBase = state.apiBaseUrl || '';
2672
- const res = await fetch(`${apiBase}/api/agent/state`);
2673
- if (!res.ok) return;
2674
- const data = await res.json();
2675
- if (!data.success) return;
2676
-
2677
- renderAgentState(data.state, data.pendingApprovals);
2678
-
2679
- // Fetch saved tasks if available
2680
- try {
2681
- const tasksRes = await fetch(`${apiBase}/api/agent/tasks`);
2682
- if (tasksRes.ok) {
2683
- const tasksData = await tasksRes.json();
2684
- if (tasksData.success && Array.isArray(tasksData.tasks)) {
2685
- tasksData.tasks.forEach(remoteTask => {
2686
- if (!tasksHistoryStore.some(t => t.taskId === remoteTask.taskId)) {
2687
- tasksHistoryStore.unshift(remoteTask);
2688
- }
2689
- });
2690
- saveTasksHistoryToStorage();
2691
- }
2692
- }
2693
- } catch { }
2694
-
2695
- updateDashboardMetrics(data.state);
2696
- } catch (err) {
2697
- console.warn('Agent state poll error:', err);
2698
- }
2699
- }
2700
-
2701
- function renderAgentState(taskState, pendingApprovals) {
2702
- if (!taskState) return;
2703
-
2704
- // Status badge
2705
- const badge = getEl('agent-status-badge');
2706
- const st = (taskState.status || 'idle').toUpperCase();
2707
- if (badge) {
2708
- badge.innerText = st;
2709
- badge.className = 'live-pulse-badge';
2710
- if (st === 'COMPLETED') {
2711
- badge.style.background = 'var(--scout-emerald-subtle)';
2712
- badge.style.borderColor = 'rgba(16, 185, 129, 0.4)';
2713
- badge.style.color = '#10b981';
2714
- } else if (st === 'EXECUTING' || st === 'RUNNING' || st === 'PLANNING') {
2715
- badge.style.background = 'var(--scout-cyan-subtle)';
2716
- badge.style.borderColor = 'rgba(56, 189, 248, 0.4)';
2717
- badge.style.color = 'var(--scout-cyan)';
2718
- } else if (st === 'WAITING_APPROVAL') {
2719
- badge.style.background = 'var(--scout-amber-subtle)';
2720
- badge.style.borderColor = 'rgba(245, 158, 11, 0.4)';
2721
- badge.style.color = '#f59e0b';
2722
- } else if (st === 'FAILED') {
2723
- badge.style.background = 'rgba(239, 68, 68, 0.12)';
2724
- badge.style.borderColor = 'rgba(239, 68, 68, 0.4)';
2725
- badge.style.color = '#ef4444';
2726
- }
2727
- }
2728
-
2729
- // Active Application Perception Pill
2730
- const appIndicator = getEl('active-app-indicator');
2731
- if (appIndicator) {
2732
- const app = taskState.active_application || (st === 'EXECUTING' ? 'Chrome & Native Desktop' : 'Workstation Ready');
2733
- let iconClass = 'fa-solid fa-desktop';
2734
- if (app.toLowerCase().includes('chrome') || app.toLowerCase().includes('browser')) iconClass = 'fa-brands fa-chrome';
2735
- else if (app.toLowerCase().includes('code') || app.toLowerCase().includes('editor')) iconClass = 'fa-solid fa-code';
2736
- else if (app.toLowerCase().includes('terminal') || app.toLowerCase().includes('bash')) iconClass = 'fa-solid fa-terminal';
2737
-
2738
- appIndicator.innerHTML = `<i class="${iconClass}"></i> Operating: ${escapeHtml(app)}`;
2739
- }
2740
-
2741
- // Current Operation Label & Spinner
2742
- const opLabel = getEl('agent-current-operation-label');
2743
- const spinner = getEl('current-op-spinner');
2744
- const idleIcon = getEl('current-op-idle-icon');
2745
- const isRunning = st === 'EXECUTING' || st === 'RUNNING' || st === 'PLANNING';
2746
-
2747
- if (spinner && idleIcon) {
2748
- spinner.style.display = isRunning ? 'inline-block' : 'none';
2749
- idleIcon.style.display = isRunning ? 'none' : 'inline-block';
2750
- }
2751
-
2752
- if (opLabel) {
2753
- if (isRunning) {
2754
- const currentStepObj = taskState.plan?.find(p => p.status === 'in_progress') || taskState.plan?.[taskState.currentStep];
2755
- opLabel.innerText = currentStepObj ? `Step ${currentStepObj.id}: ${currentStepObj.description}` : 'Synthesizing task execution trajectory...';
2756
- } else if (st === 'COMPLETED') {
2757
- opLabel.innerText = `Goal achieved: ${taskState.goal || taskState.objective || 'Task executed successfully.'}`;
2758
- } else if (st === 'FAILED') {
2759
- opLabel.innerText = `Task halted or recovered with error.`;
2760
- } else {
2761
- opLabel.innerText = 'Operator idle. Ready for autonomous workstation goal.';
2762
- }
2763
- }
2764
-
2765
- // Cancel button visibility
2766
- if (btnCancel) {
2767
- if (isRunning) btnCancel.classList.remove('hidden');
2768
- else btnCancel.classList.add('hidden');
2769
- }
2770
-
2771
- // Step counter
2772
- const stepCounter = getEl('agent-step-counter');
2773
- if (stepCounter) {
2774
- const isUnlimited = !taskState.maxSteps || taskState.maxSteps >= 9999 || taskState.maxSteps === Infinity;
2775
- stepCounter.innerText = isUnlimited ? `Step ${taskState.currentStep || 0}` : `Step ${taskState.currentStep || 0} / ${taskState.maxSteps}`;
2776
- }
2777
-
2778
- // Plan progress & checklist
2779
- const planList = getEl('agent-plan-list');
2780
- const planText = getEl('agent-plan-progress-text');
2781
- if (planList && taskState.plan && taskState.plan.length > 0) {
2782
- const completedCount = taskState.plan.filter(p => p.status === 'completed').length;
2783
- if (planText) planText.innerText = `${completedCount} / ${taskState.plan.length} steps completed`;
2784
-
2785
- planList.innerHTML = taskState.plan.map(step => {
2786
- let icon = '<i class="fa-regular fa-circle text-dim"></i>';
2787
- let stepClass = 'pending';
2788
- if (step.status === 'completed') {
2789
- icon = '<i class="fa-solid fa-circle-check text-success"></i>';
2790
- stepClass = 'completed';
2791
- } else if (step.status === 'in_progress') {
2792
- icon = '<i class="fa-solid fa-spinner fa-spin text-primary"></i>';
2793
- stepClass = 'in_progress';
2794
- } else if (step.status === 'failed') {
2795
- icon = '<i class="fa-solid fa-circle-xmark text-danger"></i>';
2796
- stepClass = 'failed';
2797
- }
2798
-
2799
- return `
2800
- <div class="scout-plan-step ${stepClass}">
2801
- ${icon}
2802
- <span style="flex: 1; min-width: 0;">Step ${step.id}: ${escapeHtml(step.description)}</span>
2803
- ${step.toolName ? `<span class="badge" style="font-size: 10px; margin-left: auto;">${escapeHtml(step.toolName)}</span>` : ''}
2804
- </div>
2805
- `;
2806
- }).join('');
2807
- }
2808
-
2809
- // Pending Approvals Banner
2810
- const banner = getEl('agent-approval-banner');
2811
- if (banner) {
2812
- if (pendingApprovals && pendingApprovals.length > 0) {
2813
- const req = pendingApprovals[0];
2814
- currentPendingApprovalId = req.id;
2815
- banner.classList.remove('hidden');
2816
- const riskBadge = getEl('approval-risk-badge');
2817
- if (riskBadge) {
2818
- riskBadge.innerText = `⚠️ ${req.riskLevel.toUpperCase()} RISK ACTION AWAITING APPROVAL`;
2819
- riskBadge.style.background = req.riskLevel === 'CRITICAL' ? '#dc2626' : '#ef4444';
2820
- }
2821
- const actTitle = getEl('approval-action-title');
2822
- if (actTitle) actTitle.innerText = `Action: ${req.action} on ${req.target || 'system'}`;
2823
- const actDesc = getEl('approval-action-desc');
2824
- if (actDesc) actDesc.innerText = req.description;
2825
- } else {
2826
- banner.classList.add('hidden');
2827
- currentPendingApprovalId = null;
2828
- }
2829
- }
2830
-
2831
- // Artifacts list in execution card
2832
- const artList = getEl('agent-artifacts-list');
2833
- if (artList) {
2834
- if (taskState.artifacts && taskState.artifacts.length > 0) {
2835
- artList.innerHTML = taskState.artifacts.map(a => `
2836
- <div style="display: flex; align-items: center; justify-content: space-between; padding: 6px 12px; background: rgba(255,255,255,0.03); border: 1px solid var(--scout-border); border-radius: 6px;">
2837
- <span><i class="fa-solid fa-file-lines text-primary" style="margin-right: 6px;"></i> <strong>${escapeHtml(a.name || a.filename)}</strong></span>
2838
- <span style="color: var(--scout-text-tertiary); font-size: 11px;">${escapeHtml(a.type || 'Deliverable')}</span>
2839
- </div>
2840
- `).join('');
2841
- } else {
2842
- artList.innerHTML = '<span style="color: var(--scout-text-tertiary);">No artifacts recorded for this session yet.</span>';
2843
- }
2844
- }
2845
-
2846
- // Render Artifacts in Gallery
2847
- renderArtifactsGallery(taskState.artifacts || []);
2848
-
2849
- // Render Activity Timeline
2850
- renderActivityTimeline(taskState.observations || []);
2851
- }
2852
-
2853
- // Task Execution Submission
2854
- taskForm?.addEventListener('submit', async (e) => {
2855
- e.preventDefault();
2856
- const goal = goalInput?.value?.trim();
2857
- if (!goal) return;
2858
- const autoApprove = autoApproveToggle?.checked || false;
2859
-
2860
- const btn = getEl('btn-start-agent');
2861
- if (btn) {
2862
- btn.disabled = true;
2863
- btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Dispatching Operator...';
2864
- }
2865
-
2866
- // 1. Try real server endpoint if connected
2867
- if (state.serverConnected) {
2868
- try {
2869
- const apiBase = state.apiBaseUrl || '';
2870
- const res = await fetch(`${apiBase}/api/agent/task`, {
2871
- method: 'POST',
2872
- headers: { 'Content-Type': 'application/json' },
2873
- body: JSON.stringify({ goal, autoApprove }),
2874
- });
2875
- const data = await res.json();
2876
- if (data.success) {
2877
- showToast(`Autonomous Agent started! Task ID: ${data.taskId.slice(0, 8)}...`, 'success');
2878
- setTimeout(fetchAgentState, 600);
2879
- return;
2880
- } else {
2881
- showToast(data.error || 'Failed to start agent task', 'error');
2882
- }
2883
- } catch (err) {
2884
- console.warn('Real server error, falling back to autonomous client simulation:', err);
2885
- } finally {
2886
- if (btn) {
2887
- btn.disabled = false;
2888
- btn.innerHTML = '<i class="fa-solid fa-play"></i> Run Scout Operator &rarr;';
2889
- }
2890
- }
2891
- }
2892
-
2893
- // 2. Standalone Cloud / Demo Mode Realistic Operator Simulation
2894
- simulateAutonomousOperator(goal, autoApprove);
2895
- if (btn) {
2896
- btn.disabled = false;
2897
- btn.innerHTML = '<i class="fa-solid fa-play"></i> Run Scout Operator &rarr;';
2898
- }
2899
- });
2900
-
2901
- // Standalone Realistic Autonomous Operator Simulation Flow
2902
- function simulateAutonomousOperator(goal, autoApprove) {
2903
- showToast('Autonomous Operator launched on workstation workspace!', 'info');
2904
- const taskId = 'task_' + Date.now().toString(36);
2905
- const startTime = new Date().toISOString();
2906
-
2907
- const simState = {
2908
- taskId,
2909
- goal,
2910
- objective: goal,
2911
- status: 'executing',
2912
- currentStep: 1,
2913
- maxSteps: 5,
2914
- active_application: 'Chrome & Workspace Driver',
2915
- active_url: 'https://developer.nvidia.com/inception',
2916
- plan: [
2917
- { id: 1, description: 'Decompose task intent into DAG execution steps', status: 'in_progress', toolName: 'scratchpad' },
2918
- { id: 2, description: 'Launch Chrome browser and navigate to target resources', status: 'pending', toolName: 'browser_open' },
2919
- { id: 3, description: 'Extract DOM structure, pricing criteria and program benefits', status: 'pending', toolName: 'browser_scrape' },
2920
- { id: 4, description: 'Execute bounded verification against retrieved data', status: 'pending', toolName: 'verifier' },
2921
- { id: 5, description: 'Compile structured report artifact and save deliverable', status: 'pending', toolName: 'file_write' },
2922
- ],
2923
- observations: [
2924
- { step: 1, timestamp: new Date().toISOString(), tool: 'scratchpad', target: 'Planner', resultSummary: 'Objective formulated: ' + goal, verified: true },
2925
- ],
2926
- artifacts: [],
2927
- created_at: startTime,
2928
- updated_at: startTime,
2929
- };
2930
-
2931
- renderAgentState(simState, []);
2932
- updateDashboardMetrics(simState);
2933
-
2934
- let stepIndex = 1;
2935
- if (activeSimulationTimer) clearInterval(activeSimulationTimer);
2936
-
2937
- activeSimulationTimer = setInterval(() => {
2938
- stepIndex++;
2939
-
2940
- if (stepIndex === 2) {
2941
- simState.currentStep = 2;
2942
- simState.plan[0].status = 'completed';
2943
- simState.plan[1].status = 'in_progress';
2944
- simState.active_application = 'Chrome';
2945
- simState.observations.push({
2946
- step: 2,
2947
- timestamp: new Date().toISOString(),
2948
- tool: 'browser_open',
2949
- target: 'https://nvidia.com',
2950
- resultSummary: 'Navigated to primary target portal and extracted page DOM coordinates.',
2951
- verified: true,
2952
- });
2953
- renderAgentState(simState, []);
2954
- } else if (stepIndex === 3) {
2955
- simState.currentStep = 3;
2956
- simState.plan[1].status = 'completed';
2957
- simState.plan[2].status = 'in_progress';
2958
- simState.active_application = 'Chrome & DOM Parser';
2959
- simState.observations.push({
2960
- step: 3,
2961
- timestamp: new Date().toISOString(),
2962
- tool: 'browser_scrape',
2963
- target: 'Inception Requirements',
2964
- resultSummary: 'Extracted eligibility requirements, GPU access vouchers, and AI acceleration perks.',
2965
- verified: true,
2966
- });
2967
- renderAgentState(simState, []);
2968
- } else if (stepIndex === 4) {
2969
- simState.currentStep = 4;
2970
- simState.plan[2].status = 'completed';
2971
- simState.plan[3].status = 'in_progress';
2972
- simState.active_application = 'Desktop Native Verifier';
2973
- simState.observations.push({
2974
- step: 4,
2975
- timestamp: new Date().toISOString(),
2976
- tool: 'verifier',
2977
- target: 'Integrity Check',
2978
- resultSummary: 'Deterministic verification successful: Zero hallucination, bounded state confirmed.',
2979
- verified: true,
2980
- });
2981
- renderAgentState(simState, []);
2982
- } else if (stepIndex === 5) {
2983
- simState.currentStep = 5;
2984
- simState.plan[3].status = 'completed';
2985
- simState.plan[4].status = 'in_progress';
2986
- simState.active_application = 'VS Code';
2987
- simState.artifacts.push({
2988
- id: 'art_' + Date.now().toString(36),
2989
- name: 'scout-summary-report.md',
2990
- filename: 'scout-summary-report.md',
2991
- type: 'Executive Markdown Report',
2992
- createdAt: new Date().toISOString(),
2993
- verified: true,
2994
- });
2995
- simState.observations.push({
2996
- step: 5,
2997
- timestamp: new Date().toISOString(),
2998
- tool: 'file_write',
2999
- target: 'scout-summary-report.md',
3000
- resultSummary: 'Generated executive summary report and saved into workspace deliverables.',
3001
- verified: true,
3002
- });
3003
- renderAgentState(simState, []);
3004
- } else if (stepIndex >= 6) {
3005
- clearInterval(activeSimulationTimer);
3006
- activeSimulationTimer = null;
3007
- simState.status = 'completed';
3008
- simState.plan[4].status = 'completed';
3009
- simState.completed_at = new Date().toISOString();
3010
- renderAgentState(simState, []);
3011
-
3012
- // Save to history store
3013
- tasksHistoryStore.unshift(simState);
3014
- saveTasksHistoryToStorage();
3015
- updateDashboardMetrics(simState);
3016
- showToast('🎉 Autonomous Operator completed task successfully! Deliverables ready.', 'success');
3017
- }
3018
- }, 1800);
3019
- }
3020
-
3021
- btnRefresh?.addEventListener('click', () => {
3022
- fetchAgentState();
3023
- showToast('Operator state refreshed', 'info');
3024
- });
3025
-
3026
- btnCancel?.addEventListener('click', async () => {
3027
- if (activeSimulationTimer) {
3028
- clearInterval(activeSimulationTimer);
3029
- activeSimulationTimer = null;
3030
- }
3031
-
3032
- if (state.serverConnected) {
3033
- try {
3034
- const apiBase = state.apiBaseUrl || '';
3035
- await fetch(`${apiBase}/api/agent/cancel`, {
3036
- method: 'POST',
3037
- headers: { 'Content-Type': 'application/json' },
3038
- body: JSON.stringify({ reason: 'Halted from Scout Command Center' }),
3039
- });
3040
- } catch { }
3041
- }
3042
-
3043
- showToast('Autonomous task cancelled by operator.', 'warning');
3044
- const idleState = {
3045
- status: 'idle',
3046
- currentStep: 0,
3047
- maxSteps: 30,
3048
- active_application: 'Workstation Ready',
3049
- plan: [],
3050
- observations: [],
3051
- artifacts: [],
3052
- };
3053
- renderAgentState(idleState, []);
3054
- updateDashboardMetrics(idleState);
3055
- });
3056
-
3057
- btnApprove?.addEventListener('click', async () => {
3058
- if (!currentPendingApprovalId) return;
3059
- try {
3060
- const apiBase = state.apiBaseUrl || '';
3061
- await fetch(`${apiBase}/api/agent/approval`, {
3062
- method: 'POST',
3063
- headers: { 'Content-Type': 'application/json' },
3064
- body: JSON.stringify({ requestId: currentPendingApprovalId, approved: true }),
3065
- });
3066
- showToast('Action approved! Agent resuming execution...', 'success');
3067
- fetchAgentState();
3068
- } catch {
3069
- showToast('Action approval sent', 'info');
3070
- }
3071
- });
3072
-
3073
- btnDeny?.addEventListener('click', async () => {
3074
- if (!currentPendingApprovalId) return;
3075
- try {
3076
- const apiBase = state.apiBaseUrl || '';
3077
- await fetch(`${apiBase}/api/agent/approval`, {
3078
- method: 'POST',
3079
- headers: { 'Content-Type': 'application/json' },
3080
- body: JSON.stringify({ requestId: currentPendingApprovalId, approved: false, reason: 'Denied by user from Dashboard UI' }),
3081
- });
3082
- showToast('Action denied. Agent informed to seek alternate path.', 'warning');
3083
- fetchAgentState();
3084
- } catch {
3085
- showToast('Action denied.', 'info');
3086
- }
3087
- });
3088
-
3089
- // Initial fetch & interval polling
3090
- fetchAgentState();
3091
- if (agentMonitorPollTimer) clearInterval(agentMonitorPollTimer);
3092
- agentMonitorPollTimer = setInterval(fetchAgentState, 2500);
3093
-
3094
- // Initial tasks and activity render
3095
- renderTasksList();
3096
- renderActivityTimeline();
3097
- renderArtifactsGallery();
3098
- }
3099
-
3100
- function updateDashboardMetrics(activeState) {
3101
- const isRunning = activeState && (activeState.status === 'executing' || activeState.status === 'running' || activeState.status === 'planning');
3102
-
3103
- if (getEl('stat-active-ops')) getEl('stat-active-ops').innerText = isRunning ? '1' : '0';
3104
- if (getEl('stat-tasks-completed')) {
3105
- const completedCount = tasksHistoryStore.filter(t => t.status === 'completed').length;
3106
- getEl('stat-tasks-completed').innerText = String(completedCount);
3107
- }
3108
- if (getEl('stat-connected-devices')) {
3109
- const sessCount = state.sessions && state.sessions.length > 0 ? state.sessions.length : 1;
3110
- getEl('stat-connected-devices').innerText = String(sessCount);
3111
- }
3112
- if (getEl('stat-credit-mode')) {
3113
- getEl('stat-credit-mode').innerText = state.byokEnabled ? 'BYOK Mode' : `${state.creditsTotal || 100} Quota`;
3114
- }
3115
-
3116
- if (getEl('sidebar-task-count')) {
3117
- getEl('sidebar-task-count').innerText = String(tasksHistoryStore.length);
3118
- }
3119
- if (getEl('sidebar-artifact-count')) {
3120
- let totalArts = 0;
3121
- tasksHistoryStore.forEach(t => { if (t.artifacts) totalArts += t.artifacts.length; });
3122
- getEl('sidebar-artifact-count').innerText = String(Math.max(totalArts, 1));
3123
- }
3124
- }
3125
-
3126
- // Tasks List Renderer (Screen 8)
3127
- function renderTasksList(filter = 'all', searchQuery = '') {
3128
- const listContainer = getEl('tasks-list-container');
3129
- const recentOverviewList = getEl('overview-recent-tasks-list');
3130
-
3131
- let filtered = [...tasksHistoryStore];
3132
- if (filter !== 'all') {
3133
- filtered = filtered.filter(t => (t.status || '').toLowerCase() === filter.toLowerCase());
3134
- }
3135
- if (searchQuery.trim()) {
3136
- const q = searchQuery.toLowerCase().trim();
3137
- filtered = filtered.filter(t => (t.goal || t.objective || '').toLowerCase().includes(q));
3138
- }
3139
-
3140
- // Render Overview Recent Tasks (Top 3)
3141
- if (recentOverviewList) {
3142
- if (tasksHistoryStore.length === 0) {
3143
- recentOverviewList.innerHTML = `
3144
- <div style="color: var(--scout-text-tertiary); font-size: 13px; text-align: center; padding: 20px 0;">
3145
- <i class="fa-solid fa-terminal" style="font-size: 24px; margin-bottom: 8px; opacity: 0.4;"></i>
3146
- <p>No past tasks recorded yet. Start your first task above.</p>
3147
- </div>
3148
- `;
3149
- } else {
3150
- recentOverviewList.innerHTML = tasksHistoryStore.slice(0, 3).map(task => {
3151
- const isSuccess = task.status === 'completed';
3152
- const statusColor = isSuccess ? '#10b981' : (task.status === 'failed' ? '#ef4444' : '#38bdf8');
3153
- return `
3154
- <div style="padding: 12px; border-radius: 8px; background: rgba(255,255,255,0.02); border: 1px solid var(--scout-border); margin-bottom: 8px; display: flex; justify-content: space-between; align-items: center; gap: 10px;">
3155
- <div style="min-width: 0; flex: 1;">
3156
- <div style="font-size: 13px; font-weight: 500; color: #ffffff; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
3157
- ${escapeHtml(task.goal || task.objective || 'Autonomous Operation')}
3158
- </div>
3159
- <div style="font-size: 11px; color: var(--scout-text-tertiary); margin-top: 2px;">
3160
- <span>${timeAgo(task.created_at || task.createdAt)}</span> &bull; <span>${task.plan ? task.plan.length : 5} steps</span>
3161
- </div>
3162
- </div>
3163
- <span class="badge" style="background: rgba(255,255,255,0.05); color: ${statusColor}; border: 1px solid ${statusColor}44; font-size: 10px; font-weight: 600;">
3164
- ${(task.status || 'IDLE').toUpperCase()}
3165
- </span>
3166
- </div>
3167
- `;
3168
- }).join('');
3169
- }
3170
- }
3171
-
3172
- // Render Full Tasks View (Screen 8)
3173
- if (listContainer) {
3174
- if (filtered.length === 0) {
3175
- listContainer.innerHTML = `
3176
- <div class="scout-card" style="padding: 40px 20px; text-align: center; color: var(--scout-text-tertiary);">
3177
- <i class="fa-solid fa-list-check" style="font-size: 32px; margin-bottom: 12px; opacity: 0.4;"></i>
3178
- <p>No tasks match the selected filter.</p>
3179
- </div>
3180
- `;
3181
- return;
3182
- }
3183
-
3184
- listContainer.innerHTML = filtered.map(task => {
3185
- const isSuccess = task.status === 'completed';
3186
- const statusColor = isSuccess ? '#10b981' : (task.status === 'failed' ? '#ef4444' : '#38bdf8');
3187
- const stepCount = task.plan ? task.plan.length : 0;
3188
- const completedCount = task.plan ? task.plan.filter(p => p.status === 'completed').length : 0;
3189
- const artCount = task.artifacts ? task.artifacts.length : 0;
3190
-
3191
- return `
3192
- <div class="scout-card" style="padding: 16px 20px;">
3193
- <div style="display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 12px; margin-bottom: 10px;">
3194
- <div>
3195
- <div style="display: flex; align-items: center; gap: 8px;">
3196
- <span class="badge" style="background: rgba(255,255,255,0.05); color: ${statusColor}; border: 1px solid ${statusColor}44; font-size: 11px; font-weight: 600;">
3197
- ${(task.status || 'COMPLETED').toUpperCase()}
3198
- </span>
3199
- <span style="font-family: var(--font-mono); font-size: 11px; color: var(--scout-text-tertiary);">
3200
- ${escapeHtml((task.taskId || '').slice(0, 12))}
3201
- </span>
3202
- </div>
3203
- <h4 style="font-size: 15px; margin: 6px 0 2px; color: #ffffff;">${escapeHtml(task.goal || task.objective || 'Autonomous Goal')}</h4>
3204
- <span style="font-size: 12px; color: var(--scout-text-tertiary); font-family: var(--font-mono);">Started: ${timeAgo(task.created_at || task.createdAt)}</span>
3205
- </div>
3206
- <div style="display: flex; align-items: center; gap: 8px;">
3207
- <span class="badge" style="font-size: 11px; background: rgba(255,255,255,0.04);"><i class="fa-solid fa-list-check"></i> ${completedCount} / ${stepCount} steps</span>
3208
- ${artCount > 0 ? `<span class="badge" style="font-size: 11px; background: rgba(225,91,55,0.1); color: var(--scout-rust); border: 1px solid rgba(225,91,55,0.25);"><i class="fa-solid fa-cube"></i> ${artCount} artifacts</span>` : ''}
3209
- </div>
3210
- </div>
3211
-
3212
- ${task.plan && task.plan.length > 0 ? `
3213
- <div style="display: flex; flex-direction: column; gap: 4px; margin-top: 10px; padding: 10px; background: rgba(10,12,17,0.4); border-radius: 6px; border: 1px solid var(--scout-border-subtle);">
3214
- ${task.plan.slice(0, 3).map(p => `
3215
- <div style="font-size: 12px; color: var(--scout-text-secondary); display: flex; align-items: center; gap: 6px;">
3216
- <i class="fa-solid fa-circle-check text-success" style="font-size: 11px;"></i>
3217
- <span>${escapeHtml(p.description)}</span>
3218
- </div>
3219
- `).join('')}
3220
- ${task.plan.length > 3 ? `<span style="font-size: 11px; color: var(--scout-text-tertiary); margin-left: 17px;">+ ${task.plan.length - 3} more steps executed</span>` : ''}
3221
- </div>
3222
- ` : ''}
3223
- </div>
3224
- `;
3225
- }).join('');
3226
- }
3227
- }
3228
-
3229
- // Activity Timeline Renderer (Screen 7)
3230
- function renderActivityTimeline(observations = []) {
3231
- const overviewTimeline = getEl('overview-timeline-list');
3232
- const fullTimeline = getEl('full-activity-timeline');
3233
-
3234
- // Build default telemetry if none provided
3235
- const baseEvents = [
3236
- { icon: 'shield-halved', type: 'success', title: 'Bounded Recovery & Safety Verifier Online', meta: 'Deterministic post-conditions active' },
3237
- { icon: 'desktop', type: 'desktop', title: 'Native Workstation Driver Active (scout_driver.exe)', meta: 'Win32 Coordinates & Window Perception' },
3238
- { icon: 'globe', type: 'browser', title: 'Autonomous Browser & DOM Parser Initialized', meta: 'DOM Ref IDs & Headless Engine' },
3239
- { icon: 'brain', type: 'success', title: 'Cognitive Scratchpad & DAG Planner Ready', meta: 'Workspace vector memory indexed' },
3240
- ];
3241
-
3242
- const obsEvents = observations.map(obs => {
3243
- let type = 'browser';
3244
- let icon = 'globe';
3245
- if (obs.tool === 'browser_open' || obs.tool === 'browser_scrape') { type = 'browser'; icon = 'globe'; }
3246
- else if (obs.tool === 'scratchpad') { type = 'success'; icon = 'brain'; }
3247
- else if (obs.tool === 'verifier') { type = 'success'; icon = 'shield-halved'; }
3248
- else if (obs.tool === 'file_write') { type = 'desktop'; icon = 'file-lines'; }
3249
-
3250
- return {
3251
- icon,
3252
- type,
3253
- title: obs.resultSummary || `${obs.tool} executed on ${obs.target || 'workspace'}`,
3254
- meta: `${timeAgo(obs.timestamp)} • Tool: ${obs.tool}`,
3255
- };
3256
- });
3257
-
3258
- const allEvents = [...obsEvents, ...baseEvents];
3259
-
3260
- const htmlString = allEvents.map(evt => `
3261
- <div class="scout-timeline-item">
3262
- <div class="scout-timeline-icon ${evt.type}"><i class="fa-solid fa-${evt.icon}"></i></div>
3263
- <div class="scout-timeline-content">
3264
- <div class="scout-timeline-title">${escapeHtml(evt.title)}</div>
3265
- <div class="scout-timeline-meta">${escapeHtml(evt.meta)}</div>
3266
- </div>
3267
- </div>
3268
- `).join('');
3269
-
3270
- if (overviewTimeline) overviewTimeline.innerHTML = allEvents.slice(0, 4).map(evt => `
3271
- <div class="scout-timeline-item">
3272
- <div class="scout-timeline-icon ${evt.type}"><i class="fa-solid fa-${evt.icon}"></i></div>
3273
- <div class="scout-timeline-content">
3274
- <div class="scout-timeline-title">${escapeHtml(evt.title)}</div>
3275
- <div class="scout-timeline-meta">${escapeHtml(evt.meta)}</div>
3276
- </div>
3277
- </div>
3278
- `).join('');
3279
-
3280
- if (fullTimeline) fullTimeline.innerHTML = htmlString;
3281
- }
3282
-
3283
- // Artifacts Gallery Renderer (Screen 9)
3284
- function renderArtifactsGallery(newArtifacts = []) {
3285
- const container = getEl('artifacts-gallery-container');
3286
- if (!container) return;
3287
-
3288
- // Collect all artifacts from tasksHistoryStore
3289
- let allArts = [];
3290
- tasksHistoryStore.forEach(t => {
3291
- if (t.artifacts && Array.isArray(t.artifacts)) {
3292
- t.artifacts.forEach(a => {
3293
- if (!allArts.some(x => x.name === a.name)) allArts.push(a);
3294
- });
3295
- }
3296
- });
3297
-
3298
- newArtifacts.forEach(a => {
3299
- if (!allArts.some(x => x.name === a.name)) allArts.push(a);
3300
- });
3301
-
3302
- // Default static artifacts if none produced yet
3303
- if (allArts.length === 0) {
3304
- allArts = [
3305
- { name: 'scan-report.json', filename: 'scan-report.json', type: 'Codebase AST Map', source: 'Scout Analyzer' },
3306
- { name: 'scout-architecture.md', filename: 'scout-architecture.md', type: 'Technical Architecture Brief', source: 'Autonomous Engine' },
3307
- ];
3308
- }
3309
-
3310
- container.innerHTML = allArts.map(art => {
3311
- const name = art.name || art.filename || 'Artifact';
3312
- let icon = 'fa-file-lines';
3313
- if (name.endsWith('.json')) icon = 'fa-file-code';
3314
- else if (name.endsWith('.md')) icon = 'fa-file-lines';
3315
- else if (name.endsWith('.pdf')) icon = 'fa-file-pdf text-danger';
3316
-
3317
- return `
3318
- <div class="scout-artifact-card">
3319
- <div class="scout-artifact-top">
3320
- <div class="scout-artifact-icon"><i class="fa-solid ${icon}"></i></div>
3321
- <div class="scout-artifact-details">
3322
- <div class="scout-artifact-name">${escapeHtml(name)}</div>
3323
- <div class="scout-artifact-desc">${escapeHtml(art.type || 'Generated Deliverable')}</div>
3324
- </div>
3325
- </div>
3326
- <div class="scout-artifact-footer">
3327
- <span>${escapeHtml(art.source || 'Scout Operator')}</span>
3328
- <button type="button" class="btn btn-xs btn-outline" onclick="showToast('Artifact copied to clipboard', 'success')"><i class="fa-solid fa-copy"></i> Copy</button>
3329
- </div>
3330
- </div>
3331
- `;
3332
- }).join('');
3333
- }
3334
-
3335
- // Enterprise Workstation View Router
3336
- function initWorkstationRouter() {
3337
- const viewLinks = document.querySelectorAll('[data-view]');
3338
- const settingsTabs = document.querySelectorAll('.scout-settings-tab');
3339
- const mobileToggle = getEl('btn-mobile-sidebar-toggle');
3340
- const sidebar = getEl('scout-sidebar');
3341
- const breadcrumbView = getEl('topbar-breadcrumb-view');
3342
- const chipButtons = document.querySelectorAll('.scout-suggestion-chip');
3343
- const modelSelect = getEl('composer-model-select');
3344
- const taskSearch = getEl('input-task-search');
3345
- const filterBtns = document.querySelectorAll('.task-filter-btn');
3346
-
3347
- function switchView(viewName) {
3348
- if (!viewName) viewName = 'overview';
3349
- const cleanName = viewName.replace('#', '').trim();
3350
-
3351
- // 1. Switch View Containers
3352
- let viewElement = getEl(`view-${cleanName}`);
3353
- if (!viewElement) {
3354
- cleanName === 'overview';
3355
- viewElement = getEl('view-overview');
3356
- }
3357
-
3358
- document.querySelectorAll('.scout-view').forEach(v => v.classList.remove('active'));
3359
- if (viewElement) viewElement.classList.add('active');
3360
-
3361
- // 2. Update Sidebar Active Navigation
3362
- document.querySelectorAll('.scout-nav-item').forEach(item => {
3363
- const itemTarget = item.getAttribute('data-view') || item.getAttribute('href')?.replace('#', '');
3364
- if (itemTarget === cleanName || (cleanName.startsWith('models') && itemTarget === 'models') || (cleanName.startsWith('usage') && itemTarget === 'usage') || (cleanName.startsWith('account') && itemTarget === 'account')) {
3365
- item.classList.add('active');
3366
- } else {
3367
- item.classList.remove('active');
3368
- }
3369
- });
3370
-
3371
- // 3. Update Settings Subnav Tabs
3372
- document.querySelectorAll('.scout-settings-tab').forEach(tab => {
3373
- const tabTarget = tab.getAttribute('href')?.replace('#', '');
3374
- if (tabTarget === cleanName) tab.classList.add('active');
3375
- else tab.classList.remove('active');
3376
- });
3377
-
3378
- // 4. Update Topbar Breadcrumb
3379
- if (breadcrumbView) {
3380
- const labels = {
3381
- overview: 'Overview',
3382
- tasks: 'Tasks',
3383
- activity: 'Activity',
3384
- artifacts: 'Artifacts',
3385
- connections: 'Connections',
3386
- computer: 'Computer Use',
3387
- cli: 'Web CLI',
3388
- models: 'Models & BYOK',
3389
- usage: 'Usage & Quotas',
3390
- account: 'Account Profile',
3391
- };
3392
- breadcrumbView.innerText = labels[cleanName] || 'Overview';
3393
- }
3394
-
3395
- if (cleanName === 'connections') {
3396
- loadMcpData();
3397
- }
3398
-
3399
- // Close mobile sidebar if opened
3400
- sidebar?.classList.remove('open');
3401
- window.scrollTo({ top: 0, behavior: 'smooth' });
3402
- }
3403
-
3404
- // Hashchange listener
3405
- window.addEventListener('hashchange', () => {
3406
- const hash = window.location.hash || '#overview';
3407
- switchView(hash);
3408
- });
3409
-
3410
- // Initial view from hash
3411
- const initialHash = window.location.hash || '#overview';
3412
- switchView(initialHash);
3413
-
3414
- // Mobile Sidebar Drawer Toggle
3415
- mobileToggle?.addEventListener('click', () => {
3416
- sidebar?.classList.toggle('open');
3417
- });
3418
-
3419
- // Close sidebar on background click
3420
- document.addEventListener('click', (e) => {
3421
- if (sidebar?.classList.contains('open') && !sidebar.contains(e.target) && !mobileToggle?.contains(e.target)) {
3422
- sidebar.classList.remove('open');
3423
- }
3424
- });
3425
-
3426
- // Quick sign out from sidebar
3427
- getEl('btn-sidebar-quick-logout')?.addEventListener('click', handleLogout);
3428
-
3429
- // Suggestion Chips Click Handling
3430
- chipButtons.forEach(chip => {
3431
- chip.addEventListener('click', () => {
3432
- const prompt = chip.getAttribute('data-prompt');
3433
- const input = getEl('agent-goal-input');
3434
- if (prompt && input) {
3435
- input.value = prompt;
3436
- input.focus();
3437
- }
3438
- });
3439
- });
3440
-
3441
- // Composer Model Select Sync
3442
- modelSelect?.addEventListener('change', (e) => {
3443
- const val = e.target.value;
3444
- const topbarModel = getEl('topbar-engine-model');
3445
- const byokSelect = getEl('select-byok-provider');
3446
-
3447
- if (topbarModel) {
3448
- const names = {
3449
- nvidia: 'Nemotron 70B',
3450
- gemini: 'Gemini 2.5 Flash',
3451
- openai: 'GPT-4o',
3452
- anthropic: 'Claude 3.7 Sonnet',
3453
- custom: 'Local LLM / Proxy',
3454
- };
3455
- topbarModel.innerText = names[val] || val.toUpperCase();
3456
- }
3457
-
3458
- if (byokSelect) byokSelect.value = val;
3459
- state.customLlmProvider = val;
3460
- });
3461
-
3462
- // Tasks Search & Filter
3463
- taskSearch?.addEventListener('input', (e) => {
3464
- const query = e.target.value;
3465
- const activeFilter = document.querySelector('.task-filter-btn.active')?.dataset?.filter || 'all';
3466
- renderTasksList(activeFilter, query);
3467
- });
3468
-
3469
- filterBtns.forEach(btn => {
3470
- btn.addEventListener('click', () => {
3471
- filterBtns.forEach(b => b.classList.remove('active'));
3472
- btn.classList.add('active');
3473
- const filter = btn.dataset.filter || 'all';
3474
- const query = taskSearch?.value || '';
3475
- renderTasksList(filter, query);
3476
- });
3477
- });
3478
- }
3479
-
3480
- // ==========================================================================
3481
- // Model Context Protocol (MCP) Cloud Ecosystem Controller
3482
- // ==========================================================================
3483
-
3484
- function getAccountMcpStorageKey() {
3485
- const email = (state.user?.email || '').trim().toLowerCase();
3486
- return email ? `scout_mcp_servers_${email}` : 'scout_cached_mcp_servers';
3487
- }
3488
-
3489
- function getSampleToolsForMcpServer(name) {
3490
- const lower = (name || '').toLowerCase();
3491
- if (lower.includes('github')) {
3492
- return [
3493
- { name: 'github_search_repositories', originalName: 'search_repositories', description: 'Search GitHub repositories with query filters and topic sorting.', inputSchema: { properties: { query: { type: 'string' } } }, enabled: true, permissionLevel: 'read' },
3494
- { name: 'github_get_file_contents', originalName: 'get_file_contents', description: 'Retrieve file contents and metadata from a repository branch.', inputSchema: { properties: { path: { type: 'string' }, repo: { type: 'string' } } }, enabled: true, permissionLevel: 'read' },
3495
- { name: 'github_create_issue', originalName: 'create_issue', description: 'Create a new issue in a GitHub repository.', inputSchema: { properties: { title: { type: 'string' }, body: { type: 'string' } } }, enabled: true, permissionLevel: 'write' },
3496
- { name: 'github_create_pull_request', originalName: 'create_pull_request', description: 'Open a pull request from a branch.', inputSchema: { properties: { title: { type: 'string' }, head: { type: 'string' }, base: { type: 'string' } } }, enabled: true, permissionLevel: 'write' }
3497
- ];
3498
- }
3499
- if (lower.includes('figma')) {
3500
- return [
3501
- { name: 'figma_get_file', originalName: 'get_file', description: 'Retrieve JSON document tree of a Figma design file.', inputSchema: { properties: { fileKey: { type: 'string' } } }, enabled: true, permissionLevel: 'read' },
3502
- { name: 'figma_get_comments', originalName: 'get_comments', description: 'List design comments and feedback threads.', inputSchema: { properties: { fileKey: { type: 'string' } } }, enabled: true, permissionLevel: 'read' },
3503
- { name: 'figma_post_comment', originalName: 'post_comment', description: 'Post an automated review comment to a canvas component.', inputSchema: { properties: { fileKey: { type: 'string' }, message: { type: 'string' } } }, enabled: true, permissionLevel: 'write' }
3504
- ];
3505
- }
3506
- if (lower.includes('motion') || lower.includes('higgsfield')) {
3507
- return [
3508
- { name: 'video_generate_scene', originalName: 'generate_scene', description: 'Generate AI video animation keyframes from script prompts.', inputSchema: { properties: { prompt: { type: 'string' }, duration: { type: 'number' } } }, enabled: true, permissionLevel: 'write' },
3509
- { name: 'video_check_render_status', originalName: 'check_render_status', description: 'Poll video rendering progress and preview stream URLs.', inputSchema: { properties: { renderId: { type: 'string' } } }, enabled: true, permissionLevel: 'read' },
3510
- { name: 'video_export_mp4', originalName: 'export_mp4', description: 'Export final rendered sequence to MP4 video asset.', inputSchema: { properties: { renderId: { type: 'string' } } }, enabled: true, permissionLevel: 'write' }
3511
- ];
3512
- }
3513
- if (lower.includes('slack') || lower.includes('discord')) {
3514
- return [
3515
- { name: 'chat_send_message', originalName: 'send_message', description: 'Send a message or structured alert to a channel.', inputSchema: { properties: { channel: { type: 'string' }, message: { type: 'string' } } }, enabled: true, permissionLevel: 'write' },
3516
- { name: 'chat_read_history', originalName: 'read_history', description: 'Read recent messages and channel context.', inputSchema: { properties: { channel: { type: 'string' }, limit: { type: 'number' } } }, enabled: true, permissionLevel: 'read' }
3517
- ];
3518
- }
3519
- const slug = lower.replace(/[^a-z0-9]/g, '_') || 'mcp';
3520
- return [
3521
- { name: `${slug}_query_context`, originalName: 'query_context', description: `Retrieve dynamic context from ${name} provider.`, inputSchema: { properties: { query: { type: 'string' } } }, enabled: true, permissionLevel: 'read' },
3522
- { name: `${slug}_execute_action`, originalName: 'execute_action', description: `Execute autonomous actions via verified ${name} MCP schema.`, inputSchema: { properties: { action: { type: 'string' }, params: { type: 'object' } } }, enabled: true, permissionLevel: 'write' },
3523
- { name: `${slug}_list_resources`, originalName: 'list_resources', description: `Enumerate available data resources and prompt templates for ${name}.`, inputSchema: { properties: {} }, enabled: true, permissionLevel: 'read' }
3524
- ];
3525
- }
3526
-
3527
- async function connectRemoteMcpInBrowser(server) {
3528
- let latencyMs = Math.floor(Math.random() * 18) + 22;
3529
- let tools = (server.tools && server.tools.length > 0) ? server.tools : [];
3530
-
3531
- if (server.transport === 'http' && server.endpoint) {
3532
- try {
3533
- const startTime = performance.now();
3534
- const headers = { 'Content-Type': 'application/json' };
3535
- if (server.token) {
3536
- if (server.authType === 'apiKey') {
3537
- headers[server.headerKey || 'x-api-key'] = server.token;
3538
- } else {
3539
- headers['Authorization'] = `Bearer ${server.token}`;
3540
- }
3541
- }
3542
-
3543
- const controller = new AbortController();
3544
- const timeoutId = setTimeout(() => controller.abort(), 4000);
3545
- const res = await fetch(server.endpoint, {
3546
- method: 'POST',
3547
- headers,
3548
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }),
3549
- signal: controller.signal
3550
- });
3551
- clearTimeout(timeoutId);
3552
- latencyMs = Math.max(12, Math.round(performance.now() - startTime));
3553
-
3554
- if (res.ok) {
3555
- const contentType = (res.headers.get('content-type') || '').toLowerCase();
3556
- if (contentType.includes('application/json')) {
3557
- const json = await res.json();
3558
- if (json?.result?.tools && Array.isArray(json.result.tools) && json.result.tools.length > 0) {
3559
- tools = json.result.tools.map(t => ({
3560
- name: t.name,
3561
- originalName: t.name,
3562
- description: t.description || 'Discovered via live MCP JSON-RPC protocol.',
3563
- inputSchema: t.inputSchema || {},
3564
- enabled: true,
3565
- permissionLevel: 'read'
3566
- }));
3567
- }
3568
- }
3569
- }
3570
- } catch (e) {
3571
- // Handled gracefully in browser mode
3572
- }
3573
- }
3574
-
3575
- if (!tools || tools.length === 0) {
3576
- tools = getSampleToolsForMcpServer(server.name);
3577
- }
3578
-
3579
- return { tools, latencyMs };
3580
- }
3581
-
3582
- let mcpSyncPollerTimer = null;
3583
- const FIRESTORE_MCP_BASE = `https://firestore.googleapis.com/v1/projects/${FIREBASE_CONFIG.projectId}/databases/(default)/documents/mcp_servers`;
3584
-
3585
- async function fetchCloudMcpServers(filterEmail) {
3586
- try {
3587
- const controller = new AbortController();
3588
- const timeoutId = setTimeout(() => controller.abort(), 4000);
3589
- const url = `${FIRESTORE_MCP_BASE}?key=${FIREBASE_CONFIG.apiKey}&pageSize=100`;
3590
- const res = await fetch(url, { signal: controller.signal });
3591
- clearTimeout(timeoutId);
3592
- if (!res.ok) return null;
3593
- const data = await res.json();
3594
- if (!data.documents || !Array.isArray(data.documents)) return [];
3595
- const servers = [];
3596
- const normEmail = filterEmail ? filterEmail.trim().toLowerCase() : '';
3597
- for (const doc of data.documents) {
3598
- try {
3599
- const fields = doc.fields || {};
3600
- const jsonStr = fields.dataJson?.stringValue;
3601
- if (!jsonStr) continue;
3602
- const server = JSON.parse(jsonStr);
3603
- const docEmail = (fields.userEmail?.stringValue || server.userEmail || '').trim().toLowerCase();
3604
- if (normEmail && docEmail && docEmail !== normEmail && docEmail !== 'global' && docEmail !== 'default') {
3605
- continue;
3606
- }
3607
- servers.push(server);
3608
- } catch {}
3609
- }
3610
- return servers;
3611
- } catch (e) {
3612
- console.warn('[MCP Cloud] Failed to fetch cloud MCP servers:', e);
3613
- return null;
3614
- }
3615
- }
3616
-
3617
- async function pushCloudMcpServer(server) {
3618
- try {
3619
- const controller = new AbortController();
3620
- const timeoutId = setTimeout(() => controller.abort(), 5000);
3621
- const docId = encodeURIComponent(server.id);
3622
- const url = `${FIRESTORE_MCP_BASE}/${docId}?key=${FIREBASE_CONFIG.apiKey}`;
3623
- const now = new Date().toISOString();
3624
- const payload = {
3625
- fields: {
3626
- id: { stringValue: server.id },
3627
- name: { stringValue: server.name || '' },
3628
- transport: { stringValue: server.transport || 'http' },
3629
- endpoint: { stringValue: server.endpoint || '' },
3630
- command: { stringValue: server.command || '' },
3631
- userEmail: { stringValue: server.userEmail || '' },
3632
- userId: { stringValue: server.userId || '' },
3633
- status: { stringValue: server.status || 'connected' },
3634
- toolCount: { integerValue: String(server.tools?.length || 0) },
3635
- updatedAt: { stringValue: now },
3636
- dataJson: { stringValue: JSON.stringify(server) }
3637
- }
3638
- };
3639
- const res = await fetch(url, {
3640
- method: 'PATCH',
3641
- headers: { 'Content-Type': 'application/json' },
3642
- body: JSON.stringify(payload),
3643
- signal: controller.signal
3644
- });
3645
- clearTimeout(timeoutId);
3646
- return res.ok;
3647
- } catch (e) {
3648
- console.warn('[MCP Cloud] Failed to push MCP server to cloud:', e);
3649
- return false;
3650
- }
3651
- }
3652
-
3653
- async function deleteCloudMcpServer(serverId) {
3654
- try {
3655
- const controller = new AbortController();
3656
- const timeoutId = setTimeout(() => controller.abort(), 4000);
3657
- const docId = encodeURIComponent(serverId);
3658
- const url = `${FIRESTORE_MCP_BASE}/${docId}?key=${FIREBASE_CONFIG.apiKey}`;
3659
- const res = await fetch(url, {
3660
- method: 'DELETE',
3661
- signal: controller.signal
3662
- });
3663
- clearTimeout(timeoutId);
3664
- return res.ok;
3665
- } catch (e) {
3666
- console.warn('[MCP Cloud] Failed to delete MCP server from cloud:', e);
3667
- return false;
3668
- }
3669
- }
3670
-
3671
- async function getMcpApiBase() {
3672
- if (state.serverConnected && state.apiBaseUrl !== undefined) {
3673
- return state.apiBaseUrl;
3674
- }
3675
- const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' || window.location.protocol === 'file:';
3676
- if (isLocalhost) {
3677
- try {
3678
- const res = await fetch('/api/status', { method: 'GET' });
3679
- if (res.ok) {
3680
- const data = await res.json();
3681
- if (data && data.status === 'ok') {
3682
- state.apiBaseUrl = '';
3683
- state.serverConnected = true;
3684
- return '';
3685
- }
3686
- }
3687
- } catch { }
3688
- }
3689
- const candidateHosts = ['http://localhost:9120', 'http://127.0.0.1:9120'];
3690
- for (const host of candidateHosts) {
3691
- try {
3692
- const controller = new AbortController();
3693
- const timeoutId = setTimeout(() => controller.abort(), 800);
3694
- const res = await fetch(`${host}/api/status`, { method: 'GET', signal: controller.signal });
3695
- clearTimeout(timeoutId);
3696
- if (res.ok) {
3697
- const data = await res.json();
3698
- if (data && data.status === 'ok') {
3699
- state.apiBaseUrl = host;
3700
- state.serverConnected = true;
3701
- return host;
3702
- }
3703
- }
3704
- } catch { }
3705
- }
3706
- return null;
3707
- }
3708
-
3709
- function renderMcpSyncStatus() {
3710
- const container = getEl('mcp-sync-status-container');
3711
- if (!container) return;
3712
-
3713
- container.innerHTML = `
3714
- <div class="mcp-sync-banner connected">
3715
- <div style="display: flex; align-items: center; gap: 10px;">
3716
- <span class="blink-dot" style="background-color: #10b981; width: 9px; height: 9px; border-radius: 50%; display: inline-block;"></span>
3717
- <span><strong>Cloud 2-Way CLI Sync Active:</strong> Synchronized with FrontTerrain Cloud Ecosystem. Changes instantly reflect in <code>scout mcp list</code>.</span>
3718
- </div>
3719
- <div style="display: flex; align-items: center; gap: 8px;">
3720
- <span style="font-size: 11px; opacity: 0.85;"><i class="fa-solid fa-arrows-rotate fa-spin" style="margin-right: 4px; color: #10b981;"></i> Cloud Sync</span>
3721
- <button class="btn btn-sm btn-outline" onclick="loadMcpData(true)" style="padding: 2px 8px; font-size: 11px;" title="Sync latest servers from Cloud">
3722
- <i class="fa-solid fa-rotate-right"></i> Refresh
3723
- </button>
3724
- </div>
3725
- </div>
3726
- `;
3727
- }
3728
-
3729
- const mcpState = {
3730
- servers: (() => {
3731
- try {
3732
- const key = (state.user?.email) ? `scout_mcp_servers_${state.user.email.toLowerCase()}` : 'scout_cached_mcp_servers';
3733
- const cached = localStorage.getItem(key) || localStorage.getItem('scout_cached_mcp_servers');
3734
- return cached ? JSON.parse(cached) : [];
3735
- } catch {
3736
- return [];
3737
- }
3738
- })(),
3739
- activity: [],
3740
- health: {},
3741
- selectedServer: null,
3742
- loading: false
3743
- };
3744
-
3745
- async function loadMcpData(forceProbe = false) {
3746
- const userEmail = (state.user?.email || '').trim().toLowerCase();
3747
- const storageKey = getAccountMcpStorageKey();
3748
-
3749
- // 1. Instantly load local cache so UI is responsive
3750
- try {
3751
- const cached = localStorage.getItem(storageKey) || localStorage.getItem('scout_cached_mcp_servers');
3752
- if (cached) {
3753
- const parsed = JSON.parse(cached);
3754
- if (Array.isArray(parsed)) {
3755
- mcpState.servers = parsed;
3756
- }
3757
- }
3758
- } catch { }
3759
-
3760
- const badgeEl = getEl('mcp-account-badge');
3761
- if (badgeEl) {
3762
- if (state.user?.email) {
3763
- badgeEl.style.display = 'inline-flex';
3764
- badgeEl.innerHTML = `<i class="fa-solid fa-user-check" style="margin-right: 4px;"></i> ${escapeHtml(state.user.email)}`;
3765
- } else {
3766
- badgeEl.style.display = 'none';
3767
- }
3768
- }
3769
-
3770
- renderMcpKpis();
3771
- renderMcpServersList();
3772
- renderMcpActivityList();
3773
- renderMcpSyncStatus();
3774
-
3775
- // 2. Fetch directly from Cloud Firestore (primary 2-way sync with CLI)
3776
- try {
3777
- const cloudServers = await fetchCloudMcpServers(userEmail);
3778
- if (cloudServers !== null && Array.isArray(cloudServers)) {
3779
- const serverMap = new Map();
3780
- for (const s of mcpState.servers) {
3781
- if (s && s.id) serverMap.set(s.id, s);
3782
- }
3783
- for (const s of cloudServers) {
3784
- if (s && s.id) serverMap.set(s.id, s);
3785
- }
3786
- mcpState.servers = Array.from(serverMap.values());
3787
- try {
3788
- localStorage.setItem(storageKey, JSON.stringify(mcpState.servers));
3789
- localStorage.setItem('scout_cached_mcp_servers', JSON.stringify(mcpState.servers));
3790
- } catch { }
3791
- renderMcpKpis();
3792
- renderMcpServersList();
3793
- }
3794
- } catch (e) {
3795
- console.warn('Cloud MCP sync fetch error:', e);
3796
- }
3797
-
3798
- // 3. Optional local bridge sync if local server happens to be running
3799
- const apiBase = await getMcpApiBase();
3800
- if (apiBase !== null) {
3801
- try {
3802
- const actRes = await fetch(`${apiBase}/api/mcp/activity?limit=50`, { method: 'GET' });
3803
- if (actRes.ok) {
3804
- const actData = await actRes.json();
3805
- if (actData.success && Array.isArray(actData.activity) && actData.activity.length > 0) {
3806
- mcpState.activity = actData.activity;
3807
- renderMcpActivityList();
3808
- }
3809
- }
3810
- } catch { }
3811
- }
3812
-
3813
- // 4. Setup background live poller (every 4s on #connections view)
3814
- if (!mcpSyncPollerTimer) {
3815
- mcpSyncPollerTimer = setInterval(async () => {
3816
- const isConnView = window.location.hash === '#connections' || document.getElementById('view-connections')?.classList.contains('active');
3817
- if (!isConnView) return;
3818
-
3819
- try {
3820
- const cloudServers = await fetchCloudMcpServers(userEmail);
3821
- if (cloudServers !== null && Array.isArray(cloudServers)) {
3822
- const serverMap = new Map();
3823
- for (const s of mcpState.servers) {
3824
- if (s && s.id) serverMap.set(s.id, s);
3825
- }
3826
- for (const s of cloudServers) {
3827
- if (s && s.id) serverMap.set(s.id, s);
3828
- }
3829
- const merged = Array.from(serverMap.values());
3830
- const newJson = JSON.stringify(merged);
3831
- const oldJson = JSON.stringify(mcpState.servers);
3832
- if (newJson !== oldJson) {
3833
- mcpState.servers = merged;
3834
- try {
3835
- localStorage.setItem(getAccountMcpStorageKey(), newJson);
3836
- localStorage.setItem('scout_cached_mcp_servers', newJson);
3837
- } catch { }
3838
- renderMcpKpis();
3839
- renderMcpServersList();
3840
- }
3841
- }
3842
- } catch { }
3843
- }, 4000);
3844
- }
3845
- }
3846
-
3847
-
3848
- function renderMcpKpis() {
3849
- const serversEl = getEl('mcp-stat-servers');
3850
- const toolsEl = getEl('mcp-stat-tools');
3851
- const invocationsEl = getEl('mcp-stat-invocations');
3852
- const healthEl = getEl('mcp-stat-health');
3853
- const sidebarBadge = getEl('sidebar-mcp-count');
3854
-
3855
- const totalServers = mcpState.servers.length;
3856
- let totalTools = 0;
3857
- let connectedCount = 0;
3858
-
3859
- mcpState.servers.forEach(s => {
3860
- if (s.tools && Array.isArray(s.tools)) {
3861
- totalTools += s.tools.filter(t => t.enabled !== false).length;
3862
- }
3863
- if (s.status === 'connected') {
3864
- connectedCount++;
3865
- }
3866
- });
3867
-
3868
- if (serversEl) serversEl.innerText = totalServers;
3869
- if (toolsEl) toolsEl.innerText = totalTools;
3870
- if (invocationsEl) invocationsEl.innerText = mcpState.activity.length;
3871
- if (sidebarBadge) sidebarBadge.innerText = totalServers;
3872
-
3873
- if (healthEl) {
3874
- if (totalServers === 0) {
3875
- healthEl.innerText = 'Idle';
3876
- healthEl.style.color = 'var(--scout-text-dim)';
3877
- } else {
3878
- const healthPct = Math.round((connectedCount / totalServers) * 100);
3879
- healthEl.innerText = `${healthPct}%`;
3880
- healthEl.style.color = healthPct === 100 ? '#10b981' : (healthPct > 50 ? '#f59e0b' : '#ef4444');
3881
- }
3882
- }
3883
- }
3884
-
3885
- function renderMcpServersList() {
3886
- const container = getEl('mcp-servers-list');
3887
- if (!container) return;
3888
-
3889
- if (mcpState.servers.length === 0) {
3890
- container.innerHTML = `
3891
- <div style="padding: 48px 24px; text-align: center;">
3892
- <div style="width: 56px; height: 56px; border-radius: 14px; background: rgba(0, 229, 255, 0.08); border: 1px solid rgba(0, 229, 255, 0.2); color: #00e5ff; display: inline-flex; align-items: center; justify-content: center; font-size: 24px; margin-bottom: 16px;">
3893
- <i class="fa-solid fa-cube"></i>
3894
- </div>
3895
- <h4 style="font-size: 16px; font-weight: 700; color: #fff; margin: 0 0 8px 0;">No External MCP Servers Connected</h4>
3896
- <p style="font-size: 13px; color: var(--scout-text-secondary); max-width: 480px; margin: 0 auto 20px auto; line-height: 1.5;">
3897
- Connect Scout to standard-compliant MCP servers (GitHub, Figma, Motion, Slack, or remote API endpoints) to empower the autonomous agent with custom tools.
3898
- </p>
3899
- <button type="button" class="btn btn-primary" onclick="openAddMcpModal()">
3900
- <i class="fa-solid fa-plus"></i> Connect First MCP Server
3901
- </button>
3902
- </div>
3903
- `;
3904
- return;
3905
- }
3906
-
3907
- const cardsHtml = mcpState.servers.map(server => {
3908
- const isConnected = server.status === 'connected';
3909
- const isConnecting = server.status === 'connecting';
3910
- const isUnauthorized = server.status === 'unauthorized';
3911
- const isError = server.status === 'error';
3912
-
3913
- let badgeClass = 'disconnected';
3914
- let badgeLabel = 'Disconnected';
3915
- if (isConnected) {
3916
- badgeClass = 'connected';
3917
- badgeLabel = 'Connected';
3918
- } else if (isConnecting) {
3919
- badgeClass = 'connecting';
3920
- badgeLabel = 'Connecting...';
3921
- } else if (isUnauthorized) {
3922
- badgeClass = 'unauthorized';
3923
- badgeLabel = 'Unauthorized';
3924
- } else if (isError) {
3925
- badgeClass = 'error';
3926
- badgeLabel = 'Offline';
3927
- }
3928
-
3929
- const h = mcpState.health[server.id] || server.health || {};
3930
- const latencyText = h.latencyMs !== undefined ? `${h.latencyMs}ms` : '--';
3931
- const toolsCount = server.tools ? server.tools.length : 0;
3932
- const activeToolsCount = server.tools ? server.tools.filter(t => t.enabled !== false).length : 0;
3933
- const isHttp = server.transport === 'http';
3934
- const endpointText = isHttp ? (server.endpoint || 'No endpoint') : `${server.command || ''} ${(server.args || []).join(' ')}`;
3935
-
3936
- return `
3937
- <div class="mcp-server-card" data-server-id="${escapeHtml(server.id)}">
3938
- <div class="mcp-server-header">
3939
- <div class="mcp-server-title-area">
3940
- <div class="mcp-server-avatar ${isHttp ? '' : 'stdio'}">
3941
- <i class="fa-solid ${isHttp ? 'fa-globe' : 'fa-terminal'}"></i>
3942
- </div>
3943
- <div>
3944
- <h4 class="mcp-server-name">
3945
- ${escapeHtml(server.name)}
3946
- <span class="badge ${isHttp ? 'badge-accent' : 'badge-primary'}" style="font-size: 10px; text-transform: uppercase;">${escapeHtml(server.transport)}</span>
3947
- </h4>
3948
- <div class="mcp-server-endpoint" title="${escapeHtml(endpointText)}">${escapeHtml(endpointText)}</div>
3949
- </div>
3950
- </div>
3951
- <span class="mcp-badge ${badgeClass}">
3952
- <span class="mcp-pulse-dot"></span>
3953
- ${badgeLabel}
3954
- </span>
3955
- </div>
3956
-
3957
- <div class="mcp-server-meta-grid">
3958
- <div class="mcp-meta-item">
3959
- <span class="mcp-meta-label">Active Tools</span>
3960
- <span class="mcp-meta-val">${activeToolsCount} / ${toolsCount}</span>
3961
- </div>
3962
- <div class="mcp-meta-item">
3963
- <span class="mcp-meta-label">Ping / Latency</span>
3964
- <span class="mcp-meta-val">${escapeHtml(latencyText)}</span>
3965
- </div>
3966
- <div class="mcp-meta-item">
3967
- <span class="mcp-meta-label">Auth Guard</span>
3968
- <span class="mcp-meta-val">${escapeHtml(server.authType || 'none')}</span>
3969
- </div>
3970
- </div>
3971
-
3972
- <div class="mcp-server-footer">
3973
- <div style="display: flex; gap: 8px; flex-wrap: wrap;">
3974
- ${isConnected ? `
3975
- <button type="button" class="btn btn-xs btn-outline" onclick="disconnectMcpServer('${escapeHtml(server.id)}')">
3976
- <i class="fa-solid fa-power-off"></i> Disconnect
3977
- </button>
3978
- ` : `
3979
- <button type="button" class="btn btn-xs btn-primary" onclick="connectMcpServer('${escapeHtml(server.id)}')">
3980
- <i class="fa-solid fa-plug"></i> Connect
3981
- </button>
3982
- `}
3983
- <button type="button" class="btn btn-xs btn-outline" onclick="openInspectMcpModal('${escapeHtml(server.id)}')">
3984
- <i class="fa-solid fa-magnifying-glass"></i> Tools (${toolsCount})
3985
- </button>
3986
- <button type="button" class="btn btn-xs btn-outline" title="Copy CLI command to connect this server in your terminal" onclick="copyMcpCliCommand('${escapeHtml(server.id)}')">
3987
- <i class="fa-solid fa-terminal text-primary"></i> Copy CLI Command
3988
- </button>
3989
- </div>
3990
- <button type="button" class="btn btn-xs btn-outline text-danger" title="Remove MCP Server" onclick="deleteMcpServer('${escapeHtml(server.id)}')">
3991
- <i class="fa-solid fa-trash"></i>
3992
- </button>
3993
- </div>
3994
- </div>
3995
- `;
3996
- }).join('');
3997
-
3998
- container.innerHTML = `<div class="mcp-servers-grid">${cardsHtml}</div>`;
3999
- }
4000
-
4001
- function renderMcpActivityList() {
4002
- const container = getEl('mcp-activity-list');
4003
- const counter = getEl('mcp-activity-counter');
4004
- if (!container) return;
4005
-
4006
- if (counter) counter.innerText = `${mcpState.activity.length} events`;
4007
-
4008
- if (mcpState.activity.length === 0) {
4009
- container.innerHTML = `
4010
- <div style="padding: 24px; text-align: center; color: var(--scout-text-dim); font-size: 13px;">
4011
- No MCP tool executions logged yet. As Scout solves goals, external tool calls will appear here.
4012
- </div>
4013
- `;
4014
- return;
4015
- }
4016
-
4017
- container.innerHTML = mcpState.activity.map(evt => {
4018
- const isSuccess = evt.status === 'success';
4019
- return `
4020
- <div style="display: flex; align-items: center; justify-content: space-between; padding: 10px 16px; border-bottom: 1px solid var(--scout-border-subtle); font-size: 12px; gap: 12px;">
4021
- <div style="display: flex; align-items: center; gap: 10px; min-width: 0;">
4022
- <span style="color: ${isSuccess ? 'var(--hr-emerald)' : 'var(--hr-rose)'}; font-size: 14px;">
4023
- <i class="fa-solid ${isSuccess ? 'fa-circle-check' : 'fa-circle-xmark'}"></i>
4024
- </span>
4025
- <div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
4026
- <strong style="color: #fff; font-family: var(--font-mono);">${escapeHtml(evt.toolName)}</strong>
4027
- <span style="color: var(--scout-text-dim); margin-left: 6px;">(${escapeHtml(evt.serverName || evt.serverId)})</span>
4028
- </div>
4029
- </div>
4030
- <div style="display: flex; align-items: center; gap: 12px; flex-shrink: 0;">
4031
- <span style="font-family: var(--font-mono); color: var(--scout-text-dim);">${evt.durationMs !== undefined ? `${evt.durationMs}ms` : ''}</span>
4032
- <span class="badge ${isSuccess ? 'badge-success' : 'badge-error'}" style="font-size: 10px; text-transform: uppercase;">${escapeHtml(evt.status)}</span>
4033
- <span style="color: var(--scout-text-dim); font-size: 11px;">${escapeHtml(timeAgo(evt.timestamp))}</span>
4034
- </div>
4035
- </div>
4036
- `;
4037
- }).join('');
4038
- }
4039
-
4040
- // Modal controls
4041
- function openAddMcpModal() {
4042
- const modal = getEl('modal-add-mcp');
4043
- if (modal) {
4044
- modal.style.display = 'flex';
4045
- toggleMcpTransportFields();
4046
- toggleMcpAuthFields();
4047
- getEl('mcp-input-name')?.focus();
4048
- }
4049
- }
4050
-
4051
- function closeAddMcpModal() {
4052
- const modal = getEl('modal-add-mcp');
4053
- if (modal) modal.style.display = 'none';
4054
- }
4055
-
4056
- function toggleMcpTransportFields() {
4057
- const selected = document.querySelector('input[name="mcp-transport"]:checked')?.value || 'http';
4058
- const httpFields = getEl('mcp-http-fields');
4059
- const stdioFields = getEl('mcp-stdio-fields');
4060
-
4061
- if (selected === 'http') {
4062
- if (httpFields) httpFields.style.display = 'block';
4063
- if (stdioFields) stdioFields.style.display = 'none';
4064
- } else {
4065
- if (httpFields) httpFields.style.display = 'none';
4066
- if (stdioFields) stdioFields.style.display = 'block';
4067
- }
4068
- }
4069
-
4070
- function toggleMcpAuthFields() {
4071
- const authType = getEl('mcp-select-auth')?.value || 'none';
4072
- const headerField = getEl('mcp-header-field');
4073
- const tokenField = getEl('mcp-token-field');
4074
-
4075
- if (authType === 'none') {
4076
- if (headerField) headerField.style.display = 'none';
4077
- if (tokenField) tokenField.style.display = 'none';
4078
- } else if (authType === 'bearer') {
4079
- if (headerField) headerField.style.display = 'none';
4080
- if (tokenField) tokenField.style.display = 'block';
4081
- } else if (authType === 'apiKey') {
4082
- if (headerField) headerField.style.display = 'block';
4083
- if (tokenField) tokenField.style.display = 'block';
4084
- }
4085
- }
4086
-
4087
- async function handleAddMcpServerSubmit(e) {
4088
- if (e) e.preventDefault();
4089
-
4090
- const name = getEl('mcp-input-name')?.value.trim();
4091
- const transport = document.querySelector('input[name="mcp-transport"]:checked')?.value || 'http';
4092
- const endpoint = getEl('mcp-input-endpoint')?.value.trim();
4093
- const command = getEl('mcp-input-command')?.value.trim();
4094
- const argsRaw = getEl('mcp-input-args')?.value.trim() || '';
4095
- const authType = getEl('mcp-select-auth')?.value || 'none';
4096
- const headerKey = getEl('mcp-input-header')?.value.trim();
4097
- const token = getEl('mcp-input-token')?.value;
4098
- const autoApproveSafe = getEl('mcp-perm-auto-approve')?.checked ?? true;
4099
- const requireConfirmationForDestructive = getEl('mcp-perm-require-confirm')?.checked ?? true;
4100
- const autoConnect = getEl('mcp-auto-connect')?.checked ?? true;
4101
-
4102
- if (!name) {
4103
- showToast('Please specify a server name.', 'error');
4104
- return;
4105
- }
4106
-
4107
- if (transport === 'http' && !endpoint) {
4108
- showToast('Please specify an HTTP endpoint URL.', 'error');
4109
- return;
4110
- }
4111
-
4112
- if (transport === 'stdio' && !command) {
4113
- showToast('Please specify an executable command.', 'error');
4114
- return;
4115
- }
4116
-
4117
- const args = argsRaw.length > 0 ? argsRaw.split(/\s+/).filter(Boolean) : [];
4118
-
4119
- const submitBtn = getEl('btn-submit-add-mcp');
4120
- if (submitBtn) {
4121
- submitBtn.disabled = true;
4122
- submitBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Connecting...';
4123
- }
4124
-
4125
- try {
4126
- const userEmail = (state.user?.email || '').trim().toLowerCase();
4127
- const userId = state.user?.id || state.user?.uid || undefined;
4128
- const normalizedAuthType = authType === 'apiKey' ? 'api-key' : authType;
4129
-
4130
- const tempServer = {
4131
- name,
4132
- transport,
4133
- endpoint: transport === 'http' ? endpoint : undefined,
4134
- command: transport === 'stdio' ? command : undefined,
4135
- args: transport === 'stdio' ? args : undefined,
4136
- authType: normalizedAuthType,
4137
- headerKey: normalizedAuthType === 'api-key' ? headerKey : undefined,
4138
- token: normalizedAuthType !== 'none' ? token : undefined,
4139
- };
4140
-
4141
- let discovered = { tools: [], latencyMs: 25 };
4142
- if (transport === 'http') {
4143
- try {
4144
- discovered = await connectRemoteMcpInBrowser(tempServer);
4145
- } catch (e) {
4146
- console.warn('Browser remote discovery info:', e);
4147
- }
4148
- }
4149
-
4150
- const newServer = {
4151
- id: `mcp_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
4152
- name,
4153
- transport,
4154
- endpoint: transport === 'http' ? endpoint : undefined,
4155
- command: transport === 'stdio' ? command : undefined,
4156
- args: transport === 'stdio' ? args : undefined,
4157
- authType: normalizedAuthType,
4158
- headerKey: normalizedAuthType === 'api-key' ? headerKey : undefined,
4159
- token: normalizedAuthType !== 'none' ? token : undefined,
4160
- status: 'connected',
4161
- userId,
4162
- userEmail: userEmail || 'default',
4163
- tools: discovered.tools || [],
4164
- health: {
4165
- latencyMs: discovered.latencyMs || 25,
4166
- status: 'healthy',
4167
- lastChecked: new Date().toISOString()
4168
- },
4169
- permissions: {
4170
- autoApproveSafe,
4171
- requireConfirmationForDestructive
4172
- },
4173
- createdAt: new Date().toISOString()
4174
- };
4175
-
4176
- // 1. Push directly to FrontTerrain Cloud Firestore (Immediate 2-way sync with CLI)
4177
- await pushCloudMcpServer(newServer);
4178
-
4179
- // 2. Notify local CLI server if running in background
4180
- const apiBase = await getMcpApiBase();
4181
- if (apiBase !== null) {
4182
- try {
4183
- await fetch(`${apiBase}/api/mcp/servers`, {
4184
- method: 'POST',
4185
- headers: { 'Content-Type': 'application/json' },
4186
- body: JSON.stringify({ ...newServer, autoConnect })
4187
- });
4188
- } catch { }
4189
- }
4190
-
4191
- // 3. Update local state and cache
4192
- const existingIdx = mcpState.servers.findIndex(s => s.id === newServer.id || s.name.toLowerCase() === newServer.name.toLowerCase());
4193
- if (existingIdx >= 0) {
4194
- mcpState.servers[existingIdx] = newServer;
4195
- } else {
4196
- mcpState.servers.unshift(newServer);
4197
- }
4198
-
4199
- const storageKey = getAccountMcpStorageKey();
4200
- try {
4201
- localStorage.setItem(storageKey, JSON.stringify(mcpState.servers));
4202
- localStorage.setItem('scout_cached_mcp_servers', JSON.stringify(mcpState.servers));
4203
- } catch { }
4204
-
4205
- mcpState.activity.unshift({
4206
- id: `mcp_act_${Date.now()}`,
4207
- serverId: newServer.id,
4208
- serverName: newServer.name,
4209
- toolName: 'mcp_handshake',
4210
- status: 'success',
4211
- durationMs: newServer.health?.latencyMs || 25,
4212
- timestamp: new Date().toISOString()
4213
- });
4214
-
4215
- showToast(`Connected MCP server "${name}"! Synced with Cloud. Run "scout mcp list" in CLI to view.`, 'success', 6000);
4216
-
4217
- closeAddMcpModal();
4218
- getEl('form-add-mcp')?.reset();
4219
- renderMcpKpis();
4220
- renderMcpServersList();
4221
- renderMcpActivityList();
4222
- } catch (err) {
4223
- showToast(err.message || 'Error connecting MCP server', 'error');
4224
- } finally {
4225
- if (submitBtn) {
4226
- submitBtn.disabled = false;
4227
- submitBtn.innerHTML = '<i class="fa-solid fa-plug"></i> Connect Server';
4228
- }
4229
- }
4230
- }
4231
-
4232
- function openInspectMcpModal(serverId) {
4233
- const server = mcpState.servers.find(s => s.id === serverId);
4234
- if (!server) {
4235
- showToast('Server not found', 'error');
4236
- return;
4237
- }
4238
-
4239
- mcpState.selectedServer = server;
4240
- const titleEl = getEl('inspect-mcp-title');
4241
- const subtitleEl = getEl('inspect-mcp-subtitle');
4242
- const contentEl = getEl('inspect-mcp-content');
4243
-
4244
- if (titleEl) titleEl.innerText = `${server.name} - Tools & Capabilities`;
4245
- if (subtitleEl) subtitleEl.innerText = `${server.transport.toUpperCase()} Transport • ${server.tools.length} Tools Available`;
4246
-
4247
- if (contentEl) {
4248
- if (!server.tools || server.tools.length === 0) {
4249
- contentEl.innerHTML = `
4250
- <div style="padding: 32px; text-align: center; color: var(--scout-text-dim);">
4251
- <i class="fa-solid fa-toolbox" style="font-size: 28px; margin-bottom: 12px; display: block; opacity: 0.5;"></i>
4252
- No tools discovered yet. Ensure the MCP server is reachable and active.
4253
- </div>
4254
- `;
4255
- } else {
4256
- contentEl.innerHTML = server.tools.map(tool => {
4257
- const isEnabled = tool.enabled !== false;
4258
- const perm = (tool.permissionLevel || 'read').toLowerCase();
4259
- const props = Object.keys(tool.inputSchema?.properties || {});
4260
- const propsText = props.length > 0 ? `Parameters: ${props.join(', ')}` : 'No required parameters';
4261
-
4262
- return `
4263
- <div class="mcp-tool-item">
4264
- <div class="mcp-tool-info">
4265
- <div class="mcp-tool-title-row">
4266
- <span class="mcp-tool-name">${escapeHtml(tool.originalName)}</span>
4267
- <span class="mcp-perm-tag ${perm}">${perm}</span>
4268
- </div>
4269
- <p class="mcp-tool-desc">${escapeHtml(tool.description || 'No description provided.')}</p>
4270
- <div class="mcp-tool-params">${escapeHtml(propsText)}</div>
4271
- </div>
4272
- <div>
4273
- <label class="mcp-toggle-switch" title="${isEnabled ? 'Tool Enabled' : 'Tool Disabled'}">
4274
- <input type="checkbox" ${isEnabled ? 'checked' : ''} onchange="toggleMcpTool('${escapeHtml(server.id)}', '${escapeHtml(tool.originalName)}', this.checked)">
4275
- <span class="mcp-toggle-slider"></span>
4276
- </label>
4277
- </div>
4278
- </div>
4279
- `;
4280
- }).join('');
4281
- }
4282
- }
4283
-
4284
- const modal = getEl('modal-inspect-mcp');
4285
- if (modal) modal.style.display = 'flex';
4286
- }
4287
-
4288
- function closeInspectMcpModal() {
4289
- const modal = getEl('modal-inspect-mcp');
4290
- if (modal) modal.style.display = 'none';
4291
- mcpState.selectedServer = null;
4292
- }
4293
-
4294
- async function connectMcpServer(serverId) {
4295
- const server = mcpState.servers.find(s => s.id === serverId);
4296
- if (!server) {
4297
- showToast('Server not found', 'error');
4298
- return;
4299
- }
4300
-
4301
- try {
4302
- server.status = 'connecting';
4303
- renderMcpServersList();
4304
- showToast(`Connecting to ${server.name}...`, 'info');
4305
-
4306
- let discovered = { tools: server.tools || [], latencyMs: 25 };
4307
- if (server.transport === 'http') {
4308
- discovered = await connectRemoteMcpInBrowser(server);
4309
- server.tools = discovered.tools;
4310
- }
4311
-
4312
- server.status = 'connected';
4313
- server.health = {
4314
- latencyMs: discovered.latencyMs || 25,
4315
- status: 'healthy',
4316
- lastChecked: new Date().toISOString()
4317
- };
4318
-
4319
- // Push update to Cloud Firestore
4320
- await pushCloudMcpServer(server);
4321
-
4322
- const apiBase = await getMcpApiBase();
4323
- if (apiBase !== null) {
4324
- try {
4325
- await fetch(`${apiBase}/api/mcp/servers/${encodeURIComponent(serverId)}/connect`, { method: 'POST' });
4326
- } catch { }
4327
- }
4328
-
4329
- const storageKey = getAccountMcpStorageKey();
4330
- try {
4331
- localStorage.setItem(storageKey, JSON.stringify(mcpState.servers));
4332
- localStorage.setItem('scout_cached_mcp_servers', JSON.stringify(mcpState.servers));
4333
- } catch { }
4334
-
4335
- renderMcpKpis();
4336
- renderMcpServersList();
4337
- renderMcpActivityList();
4338
- showToast(`Connected to ${server.name}! ${server.tools.length} tools active and synced.`, 'success');
4339
- } catch (err) {
4340
- server.status = 'error';
4341
- renderMcpServersList();
4342
- showToast(err.message || 'Error connecting to server', 'error');
4343
- }
4344
- }
4345
-
4346
- async function disconnectMcpServer(serverId) {
4347
- const server = mcpState.servers.find(s => s.id === serverId);
4348
- if (server) {
4349
- server.status = 'disconnected';
4350
- await pushCloudMcpServer(server);
4351
-
4352
- const apiBase = await getMcpApiBase();
4353
- if (apiBase !== null) {
4354
- try {
4355
- await fetch(`${apiBase}/api/mcp/servers/${encodeURIComponent(serverId)}/disconnect`, { method: 'POST' });
4356
- } catch { }
4357
- }
4358
-
4359
- const storageKey = getAccountMcpStorageKey();
4360
- try {
4361
- localStorage.setItem(storageKey, JSON.stringify(mcpState.servers));
4362
- localStorage.setItem('scout_cached_mcp_servers', JSON.stringify(mcpState.servers));
4363
- } catch { }
4364
- renderMcpKpis();
4365
- renderMcpServersList();
4366
- }
4367
- showToast('MCP server disconnected and synced.', 'info');
4368
- }
4369
-
4370
- async function deleteMcpServer(serverId) {
4371
- if (!confirm('Are you sure you want to remove this MCP server? Associated configuration will be permanently deleted.')) {
4372
- return;
4373
- }
4374
-
4375
- // Delete directly from FrontTerrain Cloud Firestore
4376
- await deleteCloudMcpServer(serverId);
4377
-
4378
- const apiBase = await getMcpApiBase();
4379
- if (apiBase !== null) {
4380
- try {
4381
- await fetch(`${apiBase}/api/mcp/servers/${encodeURIComponent(serverId)}`, {
4382
- method: 'DELETE'
4383
- });
4384
- } catch (e) {
4385
- console.warn('Failed to delete on local server:', e);
4386
- }
4387
- }
4388
-
4389
- mcpState.servers = mcpState.servers.filter(s => s.id !== serverId);
4390
- const storageKey = getAccountMcpStorageKey();
4391
- try {
4392
- localStorage.setItem(storageKey, JSON.stringify(mcpState.servers));
4393
- localStorage.setItem('scout_cached_mcp_servers', JSON.stringify(mcpState.servers));
4394
- } catch { }
4395
- renderMcpKpis();
4396
- renderMcpServersList();
4397
- showToast('MCP server removed and synced with Cloud & CLI.', 'info');
4398
- }
4399
-
4400
- async function toggleMcpTool(serverId, toolName, enabled) {
4401
- const server = mcpState.servers.find(s => s.id === serverId);
4402
- if (server && server.tools) {
4403
- const target = server.tools.find(t => t.originalName === toolName || t.name === toolName);
4404
- if (target) target.enabled = enabled;
4405
-
4406
- await pushCloudMcpServer(server);
4407
-
4408
- const apiBase = await getMcpApiBase();
4409
- if (apiBase !== null) {
4410
- try {
4411
- await fetch(`${apiBase}/api/mcp/servers/${encodeURIComponent(serverId)}/tools/${encodeURIComponent(toolName)}/toggle`, {
4412
- method: 'POST',
4413
- headers: { 'Content-Type': 'application/json' },
4414
- body: JSON.stringify({ enabled })
4415
- });
4416
- } catch { }
4417
- }
4418
-
4419
- const storageKey = getAccountMcpStorageKey();
4420
- try {
4421
- localStorage.setItem(storageKey, JSON.stringify(mcpState.servers));
4422
- localStorage.setItem('scout_cached_mcp_servers', JSON.stringify(mcpState.servers));
4423
- } catch { }
4424
- }
4425
- showToast(`Tool "${toolName}" ${enabled ? 'enabled' : 'disabled'} and synced.`, 'info');
4426
- renderMcpKpis();
4427
- renderMcpServersList();
4428
- }
4429
-
4430
- function copyMcpCliCommand(serverId) {
4431
- const server = mcpState.servers.find(s => s.id === serverId);
4432
- if (!server) {
4433
- showToast('Server not found.', 'error');
4434
- return;
4435
- }
4436
- let cmd = `scout mcp add "${server.name}" --transport ${server.transport}`;
4437
- if (server.transport === 'http' && server.endpoint) {
4438
- cmd += ` --endpoint "${server.endpoint}"`;
4439
- if (server.authType && server.authType !== 'none') {
4440
- cmd += ` --auth-type ${server.authType}`;
4441
- }
4442
- } else if (server.transport === 'stdio' && server.command) {
4443
- cmd += ` --command "${server.command}"`;
4444
- if (server.args && server.args.length > 0) {
4445
- cmd += ` --args "${server.args.join(' ')}"`;
4446
- }
4447
- }
4448
- if (navigator.clipboard && navigator.clipboard.writeText) {
4449
- navigator.clipboard.writeText(cmd).then(() => {
4450
- showToast('Copied CLI command to clipboard! Paste and run in terminal to activate.', 'success');
4451
- }).catch(() => {
4452
- prompt('Copy this CLI command for terminal:', cmd);
4453
- });
4454
- } else {
4455
- prompt('Copy this CLI command for terminal:', cmd);
4456
- }
4457
- }
4458
-
4459
- function exportMcpCliConfig() {
4460
- if (!mcpState.servers || mcpState.servers.length === 0) {
4461
- showToast('No MCP servers configured to export.', 'info');
4462
- return;
4463
- }
4464
- const cliFormat = mcpState.servers.map(s => ({
4465
- id: s.id || s.name.toLowerCase().replace(/[^a-z0-9_-]/g, '_'),
4466
- name: s.name,
4467
- transport: s.transport,
4468
- endpoint: s.endpoint,
4469
- command: s.command,
4470
- args: s.args || [],
4471
- authType: s.authType || 'none',
4472
- status: s.status || 'connected',
4473
- tools: s.tools || [],
4474
- health: s.health || { status: 'connected', latencyMs: 150, lastCheckedAt: new Date().toISOString() }
4475
- }));
4476
- const jsonStr = JSON.stringify(cliFormat, null, 2);
4477
- if (navigator.clipboard && navigator.clipboard.writeText) {
4478
- navigator.clipboard.writeText(jsonStr).then(() => {
4479
- showToast('Copied ~/.ft/mcp_servers.json configuration to clipboard!', 'success');
4480
- }).catch(() => {
4481
- prompt('Copy JSON for ~/.ft/mcp_servers.json:', jsonStr);
4482
- });
4483
- } else {
4484
- prompt('Copy JSON for ~/.ft/mcp_servers.json:', jsonStr);
4485
- }
4486
- }
4487
-
4488
- // Auto-sync when window regains focus (e.g., returning from CLI terminal)
4489
- window.addEventListener('focus', () => {
4490
- loadMcpData();
4491
- });
4492
-
4493
- // Global exports for inline HTML event handlers
4494
- window.loadMcpData = loadMcpData;
4495
- window.openAddMcpModal = openAddMcpModal;
4496
- window.closeAddMcpModal = closeAddMcpModal;
4497
- window.toggleMcpTransportFields = toggleMcpTransportFields;
4498
- window.toggleMcpAuthFields = toggleMcpAuthFields;
4499
- window.handleAddMcpServerSubmit = handleAddMcpServerSubmit;
4500
- window.openInspectMcpModal = openInspectMcpModal;
4501
- window.closeInspectMcpModal = closeInspectMcpModal;
4502
- window.connectMcpServer = connectMcpServer;
4503
- window.disconnectMcpServer = disconnectMcpServer;
4504
- window.deleteMcpServer = deleteMcpServer;
4505
- window.toggleMcpTool = toggleMcpTool;
4506
- window.copyMcpCliCommand = copyMcpCliCommand;
4507
- window.exportMcpCliConfig = exportMcpCliConfig;
4508
-
4509
-
4510
-