@hivemagnus/magnus-server 0.0.0-stage → 1.0.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 (356) hide show
  1. package/.env.example +171 -0
  2. package/LICENSE +202 -0
  3. package/README.md +169 -2
  4. package/agent-version.json +1 -0
  5. package/dist/ai/HEARTBEAT.md +56 -0
  6. package/dist/ai/IDENTITY.md +54 -0
  7. package/dist/ai/MEMORY.md +40 -0
  8. package/dist/ai/TOOLS.md +538 -0
  9. package/dist/ai/USER.md +32 -0
  10. package/dist/cli/args.js +62 -0
  11. package/dist/cli/env-catalog.js +131 -0
  12. package/dist/cli/preflight.js +89 -0
  13. package/dist/cli.js +175 -0
  14. package/dist/config/cors.js +16 -0
  15. package/dist/config/env.js +392 -0
  16. package/dist/config/features.js +16 -0
  17. package/dist/config/index.js +3 -0
  18. package/dist/config/listener-security.js +38 -0
  19. package/dist/config/version.js +31 -0
  20. package/dist/db/client.js +44 -0
  21. package/dist/db/generated/prisma/browser.js +18 -0
  22. package/dist/db/generated/prisma/client.js +35 -0
  23. package/dist/db/generated/prisma/commonInputTypes.js +11 -0
  24. package/dist/db/generated/prisma/enums.js +42 -0
  25. package/dist/db/generated/prisma/internal/class.js +50 -0
  26. package/dist/db/generated/prisma/internal/prismaNamespace.js +1598 -0
  27. package/dist/db/generated/prisma/internal/prismaNamespaceBrowser.js +1569 -0
  28. package/dist/db/generated/prisma/models/A2ATask.js +2 -0
  29. package/dist/db/generated/prisma/models/AdmissionFence.js +2 -0
  30. package/dist/db/generated/prisma/models/Agent.js +2 -0
  31. package/dist/db/generated/prisma/models/AiConversation.js +2 -0
  32. package/dist/db/generated/prisma/models/AiDashboard.js +2 -0
  33. package/dist/db/generated/prisma/models/AiMemory.js +2 -0
  34. package/dist/db/generated/prisma/models/AiMessage.js +2 -0
  35. package/dist/db/generated/prisma/models/AiScheduledOp.js +2 -0
  36. package/dist/db/generated/prisma/models/AlertConditionState.js +2 -0
  37. package/dist/db/generated/prisma/models/AlertRule.js +2 -0
  38. package/dist/db/generated/prisma/models/AlertViolation.js +2 -0
  39. package/dist/db/generated/prisma/models/AnomalyEvent.js +2 -0
  40. package/dist/db/generated/prisma/models/ApplicationObservation.js +2 -0
  41. package/dist/db/generated/prisma/models/ArdentInstallation.js +2 -0
  42. package/dist/db/generated/prisma/models/ArdentProfile.js +2 -0
  43. package/dist/db/generated/prisma/models/ArdentScopeEnrollment.js +2 -0
  44. package/dist/db/generated/prisma/models/CommandResourceFence.js +2 -0
  45. package/dist/db/generated/prisma/models/CommandResourceLease.js +2 -0
  46. package/dist/db/generated/prisma/models/CommandResult.js +2 -0
  47. package/dist/db/generated/prisma/models/CronJob.js +2 -0
  48. package/dist/db/generated/prisma/models/CronJobExecution.js +2 -0
  49. package/dist/db/generated/prisma/models/DeployJob.js +2 -0
  50. package/dist/db/generated/prisma/models/DriftScan.js +2 -0
  51. package/dist/db/generated/prisma/models/EngineeringMetricSample.js +2 -0
  52. package/dist/db/generated/prisma/models/EngineeringRecoveryExercise.js +2 -0
  53. package/dist/db/generated/prisma/models/ExecutionRun.js +2 -0
  54. package/dist/db/generated/prisma/models/FilePatchTask.js +2 -0
  55. package/dist/db/generated/prisma/models/GpuSnapshot.js +2 -0
  56. package/dist/db/generated/prisma/models/HealthSnapshot.js +2 -0
  57. package/dist/db/generated/prisma/models/HermesCoreRollout.js +2 -0
  58. package/dist/db/generated/prisma/models/HermesCoreRolloutHost.js +2 -0
  59. package/dist/db/generated/prisma/models/HermesCredentialPool.js +2 -0
  60. package/dist/db/generated/prisma/models/HermesCredentialPoolAttachment.js +2 -0
  61. package/dist/db/generated/prisma/models/HermesCronJob.js +2 -0
  62. package/dist/db/generated/prisma/models/HermesHook.js +2 -0
  63. package/dist/db/generated/prisma/models/HermesInstallation.js +2 -0
  64. package/dist/db/generated/prisma/models/HermesMcpServer.js +2 -0
  65. package/dist/db/generated/prisma/models/HermesMcpServerAttachment.js +2 -0
  66. package/dist/db/generated/prisma/models/HermesMessagingBinding.js +2 -0
  67. package/dist/db/generated/prisma/models/HermesOperationJob.js +2 -0
  68. package/dist/db/generated/prisma/models/HermesPluginInstall.js +2 -0
  69. package/dist/db/generated/prisma/models/HermesProfile.js +2 -0
  70. package/dist/db/generated/prisma/models/HermesProviderConfig.js +2 -0
  71. package/dist/db/generated/prisma/models/HermesRegistryClient.js +2 -0
  72. package/dist/db/generated/prisma/models/HermesRegistryInventory.js +2 -0
  73. package/dist/db/generated/prisma/models/HermesRegistryReceipt.js +2 -0
  74. package/dist/db/generated/prisma/models/HermesRegistryRevision.js +2 -0
  75. package/dist/db/generated/prisma/models/HermesRegistryTarget.js +2 -0
  76. package/dist/db/generated/prisma/models/HermesRole.js +2 -0
  77. package/dist/db/generated/prisma/models/HermesRoleApplication.js +2 -0
  78. package/dist/db/generated/prisma/models/HermesSkillAssignment.js +2 -0
  79. package/dist/db/generated/prisma/models/HermesToolsetPolicy.js +2 -0
  80. package/dist/db/generated/prisma/models/IncidentLesson.js +2 -0
  81. package/dist/db/generated/prisma/models/LibraryCategory.js +2 -0
  82. package/dist/db/generated/prisma/models/LibraryFile.js +2 -0
  83. package/dist/db/generated/prisma/models/LogEntry.js +2 -0
  84. package/dist/db/generated/prisma/models/MagnusReleaseCanary.js +2 -0
  85. package/dist/db/generated/prisma/models/MaintenanceWindow.js +2 -0
  86. package/dist/db/generated/prisma/models/ManagedCronDefinition.js +2 -0
  87. package/dist/db/generated/prisma/models/ManagedCronOccurrence.js +2 -0
  88. package/dist/db/generated/prisma/models/Node.js +2 -0
  89. package/dist/db/generated/prisma/models/Notification.js +2 -0
  90. package/dist/db/generated/prisma/models/NotificationPreference.js +2 -0
  91. package/dist/db/generated/prisma/models/RemediationExecution.js +2 -0
  92. package/dist/db/generated/prisma/models/RemediationRule.js +2 -0
  93. package/dist/db/generated/prisma/models/RemoteCommand.js +2 -0
  94. package/dist/db/generated/prisma/models/ResourceDrainParticipant.js +2 -0
  95. package/dist/db/generated/prisma/models/ResourceEnrollment.js +2 -0
  96. package/dist/db/generated/prisma/models/ResourceParticipantWork.js +2 -0
  97. package/dist/db/generated/prisma/models/Role.js +2 -0
  98. package/dist/db/generated/prisma/models/RoleApplication.js +2 -0
  99. package/dist/db/generated/prisma/models/RolloutTarget.js +2 -0
  100. package/dist/db/generated/prisma/models/SecurityExportOutbox.js +2 -0
  101. package/dist/db/generated/prisma/models/SecurityFusionAction.js +2 -0
  102. package/dist/db/generated/prisma/models/SecurityFusionActionApproval.js +2 -0
  103. package/dist/db/generated/prisma/models/SecurityFusionCase.js +2 -0
  104. package/dist/db/generated/prisma/models/SecurityFusionCaseActivity.js +2 -0
  105. package/dist/db/generated/prisma/models/SecurityFusionCaseEntity.js +2 -0
  106. package/dist/db/generated/prisma/models/SecurityFusionCaseEvent.js +2 -0
  107. package/dist/db/generated/prisma/models/SecurityFusionCaseRelationship.js +2 -0
  108. package/dist/db/generated/prisma/models/SecurityFusionCollector.js +2 -0
  109. package/dist/db/generated/prisma/models/SecurityFusionCommandOutbox.js +2 -0
  110. package/dist/db/generated/prisma/models/SecurityFusionDeletionReceipt.js +2 -0
  111. package/dist/db/generated/prisma/models/SecurityFusionDelivery.js +2 -0
  112. package/dist/db/generated/prisma/models/SecurityFusionEntity.js +2 -0
  113. package/dist/db/generated/prisma/models/SecurityFusionEntityAlias.js +2 -0
  114. package/dist/db/generated/prisma/models/SecurityFusionEvent.js +2 -0
  115. package/dist/db/generated/prisma/models/SecurityFusionEventEntity.js +2 -0
  116. package/dist/db/generated/prisma/models/SecurityFusionEvidence.js +2 -0
  117. package/dist/db/generated/prisma/models/SecurityFusionInvestigation.js +2 -0
  118. package/dist/db/generated/prisma/models/SecurityFusionNonce.js +2 -0
  119. package/dist/db/generated/prisma/models/SecurityFusionReceiptChainHead.js +2 -0
  120. package/dist/db/generated/prisma/models/SecurityFusionRuleVersion.js +2 -0
  121. package/dist/db/generated/prisma/models/SecurityFusionSourceState.js +2 -0
  122. package/dist/db/generated/prisma/models/SecurityServiceState.js +2 -0
  123. package/dist/db/generated/prisma/models/SharedResourceFence.js +2 -0
  124. package/dist/db/generated/prisma/models/SharedResourceLease.js +2 -0
  125. package/dist/db/generated/prisma/models/SharedResourceLeaseResource.js +2 -0
  126. package/dist/db/generated/prisma/models/SkillInstallation.js +2 -0
  127. package/dist/db/generated/prisma/models/SkillRegistryEntry.js +2 -0
  128. package/dist/db/generated/prisma/models/SkillTag.js +2 -0
  129. package/dist/db/generated/prisma/models/SkillVersion.js +2 -0
  130. package/dist/db/generated/prisma/models/TeamApprovalDecision.js +2 -0
  131. package/dist/db/generated/prisma/models/User.js +2 -0
  132. package/dist/db/generated/prisma/models/WebhookDelivery.js +2 -0
  133. package/dist/db/generated/prisma/models/WebhookEndpoint.js +2 -0
  134. package/dist/db/generated/prisma/models.js +2 -0
  135. package/dist/db/index.js +3 -0
  136. package/dist/db/read-retry.js +35 -0
  137. package/dist/db/seed.js +348 -0
  138. package/dist/index.js +162 -0
  139. package/dist/middleware/auth.js +361 -0
  140. package/dist/middleware/body-limit.js +14 -0
  141. package/dist/middleware/correlation-id.js +13 -0
  142. package/dist/middleware/error-handler.js +28 -0
  143. package/dist/middleware/iam-token.js +21 -0
  144. package/dist/middleware/rate-limit.js +78 -0
  145. package/dist/middleware/request-logger.js +85 -0
  146. package/dist/middleware/security-headers.js +23 -0
  147. package/dist/middleware/tracing.js +120 -0
  148. package/dist/middleware/user-status.js +33 -0
  149. package/dist/openapi/spec.js +2656 -0
  150. package/dist/queue/redis.js +20 -0
  151. package/dist/queue/requeue.js +27 -0
  152. package/dist/queue/workers.js +342 -0
  153. package/dist/routes/ai-schedule.js +73 -0
  154. package/dist/routes/alerts.js +79 -0
  155. package/dist/routes/anomalies.js +101 -0
  156. package/dist/routes/ardent.js +82 -0
  157. package/dist/routes/assistant.js +417 -0
  158. package/dist/routes/audit.js +138 -0
  159. package/dist/routes/codex.js +65 -0
  160. package/dist/routes/commands.js +226 -0
  161. package/dist/routes/credentials.js +58 -0
  162. package/dist/routes/cron.js +292 -0
  163. package/dist/routes/dependencies.js +49 -0
  164. package/dist/routes/deploy.js +18 -0
  165. package/dist/routes/discovery.js +168 -0
  166. package/dist/routes/docs.js +24 -0
  167. package/dist/routes/drift.js +126 -0
  168. package/dist/routes/events-stream.js +87 -0
  169. package/dist/routes/files.js +214 -0
  170. package/dist/routes/fleet-checks.js +21 -0
  171. package/dist/routes/health.js +133 -0
  172. package/dist/routes/heartbeat.js +545 -0
  173. package/dist/routes/hermes-registry.js +278 -0
  174. package/dist/routes/hermes.js +61 -0
  175. package/dist/routes/library.js +402 -0
  176. package/dist/routes/logs.js +172 -0
  177. package/dist/routes/managed-cron.js +23 -0
  178. package/dist/routes/mcp.js +39 -0
  179. package/dist/routes/metrics.js +187 -0
  180. package/dist/routes/nodes.js +951 -0
  181. package/dist/routes/notifications.js +130 -0
  182. package/dist/routes/ops.js +258 -0
  183. package/dist/routes/orchestra.js +430 -0
  184. package/dist/routes/predictions.js +23 -0
  185. package/dist/routes/profiling.js +68 -0
  186. package/dist/routes/quick-command.js +72 -0
  187. package/dist/routes/remediation.js +111 -0
  188. package/dist/routes/resource-leases.js +297 -0
  189. package/dist/routes/roles.js +370 -0
  190. package/dist/routes/rollout.js +124 -0
  191. package/dist/routes/scan.js +116 -0
  192. package/dist/routes/security-backup.js +58 -0
  193. package/dist/routes/security-fusion.js +605 -0
  194. package/dist/routes/security-integration.js +71 -0
  195. package/dist/routes/self-update.js +129 -0
  196. package/dist/routes/shared-resource-leases.js +78 -0
  197. package/dist/routes/skills.js +485 -0
  198. package/dist/routes/stats.js +96 -0
  199. package/dist/routes/team-approvals.js +23 -0
  200. package/dist/routes/terminal-ticket.js +15 -0
  201. package/dist/routes/terminal.js +17 -0
  202. package/dist/routes/topology.js +37 -0
  203. package/dist/routes/users.js +219 -0
  204. package/dist/routes/webhooks.js +137 -0
  205. package/dist/schemas/command-reconciliation.js +14 -0
  206. package/dist/schemas/commands.js +51 -0
  207. package/dist/schemas/cron.js +33 -0
  208. package/dist/schemas/deploy.js +20 -0
  209. package/dist/schemas/files.js +14 -0
  210. package/dist/schemas/hermes.js +69 -0
  211. package/dist/schemas/index.js +11 -0
  212. package/dist/schemas/library.js +48 -0
  213. package/dist/schemas/logs.js +35 -0
  214. package/dist/schemas/managed-cron.js +127 -0
  215. package/dist/schemas/node-responses.js +87 -0
  216. package/dist/schemas/node-session-receipt.js +84 -0
  217. package/dist/schemas/nodes.js +36 -0
  218. package/dist/schemas/orchestra.js +118 -0
  219. package/dist/schemas/resource-participant-reconciliation.js +99 -0
  220. package/dist/schemas/roles.js +54 -0
  221. package/dist/schemas/shared-resource-lease.js +132 -0
  222. package/dist/schemas/skills.js +44 -0
  223. package/dist/schemas/users.js +28 -0
  224. package/dist/scripts/run-disposable-recovery-exercise.js +39 -0
  225. package/dist/sdk/index.js +2 -0
  226. package/dist/sdk/node-api-client.js +474 -0
  227. package/dist/security/approval-assertion.js +66 -0
  228. package/dist/security/command-completion-registry.js +35 -0
  229. package/dist/security/command-request.js +12 -0
  230. package/dist/security/command-result-signature.js +34 -0
  231. package/dist/security/managed-http.js +45 -0
  232. package/dist/security/native-completion-registry.js +44 -0
  233. package/dist/server.js +178 -0
  234. package/dist/services/admission-fence.js +71 -0
  235. package/dist/services/ai-assistant-service.js +2523 -0
  236. package/dist/services/ai-correlation-service.js +225 -0
  237. package/dist/services/ai-export-service.js +141 -0
  238. package/dist/services/ai-insights-service.js +219 -0
  239. package/dist/services/ai-schedule-service.js +145 -0
  240. package/dist/services/ai-scratchpad-service.js +222 -0
  241. package/dist/services/ai-tools.js +1343 -0
  242. package/dist/services/alert-service.js +313 -0
  243. package/dist/services/anomaly-detector.js +419 -0
  244. package/dist/services/api-local-work.js +79 -0
  245. package/dist/services/application-probes.js +309 -0
  246. package/dist/services/ardent-scope-enrollment.js +123 -0
  247. package/dist/services/ardent-service.js +86 -0
  248. package/dist/services/audit-service.js +308 -0
  249. package/dist/services/codex-service.js +209 -0
  250. package/dist/services/command-lifecycle.js +60 -0
  251. package/dist/services/command-resource-leases.js +305 -0
  252. package/dist/services/control-host-node.js +242 -0
  253. package/dist/services/credential-rotation-service.js +294 -0
  254. package/dist/services/dependency-service.js +145 -0
  255. package/dist/services/disposable-recovery-runner.js +595 -0
  256. package/dist/services/docker-group-health.js +121 -0
  257. package/dist/services/engineering-assurance.js +492 -0
  258. package/dist/services/engineering-evidence-ledger.js +94 -0
  259. package/dist/services/engineering-metric-evidence.js +26 -0
  260. package/dist/services/event-bus.js +227 -0
  261. package/dist/services/fleet-check-log.js +102 -0
  262. package/dist/services/forecast-service.js +154 -0
  263. package/dist/services/health-retention.js +175 -0
  264. package/dist/services/heartbeat-stream.js +63 -0
  265. package/dist/services/hermes-catalog-import.js +62 -0
  266. package/dist/services/hermes-cli-parser.js +671 -0
  267. package/dist/services/hermes-core-rollout.js +90 -0
  268. package/dist/services/hermes-dashboard-endpoint.js +13 -0
  269. package/dist/services/hermes-plugin-source.js +149 -0
  270. package/dist/services/hermes-registry-service.js +258 -0
  271. package/dist/services/hermes-service.js +566 -0
  272. package/dist/services/hivemem-client.js +85 -0
  273. package/dist/services/host-local-writer.js +82 -0
  274. package/dist/services/incident-evidence.js +110 -0
  275. package/dist/services/incident-lessons.js +186 -0
  276. package/dist/services/llm-providers/anthropic.js +143 -0
  277. package/dist/services/llm-providers/index.js +7 -0
  278. package/dist/services/llm-providers/llama-cpp.js +237 -0
  279. package/dist/services/llm-providers/ollama.js +292 -0
  280. package/dist/services/llm-providers/openai-compatible.js +200 -0
  281. package/dist/services/llm-providers/provider-error.js +36 -0
  282. package/dist/services/llm-providers/registry.js +45 -0
  283. package/dist/services/llm-providers/types.js +2 -0
  284. package/dist/services/log-emitter.js +19 -0
  285. package/dist/services/log-retention.js +66 -0
  286. package/dist/services/maintenance-service.js +29 -0
  287. package/dist/services/managed-cron.js +493 -0
  288. package/dist/services/managed-ssh-admission.js +68 -0
  289. package/dist/services/monitor-pulse.js +10 -0
  290. package/dist/services/node-issue-monitor.js +71 -0
  291. package/dist/services/node-service.js +35 -0
  292. package/dist/services/notification-retention.js +51 -0
  293. package/dist/services/notification-service.js +94 -0
  294. package/dist/services/operational-observations.js +112 -0
  295. package/dist/services/operations-config.js +67 -0
  296. package/dist/services/ops-service.js +491 -0
  297. package/dist/services/orchestra-extras-service.js +370 -0
  298. package/dist/services/orchestra-resources-service.js +530 -0
  299. package/dist/services/os-scheduler-writer.js +73 -0
  300. package/dist/services/password-service.js +22 -0
  301. package/dist/services/prediction-service.js +284 -0
  302. package/dist/services/recovery-exercises.js +682 -0
  303. package/dist/services/remediation-service.js +325 -0
  304. package/dist/services/resource-enrollment.js +433 -0
  305. package/dist/services/resource-node-lock.js +18 -0
  306. package/dist/services/resource-participant-work.js +302 -0
  307. package/dist/services/role-service.js +388 -0
  308. package/dist/services/rollout-service.js +440 -0
  309. package/dist/services/security-export.js +185 -0
  310. package/dist/services/security-fusion-actions.js +22 -0
  311. package/dist/services/security-fusion-approvals.js +83 -0
  312. package/dist/services/security-fusion-evidence-integrity.js +144 -0
  313. package/dist/services/security-fusion-ingest.js +101 -0
  314. package/dist/services/security-fusion-outbox.js +185 -0
  315. package/dist/services/security-fusion-receipt-chain.js +134 -0
  316. package/dist/services/security-fusion-service.js +751 -0
  317. package/dist/services/security-fusion-verification.js +50 -0
  318. package/dist/services/self-update-service.js +200 -0
  319. package/dist/services/shared-resource-leases.js +413 -0
  320. package/dist/services/skill-publication-bundle.js +90 -0
  321. package/dist/services/skill-publication-settlement.js +36 -0
  322. package/dist/services/skill-publication-state.js +40 -0
  323. package/dist/services/skill-registry-service.js +327 -0
  324. package/dist/services/skill-service.js +148 -0
  325. package/dist/services/ssh-exec-service.js +139 -0
  326. package/dist/services/ssh-host-verification.js +27 -0
  327. package/dist/services/tailscale-node-key-service.js +75 -0
  328. package/dist/services/team-approvals.js +118 -0
  329. package/dist/services/topology-service.js +138 -0
  330. package/dist/services/transfer-authority-snapshot.js +151 -0
  331. package/dist/services/webhook-credential-migration.js +97 -0
  332. package/dist/services/webhook-security.js +242 -0
  333. package/dist/services/webhook-service.js +494 -0
  334. package/dist/types/auth.js +3 -0
  335. package/dist/types/index.js +3 -0
  336. package/dist/types/library.js +3 -0
  337. package/dist/types/notifications.js +3 -0
  338. package/dist/types/roles.js +3 -0
  339. package/dist/types/shared-contracts.js +3 -0
  340. package/dist/utils/env.js +141 -0
  341. package/dist/utils/heartbeat-peer.js +19 -0
  342. package/dist/utils/idempotency.js +45 -0
  343. package/dist/utils/ip.js +25 -0
  344. package/dist/utils/json-fields.js +94 -0
  345. package/dist/utils/local-tls.js +39 -0
  346. package/dist/utils/magnus-home.js +15 -0
  347. package/dist/utils/node-url.js +59 -0
  348. package/dist/utils/redact.js +26 -0
  349. package/dist/utils/safe-equal.js +13 -0
  350. package/dist/utils/sentinel-nodes.js +16 -0
  351. package/dist/utils/validate.js +41 -0
  352. package/package.json +119 -4
  353. package/prisma/migrations/20261031000000_baseline/migration.sql +2935 -0
  354. package/prisma/migrations/migration_lock.toml +3 -0
  355. package/prisma/schema.prisma +2185 -0
  356. package/prisma.config.ts +14 -0
