@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,1343 @@
1
+ /**
2
+ * ai-tools.ts — Tool system for the AI Fleet Operations Assistant.
3
+ *
4
+ * Provides read-only fleet data access and memory management tools
5
+ * that the AI can invoke during conversations.
6
+ */
7
+ import { readFile, writeFile, readdir, stat } from 'node:fs/promises';
8
+ import { resolve, dirname, relative, normalize } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { nanoid } from 'nanoid';
11
+ import { getDb } from '../db/index.js';
12
+ import { getFleetAnomalySummary, listAnomalyEvents } from './anomaly-detector.js';
13
+ import { queryAuditEvents } from './audit-service.js';
14
+ import { logAuditEvent } from './audit-service.js';
15
+ import { listSkills, getSkill, getSkillFile, createSkill } from './skill-service.js';
16
+ import { NodeApiClient } from '../sdk/node-api-client.js';
17
+ import { getNodeBaseUrl } from '../utils/node-url.js';
18
+ import { getNodeManagerSecret } from '../utils/env.js';
19
+ import { correlateAnomalies, getAnomalyTimeline } from './ai-correlation-service.js';
20
+ import { getHiveMemClient } from './hivemem-client.js';
21
+ import { aliasScratchpadEntry, compareScratchpadSnapshots, listScratchpadEntries, setScratchpadEntry, transformScratchpadData, } from './ai-scratchpad-service.js';
22
+ import { getDependencyHealth, getFleetReadiness, getFleetTimeline, getPredictiveMaintenance, getIncidentSummary, classifyRemediationPlan, getHermesEffectiveState, getPackageSecurityPosture, } from './ops-service.js';
23
+ import { getCodexFleetPosture } from './codex-service.js';
24
+ const __dirname = dirname(fileURLToPath(import.meta.url));
25
+ const WORKSPACE_ROOT = resolve(__dirname, '../..');
26
+ const toolRegistry = new Map();
27
+ function registerTool(name, handler) {
28
+ toolRegistry.set(name, handler);
29
+ }
30
+ function parseSystemUpdatePosture(value) {
31
+ try {
32
+ const parsed = JSON.parse(value);
33
+ if (typeof parsed.supported !== 'boolean' ||
34
+ typeof parsed.platform !== 'string' ||
35
+ !['enabled', 'disabled', 'partial', 'unsupported', 'unknown'].includes(parsed.automaticUpdates ?? '') ||
36
+ typeof parsed.rebootRequired !== 'boolean' ||
37
+ !Array.isArray(parsed.rebootRequiredPackages))
38
+ return null;
39
+ return parsed;
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ function parseWazuhPosture(value) {
46
+ try {
47
+ const parsed = JSON.parse(value);
48
+ if (typeof parsed.installed !== 'boolean' ||
49
+ !['active', 'inactive', 'failed', 'not_installed', 'unknown'].includes(parsed.serviceStatus ?? '') ||
50
+ !['enabled', 'disabled', 'static', 'unknown'].includes(parsed.enabled ?? '') ||
51
+ !(parsed.version === null || typeof parsed.version === 'string') ||
52
+ !Array.isArray(parsed.managerAddresses) ||
53
+ !parsed.managerAddresses.every((address) => typeof address === 'string')) {
54
+ return null;
55
+ }
56
+ return parsed;
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ }
62
+ // ── Fleet Health Tools ──
63
+ registerTool('getFleetStatus', async () => {
64
+ const db = getDb();
65
+ const nodes = await db.node.findMany({
66
+ orderBy: { name: 'asc' },
67
+ select: {
68
+ id: true,
69
+ name: true,
70
+ hostname: true,
71
+ ipAddress: true,
72
+ status: true,
73
+ os: true,
74
+ arch: true,
75
+ lastHeartbeatAt: true,
76
+ },
77
+ });
78
+ return { nodeCount: nodes.length, nodes, codex: getCodexFleetPosture() };
79
+ });
80
+ registerTool('getCodexFleetStatus', async () => ({
81
+ evidence: ['/api/v1/ops/codex-fleet-status'],
82
+ data: getCodexFleetPosture(),
83
+ }));
84
+ registerTool('getFleetReadiness', async () => ({
85
+ evidence: ['/api/v1/ops/readiness'],
86
+ data: await getFleetReadiness(),
87
+ }));
88
+ registerTool('getDependencyHealth', async () => ({
89
+ evidence: ['/api/v1/ops/dependency-health'],
90
+ data: await getDependencyHealth(),
91
+ }));
92
+ registerTool('getFleetTimeline', async (args) => ({
93
+ evidence: ['/api/v1/ops/timeline', '/api/v1/audit', '/api/v1/logs'],
94
+ data: await getFleetTimeline(Math.min(Number(args['limit'] ?? 80), 200)),
95
+ }));
96
+ registerTool('getKnownFailurePatterns', async () => ({
97
+ evidence: ['Magnus operational memory and current ops checklists'],
98
+ patterns: [
99
+ {
100
+ symptom: 'Agent health is green but node is absent or heartbeat returns 401',
101
+ likelyCause: 'NODE_MANAGER_SECRET drift between host agent and live Control API',
102
+ firstChecks: ['Compare non-secret fingerprints', 'restart magnus-agent', 'wait for accepted heartbeat'],
103
+ },
104
+ {
105
+ symptom: 'Nodes or Hermes skill counts look stale',
106
+ likelyCause: 'Agent discovery heartbeat drift or loose Hermes skill parsing',
107
+ firstChecks: ['Run hermes skills list on host', 'compare skills.disabled', 'refresh agent heartbeat'],
108
+ },
109
+ {
110
+ symptom: 'Transient node list or stats failure',
111
+ likelyCause: 'PostgreSQL connection pressure or a slow retained-health query',
112
+ firstChecks: ['Inspect database dependency latency', 'inspect dbReadRetries metric', 'check heartbeat write volume'],
113
+ },
114
+ ],
115
+ predictiveMaintenance: await getPredictiveMaintenance(),
116
+ }));
117
+ registerTool('summarizeIncident', async (args) => ({
118
+ evidence: ['/api/v1/ops/incident-summary', '/api/v1/logs', '/api/v1/anomalies', '/api/v1/commands', '/api/v1/notifications'],
119
+ data: await getIncidentSummary(args['nodeId'] ? String(args['nodeId']) : undefined, Math.min(Number(args['hours'] ?? 24), 168)),
120
+ }));
121
+ registerTool('classifyRemediationPlan', async (args) => ({
122
+ evidence: ['/api/v1/ops/remediation-plan/classify'],
123
+ data: classifyRemediationPlan(String(args['description'] ?? '')),
124
+ }));
125
+ registerTool('getHermesEffectiveState', async () => ({
126
+ evidence: ['/api/v1/ops/hermes-effective-state', 'on-host hermes skills list for final proof'],
127
+ data: await getHermesEffectiveState(),
128
+ }));
129
+ registerTool('getPackageSecurityPosture', async () => ({
130
+ evidence: ['/api/v1/ops/package-security-posture'],
131
+ data: await getPackageSecurityPosture(),
132
+ }));
133
+ registerTool('getNodeHealth', async (args) => {
134
+ const db = getDb();
135
+ const nodeId = String(args['nodeId'] ?? '');
136
+ if (!nodeId)
137
+ return { error: 'nodeId is required' };
138
+ const snapshot = await db.healthSnapshot.findFirst({
139
+ where: { nodeId },
140
+ orderBy: { timestamp: 'desc' },
141
+ include: { node: { select: { name: true, hostname: true, status: true } } },
142
+ });
143
+ if (!snapshot)
144
+ return { error: 'No health data for this node' };
145
+ return {
146
+ node: snapshot.node,
147
+ timestamp: snapshot.timestamp.toISOString(),
148
+ cpu: {
149
+ usagePercent: snapshot.cpuUsagePercent,
150
+ cores: snapshot.cpuCores,
151
+ loadAverage: snapshot.cpuLoadAverage,
152
+ },
153
+ memory: {
154
+ usedBytes: Number(snapshot.memoryUsedBytes),
155
+ totalBytes: Number(snapshot.memoryTotalBytes),
156
+ percent: snapshot.memoryPercent,
157
+ swapUsed: Number(snapshot.swapUsedBytes),
158
+ swapTotal: Number(snapshot.swapTotalBytes),
159
+ },
160
+ disks: JSON.parse(snapshot.disks),
161
+ network: JSON.parse(snapshot.network),
162
+ services: JSON.parse(snapshot.services),
163
+ wazuh: parseWazuhPosture(snapshot.wazuh),
164
+ systemUpdates: parseSystemUpdatePosture(snapshot.systemUpdates),
165
+ cockpitAvailable: snapshot.cockpitAvailable,
166
+ };
167
+ });
168
+ registerTool('getWazuhFleetStatus', async () => {
169
+ const db = getDb();
170
+ const nodes = await db.node.findMany({
171
+ orderBy: { name: 'asc' },
172
+ select: {
173
+ id: true,
174
+ name: true,
175
+ hostname: true,
176
+ status: true,
177
+ lastHeartbeatAt: true,
178
+ healthSnapshots: {
179
+ orderBy: { timestamp: 'desc' },
180
+ take: 1,
181
+ select: { timestamp: true, wazuh: true },
182
+ },
183
+ },
184
+ });
185
+ const inventory = nodes.map((node) => {
186
+ const snapshot = node.healthSnapshots[0] ?? null;
187
+ return {
188
+ id: node.id,
189
+ name: node.name,
190
+ hostname: node.hostname,
191
+ nodeStatus: node.status,
192
+ lastHeartbeatAt: node.lastHeartbeatAt?.toISOString() ?? null,
193
+ observedAt: snapshot?.timestamp.toISOString() ?? null,
194
+ wazuh: snapshot ? parseWazuhPosture(snapshot.wazuh) : null,
195
+ };
196
+ });
197
+ return {
198
+ total: inventory.length,
199
+ reporting: inventory.filter((node) => node.wazuh !== null).length,
200
+ installed: inventory.filter((node) => node.wazuh?.installed).length,
201
+ active: inventory.filter((node) => node.wazuh?.serviceStatus === 'active').length,
202
+ failed: inventory.filter((node) => node.wazuh?.serviceStatus === 'failed').length,
203
+ nodes: inventory,
204
+ };
205
+ });
206
+ registerTool('getSystemUpdateFleetStatus', async () => {
207
+ const db = getDb();
208
+ const nodes = await db.node.findMany({
209
+ orderBy: { name: 'asc' },
210
+ select: {
211
+ id: true, name: true, hostname: true, status: true, lastHeartbeatAt: true,
212
+ healthSnapshots: {
213
+ orderBy: { timestamp: 'desc' }, take: 1,
214
+ select: { timestamp: true, systemUpdates: true },
215
+ },
216
+ },
217
+ });
218
+ const inventory = nodes.map((node) => {
219
+ const snapshot = node.healthSnapshots[0] ?? null;
220
+ return {
221
+ id: node.id,
222
+ name: node.name,
223
+ hostname: node.hostname,
224
+ nodeStatus: node.status,
225
+ lastHeartbeatAt: node.lastHeartbeatAt?.toISOString() ?? null,
226
+ observedAt: snapshot?.timestamp.toISOString() ?? null,
227
+ systemUpdates: snapshot ? parseSystemUpdatePosture(snapshot.systemUpdates) : null,
228
+ };
229
+ });
230
+ return {
231
+ total: inventory.length,
232
+ reporting: inventory.filter((node) => node.systemUpdates !== null).length,
233
+ enabled: inventory.filter((node) => node.systemUpdates?.automaticUpdates === 'enabled').length,
234
+ actionNeeded: inventory.filter((node) => ['disabled', 'partial'].includes(node.systemUpdates?.automaticUpdates ?? '')).length,
235
+ rebootRequired: inventory.filter((node) => node.systemUpdates?.rebootRequired).length,
236
+ nodes: inventory,
237
+ };
238
+ });
239
+ registerTool('getHealthHistory', async (args) => {
240
+ const db = getDb();
241
+ const nodeId = String(args['nodeId'] ?? '');
242
+ const hours = Number(args['hours'] ?? 24);
243
+ if (!nodeId)
244
+ return { error: 'nodeId is required' };
245
+ const since = new Date(Date.now() - hours * 60 * 60 * 1000);
246
+ const snapshots = await db.healthSnapshot.findMany({
247
+ where: { nodeId, timestamp: { gte: since } },
248
+ orderBy: { timestamp: 'asc' },
249
+ select: {
250
+ timestamp: true,
251
+ cpuUsagePercent: true,
252
+ memoryPercent: true,
253
+ disks: true,
254
+ },
255
+ });
256
+ return {
257
+ nodeId,
258
+ hours,
259
+ count: snapshots.length,
260
+ snapshots: snapshots.map((s) => ({
261
+ timestamp: s.timestamp.toISOString(),
262
+ cpu: s.cpuUsagePercent,
263
+ memory: s.memoryPercent,
264
+ maxDisk: Math.max(0, ...JSON.parse(s.disks).map((d) => d.usagePercent ?? 0)),
265
+ })),
266
+ };
267
+ });
268
+ // ── Anomaly Tools ──
269
+ registerTool('getActiveAnomalies', async () => {
270
+ return getFleetAnomalySummary();
271
+ });
272
+ registerTool('getNodeAnomalies', async (args) => {
273
+ const nodeId = String(args['nodeId'] ?? '');
274
+ if (!nodeId)
275
+ return { error: 'nodeId is required' };
276
+ const result = await listAnomalyEvents({ nodeId, resolved: false, pageSize: 20 });
277
+ return result;
278
+ });
279
+ // ── Alert Tools ──
280
+ registerTool('getActiveAlerts', async () => {
281
+ const db = getDb();
282
+ const violations = await db.alertViolation.findMany({
283
+ where: { status: 'active' },
284
+ include: {
285
+ rule: { select: { name: true, metric: true, operator: true, threshold: true } },
286
+ node: { select: { name: true, hostname: true } },
287
+ },
288
+ orderBy: { createdAt: 'desc' },
289
+ take: 50,
290
+ });
291
+ return {
292
+ count: violations.length,
293
+ violations: violations.map((v) => ({
294
+ id: v.id,
295
+ node: v.node.name,
296
+ rule: v.rule.name,
297
+ metric: v.metric,
298
+ value: v.value,
299
+ threshold: v.threshold,
300
+ severity: v.severity,
301
+ createdAt: v.createdAt.toISOString(),
302
+ })),
303
+ };
304
+ });
305
+ // ── Command Tools ──
306
+ registerTool('getRecentCommands', async (args) => {
307
+ const db = getDb();
308
+ const hours = Number(args['hours'] ?? 1);
309
+ const since = new Date(Date.now() - hours * 60 * 60 * 1000);
310
+ const commands = await db.remoteCommand.findMany({
311
+ where: { createdAt: { gte: since } },
312
+ include: {
313
+ node: { select: { name: true } },
314
+ result: { select: { exitCode: true, durationMs: true } },
315
+ },
316
+ orderBy: { createdAt: 'desc' },
317
+ take: 20,
318
+ });
319
+ return {
320
+ count: commands.length,
321
+ commands: commands.map((c) => ({
322
+ id: c.id,
323
+ node: c.node.name,
324
+ command: c.command,
325
+ status: c.status,
326
+ exitCode: c.result?.exitCode,
327
+ duration: c.result?.durationMs,
328
+ createdAt: c.createdAt.toISOString(),
329
+ })),
330
+ };
331
+ });
332
+ // ── Log Tools ──
333
+ registerTool('getNodeLogs', async (args) => {
334
+ const db = getDb();
335
+ const nodeId = String(args['nodeId'] ?? '');
336
+ const lines = Math.min(Number(args['lines'] ?? 50), 200);
337
+ if (!nodeId)
338
+ return { error: 'nodeId is required' };
339
+ const logs = await db.logEntry.findMany({
340
+ where: { nodeId },
341
+ orderBy: { timestamp: 'desc' },
342
+ take: lines,
343
+ select: {
344
+ source: true,
345
+ level: true,
346
+ message: true,
347
+ timestamp: true,
348
+ },
349
+ });
350
+ return { count: logs.length, logs };
351
+ });
352
+ // ── File Tools ──
353
+ function isPathSafe(targetPath) {
354
+ const resolved = resolve(WORKSPACE_ROOT, targetPath);
355
+ const rel = relative(WORKSPACE_ROOT, resolved);
356
+ // Must stay within workspace and not traverse up
357
+ if (rel.startsWith('..') || resolve(resolved) !== resolved)
358
+ return false;
359
+ // Block access to sensitive files
360
+ const blocked = ['.env', 'node_modules', '.git', 'prisma/magnus.db'];
361
+ return !blocked.some((b) => rel.includes(b));
362
+ }
363
+ registerTool('readFile', async (args) => {
364
+ const filePath = String(args['path'] ?? '');
365
+ if (!filePath)
366
+ return { error: 'path is required' };
367
+ const resolved = resolve(WORKSPACE_ROOT, filePath);
368
+ if (!isPathSafe(filePath)) {
369
+ return { error: 'Access denied: path is outside workspace or blocked' };
370
+ }
371
+ try {
372
+ const stats = await stat(resolved);
373
+ if (stats.size > 1024 * 1024)
374
+ return { error: 'File too large (>1MB)' };
375
+ if (!stats.isFile())
376
+ return { error: 'Not a regular file' };
377
+ const content = await readFile(resolved, 'utf-8');
378
+ return { path: filePath, size: stats.size, content };
379
+ }
380
+ catch (err) {
381
+ return { error: `Cannot read file: ${err instanceof Error ? err.message : 'Unknown error'}` };
382
+ }
383
+ });
384
+ registerTool('writeFile', async (args) => {
385
+ const filePath = String(args['path'] ?? '');
386
+ const content = String(args['content'] ?? '');
387
+ if (!filePath)
388
+ return { error: 'path is required' };
389
+ const resolved = resolve(WORKSPACE_ROOT, filePath);
390
+ if (!isPathSafe(filePath)) {
391
+ return { error: 'Access denied: path is outside workspace or blocked' };
392
+ }
393
+ // Only allow writing to specific directories
394
+ const allowedPrefixes = ['audit-logs/', 'src/ai/', 'skills/'];
395
+ const rel = relative(WORKSPACE_ROOT, resolved);
396
+ const normalizedRel = normalize(rel);
397
+ if (!allowedPrefixes.some((p) => normalizedRel.startsWith(p))) {
398
+ return { error: `Write access restricted. Allowed directories: ${allowedPrefixes.join(', ')}` };
399
+ }
400
+ try {
401
+ await writeFile(resolved, content, 'utf-8');
402
+ return { path: filePath, written: true, size: content.length };
403
+ }
404
+ catch (err) {
405
+ return { error: `Cannot write file: ${err instanceof Error ? err.message : 'Unknown error'}` };
406
+ }
407
+ });
408
+ registerTool('listDirectory', async (args) => {
409
+ const dirPath = String(args['path'] ?? '.');
410
+ const resolved = resolve(WORKSPACE_ROOT, dirPath);
411
+ if (!isPathSafe(dirPath)) {
412
+ return { error: 'Access denied: path is outside workspace or blocked' };
413
+ }
414
+ try {
415
+ const entries = await readdir(resolved, { withFileTypes: true });
416
+ const items = await Promise.all(entries
417
+ .filter((e) => !e.name.startsWith('.'))
418
+ .slice(0, 100)
419
+ .map(async (e) => {
420
+ const fullPath = resolve(resolved, e.name);
421
+ try {
422
+ const s = await stat(fullPath);
423
+ return {
424
+ name: e.name,
425
+ type: e.isDirectory() ? 'directory' : 'file',
426
+ size: s.size,
427
+ modified: s.mtime.toISOString(),
428
+ };
429
+ }
430
+ catch {
431
+ return { name: e.name, type: e.isDirectory() ? 'directory' : 'file' };
432
+ }
433
+ }));
434
+ return { path: dirPath, count: items.length, entries: items };
435
+ }
436
+ catch (err) {
437
+ return { error: `Cannot list directory: ${err instanceof Error ? err.message : 'Unknown error'}` };
438
+ }
439
+ });
440
+ // ── Memory Tools (backed by HiveMem) ──
441
+ registerTool('storeMemory', async (args) => {
442
+ const key = String(args['key'] ?? '');
443
+ const content = String(args['content'] ?? '');
444
+ const category = String(args['category'] ?? 'general');
445
+ if (!key || !content)
446
+ return { error: 'key and content are required' };
447
+ const hivemem = getHiveMemClient();
448
+ if (!hivemem.configured)
449
+ return { error: 'HiveMem not configured' };
450
+ try {
451
+ const record = await hivemem.storeMemory({
452
+ content: `[${category}] ${key}: ${content}`,
453
+ type: 'semantic',
454
+ scope: 'shared',
455
+ source: 'magnus-api',
456
+ tags: [category, key],
457
+ });
458
+ return { stored: true, id: record.id, key };
459
+ }
460
+ catch (err) {
461
+ return { error: `Failed to store memory: ${err instanceof Error ? err.message : 'unknown'}` };
462
+ }
463
+ });
464
+ registerTool('recallMemories', async (args) => {
465
+ const category = args['category'] ? String(args['category']) : undefined;
466
+ const limit = Math.min(Number(args['limit'] ?? 20), 50);
467
+ const hivemem = getHiveMemClient();
468
+ if (!hivemem.configured)
469
+ return { count: 0, memories: [] };
470
+ try {
471
+ const query = category ? `category:${category}` : 'fleet node pattern preference';
472
+ const results = await hivemem.searchMemories(query, limit);
473
+ return {
474
+ count: results.length,
475
+ memories: results.map((r) => ({
476
+ id: r.id,
477
+ content: r.content,
478
+ score: r.score,
479
+ type: r.type,
480
+ tags: r.tags,
481
+ createdAt: r.created_at,
482
+ })),
483
+ };
484
+ }
485
+ catch (err) {
486
+ return { error: `Failed to recall memories: ${err instanceof Error ? err.message : 'unknown'}` };
487
+ }
488
+ });
489
+ registerTool('forgetMemory', async (args) => {
490
+ const id = String(args['key'] ?? args['id'] ?? '');
491
+ if (!id)
492
+ return { error: 'key or id is required' };
493
+ const hivemem = getHiveMemClient();
494
+ if (!hivemem.configured)
495
+ return { error: 'HiveMem not configured' };
496
+ try {
497
+ await hivemem.deleteMemory(id);
498
+ return { forgotten: true, id };
499
+ }
500
+ catch {
501
+ return { error: 'Memory not found' };
502
+ }
503
+ });
504
+ // ── Execution Tools ──
505
+ registerTool('execCommand', async (args) => {
506
+ const db = getDb();
507
+ const nodeId = String(args['nodeId'] ?? '');
508
+ const command = String(args['command'] ?? '');
509
+ const argsArr = Array.isArray(args['args']) ? args['args'].map(String) : [];
510
+ const workingDirectory = args['workingDirectory'] ? String(args['workingDirectory']) : undefined;
511
+ const timeoutSeconds = Math.min(Number(args['timeoutSeconds'] ?? 60), 120);
512
+ if (!nodeId)
513
+ return { error: 'nodeId is required' };
514
+ if (!command)
515
+ return { error: 'command is required' };
516
+ // Block dangerous commands
517
+ const blocked = ['rm -rf /', 'mkfs', 'dd if=', ':(){', 'shutdown', 'reboot', 'init 0', 'init 6', 'halt', 'poweroff'];
518
+ const fullCmd = [command, ...argsArr].join(' ').toLowerCase();
519
+ if (blocked.some((b) => fullCmd.includes(b))) {
520
+ return { error: 'Command blocked: potentially destructive operation' };
521
+ }
522
+ const node = await db.node.findUnique({ where: { id: nodeId } });
523
+ if (!node)
524
+ return { error: 'Node not found' };
525
+ if (node.status !== 'ONLINE')
526
+ return { error: `Node is ${node.status}, must be ONLINE` };
527
+ const commandId = `cmd-${nanoid()}`;
528
+ try {
529
+ const client = new NodeApiClient({
530
+ baseUrl: getNodeBaseUrl(node.ipAddress, node.port),
531
+ resourceNodeId: nodeId, resourceActorId: 'system:ai-assistant',
532
+ nodeToken: getNodeManagerSecret(),
533
+ timeout: (timeoutSeconds + 5) * 1_000,
534
+ });
535
+ const rawResponse = await client.executeCommand({
536
+ commandId,
537
+ command,
538
+ args: argsArr,
539
+ workingDirectory,
540
+ timeoutSeconds,
541
+ });
542
+ const result = rawResponse.data;
543
+ await logAuditEvent({
544
+ action: 'command.ai_exec',
545
+ actorId: 'ai-assistant',
546
+ actorType: 'system',
547
+ targetType: 'node',
548
+ targetId: nodeId,
549
+ details: { command, args: argsArr, exitCode: result.exitCode, durationMs: result.durationMs },
550
+ });
551
+ return {
552
+ node: node.name,
553
+ command,
554
+ args: argsArr,
555
+ exitCode: result.exitCode,
556
+ stdout: result.stdout?.slice(0, 8192) ?? '',
557
+ stderr: result.stderr?.slice(0, 4096) ?? '',
558
+ durationMs: result.durationMs,
559
+ };
560
+ }
561
+ catch (err) {
562
+ return { error: `Execution failed: ${err instanceof Error ? err.message : 'Unknown error'}` };
563
+ }
564
+ });
565
+ // ── Search Tools ──
566
+ registerTool('searchNodes', async (args) => {
567
+ const db = getDb();
568
+ const query = String(args['query'] ?? '');
569
+ const status = args['status'] ? String(args['status']).toUpperCase() : undefined;
570
+ if (!query && !status)
571
+ return { error: 'query or status is required' };
572
+ const where = {};
573
+ if (status)
574
+ where['status'] = status;
575
+ if (query) {
576
+ where['OR'] = [
577
+ { name: { contains: query } },
578
+ { hostname: { contains: query } },
579
+ { ipAddress: { contains: query } },
580
+ { os: { contains: query } },
581
+ ];
582
+ }
583
+ const nodes = await db.node.findMany({
584
+ where,
585
+ orderBy: { name: 'asc' },
586
+ take: 50,
587
+ select: {
588
+ id: true,
589
+ name: true,
590
+ hostname: true,
591
+ ipAddress: true,
592
+ status: true,
593
+ os: true,
594
+ arch: true,
595
+ lastHeartbeatAt: true,
596
+ },
597
+ });
598
+ return { count: nodes.length, query: query || undefined, status: status || undefined, nodes };
599
+ });
600
+ // ── Cron Tools ──
601
+ registerTool('getCronJobs', async (args) => {
602
+ const db = getDb();
603
+ const nodeId = args['nodeId'] ? String(args['nodeId']) : undefined;
604
+ const where = {};
605
+ if (nodeId)
606
+ where['nodeId'] = nodeId;
607
+ const jobs = await db.cronJob.findMany({
608
+ where,
609
+ orderBy: { name: 'asc' },
610
+ take: 100,
611
+ include: {
612
+ node: { select: { name: true } },
613
+ },
614
+ });
615
+ return {
616
+ count: jobs.length,
617
+ jobs: jobs.map((j) => ({
618
+ id: j.id,
619
+ node: j.node.name,
620
+ nodeId: j.nodeId,
621
+ name: j.name,
622
+ schedule: j.schedule,
623
+ command: j.command,
624
+ status: j.status,
625
+ lastRunAt: j.lastRunAt?.toISOString() ?? null,
626
+ lastRunExitCode: j.lastRunExitCode,
627
+ createdAt: j.createdAt.toISOString(),
628
+ })),
629
+ };
630
+ });
631
+ // ── Skill Tools ──
632
+ registerTool('getSkills', async () => {
633
+ const skills = await listSkills();
634
+ return {
635
+ count: skills.length,
636
+ skills: skills.map((s) => ({
637
+ name: s.name,
638
+ version: s.version,
639
+ description: s.description,
640
+ author: s.author,
641
+ tags: s.tags,
642
+ entryPoint: s.entryPoint,
643
+ files: s.files,
644
+ })),
645
+ };
646
+ });
647
+ // ── Statistics Tools ──
648
+ registerTool('getDashboardStats', async () => {
649
+ const db = getDb();
650
+ const [totalNodes, onlineNodes, offlineNodes, degradedNodes, totalCommands, runningCommands, pendingCommands, totalCronJobs, activeCronJobs,] = await Promise.all([
651
+ db.node.count(),
652
+ db.node.count({ where: { status: 'ONLINE' } }),
653
+ db.node.count({ where: { status: 'OFFLINE' } }),
654
+ db.node.count({ where: { status: 'DEGRADED' } }),
655
+ db.remoteCommand.count(),
656
+ db.remoteCommand.count({ where: { status: 'RUNNING' } }),
657
+ db.remoteCommand.count({ where: { status: 'PENDING' } }),
658
+ db.cronJob.count(),
659
+ db.cronJob.count({ where: { status: 'ACTIVE' } }),
660
+ ]);
661
+ // Avg CPU/memory from latest health per online node
662
+ const latestHealth = await db.healthSnapshot.findMany({
663
+ where: { node: { status: 'ONLINE' } },
664
+ orderBy: { timestamp: 'desc' },
665
+ distinct: ['nodeId'],
666
+ select: { cpuUsagePercent: true, memoryPercent: true },
667
+ });
668
+ const avgCpu = latestHealth.length > 0
669
+ ? Math.round((latestHealth.reduce((s, h) => s + h.cpuUsagePercent, 0) / latestHealth.length) * 10) / 10
670
+ : null;
671
+ const avgMemory = latestHealth.length > 0
672
+ ? Math.round((latestHealth.reduce((s, h) => s + h.memoryPercent, 0) / latestHealth.length) * 10) / 10
673
+ : null;
674
+ return {
675
+ nodes: { total: totalNodes, online: onlineNodes, offline: offlineNodes, degraded: degradedNodes },
676
+ commands: { total: totalCommands, running: runningCommands, pending: pendingCommands },
677
+ cron: { total: totalCronJobs, active: activeCronJobs },
678
+ health: { avgCpuPercent: avgCpu, avgMemoryPercent: avgMemory, reportingNodes: latestHealth.length },
679
+ };
680
+ });
681
+ // ── Audit Tools ──
682
+ registerTool('getAuditLog', async (args) => {
683
+ const date = args['date'] ? String(args['date']) : undefined;
684
+ const action = args['action'] ? String(args['action']) : undefined;
685
+ const limit = Math.min(Number(args['limit'] ?? 25), 100);
686
+ const result = await queryAuditEvents({ date, action, pageSize: limit });
687
+ return {
688
+ date: date ?? new Date().toISOString().slice(0, 10),
689
+ total: result.total,
690
+ count: result.events.length,
691
+ events: result.events.map((e) => ({
692
+ id: e.id,
693
+ action: e.action,
694
+ actorId: e.actorId,
695
+ actorType: e.actorType,
696
+ targetType: e.targetType,
697
+ targetId: e.targetId,
698
+ timestamp: e.timestamp,
699
+ })),
700
+ };
701
+ });
702
+ // ── Node Details Tools ──
703
+ registerTool('getNodeDetails', async (args) => {
704
+ const db = getDb();
705
+ const nodeId = String(args['nodeId'] ?? '');
706
+ const includeSoftwareVersions = args['includeSoftwareVersions'] === true;
707
+ if (!nodeId)
708
+ return { error: 'nodeId is required' };
709
+ const node = await db.node.findUnique({
710
+ where: { id: nodeId },
711
+ include: {
712
+ agent: true,
713
+ healthSnapshots: {
714
+ orderBy: { timestamp: 'desc' },
715
+ take: 1,
716
+ },
717
+ },
718
+ });
719
+ if (!node)
720
+ return { error: 'Node not found' };
721
+ const latestHealth = node.healthSnapshots[0] ?? null;
722
+ const result = {
723
+ id: node.id,
724
+ name: node.name,
725
+ hostname: node.hostname,
726
+ ipAddress: node.ipAddress,
727
+ port: node.port,
728
+ status: node.status,
729
+ os: node.os,
730
+ arch: node.arch,
731
+ tags: node.tags ? JSON.parse(node.tags) : [],
732
+ metadata: node.metadata ? JSON.parse(node.metadata) : {},
733
+ lastHeartbeatAt: node.lastHeartbeatAt?.toISOString() ?? null,
734
+ createdAt: node.createdAt.toISOString(),
735
+ updatedAt: node.updatedAt.toISOString(),
736
+ agent: node.agent ? {
737
+ id: node.agent.id,
738
+ version: node.agent.version,
739
+ status: node.agent.status,
740
+ pid: node.agent.pid,
741
+ startedAt: node.agent.startedAt?.toISOString() ?? null,
742
+ capabilities: node.agent.capabilities ? JSON.parse(node.agent.capabilities) : [],
743
+ } : null,
744
+ health: latestHealth ? {
745
+ timestamp: latestHealth.timestamp.toISOString(),
746
+ cpu: {
747
+ usagePercent: latestHealth.cpuUsagePercent,
748
+ cores: latestHealth.cpuCores,
749
+ loadAverage: latestHealth.cpuLoadAverage,
750
+ },
751
+ memory: {
752
+ usedBytes: Number(latestHealth.memoryUsedBytes),
753
+ totalBytes: Number(latestHealth.memoryTotalBytes),
754
+ percent: latestHealth.memoryPercent,
755
+ },
756
+ disks: JSON.parse(latestHealth.disks),
757
+ network: JSON.parse(latestHealth.network),
758
+ services: JSON.parse(latestHealth.services),
759
+ wazuh: parseWazuhPosture(latestHealth.wazuh),
760
+ systemUpdates: parseSystemUpdatePosture(latestHealth.systemUpdates),
761
+ } : null,
762
+ };
763
+ // Optionally fetch live software versions via quick command
764
+ if (includeSoftwareVersions && node.status === 'ONLINE') {
765
+ try {
766
+ const client = new NodeApiClient({
767
+ baseUrl: getNodeBaseUrl(node.ipAddress, node.port),
768
+ resourceNodeId: nodeId, resourceActorId: 'system:ai-assistant',
769
+ nodeToken: getNodeManagerSecret(),
770
+ timeout: 30_000,
771
+ });
772
+ const versionCmd = [
773
+ 'echo "NODE_VERSION=$(node --version 2>/dev/null || echo N/A)"',
774
+ 'echo "NPM_VERSION=$(npm --version 2>/dev/null || echo N/A)"',
775
+ 'echo "PYTHON_VERSION=$(python3 --version 2>/dev/null || echo N/A)"',
776
+ 'echo "KERNEL=$(uname -r)"',
777
+ 'echo "REDIS_VERSION=$(redis-server --version 2>/dev/null | head -1 || echo N/A)"',
778
+ 'echo "DOCKER_VERSION=$(docker --version 2>/dev/null || echo N/A)"',
779
+ 'echo "UPTIME=$(uptime -p 2>/dev/null || uptime)"',
780
+ 'apt list --upgradable 2>/dev/null | tail -n +2 | head -20 || true',
781
+ ].join(' && ');
782
+ const rawResponse = await client.executeCommand({
783
+ commandId: `cmd-${nanoid()}`,
784
+ command: 'bash',
785
+ args: ['-c', versionCmd],
786
+ timeoutSeconds: 20,
787
+ });
788
+ result['softwareVersions'] = rawResponse.data.stdout ?? '';
789
+ result['softwareVersionsExitCode'] = rawResponse.data.exitCode;
790
+ }
791
+ catch (err) {
792
+ result['softwareVersions'] = null;
793
+ result['softwareVersionsError'] = err instanceof Error ? err.message : 'Failed to fetch';
794
+ }
795
+ }
796
+ return result;
797
+ });
798
+ // ── Skill Execution Tools ──
799
+ registerTool('runSkill', async (args) => {
800
+ const nodeId = String(args['nodeId'] ?? '');
801
+ const skillName = String(args['skillName'] ?? '');
802
+ const action = String(args['action'] ?? 'run');
803
+ if (!nodeId || !skillName)
804
+ return { error: 'nodeId and skillName are required' };
805
+ const db = getDb();
806
+ const node = await db.node.findUnique({
807
+ where: { id: nodeId },
808
+ select: { ipAddress: true, port: true, status: true },
809
+ });
810
+ if (!node)
811
+ return { error: 'Node not found' };
812
+ if (node.status !== 'ONLINE')
813
+ return { error: `Node is ${node.status}, cannot execute skill` };
814
+ // Verify skill exists
815
+ const skill = await getSkill(skillName);
816
+ if (!skill)
817
+ return { error: `Skill "${skillName}" not found` };
818
+ // Execute via agent
819
+ const client = new NodeApiClient({
820
+ baseUrl: getNodeBaseUrl(node.ipAddress, node.port),
821
+ resourceNodeId: nodeId, resourceActorId: 'system:ai-assistant',
822
+ nodeToken: getNodeManagerSecret(),
823
+ timeout: 120_000,
824
+ });
825
+ const result = await client.executeCommand({
826
+ commandId: `cmd-${nanoid()}`,
827
+ command: 'bash',
828
+ args: ['-c', `cd /opt/magnus/skills/${skillName} && bash ${action}.sh`],
829
+ timeoutSeconds: 90,
830
+ });
831
+ await logAuditEvent({
832
+ action: 'command.ai_exec',
833
+ actorId: 'ai-assistant',
834
+ actorType: 'system',
835
+ targetType: 'skill',
836
+ targetId: `${nodeId}/${skillName}`,
837
+ details: { action, exitCode: result.data.exitCode },
838
+ });
839
+ return {
840
+ skillName,
841
+ action,
842
+ nodeId,
843
+ exitCode: result.data.exitCode,
844
+ stdout: (result.data.stdout ?? '').slice(0, 4000),
845
+ stderr: (result.data.stderr ?? '').slice(0, 2000),
846
+ };
847
+ });
848
+ // ── Cross-Fleet Correlation Tools ──
849
+ registerTool('correlateAnomalies', async (args) => {
850
+ const windowMinutes = Number(args['windowMinutes'] ?? 5);
851
+ const includeResolved = args['includeResolved'] === true;
852
+ const groups = await correlateAnomalies({ windowMinutes, includeResolved });
853
+ return {
854
+ totalGroups: groups.length,
855
+ groups: groups.map(g => ({
856
+ id: g.id,
857
+ pattern: g.pattern,
858
+ timeWindow: g.timeWindow,
859
+ affectedNodes: g.affectedNodes,
860
+ metrics: g.metrics,
861
+ anomalyCount: g.anomalies.length,
862
+ relatedCommandCount: g.relatedCommands.length,
863
+ anomalies: g.anomalies.slice(0, 10),
864
+ relatedCommands: g.relatedCommands.slice(0, 5),
865
+ })),
866
+ };
867
+ });
868
+ registerTool('getAnomalyTimeline', async (args) => {
869
+ const hours = Number(args['hours'] ?? 24);
870
+ const nodeId = args['nodeId'] ? String(args['nodeId']) : undefined;
871
+ return getAnomalyTimeline({ hours, nodeId });
872
+ });
873
+ // ── Skill Authoring Tools ──
874
+ registerTool('createSkillDraft', async (args) => {
875
+ const name = String(args['name'] ?? '');
876
+ const description = String(args['description'] ?? '');
877
+ const tags = args['tags'] ?? [];
878
+ const scriptContent = String(args['scriptContent'] ?? '#!/usr/bin/env bash\nset -euo pipefail\necho "TODO: implement"');
879
+ if (!name)
880
+ return { error: 'name is required' };
881
+ if (!/^[a-z0-9-]+$/.test(name))
882
+ return { error: 'name must be lowercase alphanumeric with hyphens' };
883
+ // Check if skill already exists
884
+ const existing = await getSkill(name);
885
+ if (existing)
886
+ return { error: `Skill "${name}" already exists` };
887
+ await createSkill({
888
+ name,
889
+ description: description || `AI-generated skill: ${name}`,
890
+ version: '0.1.0',
891
+ tags,
892
+ });
893
+ // Write skill files
894
+ const skillDir = resolve(WORKSPACE_ROOT, 'skills', name);
895
+ await writeFile(resolve(skillDir, 'run.sh'), scriptContent, 'utf-8');
896
+ await writeFile(resolve(skillDir, 'README.md'), `# ${name}\n\n${description}\n\nGenerated by AI Assistant.\n`, 'utf-8');
897
+ await logAuditEvent({
898
+ action: 'skill.create',
899
+ actorId: 'ai-assistant',
900
+ actorType: 'system',
901
+ targetType: 'skill',
902
+ targetId: name,
903
+ details: { description, tags },
904
+ });
905
+ return { created: true, name, description, tags };
906
+ });
907
+ registerTool('generateRunbook', async (args) => {
908
+ const name = String(args['name'] ?? '');
909
+ const description = String(args['description'] ?? '');
910
+ const scenario = String(args['scenario'] ?? '');
911
+ const tags = args['tags'] ?? ['runbook'];
912
+ if (!name)
913
+ return { error: 'name is required' };
914
+ if (!scenario)
915
+ return { error: 'scenario is required' };
916
+ if (!/^[a-z0-9-]+$/.test(name))
917
+ return { error: 'name must be lowercase alphanumeric with hyphens' };
918
+ const existing = await getSkill(name);
919
+ if (existing)
920
+ return { error: `Skill "${name}" already exists` };
921
+ // Generate a structured runbook script with pre-checks, steps, rollback
922
+ const scriptContent = `#!/usr/bin/env bash
923
+ set -euo pipefail
924
+
925
+ # Runbook: ${name}
926
+ # Description: ${description}
927
+ # Scenario: ${scenario}
928
+ # Generated by AI Assistant
929
+ # Tags: ${tags.join(', ')}
930
+
931
+ RUNBOOK_NAME="${name}"
932
+ LOG_FILE="/tmp/\${RUNBOOK_NAME}-\$(date +%Y%m%d-%H%M%S).log"
933
+
934
+ log() { echo "[\$(date '+%Y-%m-%d %H:%M:%S')] [$1] \$2" | tee -a "\$LOG_FILE"; }
935
+ info() { log "INFO" "\$1"; }
936
+ warn() { log "WARN" "\$1"; }
937
+ error() { log "ERROR" "\$1"; }
938
+ step() { log "STEP" "── \$1 ──"; }
939
+
940
+ cleanup() {
941
+ if [ \$? -ne 0 ]; then
942
+ error "Runbook failed. See log: \$LOG_FILE"
943
+ error "Consider running rollback procedures manually."
944
+ fi
945
+ }
946
+ trap cleanup EXIT
947
+
948
+ info "Starting runbook: ${name}"
949
+ info "Description: ${description}"
950
+
951
+ # ── Pre-checks ──
952
+ step "Pre-checks"
953
+ # TODO: Add pre-condition checks based on scenario
954
+ info "Pre-checks passed"
955
+
956
+ # ── Action Steps ──
957
+ step "Execute main actions"
958
+ # TODO: Implement the operational steps for:
959
+ # ${scenario.replace(/\n/g, '\n# ')}
960
+ info "Actions completed"
961
+
962
+ # ── Validation ──
963
+ step "Post-action validation"
964
+ # TODO: Verify the action was successful
965
+ info "Validation passed"
966
+
967
+ # ── Rollback (manual trigger) ──
968
+ # To rollback, uncomment the section below:
969
+ # step "Rollback"
970
+ # TODO: Add rollback procedures
971
+ # info "Rollback completed"
972
+
973
+ info "Runbook completed successfully. Log saved to: \$LOG_FILE"
974
+ `;
975
+ await createSkill({
976
+ name,
977
+ description: description || `AI-generated runbook: ${name}`,
978
+ version: '0.1.0',
979
+ tags: [...new Set([...tags, 'runbook'])],
980
+ });
981
+ const skillDir = resolve(WORKSPACE_ROOT, 'skills', name);
982
+ await writeFile(resolve(skillDir, 'run.sh'), scriptContent, 'utf-8');
983
+ const readmeContent = `# ${name}
984
+
985
+ ${description}
986
+
987
+ ## Scenario
988
+
989
+ ${scenario}
990
+
991
+ ## Usage
992
+
993
+ \`\`\`bash
994
+ bash run.sh
995
+ \`\`\`
996
+
997
+ ## Steps
998
+
999
+ 1. **Pre-checks** — Validates prerequisites
1000
+ 2. **Action Steps** — Executes the operational procedure
1001
+ 3. **Validation** — Verifies success
1002
+ 4. **Rollback** — (Manual) Reverts changes if needed
1003
+
1004
+ ## Tags
1005
+
1006
+ ${tags.map((t) => `- ${t}`).join('\n')}
1007
+
1008
+ ---
1009
+
1010
+ *Generated by AI Assistant*
1011
+ `;
1012
+ await writeFile(resolve(skillDir, 'README.md'), readmeContent, 'utf-8');
1013
+ await logAuditEvent({
1014
+ action: 'runbook.generate',
1015
+ actorId: 'ai-assistant',
1016
+ actorType: 'system',
1017
+ targetType: 'skill',
1018
+ targetId: name,
1019
+ details: { description, scenario, tags },
1020
+ });
1021
+ return { created: true, name, description, tags, type: 'runbook' };
1022
+ });
1023
+ registerTool('listSkillActions', async (args) => {
1024
+ const skillName = args['skillName'] ? String(args['skillName']) : undefined;
1025
+ const skills = await listSkills();
1026
+ const result = [];
1027
+ for (const skill of skills) {
1028
+ if (skillName && skill.name !== skillName)
1029
+ continue;
1030
+ // Read README if it exists
1031
+ let readme = null;
1032
+ try {
1033
+ readme = await getSkillFile(skill.name, 'README.md');
1034
+ }
1035
+ catch {
1036
+ // No README
1037
+ }
1038
+ result.push({
1039
+ name: skill.name,
1040
+ version: skill.version,
1041
+ description: skill.description,
1042
+ tags: skill.tags,
1043
+ files: skill.files,
1044
+ readme: readme ? readme.slice(0, 2000) : null,
1045
+ });
1046
+ }
1047
+ return { count: result.length, skills: result };
1048
+ });
1049
+ const COMMAND_TEMPLATES = [
1050
+ // Service management
1051
+ {
1052
+ pattern: /(?:restart|start|stop|status|enable|disable)\s+(?:the\s+)?(\S+)\s*(?:service)?/i,
1053
+ command: 'systemctl',
1054
+ args: (match) => {
1055
+ const action = match[0].match(/^(restart|start|stop|status|enable|disable)/i)?.[1]?.toLowerCase() ?? 'status';
1056
+ const service = match[1];
1057
+ return [action, service];
1058
+ },
1059
+ description: 'Manage systemd services',
1060
+ requiresConfirmation: true,
1061
+ },
1062
+ // Package operations
1063
+ {
1064
+ pattern: /(?:install|update|upgrade|remove|uninstall)\s+(?:package\s+)?(\S+)/i,
1065
+ command: 'apt-get',
1066
+ args: (match) => {
1067
+ const raw = match[0].match(/^(install|update|upgrade|remove|uninstall)/i)?.[1]?.toLowerCase() ?? 'install';
1068
+ const action = raw === 'uninstall' ? 'remove' : raw;
1069
+ const pkg = match[1];
1070
+ return ['-y', action, pkg];
1071
+ },
1072
+ description: 'Package management (apt)',
1073
+ requiresConfirmation: true,
1074
+ },
1075
+ // Log viewing — journalctl
1076
+ {
1077
+ pattern: /(?:show|view|get|tail|check)\s+(?:the\s+)?(?:logs?|journal)\s+(?:for|of|from)\s+(\S+)/i,
1078
+ command: 'journalctl',
1079
+ args: (match) => ['-u', match[1], '-n', '50', '--no-pager'],
1080
+ description: 'View systemd journal logs',
1081
+ requiresConfirmation: false,
1082
+ },
1083
+ // Log viewing — tail
1084
+ {
1085
+ pattern: /tail\s+(?:-[nf]\s+\d+\s+)?(\S+)/i,
1086
+ command: 'tail',
1087
+ args: (match) => ['-n', '100', match[1]],
1088
+ description: 'Tail a log file',
1089
+ requiresConfirmation: false,
1090
+ },
1091
+ // Disk usage
1092
+ {
1093
+ pattern: /(?:disk\s+(?:usage|space)|df|free\s+space|disk\s+free)/i,
1094
+ command: 'df',
1095
+ args: () => ['-h'],
1096
+ description: 'Show disk usage',
1097
+ requiresConfirmation: false,
1098
+ },
1099
+ // Directory size
1100
+ {
1101
+ pattern: /(?:directory\s+size|folder\s+size|du)\s+(?:of\s+)?(\S+)/i,
1102
+ command: 'du',
1103
+ args: (match) => ['-sh', match[1]],
1104
+ description: 'Show directory size',
1105
+ requiresConfirmation: false,
1106
+ },
1107
+ // Network — connections
1108
+ {
1109
+ pattern: /(?:network\s+connections|listening\s+ports|open\s+ports|ss|netstat)/i,
1110
+ command: 'ss',
1111
+ args: () => ['-tlnp'],
1112
+ description: 'Show listening ports and connections',
1113
+ requiresConfirmation: false,
1114
+ },
1115
+ // Network — ping
1116
+ {
1117
+ pattern: /ping\s+(\S+)/i,
1118
+ command: 'ping',
1119
+ args: (match) => ['-c', '4', match[1]],
1120
+ description: 'Ping a host',
1121
+ requiresConfirmation: false,
1122
+ },
1123
+ // Network — traceroute
1124
+ {
1125
+ pattern: /traceroute\s+(\S+)/i,
1126
+ command: 'traceroute',
1127
+ args: (match) => ['-m', '15', match[1]],
1128
+ description: 'Trace route to host',
1129
+ requiresConfirmation: false,
1130
+ },
1131
+ // Process inspection
1132
+ {
1133
+ pattern: /(?:top\s+processes|running\s+processes|process\s+list|high\s+cpu|memory\s+hogs)/i,
1134
+ command: 'ps',
1135
+ args: () => ['aux', '--sort=-pcpu'],
1136
+ description: 'List processes sorted by CPU',
1137
+ requiresConfirmation: false,
1138
+ },
1139
+ // Uptime
1140
+ {
1141
+ pattern: /uptime/i,
1142
+ command: 'uptime',
1143
+ args: () => [],
1144
+ description: 'Show system uptime',
1145
+ requiresConfirmation: false,
1146
+ },
1147
+ // Memory info
1148
+ {
1149
+ pattern: /(?:memory\s+usage|free\s+memory|ram\s+usage|free)/i,
1150
+ command: 'free',
1151
+ args: () => ['-h'],
1152
+ description: 'Show memory usage',
1153
+ requiresConfirmation: false,
1154
+ },
1155
+ ];
1156
+ registerTool('executeNaturalCommand', async (args) => {
1157
+ const db = getDb();
1158
+ const intent = String(args['intent'] ?? '');
1159
+ const nodeName = args['nodeName'] ? String(args['nodeName']) : undefined;
1160
+ if (!intent)
1161
+ return { error: 'intent is required — describe what you want to do' };
1162
+ // Resolve node by name if provided
1163
+ let nodeId;
1164
+ let resolvedNodeName;
1165
+ if (nodeName) {
1166
+ const node = await db.node.findFirst({
1167
+ where: {
1168
+ OR: [
1169
+ { name: { contains: nodeName } },
1170
+ { hostname: { contains: nodeName } },
1171
+ ],
1172
+ },
1173
+ select: { id: true, name: true, status: true },
1174
+ });
1175
+ if (!node)
1176
+ return { error: `No node found matching "${nodeName}"` };
1177
+ if (node.status !== 'ONLINE')
1178
+ return { error: `Node "${node.name}" is ${node.status}, must be ONLINE` };
1179
+ nodeId = node.id;
1180
+ resolvedNodeName = node.name;
1181
+ }
1182
+ else {
1183
+ // If no node specified, try to extract from intent text
1184
+ const nodes = await db.node.findMany({
1185
+ where: { status: 'ONLINE' },
1186
+ select: { id: true, name: true, hostname: true },
1187
+ });
1188
+ for (const n of nodes) {
1189
+ if (intent.toLowerCase().includes(n.name.toLowerCase()) || intent.toLowerCase().includes(n.hostname.toLowerCase())) {
1190
+ nodeId = n.id;
1191
+ resolvedNodeName = n.name;
1192
+ break;
1193
+ }
1194
+ }
1195
+ if (!nodeId) {
1196
+ return { error: 'Could not determine target node. Please specify which node to run on.' };
1197
+ }
1198
+ }
1199
+ // Match against command templates
1200
+ let matched = null;
1201
+ for (const tpl of COMMAND_TEMPLATES) {
1202
+ const m = intent.match(tpl.pattern);
1203
+ if (m) {
1204
+ matched = {
1205
+ command: tpl.command,
1206
+ args: tpl.args(m, intent),
1207
+ description: tpl.description,
1208
+ requiresConfirmation: tpl.requiresConfirmation,
1209
+ };
1210
+ break;
1211
+ }
1212
+ }
1213
+ if (!matched) {
1214
+ return {
1215
+ error: 'Could not translate intent to a known command. Supported operations: service management (start/stop/restart), package ops (install/update/remove), log viewing, disk usage, network diagnostics, process listing.',
1216
+ };
1217
+ }
1218
+ const fullCommand = [matched.command, ...matched.args].join(' ');
1219
+ return {
1220
+ type: 'commandPreview',
1221
+ command: matched.command,
1222
+ args: matched.args,
1223
+ fullCommand,
1224
+ description: matched.description,
1225
+ nodeId,
1226
+ nodeName: resolvedNodeName,
1227
+ requiresConfirmation: matched.requiresConfirmation,
1228
+ intent,
1229
+ };
1230
+ });
1231
+ // ── REPL Scratchpad Tools ──
1232
+ function getScratchpadConversationId(args) {
1233
+ const conversationId = String(args['_conversationId'] ?? '');
1234
+ if (!conversationId) {
1235
+ throw new Error('Scratchpad tools require an active conversation');
1236
+ }
1237
+ return conversationId;
1238
+ }
1239
+ registerTool('listScratchpadVariables', async (args) => {
1240
+ const conversationId = getScratchpadConversationId(args);
1241
+ const entries = listScratchpadEntries(conversationId);
1242
+ return {
1243
+ count: entries.length,
1244
+ entries: entries.map((entry) => ({
1245
+ name: entry.name,
1246
+ source: entry.source,
1247
+ summary: entry.summary,
1248
+ updatedAt: entry.updatedAt,
1249
+ })),
1250
+ };
1251
+ });
1252
+ registerTool('saveResult', async (args) => {
1253
+ const conversationId = getScratchpadConversationId(args);
1254
+ const name = String(args['name'] ?? 'saved_result');
1255
+ const sourceName = String(args['sourceName'] ?? 'last_result');
1256
+ if (args['value'] !== undefined) {
1257
+ const entry = setScratchpadEntry(conversationId, name, args['value'], 'scratchpad.manual');
1258
+ return {
1259
+ saved: true,
1260
+ name: entry.name,
1261
+ source: entry.source,
1262
+ summary: entry.summary,
1263
+ };
1264
+ }
1265
+ const entry = aliasScratchpadEntry(conversationId, sourceName, name, 'scratchpad.alias');
1266
+ return {
1267
+ saved: true,
1268
+ name: entry.name,
1269
+ sourceName,
1270
+ summary: entry.summary,
1271
+ };
1272
+ });
1273
+ registerTool('transformData', async (args) => {
1274
+ const conversationId = getScratchpadConversationId(args);
1275
+ const sourceName = String(args['sourceName'] ?? 'last_result');
1276
+ const operation = String(args['operation'] ?? 'count');
1277
+ const entry = transformScratchpadData({
1278
+ conversationId,
1279
+ sourceName,
1280
+ operation,
1281
+ outputName: args['outputName'] ? String(args['outputName']) : undefined,
1282
+ field: args['field'] ? String(args['field']) : undefined,
1283
+ value: args['value'],
1284
+ order: args['order'] === 'desc' ? 'desc' : 'asc',
1285
+ });
1286
+ return {
1287
+ transformed: true,
1288
+ name: entry.name,
1289
+ sourceName,
1290
+ summary: entry.summary,
1291
+ value: entry.value,
1292
+ };
1293
+ });
1294
+ registerTool('compareSnapshots', async (args) => {
1295
+ const conversationId = getScratchpadConversationId(args);
1296
+ const leftName = String(args['leftName'] ?? 'last_result');
1297
+ const rightName = String(args['rightName'] ?? '');
1298
+ if (!rightName)
1299
+ return { error: 'rightName is required' };
1300
+ const entry = compareScratchpadSnapshots(conversationId, leftName, rightName);
1301
+ return {
1302
+ compared: true,
1303
+ name: entry.name,
1304
+ summary: entry.summary,
1305
+ result: entry.value,
1306
+ };
1307
+ });
1308
+ // ── Predictive failure detection ──
1309
+ registerTool('getFleetPredictions', async () => {
1310
+ const { getFleetPredictions } = await import('./prediction-service.js');
1311
+ return getFleetPredictions();
1312
+ });
1313
+ registerTool('getNodePredictions', async (args) => {
1314
+ const nodeId = args['nodeId'];
1315
+ if (!nodeId)
1316
+ return { error: 'nodeId is required' };
1317
+ const { getNodePredictions } = await import('./prediction-service.js');
1318
+ return getNodePredictions(nodeId);
1319
+ });
1320
+ // ── Tool executor ──
1321
+ export async function executeAiTool(call) {
1322
+ const handler = toolRegistry.get(call.name);
1323
+ if (!handler) {
1324
+ return { name: call.name, success: false, result: null, error: `Unknown tool: ${call.name}` };
1325
+ }
1326
+ try {
1327
+ const result = await handler(call.arguments);
1328
+ return { name: call.name, success: true, result };
1329
+ }
1330
+ catch (err) {
1331
+ return {
1332
+ name: call.name,
1333
+ success: false,
1334
+ result: null,
1335
+ error: err instanceof Error ? err.message : 'Tool execution failed',
1336
+ };
1337
+ }
1338
+ }
1339
+ /** List all available tools (for documentation/introspection). */
1340
+ export function listAvailableTools() {
1341
+ return Array.from(toolRegistry.keys());
1342
+ }
1343
+ //# sourceMappingURL=ai-tools.js.map