@pixelbyte-software/pixcode 1.51.8 → 1.51.9

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 (307) hide show
  1. package/CODE_OF_CONDUCT.md +41 -41
  2. package/CONTRIBUTING.md +155 -155
  3. package/LICENSE +718 -718
  4. package/README.de.md +169 -169
  5. package/README.ja.md +167 -167
  6. package/README.ko.md +167 -167
  7. package/README.md +419 -419
  8. package/README.ru.md +169 -169
  9. package/README.tr.md +298 -298
  10. package/README.zh-CN.md +167 -167
  11. package/SECURITY.md +46 -46
  12. package/dist/api-automation.html +110 -110
  13. package/dist/api-docs.html +548 -548
  14. package/dist/assets/{index--kNEhygZ.js → index-Gs7C4hZT.js} +69 -69
  15. package/dist/clear-cache.html +85 -85
  16. package/dist/convert-icons.md +52 -52
  17. package/dist/docs.html +308 -308
  18. package/dist/favicon.svg +8 -8
  19. package/dist/features.html +133 -133
  20. package/dist/generate-icons.js +48 -48
  21. package/dist/humans.txt +15 -15
  22. package/dist/icons/codex-white.svg +3 -3
  23. package/dist/icons/codex.svg +3 -3
  24. package/dist/icons/cursor-white.svg +11 -11
  25. package/dist/icons/icon-128x128.svg +9 -9
  26. package/dist/icons/icon-144x144.svg +9 -9
  27. package/dist/icons/icon-152x152.svg +9 -9
  28. package/dist/icons/icon-192x192.svg +9 -9
  29. package/dist/icons/icon-384x384.svg +9 -9
  30. package/dist/icons/icon-512x512.svg +9 -9
  31. package/dist/icons/icon-72x72.svg +9 -9
  32. package/dist/icons/icon-96x96.svg +9 -9
  33. package/dist/icons/icon-template.svg +9 -9
  34. package/dist/icons/qwen-logo.svg +14 -14
  35. package/dist/index.html +58 -58
  36. package/dist/landing.html +268 -268
  37. package/dist/llms-full.txt +119 -119
  38. package/dist/llms.txt +53 -53
  39. package/dist/logo.svg +12 -12
  40. package/dist/manifest.json +60 -60
  41. package/dist/openapi.yaml +1696 -1696
  42. package/dist/orchestration.html +125 -125
  43. package/dist/robots.txt +4 -4
  44. package/dist/site.css +692 -692
  45. package/dist/sitemap.xml +51 -51
  46. package/dist/sw.js +132 -132
  47. package/dist-server/server/cli.js +96 -96
  48. package/dist-server/server/daemon/manager.js +33 -33
  49. package/dist-server/server/daemon-manager.js +64 -64
  50. package/dist-server/server/index.js +91 -65
  51. package/dist-server/server/index.js.map +1 -1
  52. package/dist-server/server/routes/commands.js +25 -25
  53. package/dist-server/server/routes/git.js +17 -17
  54. package/dist-server/server/routes/live-view.js +46 -46
  55. package/dist-server/server/services/hermes-gateway.js +5 -5
  56. package/dist-server/server/services/public-api-manifest.js +51 -51
  57. package/package.json +222 -222
  58. package/scripts/fix-node-pty.js +67 -67
  59. package/scripts/github/create-v1.38-issues.mjs +351 -351
  60. package/scripts/github/create-vscode-workbench-issues.mjs +121 -121
  61. package/scripts/hermes/configure-pixcode-mcp.mjs +165 -165
  62. package/scripts/hermes/pixcode-mcp-server.mjs +1009 -1009
  63. package/scripts/smoke/changes-panel-layout.mjs +48 -48
  64. package/scripts/smoke/chat-composer-fixed-layout.mjs +55 -55
  65. package/scripts/smoke/chat-message-timeline-order.mjs +41 -41
  66. package/scripts/smoke/chat-realtime-hydration.mjs +44 -44
  67. package/scripts/smoke/chat-session-provider-pools.mjs +35 -35
  68. package/scripts/smoke/chat-session-state.mjs +19 -19
  69. package/scripts/smoke/code-editor-theme.mjs +55 -55
  70. package/scripts/smoke/code-editor-vscode-engine.mjs +91 -91
  71. package/scripts/smoke/command-center-agent-writes.mjs +79 -79
  72. package/scripts/smoke/command-center-non-git.mjs +46 -46
  73. package/scripts/smoke/context-packet.mjs +43 -43
  74. package/scripts/smoke/control-room-ux-redesign.mjs +91 -91
  75. package/scripts/smoke/daemon-entrypoint.mjs +20 -20
  76. package/scripts/smoke/default-landing-routing.mjs +33 -33
  77. package/scripts/smoke/desktop-native-notifications.mjs +30 -30
  78. package/scripts/smoke/desktop-tray-icon.mjs +33 -33
  79. package/scripts/smoke/discord-release-workflow.mjs +24 -24
  80. package/scripts/smoke/git-install-update.mjs +255 -255
  81. package/scripts/smoke/handoff-artifact-protocol.mjs +50 -50
  82. package/scripts/smoke/hermes-api-install.mjs +56 -56
  83. package/scripts/smoke/hermes-gateway-persistence.mjs +104 -104
  84. package/scripts/smoke/hermes-mcp-pixcode-roundtrip.mjs +426 -426
  85. package/scripts/smoke/hermes-rest-chat-api.mjs +162 -162
  86. package/scripts/smoke/hermes-rest-chat-live.mjs +45 -45
  87. package/scripts/smoke/hermes-rest-codex-launch.mjs +209 -209
  88. package/scripts/smoke/hermes-rest-gateway.mjs +79 -79
  89. package/scripts/smoke/hermes-rest-live.mjs +42 -42
  90. package/scripts/smoke/hermes-roundtrip.mjs +167 -167
  91. package/scripts/smoke/hermes-settings-commands.mjs +349 -349
  92. package/scripts/smoke/hermes-smoke-launcher-guard.mjs +34 -34
  93. package/scripts/smoke/live-view-diagnostics.mjs +53 -53
  94. package/scripts/smoke/live-view-environment.mjs +92 -92
  95. package/scripts/smoke/live-view-integration.mjs +450 -450
  96. package/scripts/smoke/mac-desktop-runtime.mjs +37 -37
  97. package/scripts/smoke/mobile-tunnel-guidance.mjs +29 -29
  98. package/scripts/smoke/model-registry.mjs +36 -36
  99. package/scripts/smoke/multi-project-ui.mjs +45 -45
  100. package/scripts/smoke/multi-worker-slots.mjs +42 -42
  101. package/scripts/smoke/notification-center.mjs +87 -87
  102. package/scripts/smoke/notification-inapp-preference.mjs +23 -23
  103. package/scripts/smoke/notification-taxonomy.mjs +58 -58
  104. package/scripts/smoke/orchestration-api.mjs +172 -172
  105. package/scripts/smoke/orchestration-execution-dashboard.mjs +33 -33
  106. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  107. package/scripts/smoke/orchestration-mobile-scroll.mjs +29 -29
  108. package/scripts/smoke/orchestration-model-sync.mjs +30 -30
  109. package/scripts/smoke/orchestration-permission-fallback.mjs +34 -34
  110. package/scripts/smoke/orchestration-runtime-guards.mjs +48 -48
  111. package/scripts/smoke/orchestration-user-facing-output.mjs +25 -25
  112. package/scripts/smoke/permission-policy.mjs +50 -50
  113. package/scripts/smoke/pixcode-workbench-1-48.mjs +167 -167
  114. package/scripts/smoke/provider-models-opencode-live.mjs +66 -66
  115. package/scripts/smoke/provider-rest-api.mjs +124 -124
  116. package/scripts/smoke/provider-selection-status.mjs +52 -52
  117. package/scripts/smoke/run-state-refresh.mjs +52 -52
  118. package/scripts/smoke/runtime-manager.mjs +99 -99
  119. package/scripts/smoke/shell-manual-disconnect.mjs +30 -30
  120. package/scripts/smoke/side-panel-editor-layout.mjs +34 -34
  121. package/scripts/smoke/static-root-routing.mjs +21 -21
  122. package/scripts/smoke/strict-handoff-compact.mjs +60 -60
  123. package/scripts/smoke/taskmaster-config.mjs +24 -24
  124. package/scripts/smoke/taskmaster-execution-telegram.mjs +3 -3
  125. package/scripts/smoke/taskmaster-onboarding.mjs +3 -3
  126. package/scripts/smoke/taskmaster-run-graph.mjs +3 -3
  127. package/scripts/smoke/telegram-control.mjs +242 -242
  128. package/scripts/smoke/tunnel-persistence.mjs +56 -56
  129. package/scripts/smoke/update-issue-progress.mjs +69 -69
  130. package/scripts/smoke/update-ux.mjs +55 -55
  131. package/scripts/smoke/v138-completion.mjs +132 -132
  132. package/scripts/smoke/v138-desktop-release-hardening.mjs +69 -69
  133. package/scripts/smoke/v138-diagnostics.mjs +63 -63
  134. package/scripts/smoke/v138-issue-planner.mjs +33 -33
  135. package/scripts/smoke/v143-remote-control.mjs +76 -76
  136. package/scripts/smoke/v144-production-loop.mjs +47 -47
  137. package/scripts/smoke/v145-platformization.mjs +46 -46
  138. package/scripts/smoke/v146-control-room-ui.mjs +150 -150
  139. package/scripts/smoke/version-modal-autoshow.mjs +29 -29
  140. package/scripts/smoke/vscode-workbench-layout.mjs +63 -63
  141. package/scripts/smoke/vscode-workbench-polish.mjs +461 -461
  142. package/scripts/smoke/workflow-fallback-replay.mjs +56 -56
  143. package/scripts/smoke/workflow-templates.mjs +43 -43
  144. package/scripts/smoke/workflow-trace-timeline.mjs +46 -46
  145. package/scripts/update-git-install.mjs +283 -283
  146. package/server/claude-sdk.js +920 -920
  147. package/server/cli.js +1035 -1035
  148. package/server/constants/config.js +4 -4
  149. package/server/cursor-cli.js +344 -344
  150. package/server/daemon/manager.js +563 -563
  151. package/server/daemon-manager.js +964 -964
  152. package/server/database/db.js +895 -895
  153. package/server/database/json-store.js +197 -197
  154. package/server/gemini-cli.js +550 -550
  155. package/server/gemini-response-handler.js +79 -79
  156. package/server/index.js +111 -81
  157. package/server/load-env.js +35 -35
  158. package/server/middleware/auth.js +155 -155
  159. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  160. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +63 -63
  161. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +286 -286
  162. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  163. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  164. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  165. package/server/modules/orchestration/a2a/adapters/json-event.adapter.ts +100 -100
  166. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  167. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  168. package/server/modules/orchestration/a2a/agent-card.ts +55 -55
  169. package/server/modules/orchestration/a2a/routes.ts +590 -590
  170. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  171. package/server/modules/orchestration/a2a/types.ts +126 -126
  172. package/server/modules/orchestration/a2a/validator.ts +113 -113
  173. package/server/modules/orchestration/hermes/hermes.routes.ts +642 -642
  174. package/server/modules/orchestration/index.ts +101 -101
  175. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  176. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  177. package/server/modules/orchestration/preview/types.ts +19 -19
  178. package/server/modules/orchestration/security/permission-policy.ts +401 -401
  179. package/server/modules/orchestration/tasks/orchestration-task-store.ts +41 -41
  180. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +64 -64
  181. package/server/modules/orchestration/tasks/orchestration-task.service.ts +209 -209
  182. package/server/modules/orchestration/tasks/orchestration-task.types.ts +40 -40
  183. package/server/modules/orchestration/tasks/task-run-graph.ts +155 -155
  184. package/server/modules/orchestration/workflows/approval-queue.ts +106 -106
  185. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  186. package/server/modules/orchestration/workflows/context-packet.ts +186 -186
  187. package/server/modules/orchestration/workflows/handoff-artifact.ts +175 -175
  188. package/server/modules/orchestration/workflows/workflow-fallback-policy.ts +161 -161
  189. package/server/modules/orchestration/workflows/workflow-replay.ts +254 -254
  190. package/server/modules/orchestration/workflows/workflow-runner.ts +2070 -2070
  191. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  192. package/server/modules/orchestration/workflows/workflow-templates.ts +272 -272
  193. package/server/modules/orchestration/workflows/workflow-trace.ts +424 -424
  194. package/server/modules/orchestration/workflows/workflow.routes.ts +586 -586
  195. package/server/modules/orchestration/workflows/workflow.types.ts +111 -111
  196. package/server/modules/orchestration/workflows/workspace-target.ts +122 -122
  197. package/server/modules/orchestration/workspace/docker-workspace.ts +136 -136
  198. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  199. package/server/modules/orchestration/workspace/types.ts +52 -52
  200. package/server/modules/orchestration/workspace/workspace-manager.ts +102 -102
  201. package/server/modules/orchestration/workspace/worktree-workspace.ts +126 -126
  202. package/server/modules/providers/index.ts +2 -2
  203. package/server/modules/providers/list/claude/claude-auth.provider.ts +146 -146
  204. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  205. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  206. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  207. package/server/modules/providers/list/codex/codex-auth.provider.ts +117 -117
  208. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  209. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  210. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  211. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +147 -147
  212. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  213. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  214. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  215. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +173 -173
  216. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  217. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  218. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  219. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +131 -131
  220. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
  221. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +286 -286
  222. package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
  223. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +146 -146
  224. package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
  225. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  226. package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
  227. package/server/modules/providers/provider.registry.ts +40 -40
  228. package/server/modules/providers/provider.routes.ts +891 -891
  229. package/server/modules/providers/services/mcp.service.ts +86 -86
  230. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  231. package/server/modules/providers/services/sessions.service.ts +45 -45
  232. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  233. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  234. package/server/modules/providers/shared/provider-configs.ts +142 -142
  235. package/server/modules/providers/tests/mcp.test.ts +293 -293
  236. package/server/openai-codex.js +462 -462
  237. package/server/opencode-cli.js +491 -491
  238. package/server/opencode-response-handler.js +111 -111
  239. package/server/projects.js +3008 -3008
  240. package/server/qwen-code-cli.js +410 -410
  241. package/server/qwen-response-handler.js +73 -73
  242. package/server/routes/agent.js +1435 -1435
  243. package/server/routes/auth.js +142 -142
  244. package/server/routes/codex.js +20 -20
  245. package/server/routes/commands.js +538 -538
  246. package/server/routes/cursor.js +61 -61
  247. package/server/routes/diagnostics.js +41 -41
  248. package/server/routes/gemini.js +25 -25
  249. package/server/routes/git.js +1641 -1641
  250. package/server/routes/live-view.js +387 -387
  251. package/server/routes/mcp-utils.js +13 -13
  252. package/server/routes/messages.js +50 -50
  253. package/server/routes/network.js +117 -117
  254. package/server/routes/platformization.js +182 -182
  255. package/server/routes/plugins.js +320 -320
  256. package/server/routes/production-agent-loop.js +90 -90
  257. package/server/routes/projects.js +911 -911
  258. package/server/routes/public-api.js +34 -34
  259. package/server/routes/qwen.js +27 -27
  260. package/server/routes/remote.js +50 -50
  261. package/server/routes/settings.js +321 -321
  262. package/server/routes/telegram.js +140 -140
  263. package/server/routes/user.js +125 -125
  264. package/server/routes/webhooks.js +63 -63
  265. package/server/services/control-room.js +102 -102
  266. package/server/services/diagnostics.js +165 -165
  267. package/server/services/external-access.js +375 -375
  268. package/server/services/hermes-gateway.js +1562 -1562
  269. package/server/services/hermes-install-jobs.js +729 -729
  270. package/server/services/install-jobs.js +715 -715
  271. package/server/services/live-view.js +956 -956
  272. package/server/services/managed-runtimes.js +493 -493
  273. package/server/services/model-registry.js +144 -144
  274. package/server/services/notification-orchestrator.js +365 -365
  275. package/server/services/notification-taxonomy.js +204 -204
  276. package/server/services/platformization.js +773 -773
  277. package/server/services/production-agent-loop.js +248 -248
  278. package/server/services/provider-cli-versions.js +149 -149
  279. package/server/services/provider-credentials.js +189 -189
  280. package/server/services/provider-models.js +396 -396
  281. package/server/services/public-api-manifest.js +190 -190
  282. package/server/services/remote-connection.js +127 -127
  283. package/server/services/runtime-manager.js +323 -323
  284. package/server/services/startup-update.js +234 -234
  285. package/server/services/telegram/bot.js +331 -331
  286. package/server/services/telegram/control-center.js +979 -979
  287. package/server/services/telegram/telegram-http-client.js +151 -151
  288. package/server/services/telegram/translations.js +340 -340
  289. package/server/services/vapid-keys.js +36 -36
  290. package/server/services/webhooks.js +216 -216
  291. package/server/sessionManager.js +225 -225
  292. package/server/shared/interfaces.ts +54 -54
  293. package/server/shared/types.ts +172 -172
  294. package/server/shared/utils.ts +193 -193
  295. package/server/tsconfig.json +36 -36
  296. package/server/utils/colors.js +21 -21
  297. package/server/utils/commandParser.js +305 -305
  298. package/server/utils/frontmatter.js +18 -18
  299. package/server/utils/gitConfig.js +34 -34
  300. package/server/utils/plugin-loader.js +457 -457
  301. package/server/utils/plugin-process-manager.js +185 -185
  302. package/server/utils/port-access.js +209 -209
  303. package/server/utils/runtime-paths.js +37 -37
  304. package/server/utils/url-detection.js +71 -71
  305. package/server/vite-daemon.js +79 -79
  306. package/shared/modelConstants.js +161 -161
  307. package/shared/networkHosts.js +22 -22