@@ -0,0 +1,671 @@
1
+ const START = '__MAGNUS_HERMES_JSON_START__';
2
+ const END = '__MAGNUS_HERMES_JSON_END__';
3
+ function asRecord(value) {
4
+ return value && typeof value === 'object' && !Array.isArray(value)
5
+ ? value
6
+ : {};
7
+ }
8
+ function asString(value, fallback = '') {
9
+ return typeof value === 'string' ? value : fallback;
10
+ }
11
+ function asNullableString(value) {
12
+ return typeof value === 'string' && value.length > 0 ? value : null;
13
+ }
14
+ function asBoolean(value, fallback = false) {
15
+ return typeof value === 'boolean' ? value : fallback;
16
+ }
17
+ function asNullableNumber(value) {
18
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
19
+ }
20
+ function asRecordArray(value) {
21
+ return Array.isArray(value)
22
+ ? value.map(asRecord).filter((record) => Object.keys(record).length > 0)
23
+ : [];
24
+ }
25
+ export function normalizeServiceStatus(value) {
26
+ const text = String(value ?? '').toLowerCase();
27
+ if (['active', 'running', 'ok', 'healthy'].includes(text))
28
+ return 'running';
29
+ if (['inactive', 'dead'].includes(text))
30
+ return 'inactive';
31
+ if (['stopped', 'stop'].includes(text))
32
+ return 'stopped';
33
+ if (['failed', 'failure'].includes(text))
34
+ return 'failed';
35
+ if (['error', 'errored'].includes(text))
36
+ return 'error';
37
+ if (['not_installed', 'missing', 'not-found'].includes(text))
38
+ return 'not_installed';
39
+ return 'unknown';
40
+ }
41
+ export function normalizeInstallationStatus(value, installed) {
42
+ const text = String(value ?? '').toLowerCase();
43
+ if (!installed)
44
+ return 'not_installed';
45
+ if (['running', 'detected', 'needs_setup', 'degraded', 'error', 'unknown'].includes(text)) {
46
+ return text;
47
+ }
48
+ return installed ? 'detected' : 'not_installed';
49
+ }
50
+ export function extractHermesJson(stdout) {
51
+ const start = stdout.indexOf(START);
52
+ const end = stdout.indexOf(END);
53
+ if (start === -1 || end === -1 || end <= start) {
54
+ throw new Error('Hermes command did not return a parseable Magnus JSON envelope');
55
+ }
56
+ const jsonText = stdout.slice(start + START.length, end).trim();
57
+ return JSON.parse(jsonText);
58
+ }
59
+ export function parseProfileListText(text, hermesHome) {
60
+ const profiles = [];
61
+ for (const rawLine of text.split('\n')) {
62
+ const line = rawLine.trim();
63
+ if (!line || /^(name|profiles?|[-=]+)/i.test(line))
64
+ continue;
65
+ const isDefault = line.startsWith('*') || line.startsWith('◆') || /\bdefault\b/i.test(line);
66
+ const cleaned = line.replace(/^[*◆◇•]\s*/, '').replace(/\s+\(default\)$/i, '').trim();
67
+ const name = cleaned.split(/\s+/)[0];
68
+ if (!name || /[:]/.test(name))
69
+ continue;
70
+ profiles.push({
71
+ name,
72
+ description: '',
73
+ profileHome: `${hermesHome.replace(/\/+$/, '')}/profiles/${name}`,
74
+ isDefault,
75
+ gatewayStatus: 'unknown',
76
+ apiServerEnabled: false,
77
+ apiServerHost: '127.0.0.1',
78
+ apiServerPort: null,
79
+ providerSummary: null,
80
+ modelSummary: null,
81
+ distribution: null,
82
+ metadata: { source: 'profile-list-text' },
83
+ });
84
+ }
85
+ return profiles;
86
+ }
87
+ export function parseHermesDetectionOutput(stdout) {
88
+ const envelope = extractHermesJson(stdout);
89
+ const installed = asBoolean(envelope['installed']);
90
+ const hermesHome = asString(envelope['hermesHome'], '~/.hermes');
91
+ const rawProfiles = Array.isArray(envelope['profiles']) ? envelope['profiles'] : [];
92
+ const fallbackProfiles = rawProfiles.length === 0 && typeof envelope['profileListText'] === 'string'
93
+ ? parseProfileListText(envelope['profileListText'], hermesHome)
94
+ : [];
95
+ const profiles = rawProfiles.length > 0
96
+ ? rawProfiles.map((item) => {
97
+ const record = asRecord(item);
98
+ const name = asString(record['name']);
99
+ return {
100
+ name,
101
+ description: asString(record['description']),
102
+ profileHome: asString(record['profileHome'], asString(record['profile_home'], `${hermesHome.replace(/\/+$/, '')}/profiles/${name}`)),
103
+ isDefault: asBoolean(record['isDefault'], asBoolean(record['is_default'], name === 'default')),
104
+ gatewayStatus: normalizeServiceStatus(record['gatewayStatus'] ?? record['gateway_status']),
105
+ apiServerEnabled: asBoolean(record['apiServerEnabled'], asBoolean(record['api_server_enabled'])),
106
+ apiServerHost: asString(record['apiServerHost'], asString(record['api_server_host'], '127.0.0.1')),
107
+ apiServerPort: asNullableNumber(record['apiServerPort']) ?? asNullableNumber(record['api_server_port']),
108
+ providerSummary: asNullableString(record['providerSummary']) ?? asNullableString(record['provider_summary']),
109
+ modelSummary: asNullableString(record['modelSummary']) ?? asNullableString(record['model_summary']) ?? asNullableString(record['model']),
110
+ distribution: asNullableString(record['distribution']),
111
+ metadata: asRecord(record['metadata']),
112
+ };
113
+ }).filter((profile) => profile.name.length > 0)
114
+ : fallbackProfiles;
115
+ const skills = asRecordArray(envelope['skills']).map((record) => ({
116
+ slug: asString(record['slug']),
117
+ category: asNullableString(record['category']),
118
+ source: asString(record['source'], 'detected'),
119
+ enabled: asBoolean(record['enabled'], false),
120
+ metadata: asRecord(record['metadata']),
121
+ })).filter((skill) => skill.slug.length > 0);
122
+ const toolsets = asRecordArray(envelope['toolsets']).map((record) => ({
123
+ toolset: asString(record['toolset']),
124
+ enabled: asBoolean(record['enabled'], true),
125
+ metadata: asRecord(record['metadata']),
126
+ })).filter((toolset) => toolset.toolset.length > 0);
127
+ const providers = asRecordArray(envelope['providers']).map((record) => ({
128
+ profileName: asNullableString(record['profileName']),
129
+ provider: asString(record['provider']),
130
+ model: asNullableString(record['model']),
131
+ configured: asBoolean(record['configured'], true),
132
+ metadata: asRecord(record['metadata']),
133
+ })).filter((provider) => provider.provider.length > 0);
134
+ const plugins = asRecordArray(envelope['plugins']).map((record) => ({
135
+ slug: asString(record['slug']),
136
+ pluginType: asString(record['pluginType'], 'general'),
137
+ version: asNullableString(record['version']),
138
+ status: asString(record['status'], 'detected'),
139
+ healthState: asString(record['healthState'], 'unknown'),
140
+ metadata: asRecord(record['metadata']),
141
+ })).filter((plugin) => plugin.slug.length > 0);
142
+ const messagingBindings = asRecordArray(envelope['messagingBindings']).map((record) => ({
143
+ platform: asString(record['platform']),
144
+ channelIds: Array.isArray(record['channelIds']) ? record['channelIds'].filter((item) => typeof item === 'string') : [],
145
+ voiceEnabled: asBoolean(record['voiceEnabled']),
146
+ voiceModel: asNullableString(record['voiceModel']),
147
+ ttsProvider: asNullableString(record['ttsProvider']),
148
+ secretRef: asNullableString(record['secretRef']),
149
+ status: asString(record['status'], 'detected'),
150
+ metadata: asRecord(record['metadata']),
151
+ })).filter((binding) => binding.platform.length > 0);
152
+ return {
153
+ installed,
154
+ status: normalizeInstallationStatus(envelope['status'], installed),
155
+ version: asNullableString(envelope['version']),
156
+ hermesBin: asString(envelope['hermesBin'], 'hermes'),
157
+ hermesHome,
158
+ gatewayStatus: normalizeServiceStatus(envelope['gatewayStatus']),
159
+ dashboardStatus: normalizeServiceStatus(envelope['dashboardStatus']),
160
+ apiServerEnabled: asBoolean(envelope['apiServerEnabled']),
161
+ apiServerHost: asString(envelope['apiServerHost'], '127.0.0.1'),
162
+ apiServerPort: asNullableNumber(envelope['apiServerPort']),
163
+ profiles,
164
+ skills,
165
+ toolsets,
166
+ providers,
167
+ plugins,
168
+ messagingBindings,
169
+ raw: envelope,
170
+ };
171
+ }
172
+ export function buildHermesDetectionScript(options) {
173
+ const payload = Buffer.from(JSON.stringify(options), 'utf-8').toString('base64');
174
+ return String.raw `
175
+ set +e
176
+ MAGNUS_HERMES_PAYLOAD='${payload}' python3 - <<'PY'
177
+ import base64, json, os, pathlib, re, shutil, subprocess
178
+
179
+ START = '${START}'
180
+ END = '${END}'
181
+ opts = json.loads(base64.b64decode(os.environ['MAGNUS_HERMES_PAYLOAD']).decode('utf-8'))
182
+ hermes_home = os.path.expanduser(opts.get('hermesHome') or '~/.hermes')
183
+ requested_bin = opts.get('hermesBin') or 'hermes'
184
+ dashboard_port = int(opts.get('dashboardPort') or 9119)
185
+
186
+
187
+ def looks_like_hermes_home(path):
188
+ home = pathlib.Path(path)
189
+ return (home / 'config.yaml').exists() or (home / '.env').exists() or (home / 'profiles').exists()
190
+
191
+
192
+ candidate_homes = []
193
+ for item in [
194
+ hermes_home,
195
+ os.environ.get('HERMES_HOME'),
196
+ os.path.expanduser('~/.hermes'),
197
+ os.path.expanduser('~/.config/hermes'),
198
+ os.path.expanduser('~/.config/hermes-agent'),
199
+ '/opt/hermes-agent',
200
+ '/opt/hermes',
201
+ ]:
202
+ if item and item not in candidate_homes:
203
+ candidate_homes.append(item)
204
+ if not looks_like_hermes_home(hermes_home):
205
+ for candidate_home in candidate_homes:
206
+ if looks_like_hermes_home(candidate_home):
207
+ hermes_home = candidate_home
208
+ break
209
+
210
+
211
+ def run(cmd, output_limit=20000):
212
+ try:
213
+ proc = subprocess.run(cmd, text=True, capture_output=True, timeout=15, env={**os.environ, 'HERMES_HOME': hermes_home, 'COLUMNS': '240'})
214
+ return {'code': proc.returncode, 'stdout': (proc.stdout or '')[:output_limit], 'stderr': (proc.stderr or '')[:output_limit]}
215
+ except Exception as exc:
216
+ return {'code': 127, 'stdout': '', 'stderr': str(exc)}
217
+
218
+ candidate_bins = []
219
+ if requested_bin:
220
+ candidate_bins.append(requested_bin)
221
+ candidate_bins.extend([
222
+ 'hermes',
223
+ os.path.expanduser('~/.local/bin/hermes'),
224
+ os.path.join(hermes_home, 'bin', 'hermes'),
225
+ os.path.join(hermes_home, 'hermes'),
226
+ os.path.join(hermes_home, 'hermes-agent', 'hermes'),
227
+ ])
228
+ resolved_bin = ''
229
+ for candidate in candidate_bins:
230
+ expanded = os.path.expanduser(candidate)
231
+ found = shutil.which(expanded) if os.path.sep not in expanded else (expanded if os.path.exists(expanded) and os.access(expanded, os.X_OK) else '')
232
+ if found:
233
+ resolved_bin = found
234
+ break
235
+ installed = bool(resolved_bin) or pathlib.Path(hermes_home).exists()
236
+ version = None
237
+ profile_list_text = ''
238
+ profiles = []
239
+ skills = []
240
+ toolsets = []
241
+ providers = []
242
+ plugins = []
243
+ messaging_bindings = []
244
+
245
+ def first_nonempty(text):
246
+ for line in text.splitlines():
247
+ line = line.strip()
248
+ if line:
249
+ return line
250
+ return None
251
+
252
+
253
+ def clean_cell(text):
254
+ return re.sub(r'\s+', ' ', text.replace('…', '')).strip()
255
+
256
+
257
+ def is_decoration_text(text):
258
+ return bool(text) and not re.search(r'[A-Za-z0-9]', text)
259
+
260
+
261
+ def rich_rows(text):
262
+ rows = []
263
+ for raw in text.splitlines():
264
+ line = raw.strip()
265
+ if not line.startswith('│'):
266
+ continue
267
+ cells = [clean_cell(part) for part in line.strip('│').split('│')]
268
+ if not cells:
269
+ continue
270
+ nonempty = [cell for cell in cells if cell]
271
+ if nonempty and all(is_decoration_text(cell) for cell in nonempty):
272
+ continue
273
+ if is_decoration_text(cells[0]) or re.match(r'^(name|profile|tool|status)$', cells[0], re.I):
274
+ continue
275
+ rows.append(cells)
276
+ return rows
277
+
278
+ if resolved_bin:
279
+ version_result = run([resolved_bin, '--version'])
280
+ version = first_nonempty(version_result['stdout']) or first_nonempty(version_result['stderr'])
281
+ profile_result = run([resolved_bin, 'profile', 'list'])
282
+ profile_list_text = (profile_result['stdout'] or profile_result['stderr'] or '')[:20000]
283
+
284
+ profile_rows = rich_rows(profile_list_text)
285
+ if profile_rows:
286
+ for cells in profile_rows:
287
+ name_cell = cells[0] if cells else ''
288
+ is_default = name_cell.startswith('*') or name_cell.startswith('◆') or 'default' in name_cell.lower()
289
+ name = re.sub(r'^[*◆◇•]\s*', '', name_cell).split()[0] if name_cell.split() else ''
290
+ if not name or ':' in name or is_decoration_text(name):
291
+ continue
292
+ model = cells[1] if len(cells) > 1 and cells[1] not in ('—', '-') else None
293
+ gateway = cells[2] if len(cells) > 2 else 'unknown'
294
+ alias = cells[3] if len(cells) > 3 and cells[3] not in ('—', '-') else None
295
+ distribution = cells[4] if len(cells) > 4 and cells[4] not in ('—', '-') else None
296
+ profiles.append({
297
+ 'name': name,
298
+ 'description': '',
299
+ 'profileHome': os.path.join(hermes_home, 'profiles', name),
300
+ 'isDefault': is_default,
301
+ 'gatewayStatus': gateway,
302
+ 'apiServerEnabled': False,
303
+ 'apiServerHost': '127.0.0.1',
304
+ 'apiServerPort': None,
305
+ 'providerSummary': None,
306
+ 'modelSummary': model,
307
+ 'distribution': distribution,
308
+ 'metadata': {'source': 'hermes profile list', 'alias': alias},
309
+ })
310
+ else:
311
+ for raw in profile_list_text.splitlines():
312
+ line = raw.strip()
313
+ if not line or re.match(r'^(name|profiles?|[-=]+)', line, re.I):
314
+ continue
315
+ is_default = line.startswith('*') or line.startswith('◆') or 'default' in line.lower()
316
+ cleaned = re.sub(r'^[*◆◇•]\s*', '', line)
317
+ cleaned = re.sub(r'\s+\(default\)$', '', cleaned, flags=re.I).strip()
318
+ if is_decoration_text(cleaned):
319
+ continue
320
+ parts = re.split(r'\s{2,}', cleaned)
321
+ name = parts[0].split()[0] if parts and parts[0].split() else ''
322
+ if not name or ':' in name or is_decoration_text(name):
323
+ continue
324
+ model = parts[1] if len(parts) > 1 and parts[1] not in ('—', '-') else None
325
+ gateway = parts[2] if len(parts) > 2 else 'unknown'
326
+ alias = parts[3] if len(parts) > 3 and parts[3] not in ('—', '-') else None
327
+ distribution = parts[4] if len(parts) > 4 and parts[4] not in ('—', '-') else None
328
+ profiles.append({
329
+ 'name': name,
330
+ 'description': '',
331
+ 'profileHome': os.path.join(hermes_home, 'profiles', name),
332
+ 'isDefault': is_default,
333
+ 'gatewayStatus': gateway,
334
+ 'apiServerEnabled': False,
335
+ 'apiServerHost': '127.0.0.1',
336
+ 'apiServerPort': None,
337
+ 'providerSummary': None,
338
+ 'modelSummary': model,
339
+ 'distribution': distribution,
340
+ 'metadata': {'source': 'hermes profile list', 'alias': alias},
341
+ })
342
+
343
+ skills_result = run([resolved_bin, 'skills', 'list'], output_limit=1048576)
344
+ for cells in rich_rows(skills_result.get('stdout') or skills_result.get('stderr') or ''):
345
+ if len(cells) >= 5:
346
+ status_value = cells[4].lower()
347
+ skills.append({'slug': cells[0], 'category': cells[1] or None, 'source': cells[2] or 'detected', 'enabled': status_value == 'enabled', 'metadata': {'trust': cells[3], 'status': status_value or 'unknown', 'source': 'hermes skills list'}})
348
+
349
+ tools_result = run([resolved_bin, 'tools', 'list'])
350
+ for raw in (tools_result.get('stdout') or tools_result.get('stderr') or '').splitlines():
351
+ line = raw.strip()
352
+ match = re.match(r'^(✓|✗)\s+(enabled|disabled)\s+([a-zA-Z0-9_.-]+)\s+(.*)$', line)
353
+ if match:
354
+ toolsets.append({'toolset': match.group(3), 'enabled': match.group(2) == 'enabled', 'metadata': {'label': clean_cell(match.group(4)), 'source': 'hermes tools list'}})
355
+
356
+ plugins_result = run([resolved_bin, 'plugins', 'list'])
357
+ for cells in rich_rows(plugins_result.get('stdout') or plugins_result.get('stderr') or ''):
358
+ if len(cells) >= 5 and cells[0]:
359
+ status_value = cells[1].lower().replace(' ', '_') or 'detected'
360
+ plugins.append({'slug': cells[0], 'pluginType': cells[0].split('/')[0] if '/' in cells[0] else 'general', 'version': cells[2] or None, 'status': status_value, 'healthState': 'unknown', 'metadata': {'source': cells[4] or 'hermes plugins list'}})
361
+
362
+ gateway_result = run([resolved_bin, 'gateway', 'status'])
363
+ gateway_text = (gateway_result['stdout'] + gateway_result['stderr']).lower()
364
+ else:
365
+ gateway_result = {'code': 127, 'stdout': '', 'stderr': 'hermes binary not found'}
366
+ gateway_text = ''
367
+
368
+ # Profile discovery fallback: Hermes can be installed with a valid home even when
369
+ # the binary is not visible to a non-login SSH shell. Scan profile directories,
370
+ # then use the implicit default profile convention for existing Hermes homes.
371
+ if not profiles:
372
+ profiles_dir = pathlib.Path(hermes_home) / 'profiles'
373
+ if profiles_dir.exists():
374
+ for profile_dir in sorted(profiles_dir.iterdir(), key=lambda p: p.name):
375
+ if not profile_dir.is_dir():
376
+ continue
377
+ name = profile_dir.name.strip()
378
+ if not name or not re.match(r'^[A-Za-z0-9_.-]+$', name):
379
+ continue
380
+ profiles.append({
381
+ 'name': name,
382
+ 'description': '',
383
+ 'profileHome': str(profile_dir),
384
+ 'isDefault': name == 'default',
385
+ 'gatewayStatus': 'unknown',
386
+ 'apiServerEnabled': False,
387
+ 'apiServerHost': '127.0.0.1',
388
+ 'apiServerPort': None,
389
+ 'providerSummary': None,
390
+ 'modelSummary': None,
391
+ 'distribution': None,
392
+ 'metadata': {'source': 'filesystem profiles'},
393
+ })
394
+ if installed and not profiles and pathlib.Path(hermes_home).exists():
395
+ profiles.append({
396
+ 'name': 'default',
397
+ 'description': '',
398
+ 'profileHome': str(pathlib.Path(hermes_home) / 'profiles' / 'default'),
399
+ 'isDefault': True,
400
+ 'gatewayStatus': 'unknown',
401
+ 'apiServerEnabled': False,
402
+ 'apiServerHost': '127.0.0.1',
403
+ 'apiServerPort': None,
404
+ 'providerSummary': None,
405
+ 'modelSummary': None,
406
+ 'distribution': None,
407
+ 'metadata': {'source': 'implicit-default-profile'},
408
+ })
409
+
410
+ # Check systemd and port hints for local dashboard status.
411
+ dash_user = run(['systemctl', '--user', 'is-active', 'hermes-dashboard.service'])
412
+ dash_system = run(['systemctl', 'is-active', 'hermes-dashboard.service'])
413
+ dash_text = (dash_user['stdout'] + dash_user['stderr'] + dash_system['stdout'] + dash_system['stderr']).lower()
414
+
415
+ # Read base .env for API server hints and configured provider key names. Do not return secret values.
416
+ env_path = pathlib.Path(hermes_home) / '.env'
417
+ api_enabled = False
418
+ api_host = '127.0.0.1'
419
+ api_port = None
420
+ env_values = {}
421
+ env_keys = []
422
+ configured_provider_keys = []
423
+ if env_path.exists():
424
+ try:
425
+ for line in env_path.read_text(errors='ignore').splitlines():
426
+ if line.startswith('API_SERVER_ENABLED='):
427
+ api_enabled = line.split('=', 1)[1].strip().lower() == 'true'
428
+ elif line.startswith('API_SERVER_HOST='):
429
+ api_host = line.split('=', 1)[1].strip() or api_host
430
+ elif line.startswith('API_SERVER_PORT='):
431
+ try:
432
+ api_port = int(line.split('=', 1)[1].strip())
433
+ except Exception:
434
+ api_port = None
435
+ key = line.split('=', 1)[0].strip() if '=' in line else ''
436
+ value = line.split('=', 1)[1].strip() if '=' in line else ''
437
+ if key:
438
+ env_values[key] = value
439
+ env_keys.append(key)
440
+ if key.endswith('_API_KEY') or key.endswith('_TOKEN'):
441
+ configured_provider_keys.append(key)
442
+ except Exception:
443
+ pass
444
+
445
+ config_path = pathlib.Path(hermes_home) / 'config.yaml'
446
+ config_data = {}
447
+ if config_path.exists():
448
+ try:
449
+ import yaml
450
+ loaded = yaml.safe_load(config_path.read_text(errors='ignore'))
451
+ if isinstance(loaded, dict):
452
+ config_data = loaded
453
+ except Exception:
454
+ config_data = {}
455
+
456
+ model_provider = None
457
+ model_name = None
458
+ configured_provider_names = []
459
+ seen_providers = set()
460
+
461
+
462
+ def normalize_list(value):
463
+ if value is None:
464
+ return []
465
+ if isinstance(value, list):
466
+ return value
467
+ if isinstance(value, tuple):
468
+ return list(value)
469
+ if isinstance(value, dict):
470
+ return list(value.keys())
471
+ if isinstance(value, str):
472
+ text = value.strip()
473
+ if not text:
474
+ return []
475
+ if ',' in text:
476
+ return [part.strip() for part in text.split(',')]
477
+ return [text]
478
+ return []
479
+
480
+
481
+ def provider_from_env_key(key):
482
+ known_prefixes = {
483
+ 'ANTHROPIC': 'anthropic',
484
+ 'OPENAI': 'openai',
485
+ 'OPENROUTER': 'openrouter',
486
+ 'GOOGLE': 'google',
487
+ 'GEMINI': 'google',
488
+ 'GROQ': 'groq',
489
+ 'MISTRAL': 'mistral',
490
+ 'TOGETHER': 'together',
491
+ 'XAI': 'xai',
492
+ 'DEEPSEEK': 'deepseek',
493
+ 'PERPLEXITY': 'perplexity',
494
+ 'COHERE': 'cohere',
495
+ 'MINIMAX': 'minimax',
496
+ 'AZURE_OPENAI': 'azure-openai',
497
+ 'AWS': 'bedrock',
498
+ 'BEDROCK': 'bedrock',
499
+ }
500
+ for prefix, provider in known_prefixes.items():
501
+ if key == prefix + '_API_KEY' or key.startswith(prefix + '_'):
502
+ return provider
503
+ return None
504
+
505
+
506
+ def clean_provider_name(value):
507
+ if not isinstance(value, str):
508
+ return None
509
+ name = value.strip().strip('"\'')
510
+ if not name or '://' in name or '/' in name or len(name) > 80:
511
+ return None
512
+ if not re.match(r'^[A-Za-z0-9_.-]+$', name):
513
+ return None
514
+ return name
515
+
516
+
517
+ def add_provider(provider, model=None, source='config', metadata=None):
518
+ name = clean_provider_name(provider)
519
+ if not name:
520
+ return
521
+ key = (name, model or '')
522
+ if key in seen_providers:
523
+ return
524
+ seen_providers.add(key)
525
+ configured_provider_names.append(name)
526
+ providers.append({'profileName': None, 'provider': name, 'model': model if isinstance(model, str) and model else None, 'configured': True, 'metadata': {'source': source, **(metadata or {})}})
527
+
528
+
529
+ if config_data:
530
+ model_section = config_data.get('model') if isinstance(config_data.get('model'), dict) else {}
531
+ model_provider = clean_provider_name(model_section.get('provider')) if isinstance(model_section, dict) else None
532
+ model_name = model_section.get('default') if isinstance(model_section.get('default'), str) else None
533
+ if model_provider or model_name:
534
+ add_provider(model_provider or 'configured-model', model_name, 'config.model')
535
+
536
+ for name in normalize_list(config_data.get('providers')):
537
+ add_provider(str(name), None, 'config.providers')
538
+ for name in normalize_list(config_data.get('fallback_providers')):
539
+ add_provider(str(name), None, 'config.fallback_providers')
540
+
541
+ fallback_model = config_data.get('fallback_model')
542
+ if isinstance(fallback_model, dict):
543
+ add_provider(fallback_model.get('provider'), fallback_model.get('model') if isinstance(fallback_model.get('model'), str) else None, 'config.fallback_model')
544
+
545
+ skip_sections = {'telegram', 'discord', 'slack', 'qqbot', 'google_chat', 'messaging', 'integrations', 'model_catalog'}
546
+ def walk_provider_configs(obj, path=()):
547
+ if isinstance(obj, dict):
548
+ top = path[0] if path else ''
549
+ if top not in skip_sections and isinstance(obj.get('provider'), str):
550
+ model_value = obj.get('model') or obj.get('default') or obj.get('model_id')
551
+ add_provider(obj.get('provider'), model_value if isinstance(model_value, str) else None, 'config.' + '.'.join(path) if path else 'config')
552
+ for key, value in obj.items():
553
+ walk_provider_configs(value, path + (str(key),))
554
+ elif isinstance(obj, list):
555
+ for index, value in enumerate(obj):
556
+ walk_provider_configs(value, path + (str(index),))
557
+ walk_provider_configs(config_data)
558
+
559
+ for key in configured_provider_keys:
560
+ env_provider = provider_from_env_key(key)
561
+ if env_provider:
562
+ add_provider(env_provider, None, 'env-key', {'configuredKey': key})
563
+
564
+ for profile in profiles:
565
+ if profile.get('modelSummary'):
566
+ providers.append({'profileName': profile.get('name'), 'provider': model_provider or (configured_provider_names[0] if configured_provider_names else 'default'), 'model': profile.get('modelSummary'), 'configured': True, 'metadata': {'source': 'hermes profile list'}})
567
+
568
+
569
+ def env_present(key):
570
+ return bool(env_values.get(key))
571
+
572
+
573
+ def add_messaging_binding(platform, section, token_keys, channel_env_keys=()):
574
+ section = section if isinstance(section, dict) else {}
575
+ channel_ids = []
576
+ for key in ('allowed_chats', 'allowed_channels', 'free_response_channels'):
577
+ channel_ids.extend(str(item) for item in normalize_list(section.get(key)) if str(item).strip())
578
+ prompts = section.get('channel_prompts')
579
+ if isinstance(prompts, dict):
580
+ channel_ids.extend(str(key) for key in prompts.keys() if str(key).strip())
581
+ for key in channel_env_keys:
582
+ if env_values.get(key):
583
+ channel_ids.append(env_values[key])
584
+ channel_ids = sorted(set(channel_ids))
585
+ secret_key = next((key for key in token_keys if env_present(key)), None)
586
+ configured = bool(secret_key or channel_ids or section)
587
+ if configured:
588
+ messaging_bindings.append({
589
+ 'platform': platform,
590
+ 'channelIds': channel_ids,
591
+ 'voiceEnabled': bool(section.get('voice_enabled') or section.get('voice')),
592
+ 'voiceModel': section.get('voice_model') if isinstance(section.get('voice_model'), str) else None,
593
+ 'ttsProvider': section.get('tts_provider') if isinstance(section.get('tts_provider'), str) else None,
594
+ 'secretRef': ('env:' + secret_key) if secret_key else None,
595
+ 'status': 'detected',
596
+ 'metadata': {'source': 'sanitized-config', 'configuredKeys': [key for key in token_keys if key in env_values]},
597
+ })
598
+
599
+ if config_data or env_values:
600
+ add_messaging_binding('telegram', config_data.get('telegram') if isinstance(config_data, dict) else {}, ['TELEGRAM_BOT_TOKEN'], ['TELEGRAM_HOME_CHANNEL'])
601
+ add_messaging_binding('discord', config_data.get('discord') if isinstance(config_data, dict) else {}, ['DISCORD_BOT_TOKEN'])
602
+ add_messaging_binding('slack', config_data.get('slack') if isinstance(config_data, dict) else {}, ['SLACK_BOT_TOKEN', 'SLACK_APP_TOKEN'])
603
+
604
+ plugins_dir = pathlib.Path(hermes_home) / 'plugins'
605
+ if plugins_dir.exists():
606
+ for plugin_yaml in plugins_dir.glob('*/*/plugin.yaml'):
607
+ slug = '/'.join(plugin_yaml.relative_to(plugins_dir).parts[:-1])
608
+ if slug and not any(p.get('slug') == slug for p in plugins):
609
+ plugins.append({'slug': slug, 'pluginType': slug.split('/')[0], 'version': None, 'status': 'detected', 'healthState': 'unknown', 'metadata': {'source': 'filesystem'}})
610
+
611
+ status = 'not_installed'
612
+ if installed:
613
+ status = 'detected'
614
+ if 'running' in gateway_text or 'active' in gateway_text:
615
+ status = 'running'
616
+ elif resolved_bin and not pathlib.Path(hermes_home).exists():
617
+ status = 'needs_setup'
618
+
619
+ out = {
620
+ 'installed': installed,
621
+ 'status': status,
622
+ 'version': version,
623
+ 'hermesBin': resolved_bin or requested_bin,
624
+ 'hermesHome': hermes_home,
625
+ 'gatewayStatus': 'running' if ('running' in gateway_text or 'active' in gateway_text) else ('error' if gateway_result.get('code') not in (0, None) and resolved_bin else 'unknown'),
626
+ 'dashboardStatus': 'running' if 'active' in dash_text else ('inactive' if 'inactive' in dash_text else 'unknown'),
627
+ 'dashboardPort': dashboard_port,
628
+ 'apiServerEnabled': api_enabled,
629
+ 'apiServerHost': api_host,
630
+ 'apiServerPort': api_port,
631
+ 'profiles': profiles,
632
+ 'skills': skills,
633
+ 'toolsets': toolsets,
634
+ 'providers': providers,
635
+ 'plugins': plugins,
636
+ 'messagingBindings': messaging_bindings,
637
+ 'profileListText': profile_list_text,
638
+ 'configuration': {
639
+ 'configPresent': config_path.exists(),
640
+ 'configPath': str(config_path) if config_path.exists() else None,
641
+ 'envPath': str(env_path) if env_path.exists() else None,
642
+ 'envKeys': sorted(set(env_keys)),
643
+ 'modelProvider': model_provider,
644
+ 'modelName': model_name,
645
+ 'modelBaseUrl': config_data.get('model', {}).get('base_url') if isinstance(config_data.get('model'), dict) else None,
646
+ 'openaiRuntime': config_data.get('model', {}).get('openai_runtime') if isinstance(config_data.get('model'), dict) else None,
647
+ 'magnusRouterConfigured': model_provider == 'custom',
648
+ 'memoryProvider': config_data.get('memory', {}).get('provider') if isinstance(config_data.get('memory'), dict) else None,
649
+ 'hiveMemConfigured': config_data.get('memory', {}).get('provider') == 'hivemem' if isinstance(config_data.get('memory'), dict) else False,
650
+ 'hiveMemPluginInstalled': pathlib.Path(hermes_home, 'plugins', 'memory', 'hivemem', '__init__.py').exists(),
651
+ 'hiveMemApiUrl': env_values.get('HERMES_HIVEMEM_API_URL') or env_values.get('HIVEMEM_URL'),
652
+ 'magnusSkills': {
653
+ 'status': 'available' if os.environ.get('MAGNUS_SKILLS_DIR') else 'not_configured',
654
+ 'message': 'Hermes Agent skills are published from magnus-skills and reconciled through magnus-agent.' if os.environ.get('MAGNUS_SKILLS_DIR') else 'Set MAGNUS_SKILLS_DIR on this node to expose the magnus-skills catalogue to Hermes Agent profiles.',
655
+ },
656
+ },
657
+ 'rawChecks': {
658
+ 'version': version,
659
+ 'gatewayCode': gateway_result.get('code'),
660
+ 'dashboardUserCode': dash_user.get('code'),
661
+ 'dashboardSystemCode': dash_system.get('code'),
662
+ 'hermesHomeExists': pathlib.Path(hermes_home).exists(),
663
+ },
664
+ }
665
+ print(START)
666
+ print(json.dumps(out))
667
+ print(END)
668
+ PY
669
+ `;
670
+ }
671
+ //# sourceMappingURL=hermes-cli-parser.js.map