@@ -1,642 +1,642 @@
1
- import os from 'node:os';
2
- import { EventEmitter } from 'node:events';
3
-
4
- import express, { type Request, type Response, type Router } from 'express';
5
-
6
- import { adapterRegistry } from '@/modules/orchestration/a2a/adapter-registry.js';
7
- import { a2aTaskStore as hermesTaskStore } from '@/modules/orchestration/a2a/task-store.js';
8
- import {
9
- cancelHermesInstallJob,
10
- createHermesInstallJob,
11
- getHermesInstallJob,
12
- readHermesInstallStatus,
13
- snapshotHermesInstallDonePayload,
14
- } from '@/services/hermes-install-jobs.js';
15
- import {
16
- ensureHermesGateway,
17
- getHermesGatewayStatus,
18
- probeHermesGateway,
19
- readHermesControlPlane,
20
- readHermesDiagnostics,
21
- repairHermesControlPlane,
22
- requestHermesGateway,
23
- runHermesGatewayPrompt,
24
- stopHermesGateway,
25
- } from '@/services/hermes-gateway.js';
26
-
27
- const HERMES_TERMINAL_LAUNCH_LIMIT = 100;
28
- const HERMES_TERMINAL_LAUNCH_PROVIDERS = new Set(['claude', 'codex', 'cursor', 'gemini', 'qwen', 'opencode']);
29
- const HERMES_TERMINAL_LAUNCH_STREAM_HEARTBEAT_MS = 25000;
30
-
31
- type HermesTerminalLaunchEvent = {
32
- id: number;
33
- provider: string;
34
- projectPath: string | null;
35
- prompt: string | null;
36
- startupInput: string | null;
37
- forceNewSession: boolean;
38
- permissionMode: string | null;
39
- skipPermissions: boolean;
40
- bypassPermissions: boolean;
41
- source: string;
42
- createdAt: string;
43
- };
44
-
45
- type HermesRouterOptions = {
46
- appRoot?: string;
47
- createHermesApiKey?: (userId: number | string | null | undefined) => string | null;
48
- resolvePublicBaseUrl?: (req: Request) => string;
49
- };
50
-
51
- type PixcodeRequest = Request & {
52
- user?: {
53
- id?: number | string;
54
- userId?: number | string;
55
- };
56
- };
57
-
58
- let nextHermesTerminalLaunchId = 1;
59
- const hermesTerminalLaunches: HermesTerminalLaunchEvent[] = [];
60
- const hermesTerminalLaunchEmitter = new EventEmitter();
61
- hermesTerminalLaunchEmitter.setMaxListeners(200);
62
-
63
- function writeSse(res: Response, event: string, payload: unknown) {
64
- res.write(`event: ${event}\n`);
65
- res.write(`data: ${JSON.stringify(payload)}\n\n`);
66
- }
67
-
68
- function readUserId(req: PixcodeRequest) {
69
- return req.user?.id ?? req.user?.userId ?? null;
70
- }
71
-
72
- function resolveHermesMcpBaseUrl() {
73
- const configured = process.env.PIXCODE_INTERNAL_BASE_URL || process.env.PIXCODE_HERMES_BASE_URL;
74
- if (configured) return configured.replace(/\/$/, '');
75
-
76
- return `http://127.0.0.1:${process.env.SERVER_PORT ?? process.env.PORT ?? '3001'}`;
77
- }
78
-
79
- function readAfterId(req: Request) {
80
- const after = Number.parseInt(typeof req.query.after === 'string' ? req.query.after : '0', 10);
81
- return Number.isFinite(after) ? after : 0;
82
- }
83
-
84
- function rememberHermesTerminalLaunch(event: HermesTerminalLaunchEvent) {
85
- hermesTerminalLaunches.push(event);
86
- if (hermesTerminalLaunches.length > HERMES_TERMINAL_LAUNCH_LIMIT) {
87
- hermesTerminalLaunches.splice(0, hermesTerminalLaunches.length - HERMES_TERMINAL_LAUNCH_LIMIT);
88
- }
89
- hermesTerminalLaunchEmitter.emit('terminal-launch', event);
90
- }
91
-
92
- function readTrimmedString(value: unknown) {
93
- return typeof value === 'string' && value.trim() ? value.trim() : null;
94
- }
95
-
96
- function readBoolean(value: unknown) {
97
- return value === true || value === 'true' || value === '1';
98
- }
99
-
100
- function isLegacyPromptLikelyStartupInput(prompt: string | null) {
101
- if (!prompt || prompt.length > 160 || prompt.includes('\n')) return false;
102
- if (/^[/:!@]/u.test(prompt)) return true;
103
- if (prompt.includes(':')) return false;
104
- if (/\b(user|request|reason|audit|task|kullanıcı|kullanicinin|istek|isteği|gorev|görev|terminal|codex|claude|qwen|gemini|cursor|opencode|open|aç|ac|başlat|baslat|send|gönder|gonder)\b/iu.test(prompt)) {
105
- return false;
106
- }
107
- return prompt.length <= 80;
108
- }
109
-
110
- export function createHermesRouter(options: HermesRouterOptions = {}): Router {
111
- const router = express.Router();
112
-
113
- router.get('/status', (_req, res) => {
114
- res.json({
115
- id: 'hermes',
116
- name: 'Hermes Agent',
117
- product: 'Pixcode',
118
- runtime: {
119
- mode: process.env.PIXCODE_MANAGED_PLATFORM === '1' ? 'managed' : 'local',
120
- host: os.hostname(),
121
- node: process.version,
122
- pid: process.pid,
123
- },
124
- capabilities: [
125
- 'project-aware CLI orchestration',
126
- 'background checks and tests',
127
- 'workspace-scoped terminal operations',
128
- 'run history and artifact review',
129
- ],
130
- });
131
- });
132
-
133
- router.get('/context', (req, res) => {
134
- const project = typeof req.query.project === 'string' ? req.query.project : null;
135
- const cwd = typeof req.query.cwd === 'string' ? req.query.cwd : process.cwd();
136
- res.json({
137
- agent: 'Hermes Agent',
138
- product: 'Pixcode',
139
- project,
140
- cwd,
141
- local: true,
142
- message: project
143
- ? `Hermes is operating inside Pixcode for ${project}.`
144
- : 'Hermes is operating inside Pixcode.',
145
- });
146
- });
147
-
148
- router.get('/install-status', (_req, res) => {
149
- res.json(readHermesInstallStatus());
150
- });
151
-
152
- router.get('/gateway/status', (req, res) => {
153
- const projectPath = typeof req.query.projectPath === 'string' ? req.query.projectPath : null;
154
- res.json(getHermesGatewayStatus(projectPath));
155
- });
156
-
157
- router.post('/gateway/start', async (req: PixcodeRequest, res) => {
158
- const apiKey = options.createHermesApiKey?.(readUserId(req)) ?? null;
159
- if (!apiKey) {
160
- res.status(500).json({
161
- error: {
162
- code: 'HERMES_API_KEY_UNAVAILABLE',
163
- message: 'Pixcode could not create a Hermes MCP API key for this user.',
164
- },
165
- });
166
- return;
167
- }
168
-
169
- const body = (req.body ?? {}) as Record<string, unknown>;
170
- try {
171
- const gateway = await ensureHermesGateway({
172
- appRoot: options.appRoot ?? process.cwd(),
173
- pixcodeApiKey: apiKey,
174
- pixcodeBaseUrl: resolveHermesMcpBaseUrl(),
175
- projectPath: typeof body.projectPath === 'string' ? body.projectPath : undefined,
176
- });
177
- res.status(202).json(gateway);
178
- } catch (error) {
179
- res.status(500).json({
180
- error: {
181
- code: 'HERMES_GATEWAY_START_FAILED',
182
- message: error instanceof Error ? error.message : String(error),
183
- },
184
- });
185
- }
186
- });
187
-
188
- router.post('/gateway/probe', async (req: PixcodeRequest, res) => {
189
- const body = (req.body ?? {}) as Record<string, unknown>;
190
- const projectPath = typeof body.projectPath === 'string' ? body.projectPath : null;
191
- const input = typeof body.input === 'string' ? body.input : undefined;
192
- const shouldStart = body.startIfNeeded === true;
193
-
194
- try {
195
- if (shouldStart) {
196
- const apiKey = options.createHermesApiKey?.(readUserId(req)) ?? null;
197
- if (!apiKey) {
198
- res.status(500).json({
199
- error: {
200
- code: 'HERMES_API_KEY_UNAVAILABLE',
201
- message: 'Pixcode could not create a Hermes MCP API key for this user.',
202
- },
203
- });
204
- return;
205
- }
206
- await ensureHermesGateway({
207
- appRoot: options.appRoot ?? process.cwd(),
208
- pixcodeApiKey: apiKey,
209
- pixcodeBaseUrl: resolveHermesMcpBaseUrl(),
210
- projectPath: projectPath ?? undefined,
211
- });
212
- }
213
-
214
- const probe = await probeHermesGateway(projectPath, { input });
215
- res.status(probe.ok ? 200 : 503).json(probe);
216
- } catch (error) {
217
- res.status(500).json({
218
- error: {
219
- code: 'HERMES_GATEWAY_PROBE_FAILED',
220
- message: error instanceof Error ? error.message : String(error),
221
- },
222
- });
223
- }
224
- });
225
-
226
- router.post('/gateway/chat', async (req: PixcodeRequest, res) => {
227
- const body = (req.body ?? {}) as Record<string, unknown>;
228
- const projectPath = typeof body.projectPath === 'string' && body.projectPath.trim()
229
- ? body.projectPath.trim()
230
- : undefined;
231
- const input = typeof body.input === 'string' ? body.input.trim() : '';
232
- const sessionId = typeof body.sessionId === 'string' && body.sessionId.trim()
233
- ? body.sessionId.trim()
234
- : undefined;
235
-
236
- if (!input) {
237
- res.status(400).json({
238
- error: {
239
- code: 'HERMES_PROMPT_REQUIRED',
240
- message: 'Hermes prompt is required.',
241
- },
242
- });
243
- return;
244
- }
245
-
246
- const apiKey = options.createHermesApiKey?.(readUserId(req)) ?? null;
247
- if (!apiKey) {
248
- res.status(500).json({
249
- error: {
250
- code: 'HERMES_API_KEY_UNAVAILABLE',
251
- message: 'Pixcode could not create a Hermes MCP API key for this user.',
252
- },
253
- });
254
- return;
255
- }
256
-
257
- try {
258
- const gateway = await ensureHermesGateway({
259
- appRoot: options.appRoot ?? process.cwd(),
260
- pixcodeApiKey: apiKey,
261
- pixcodeBaseUrl: resolveHermesMcpBaseUrl(),
262
- projectPath,
263
- probeExisting: false,
264
- });
265
- const run = await runHermesGatewayPrompt(projectPath, {
266
- input,
267
- sessionId,
268
- });
269
-
270
- res.status(run.ok ? 200 : 502).json({
271
- ok: run.ok,
272
- gateway,
273
- run,
274
- message: run.message,
275
- error: run.error ?? null,
276
- });
277
- } catch (error) {
278
- res.status(500).json({
279
- error: {
280
- code: 'HERMES_GATEWAY_CHAT_FAILED',
281
- message: error instanceof Error ? error.message : String(error),
282
- },
283
- });
284
- }
285
- });
286
-
287
- router.post('/gateway/request', async (req: PixcodeRequest, res) => {
288
- const body = (req.body ?? {}) as Record<string, unknown>;
289
- const projectPath = typeof body.projectPath === 'string' && body.projectPath.trim()
290
- ? body.projectPath.trim()
291
- : undefined;
292
- const endpoint = typeof body.endpoint === 'string' ? body.endpoint : body.path;
293
- const method = typeof body.method === 'string' ? body.method : 'GET';
294
-
295
- try {
296
- if (body.startIfNeeded === true) {
297
- const apiKey = options.createHermesApiKey?.(readUserId(req)) ?? null;
298
- if (!apiKey) {
299
- res.status(500).json({
300
- error: {
301
- code: 'HERMES_API_KEY_UNAVAILABLE',
302
- message: 'Pixcode could not create a Hermes MCP API key for this user.',
303
- },
304
- });
305
- return;
306
- }
307
- await ensureHermesGateway({
308
- appRoot: options.appRoot ?? process.cwd(),
309
- pixcodeApiKey: apiKey,
310
- pixcodeBaseUrl: resolveHermesMcpBaseUrl(),
311
- projectPath,
312
- });
313
- }
314
-
315
- const gatewayResponse = await requestHermesGateway(projectPath, {
316
- endpoint,
317
- method,
318
- body: body.body,
319
- timeoutMs: typeof body.timeoutMs === 'number' ? body.timeoutMs : undefined,
320
- });
321
- res.status(gatewayResponse.ok ? 200 : 502).json(gatewayResponse);
322
- } catch (error) {
323
- res.status(500).json({
324
- error: {
325
- code: 'HERMES_GATEWAY_REQUEST_FAILED',
326
- message: error instanceof Error ? error.message : String(error),
327
- },
328
- });
329
- }
330
- });
331
-
332
- router.get('/diagnostics', async (req, res) => {
333
- const projectPath = typeof req.query.projectPath === 'string' && req.query.projectPath.trim()
334
- ? req.query.projectPath.trim()
335
- : undefined;
336
-
337
- try {
338
- const diagnostics = await readHermesDiagnostics({
339
- appRoot: options.appRoot ?? process.cwd(),
340
- projectPath,
341
- });
342
- res.status(diagnostics.ok ? 200 : 503).json(diagnostics);
343
- } catch (error) {
344
- res.status(500).json({
345
- error: {
346
- code: 'HERMES_DIAGNOSTICS_FAILED',
347
- message: error instanceof Error ? error.message : String(error),
348
- },
349
- });
350
- }
351
- });
352
-
353
- router.get('/control-plane', async (req, res) => {
354
- const projectPath = typeof req.query.projectPath === 'string' && req.query.projectPath.trim()
355
- ? req.query.projectPath.trim()
356
- : undefined;
357
-
358
- try {
359
- const controlPlane = await readHermesControlPlane({
360
- appRoot: options.appRoot ?? process.cwd(),
361
- projectPath,
362
- });
363
- res.status(controlPlane.ok ? 200 : 503).json(controlPlane);
364
- } catch (error) {
365
- res.status(500).json({
366
- error: {
367
- code: 'HERMES_CONTROL_PLANE_FAILED',
368
- message: error instanceof Error ? error.message : String(error),
369
- },
370
- });
371
- }
372
- });
373
-
374
- router.post('/control-plane/repair', async (req: PixcodeRequest, res) => {
375
- const apiKey = options.createHermesApiKey?.(readUserId(req)) ?? null;
376
- if (!apiKey) {
377
- res.status(500).json({
378
- error: {
379
- code: 'HERMES_API_KEY_UNAVAILABLE',
380
- message: 'Pixcode could not create a Hermes MCP API key for this user.',
381
- },
382
- });
383
- return;
384
- }
385
-
386
- const body = (req.body ?? {}) as Record<string, unknown>;
387
- const projectPath = typeof body.projectPath === 'string' && body.projectPath.trim()
388
- ? body.projectPath.trim()
389
- : undefined;
390
-
391
- try {
392
- const repaired = await repairHermesControlPlane({
393
- appRoot: options.appRoot ?? process.cwd(),
394
- pixcodeApiKey: apiKey,
395
- pixcodeBaseUrl: resolveHermesMcpBaseUrl(),
396
- projectPath,
397
- forceRestart: readBoolean(body.forceRestart),
398
- });
399
- res.status(repaired.ok ? 200 : 202).json(repaired);
400
- } catch (error) {
401
- res.status(500).json({
402
- error: {
403
- code: 'HERMES_CONTROL_PLANE_REPAIR_FAILED',
404
- message: error instanceof Error ? error.message : String(error),
405
- },
406
- });
407
- }
408
- });
409
-
410
- router.post('/gateway/stop', (req, res) => {
411
- const body = (req.body ?? {}) as Record<string, unknown>;
412
- const projectPath = typeof body.projectPath === 'string' ? body.projectPath : null;
413
- res.json(stopHermesGateway(projectPath));
414
- });
415
-
416
- router.post('/install', (req: PixcodeRequest, res) => {
417
- const apiKey = options.createHermesApiKey?.(readUserId(req)) ?? null;
418
- if (!apiKey) {
419
- res.status(500).json({
420
- error: {
421
- code: 'HERMES_API_KEY_UNAVAILABLE',
422
- message: 'Pixcode could not create a Hermes MCP API key for this user.',
423
- },
424
- });
425
- return;
426
- }
427
-
428
- const body = (req.body ?? {}) as Record<string, unknown>;
429
- const job = createHermesInstallJob({
430
- appRoot: options.appRoot ?? process.cwd(),
431
- force: Boolean(body.force),
432
- pixcodeApiKey: apiKey,
433
- pixcodeBaseUrl: resolveHermesMcpBaseUrl(),
434
- skipBrowser: body.skipBrowser !== false,
435
- });
436
-
437
- res.status(202).json({
438
- jobId: job.id,
439
- provider: 'hermes',
440
- status: job.status,
441
- startedAt: job.startedAt,
442
- });
443
- });
444
-
445
- router.get('/install/:jobId/stream', (req, res) => {
446
- const job = getHermesInstallJob(req.params.jobId);
447
- if (!job) {
448
- res.status(404).json({
449
- error: {
450
- code: 'HERMES_INSTALL_JOB_NOT_FOUND',
451
- message: 'Hermes install job not found or already expired.',
452
- },
453
- });
454
- return;
455
- }
456
-
457
- res.setHeader('Content-Type', 'text/event-stream');
458
- res.setHeader('Cache-Control', 'no-cache, no-transform');
459
- res.setHeader('Connection', 'keep-alive');
460
- res.setHeader('X-Accel-Buffering', 'no');
461
- if (typeof res.flushHeaders === 'function') res.flushHeaders();
462
- try {
463
- (res.socket as NodeJS.Socket & { setNoDelay?: (on: boolean) => void })?.setNoDelay?.(true);
464
- } catch { /* noop */ }
465
-
466
- let closed = false;
467
- const safeWrite = (event: string, payload: unknown) => {
468
- if (closed) return;
469
- try { writeSse(res, event, payload); } catch { /* socket gone */ }
470
- };
471
-
472
- try { res.write(': start\n\n'); } catch { /* noop */ }
473
- const heartbeat = setInterval(() => {
474
- if (closed) return;
475
- try { res.write(': ping\n\n'); } catch { /* noop */ }
476
- }, 5000);
477
-
478
- for (const entry of job.logs) {
479
- safeWrite('log', { stream: entry.stream, chunk: entry.chunk });
480
- }
481
-
482
- const onLog = (entry: { stream: string; chunk: string }) => {
483
- safeWrite('log', { stream: entry.stream, chunk: entry.chunk });
484
- };
485
- const onDone = (payload: Record<string, unknown>) => {
486
- safeWrite('done', payload);
487
- cleanup();
488
- try { res.end(); } catch { /* noop */ }
489
- };
490
- function cleanup() {
491
- if (closed) return;
492
- closed = true;
493
- clearInterval(heartbeat);
494
- job.emitter.off('log', onLog);
495
- job.emitter.off('done', onDone);
496
- }
497
-
498
- if (job.status !== 'running') {
499
- safeWrite('done', snapshotHermesInstallDonePayload(job));
500
- cleanup();
501
- try { res.end(); } catch { /* noop */ }
502
- return;
503
- }
504
-
505
- job.emitter.on('log', onLog);
506
- job.emitter.once('done', onDone);
507
- req.on('close', cleanup);
508
- });
509
-
510
- router.delete('/install/:jobId', (req, res) => {
511
- const job = getHermesInstallJob(req.params.jobId);
512
- if (!job) {
513
- res.status(404).json({
514
- error: {
515
- code: 'HERMES_INSTALL_JOB_NOT_FOUND',
516
- message: 'Hermes install job not found.',
517
- },
518
- });
519
- return;
520
- }
521
-
522
- res.json({ cancelled: cancelHermesInstallJob(req.params.jobId) });
523
- });
524
-
525
- router.get('/agents', (_req, res) => {
526
- res.json({
527
- agent: 'hermes',
528
- agents: adapterRegistry.agentCards().map((agent) => ({
529
- ...agent,
530
- coordinator: 'hermes',
531
- })),
532
- });
533
- });
534
-
535
- router.get('/terminal-launches', (req, res) => {
536
- const afterId = readAfterId(req);
537
- res.json({
538
- events: hermesTerminalLaunches.filter((event) => event.id > afterId),
539
- });
540
- });
541
-
542
- router.get('/terminal-launches/stream', (req, res) => {
543
- const afterId = readAfterId(req);
544
-
545
- res.setHeader('Content-Type', 'text/event-stream');
546
- res.setHeader('Cache-Control', 'no-cache, no-transform');
547
- res.setHeader('Connection', 'keep-alive');
548
- res.setHeader('X-Accel-Buffering', 'no');
549
- if (typeof res.flushHeaders === 'function') res.flushHeaders();
550
- try {
551
- (res.socket as NodeJS.Socket & { setNoDelay?: (on: boolean) => void })?.setNoDelay?.(true);
552
- } catch { /* noop */ }
553
-
554
- let closed = false;
555
- const safeWrite = (event: string, payload: unknown) => {
556
- if (closed) return;
557
- try { writeSse(res, event, payload); } catch { /* socket gone */ }
558
- };
559
-
560
- try { res.write(': start\n\n'); } catch { /* noop */ }
561
- const replayed = hermesTerminalLaunches.filter((event) => event.id > afterId);
562
- for (const event of replayed) {
563
- safeWrite('terminal-launch', event);
564
- }
565
- safeWrite('ready', {
566
- latestId: hermesTerminalLaunches[hermesTerminalLaunches.length - 1]?.id ?? afterId,
567
- replayed: replayed.length,
568
- });
569
-
570
- const heartbeat = setInterval(() => {
571
- if (closed) return;
572
- try { res.write(': ping\n\n'); } catch { /* noop */ }
573
- }, HERMES_TERMINAL_LAUNCH_STREAM_HEARTBEAT_MS);
574
-
575
- const onTerminalLaunch = (event: HermesTerminalLaunchEvent) => {
576
- safeWrite('terminal-launch', event);
577
- };
578
- hermesTerminalLaunchEmitter.on('terminal-launch', onTerminalLaunch);
579
-
580
- const cleanup = () => {
581
- if (closed) return;
582
- closed = true;
583
- clearInterval(heartbeat);
584
- hermesTerminalLaunchEmitter.off('terminal-launch', onTerminalLaunch);
585
- };
586
-
587
- req.on('close', cleanup);
588
- });
589
-
590
- router.post('/terminal-launches', (req, res) => {
591
- const body = (req.body ?? {}) as Record<string, unknown>;
592
- const provider = typeof body.provider === 'string' ? body.provider.trim() : '';
593
- if (!HERMES_TERMINAL_LAUNCH_PROVIDERS.has(provider)) {
594
- res.status(400).json({ error: { code: 'INVALID_PROVIDER', message: provider || 'provider is required' } });
595
- return;
596
- }
597
-
598
- const projectPath = typeof body.projectPath === 'string' && body.projectPath.trim()
599
- ? body.projectPath.trim()
600
- : null;
601
- const prompt = readTrimmedString(body.prompt ?? body.reason);
602
- const requestedStartupInput = readTrimmedString(body.startupInput ?? body.input);
603
- const startupInput = requestedStartupInput ?? (isLegacyPromptLikelyStartupInput(prompt) ? prompt : null);
604
- const forceNewSession = readBoolean(body.forceNewSession ?? body.newSession ?? body.freshSession);
605
- const bypassPermissions = readBoolean(body.bypassPermissions);
606
- const skipPermissions = readBoolean(body.skipPermissions) || bypassPermissions;
607
- const requestedPermissionMode = readTrimmedString(body.permissionMode);
608
- const permissionMode = requestedPermissionMode ?? (skipPermissions ? 'bypassPermissions' : null);
609
-
610
- const event: HermesTerminalLaunchEvent = {
611
- id: nextHermesTerminalLaunchId,
612
- provider,
613
- projectPath,
614
- prompt,
615
- startupInput,
616
- forceNewSession,
617
- permissionMode,
618
- skipPermissions,
619
- bypassPermissions,
620
- source: 'hermes-mcp',
621
- createdAt: new Date().toISOString(),
622
- };
623
- nextHermesTerminalLaunchId += 1;
624
- rememberHermesTerminalLaunch(event);
625
-
626
- res.status(201).json({ event });
627
- });
628
-
629
- router.get('/tasks/:id', (req, res) => {
630
- const task = hermesTaskStore.get(req.params.id);
631
- if (!task) {
632
- res.status(404).json({ error: { code: 'HERMES_TASK_NOT_FOUND', message: req.params.id } });
633
- return;
634
- }
635
- res.json({
636
- ...task,
637
- hermesTaskId: task.id,
638
- });
639
- });
640
-
641
- return router;
642
- }
1
+ import os from 'node:os';
2
+ import { EventEmitter } from 'node:events';
3
+
4
+ import express, { type Request, type Response, type Router } from 'express';
5
+
6
+ import { adapterRegistry } from '@/modules/orchestration/a2a/adapter-registry.js';
7
+ import { a2aTaskStore as hermesTaskStore } from '@/modules/orchestration/a2a/task-store.js';
8
+ import {
9
+ cancelHermesInstallJob,
10
+ createHermesInstallJob,
11
+ getHermesInstallJob,
12
+ readHermesInstallStatus,
13
+ snapshotHermesInstallDonePayload,
14
+ } from '@/services/hermes-install-jobs.js';
15
+ import {
16
+ ensureHermesGateway,
17
+ getHermesGatewayStatus,
18
+ probeHermesGateway,
19
+ readHermesControlPlane,
20
+ readHermesDiagnostics,
21
+ repairHermesControlPlane,
22
+ requestHermesGateway,
23
+ runHermesGatewayPrompt,
24
+ stopHermesGateway,
25
+ } from '@/services/hermes-gateway.js';
26
+
27
+ const HERMES_TERMINAL_LAUNCH_LIMIT = 100;
28
+ const HERMES_TERMINAL_LAUNCH_PROVIDERS = new Set(['claude', 'codex', 'cursor', 'gemini', 'qwen', 'opencode']);
29
+ const HERMES_TERMINAL_LAUNCH_STREAM_HEARTBEAT_MS = 25000;
30
+
31
+ type HermesTerminalLaunchEvent = {
32
+ id: number;
33
+ provider: string;
34
+ projectPath: string | null;
35
+ prompt: string | null;
36
+ startupInput: string | null;
37
+ forceNewSession: boolean;
38
+ permissionMode: string | null;
39
+ skipPermissions: boolean;
40
+ bypassPermissions: boolean;
41
+ source: string;
42
+ createdAt: string;
43
+ };
44
+
45
+ type HermesRouterOptions = {
46
+ appRoot?: string;
47
+ createHermesApiKey?: (userId: number | string | null | undefined) => string | null;
48
+ resolvePublicBaseUrl?: (req: Request) => string;
49
+ };
50
+
51
+ type PixcodeRequest = Request & {
52
+ user?: {
53
+ id?: number | string;
54
+ userId?: number | string;
55
+ };
56
+ };
57
+
58
+ let nextHermesTerminalLaunchId = 1;
59
+ const hermesTerminalLaunches: HermesTerminalLaunchEvent[] = [];
60
+ const hermesTerminalLaunchEmitter = new EventEmitter();
61
+ hermesTerminalLaunchEmitter.setMaxListeners(200);
62
+
63
+ function writeSse(res: Response, event: string, payload: unknown) {
64
+ res.write(`event: ${event}\n`);
65
+ res.write(`data: ${JSON.stringify(payload)}\n\n`);
66
+ }
67
+
68
+ function readUserId(req: PixcodeRequest) {
69
+ return req.user?.id ?? req.user?.userId ?? null;
70
+ }
71
+
72
+ function resolveHermesMcpBaseUrl() {
73
+ const configured = process.env.PIXCODE_INTERNAL_BASE_URL || process.env.PIXCODE_HERMES_BASE_URL;
74
+ if (configured) return configured.replace(/\/$/, '');
75
+
76
+ return `http://127.0.0.1:${process.env.SERVER_PORT ?? process.env.PORT ?? '3001'}`;
77
+ }
78
+
79
+ function readAfterId(req: Request) {
80
+ const after = Number.parseInt(typeof req.query.after === 'string' ? req.query.after : '0', 10);
81
+ return Number.isFinite(after) ? after : 0;
82
+ }
83
+
84
+ function rememberHermesTerminalLaunch(event: HermesTerminalLaunchEvent) {
85
+ hermesTerminalLaunches.push(event);
86
+ if (hermesTerminalLaunches.length > HERMES_TERMINAL_LAUNCH_LIMIT) {
87
+ hermesTerminalLaunches.splice(0, hermesTerminalLaunches.length - HERMES_TERMINAL_LAUNCH_LIMIT);
88
+ }
89
+ hermesTerminalLaunchEmitter.emit('terminal-launch', event);
90
+ }
91
+
92
+ function readTrimmedString(value: unknown) {
93
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
94
+ }
95
+
96
+ function readBoolean(value: unknown) {
97
+ return value === true || value === 'true' || value === '1';
98
+ }
99
+
100
+ function isLegacyPromptLikelyStartupInput(prompt: string | null) {
101
+ if (!prompt || prompt.length > 160 || prompt.includes('\n')) return false;
102
+ if (/^[/:!@]/u.test(prompt)) return true;
103
+ if (prompt.includes(':')) return false;
104
+ if (/\b(user|request|reason|audit|task|kullanıcı|kullanicinin|istek|isteği|gorev|görev|terminal|codex|claude|qwen|gemini|cursor|opencode|open|aç|ac|başlat|baslat|send|gönder|gonder)\b/iu.test(prompt)) {
105
+ return false;
106
+ }
107
+ return prompt.length <= 80;
108
+ }
109
+
110
+ export function createHermesRouter(options: HermesRouterOptions = {}): Router {
111
+ const router = express.Router();
112
+
113
+ router.get('/status', (_req, res) => {
114
+ res.json({
115
+ id: 'hermes',
116
+ name: 'Hermes Agent',
117
+ product: 'Pixcode',
118
+ runtime: {
119
+ mode: process.env.PIXCODE_MANAGED_PLATFORM === '1' ? 'managed' : 'local',
120
+ host: os.hostname(),
121
+ node: process.version,
122
+ pid: process.pid,
123
+ },
124
+ capabilities: [
125
+ 'project-aware CLI orchestration',
126
+ 'background checks and tests',
127
+ 'workspace-scoped terminal operations',
128
+ 'run history and artifact review',
129
+ ],
130
+ });
131
+ });
132
+
133
+ router.get('/context', (req, res) => {
134
+ const project = typeof req.query.project === 'string' ? req.query.project : null;
135
+ const cwd = typeof req.query.cwd === 'string' ? req.query.cwd : process.cwd();
136
+ res.json({
137
+ agent: 'Hermes Agent',
138
+ product: 'Pixcode',
139
+ project,
140
+ cwd,
141
+ local: true,
142
+ message: project
143
+ ? `Hermes is operating inside Pixcode for ${project}.`
144
+ : 'Hermes is operating inside Pixcode.',
145
+ });
146
+ });
147
+
148
+ router.get('/install-status', (_req, res) => {
149
+ res.json(readHermesInstallStatus());
150
+ });
151
+
152
+ router.get('/gateway/status', (req, res) => {
153
+ const projectPath = typeof req.query.projectPath === 'string' ? req.query.projectPath : null;
154
+ res.json(getHermesGatewayStatus(projectPath));
155
+ });
156
+
157
+ router.post('/gateway/start', async (req: PixcodeRequest, res) => {
158
+ const apiKey = options.createHermesApiKey?.(readUserId(req)) ?? null;
159
+ if (!apiKey) {
160
+ res.status(500).json({
161
+ error: {
162
+ code: 'HERMES_API_KEY_UNAVAILABLE',
163
+ message: 'Pixcode could not create a Hermes MCP API key for this user.',
164
+ },
165
+ });
166
+ return;
167
+ }
168
+
169
+ const body = (req.body ?? {}) as Record<string, unknown>;
170
+ try {
171
+ const gateway = await ensureHermesGateway({
172
+ appRoot: options.appRoot ?? process.cwd(),
173
+ pixcodeApiKey: apiKey,
174
+ pixcodeBaseUrl: resolveHermesMcpBaseUrl(),
175
+ projectPath: typeof body.projectPath === 'string' ? body.projectPath : undefined,
176
+ });
177
+ res.status(202).json(gateway);
178
+ } catch (error) {
179
+ res.status(500).json({
180
+ error: {
181
+ code: 'HERMES_GATEWAY_START_FAILED',
182
+ message: error instanceof Error ? error.message : String(error),
183
+ },
184
+ });
185
+ }
186
+ });
187
+
188
+ router.post('/gateway/probe', async (req: PixcodeRequest, res) => {
189
+ const body = (req.body ?? {}) as Record<string, unknown>;
190
+ const projectPath = typeof body.projectPath === 'string' ? body.projectPath : null;
191
+ const input = typeof body.input === 'string' ? body.input : undefined;
192
+ const shouldStart = body.startIfNeeded === true;
193
+
194
+ try {
195
+ if (shouldStart) {
196
+ const apiKey = options.createHermesApiKey?.(readUserId(req)) ?? null;
197
+ if (!apiKey) {
198
+ res.status(500).json({
199
+ error: {
200
+ code: 'HERMES_API_KEY_UNAVAILABLE',
201
+ message: 'Pixcode could not create a Hermes MCP API key for this user.',
202
+ },
203
+ });
204
+ return;
205
+ }
206
+ await ensureHermesGateway({
207
+ appRoot: options.appRoot ?? process.cwd(),
208
+ pixcodeApiKey: apiKey,
209
+ pixcodeBaseUrl: resolveHermesMcpBaseUrl(),
210
+ projectPath: projectPath ?? undefined,
211
+ });
212
+ }
213
+
214
+ const probe = await probeHermesGateway(projectPath, { input });
215
+ res.status(probe.ok ? 200 : 503).json(probe);
216
+ } catch (error) {
217
+ res.status(500).json({
218
+ error: {
219
+ code: 'HERMES_GATEWAY_PROBE_FAILED',
220
+ message: error instanceof Error ? error.message : String(error),
221
+ },
222
+ });
223
+ }
224
+ });
225
+
226
+ router.post('/gateway/chat', async (req: PixcodeRequest, res) => {
227
+ const body = (req.body ?? {}) as Record<string, unknown>;
228
+ const projectPath = typeof body.projectPath === 'string' && body.projectPath.trim()
229
+ ? body.projectPath.trim()
230
+ : undefined;
231
+ const input = typeof body.input === 'string' ? body.input.trim() : '';
232
+ const sessionId = typeof body.sessionId === 'string' && body.sessionId.trim()
233
+ ? body.sessionId.trim()
234
+ : undefined;
235
+
236
+ if (!input) {
237
+ res.status(400).json({
238
+ error: {
239
+ code: 'HERMES_PROMPT_REQUIRED',
240
+ message: 'Hermes prompt is required.',
241
+ },
242
+ });
243
+ return;
244
+ }
245
+
246
+ const apiKey = options.createHermesApiKey?.(readUserId(req)) ?? null;
247
+ if (!apiKey) {
248
+ res.status(500).json({
249
+ error: {
250
+ code: 'HERMES_API_KEY_UNAVAILABLE',
251
+ message: 'Pixcode could not create a Hermes MCP API key for this user.',
252
+ },
253
+ });
254
+ return;
255
+ }
256
+
257
+ try {
258
+ const gateway = await ensureHermesGateway({
259
+ appRoot: options.appRoot ?? process.cwd(),
260
+ pixcodeApiKey: apiKey,
261
+ pixcodeBaseUrl: resolveHermesMcpBaseUrl(),
262
+ projectPath,
263
+ probeExisting: false,
264
+ });
265
+ const run = await runHermesGatewayPrompt(projectPath, {
266
+ input,
267
+ sessionId,
268
+ });
269
+
270
+ res.status(run.ok ? 200 : 502).json({
271
+ ok: run.ok,
272
+ gateway,
273
+ run,
274
+ message: run.message,
275
+ error: run.error ?? null,
276
+ });
277
+ } catch (error) {
278
+ res.status(500).json({
279
+ error: {
280
+ code: 'HERMES_GATEWAY_CHAT_FAILED',
281
+ message: error instanceof Error ? error.message : String(error),
282
+ },
283
+ });
284
+ }
285
+ });
286
+
287
+ router.post('/gateway/request', async (req: PixcodeRequest, res) => {
288
+ const body = (req.body ?? {}) as Record<string, unknown>;
289
+ const projectPath = typeof body.projectPath === 'string' && body.projectPath.trim()
290
+ ? body.projectPath.trim()
291
+ : undefined;
292
+ const endpoint = typeof body.endpoint === 'string' ? body.endpoint : body.path;
293
+ const method = typeof body.method === 'string' ? body.method : 'GET';
294
+
295
+ try {
296
+ if (body.startIfNeeded === true) {
297
+ const apiKey = options.createHermesApiKey?.(readUserId(req)) ?? null;
298
+ if (!apiKey) {
299
+ res.status(500).json({
300
+ error: {
301
+ code: 'HERMES_API_KEY_UNAVAILABLE',
302
+ message: 'Pixcode could not create a Hermes MCP API key for this user.',
303
+ },
304
+ });
305
+ return;
306
+ }
307
+ await ensureHermesGateway({
308
+ appRoot: options.appRoot ?? process.cwd(),
309
+ pixcodeApiKey: apiKey,
310
+ pixcodeBaseUrl: resolveHermesMcpBaseUrl(),
311
+ projectPath,
312
+ });
313
+ }
314
+
315
+ const gatewayResponse = await requestHermesGateway(projectPath, {
316
+ endpoint,
317
+ method,
318
+ body: body.body,
319
+ timeoutMs: typeof body.timeoutMs === 'number' ? body.timeoutMs : undefined,
320
+ });
321
+ res.status(gatewayResponse.ok ? 200 : 502).json(gatewayResponse);
322
+ } catch (error) {
323
+ res.status(500).json({
324
+ error: {
325
+ code: 'HERMES_GATEWAY_REQUEST_FAILED',
326
+ message: error instanceof Error ? error.message : String(error),
327
+ },
328
+ });
329
+ }
330
+ });
331
+
332
+ router.get('/diagnostics', async (req, res) => {
333
+ const projectPath = typeof req.query.projectPath === 'string' && req.query.projectPath.trim()
334
+ ? req.query.projectPath.trim()
335
+ : undefined;
336
+
337
+ try {
338
+ const diagnostics = await readHermesDiagnostics({
339
+ appRoot: options.appRoot ?? process.cwd(),
340
+ projectPath,
341
+ });
342
+ res.status(diagnostics.ok ? 200 : 503).json(diagnostics);
343
+ } catch (error) {
344
+ res.status(500).json({
345
+ error: {
346
+ code: 'HERMES_DIAGNOSTICS_FAILED',
347
+ message: error instanceof Error ? error.message : String(error),
348
+ },
349
+ });
350
+ }
351
+ });
352
+
353
+ router.get('/control-plane', async (req, res) => {
354
+ const projectPath = typeof req.query.projectPath === 'string' && req.query.projectPath.trim()
355
+ ? req.query.projectPath.trim()
356
+ : undefined;
357
+
358
+ try {
359
+ const controlPlane = await readHermesControlPlane({
360
+ appRoot: options.appRoot ?? process.cwd(),
361
+ projectPath,
362
+ });
363
+ res.status(controlPlane.ok ? 200 : 503).json(controlPlane);
364
+ } catch (error) {
365
+ res.status(500).json({
366
+ error: {
367
+ code: 'HERMES_CONTROL_PLANE_FAILED',
368
+ message: error instanceof Error ? error.message : String(error),
369
+ },
370
+ });
371
+ }
372
+ });
373
+
374
+ router.post('/control-plane/repair', async (req: PixcodeRequest, res) => {
375
+ const apiKey = options.createHermesApiKey?.(readUserId(req)) ?? null;
376
+ if (!apiKey) {
377
+ res.status(500).json({
378
+ error: {
379
+ code: 'HERMES_API_KEY_UNAVAILABLE',
380
+ message: 'Pixcode could not create a Hermes MCP API key for this user.',
381
+ },
382
+ });
383
+ return;
384
+ }
385
+
386
+ const body = (req.body ?? {}) as Record<string, unknown>;
387
+ const projectPath = typeof body.projectPath === 'string' && body.projectPath.trim()
388
+ ? body.projectPath.trim()
389
+ : undefined;
390
+
391
+ try {
392
+ const repaired = await repairHermesControlPlane({
393
+ appRoot: options.appRoot ?? process.cwd(),
394
+ pixcodeApiKey: apiKey,
395
+ pixcodeBaseUrl: resolveHermesMcpBaseUrl(),
396
+ projectPath,
397
+ forceRestart: readBoolean(body.forceRestart),
398
+ });
399
+ res.status(repaired.ok ? 200 : 202).json(repaired);
400
+ } catch (error) {
401
+ res.status(500).json({
402
+ error: {
403
+ code: 'HERMES_CONTROL_PLANE_REPAIR_FAILED',
404
+ message: error instanceof Error ? error.message : String(error),
405
+ },
406
+ });
407
+ }
408
+ });
409
+
410
+ router.post('/gateway/stop', (req, res) => {
411
+ const body = (req.body ?? {}) as Record<string, unknown>;
412
+ const projectPath = typeof body.projectPath === 'string' ? body.projectPath : null;
413
+ res.json(stopHermesGateway(projectPath));
414
+ });
415
+
416
+ router.post('/install', (req: PixcodeRequest, res) => {
417
+ const apiKey = options.createHermesApiKey?.(readUserId(req)) ?? null;
418
+ if (!apiKey) {
419
+ res.status(500).json({
420
+ error: {
421
+ code: 'HERMES_API_KEY_UNAVAILABLE',
422
+ message: 'Pixcode could not create a Hermes MCP API key for this user.',
423
+ },
424
+ });
425
+ return;
426
+ }
427
+
428
+ const body = (req.body ?? {}) as Record<string, unknown>;
429
+ const job = createHermesInstallJob({
430
+ appRoot: options.appRoot ?? process.cwd(),
431
+ force: Boolean(body.force),
432
+ pixcodeApiKey: apiKey,
433
+ pixcodeBaseUrl: resolveHermesMcpBaseUrl(),
434
+ skipBrowser: body.skipBrowser !== false,
435
+ });
436
+
437
+ res.status(202).json({
438
+ jobId: job.id,
439
+ provider: 'hermes',
440
+ status: job.status,
441
+ startedAt: job.startedAt,
442
+ });
443
+ });
444
+
445
+ router.get('/install/:jobId/stream', (req, res) => {
446
+ const job = getHermesInstallJob(req.params.jobId);
447
+ if (!job) {
448
+ res.status(404).json({
449
+ error: {
450
+ code: 'HERMES_INSTALL_JOB_NOT_FOUND',
451
+ message: 'Hermes install job not found or already expired.',
452
+ },
453
+ });
454
+ return;
455
+ }
456
+
457
+ res.setHeader('Content-Type', 'text/event-stream');
458
+ res.setHeader('Cache-Control', 'no-cache, no-transform');
459
+ res.setHeader('Connection', 'keep-alive');
460
+ res.setHeader('X-Accel-Buffering', 'no');
461
+ if (typeof res.flushHeaders === 'function') res.flushHeaders();
462
+ try {
463
+ (res.socket as NodeJS.Socket & { setNoDelay?: (on: boolean) => void })?.setNoDelay?.(true);
464
+ } catch { /* noop */ }
465
+
466
+ let closed = false;
467
+ const safeWrite = (event: string, payload: unknown) => {
468
+ if (closed) return;
469
+ try { writeSse(res, event, payload); } catch { /* socket gone */ }
470
+ };
471
+
472
+ try { res.write(': start\n\n'); } catch { /* noop */ }
473
+ const heartbeat = setInterval(() => {
474
+ if (closed) return;
475
+ try { res.write(': ping\n\n'); } catch { /* noop */ }
476
+ }, 5000);
477
+
478
+ for (const entry of job.logs) {
479
+ safeWrite('log', { stream: entry.stream, chunk: entry.chunk });
480
+ }
481
+
482
+ const onLog = (entry: { stream: string; chunk: string }) => {
483
+ safeWrite('log', { stream: entry.stream, chunk: entry.chunk });
484
+ };
485
+ const onDone = (payload: Record<string, unknown>) => {
486
+ safeWrite('done', payload);
487
+ cleanup();
488
+ try { res.end(); } catch { /* noop */ }
489
+ };
490
+ function cleanup() {
491
+ if (closed) return;
492
+ closed = true;
493
+ clearInterval(heartbeat);
494
+ job.emitter.off('log', onLog);
495
+ job.emitter.off('done', onDone);
496
+ }
497
+
498
+ if (job.status !== 'running') {
499
+ safeWrite('done', snapshotHermesInstallDonePayload(job));
500
+ cleanup();
501
+ try { res.end(); } catch { /* noop */ }
502
+ return;
503
+ }
504
+
505
+ job.emitter.on('log', onLog);
506
+ job.emitter.once('done', onDone);
507
+ req.on('close', cleanup);
508
+ });
509
+
510
+ router.delete('/install/:jobId', (req, res) => {
511
+ const job = getHermesInstallJob(req.params.jobId);
512
+ if (!job) {
513
+ res.status(404).json({
514
+ error: {
515
+ code: 'HERMES_INSTALL_JOB_NOT_FOUND',
516
+ message: 'Hermes install job not found.',
517
+ },
518
+ });
519
+ return;
520
+ }
521
+
522
+ res.json({ cancelled: cancelHermesInstallJob(req.params.jobId) });
523
+ });
524
+
525
+ router.get('/agents', (_req, res) => {
526
+ res.json({
527
+ agent: 'hermes',
528
+ agents: adapterRegistry.agentCards().map((agent) => ({
529
+ ...agent,
530
+ coordinator: 'hermes',
531
+ })),
532
+ });
533
+ });
534
+
535
+ router.get('/terminal-launches', (req, res) => {
536
+ const afterId = readAfterId(req);
537
+ res.json({
538
+ events: hermesTerminalLaunches.filter((event) => event.id > afterId),
539
+ });
540
+ });
541
+
542
+ router.get('/terminal-launches/stream', (req, res) => {
543
+ const afterId = readAfterId(req);
544
+
545
+ res.setHeader('Content-Type', 'text/event-stream');
546
+ res.setHeader('Cache-Control', 'no-cache, no-transform');
547
+ res.setHeader('Connection', 'keep-alive');
548
+ res.setHeader('X-Accel-Buffering', 'no');
549
+ if (typeof res.flushHeaders === 'function') res.flushHeaders();
550
+ try {
551
+ (res.socket as NodeJS.Socket & { setNoDelay?: (on: boolean) => void })?.setNoDelay?.(true);
552
+ } catch { /* noop */ }
553
+
554
+ let closed = false;
555
+ const safeWrite = (event: string, payload: unknown) => {
556
+ if (closed) return;
557
+ try { writeSse(res, event, payload); } catch { /* socket gone */ }
558
+ };
559
+
560
+ try { res.write(': start\n\n'); } catch { /* noop */ }
561
+ const replayed = hermesTerminalLaunches.filter((event) => event.id > afterId);
562
+ for (const event of replayed) {
563
+ safeWrite('terminal-launch', event);
564
+ }
565
+ safeWrite('ready', {
566
+ latestId: hermesTerminalLaunches[hermesTerminalLaunches.length - 1]?.id ?? afterId,
567
+ replayed: replayed.length,
568
+ });
569
+
570
+ const heartbeat = setInterval(() => {
571
+ if (closed) return;
572
+ try { res.write(': ping\n\n'); } catch { /* noop */ }
573
+ }, HERMES_TERMINAL_LAUNCH_STREAM_HEARTBEAT_MS);
574
+
575
+ const onTerminalLaunch = (event: HermesTerminalLaunchEvent) => {
576
+ safeWrite('terminal-launch', event);
577
+ };
578
+ hermesTerminalLaunchEmitter.on('terminal-launch', onTerminalLaunch);
579
+
580
+ const cleanup = () => {
581
+ if (closed) return;
582
+ closed = true;
583
+ clearInterval(heartbeat);
584
+ hermesTerminalLaunchEmitter.off('terminal-launch', onTerminalLaunch);
585
+ };
586
+
587
+ req.on('close', cleanup);
588
+ });
589
+
590
+ router.post('/terminal-launches', (req, res) => {
591
+ const body = (req.body ?? {}) as Record<string, unknown>;
592
+ const provider = typeof body.provider === 'string' ? body.provider.trim() : '';
593
+ if (!HERMES_TERMINAL_LAUNCH_PROVIDERS.has(provider)) {
594
+ res.status(400).json({ error: { code: 'INVALID_PROVIDER', message: provider || 'provider is required' } });
595
+ return;
596
+ }
597
+
598
+ const projectPath = typeof body.projectPath === 'string' && body.projectPath.trim()
599
+ ? body.projectPath.trim()
600
+ : null;
601
+ const prompt = readTrimmedString(body.prompt ?? body.reason);
602
+ const requestedStartupInput = readTrimmedString(body.startupInput ?? body.input);
603
+ const startupInput = requestedStartupInput ?? (isLegacyPromptLikelyStartupInput(prompt) ? prompt : null);
604
+ const forceNewSession = readBoolean(body.forceNewSession ?? body.newSession ?? body.freshSession);
605
+ const bypassPermissions = readBoolean(body.bypassPermissions);
606
+ const skipPermissions = readBoolean(body.skipPermissions) || bypassPermissions;
607
+ const requestedPermissionMode = readTrimmedString(body.permissionMode);
608
+ const permissionMode = requestedPermissionMode ?? (skipPermissions ? 'bypassPermissions' : null);
609
+
610
+ const event: HermesTerminalLaunchEvent = {
611
+ id: nextHermesTerminalLaunchId,
612
+ provider,
613
+ projectPath,
614
+ prompt,
615
+ startupInput,
616
+ forceNewSession,
617
+ permissionMode,
618
+ skipPermissions,
619
+ bypassPermissions,
620
+ source: 'hermes-mcp',
621
+ createdAt: new Date().toISOString(),
622
+ };
623
+ nextHermesTerminalLaunchId += 1;
624
+ rememberHermesTerminalLaunch(event);
625
+
626
+ res.status(201).json({ event });
627
+ });
628
+
629
+ router.get('/tasks/:id', (req, res) => {
630
+ const task = hermesTaskStore.get(req.params.id);
631
+ if (!task) {
632
+ res.status(404).json({ error: { code: 'HERMES_TASK_NOT_FOUND', message: req.params.id } });
633
+ return;
634
+ }
635
+ res.json({
636
+ ...task,
637
+ hermesTaskId: task.id,
638
+ });
639
+ });
640
+
641
+ return router;
642
+ }