Files
Hermes-ui/packages/server/src/services/hermes/hermes.ts
T
ekko 477af66232 fix: auth bypass, SPA serving, and provider improvements (#97)
* feat(chat): polish syntax highlighting and tool payload rendering (#94)

* [verified] feat(chat): polish syntax highlighting and tool payload rendering

* [verified] fix(chat): tighten large tool payload rendering

* docs: update data volume path in Docker docs

Align documentation with docker-compose.yml change:
hermes-web-ui-data -> hermes-web-ui, /app/dist/data -> /root/.hermes-web-ui

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: bundle server build and restructure service modules

- Add build-server.mjs script for standalone server compilation
- Add logger service with structured output
- Restructure auth, gateway-manager, hermes-cli, hermes services
- Update docker-compose volume mount path
- Update tsconfig and entry point for bundled server

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: separate controllers from routes and centralize route registration

- Extract business logic from route handlers into controllers/
- Add centralized route registry in routes/index.ts with public/auth/protected layers
- Replace global auth whitelist with sequential middleware registration
- Extract shared helpers to services/config-helpers.ts
- Allow custom provider name to be user-editable in ProviderFormModal
- Deduplicate custom providers by poolKey instead of base_url in getAvailable

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: auth bypass via path case, SPA serving, and provider improvements

- Fix auth bypass: path case-insensitive check for /api, /v1, /upload
- Fix SPA returning 401: skip auth for non-API paths (static files)
- Fix profile switch: use local loading state instead of shared store ref
- Auto-append /v1 to base_url when fetching models (frontend + backend)
- Guard .env writing to built-in providers only
- Add builtin field to provider presets, enable base_url input in form
- Print auth token to console on startup (pino only writes to file)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Zhicheng Han <43314240+hanzckernel@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-21 12:35:48 +08:00

129 lines
3.4 KiB
TypeScript

import { config } from '../../config'
import { logger } from '../logger'
const UPSTREAM = config.upstream.replace(/\/$/, '')
/**
* Send an instruction to Hermes Agent via /v1/runs
*/
export async function sendInstruction(params: {
input: string | any[]
instructions?: string
conversationHistory?: any[]
sessionId?: string
authToken?: string
}): Promise<{ run_id: string; status: string }> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
}
if (params.authToken) {
headers['Authorization'] = `Bearer ${params.authToken}`
}
const body: any = { input: params.input }
if (params.instructions) body.instructions = params.instructions
if (params.conversationHistory) body.conversation_history = params.conversationHistory
if (params.sessionId) body.session_id = params.sessionId
const res = await fetch(`${UPSTREAM}/v1/runs`, {
method: 'POST',
headers,
body: JSON.stringify(body),
})
if (!res.ok) {
const text = await res.text()
throw new Error(`Hermes API error ${res.status}: ${text}`)
}
return res.json()
}
/**
* Get run status (poll /v1/runs/:id if supported)
*/
export async function getRunStatus(runId: string): Promise<any> {
const res = await fetch(`${UPSTREAM}/v1/runs/${runId}`)
if (!res.ok) {
throw new Error(`Failed to get run status: ${res.status}`)
}
return res.json()
}
/**
* Subscribe to SSE events for a run
*/
export async function* streamRunEvents(runId: string, authToken?: string): AsyncGenerator<any> {
const headers: Record<string, string> = {}
if (authToken) {
headers['Authorization'] = `Bearer ${authToken}`
}
const res = await fetch(`${UPSTREAM}/v1/runs/${runId}/events`, { headers })
if (!res.ok || !res.body) {
throw new Error(`Failed to stream run events: ${res.status}`)
}
const reader = res.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
try {
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() || ''
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6).trim()
if (data === '[DONE]') return
try {
const event = JSON.parse(data)
yield event
if (event.event === 'run.completed' || event.event === 'run.failed') return
} catch { /* skip malformed lines */ }
}
}
}
} finally {
reader.releaseLock()
}
}
/**
* Health check
*/
export async function healthCheck(): Promise<{ status: string; version?: string }> {
const res = await fetch(`${UPSTREAM}/health`)
return res.json()
}
/**
* Fetch available models
*/
export async function fetchModels(): Promise<{ data: Array<{ id: string }> }> {
const res = await fetch(`${UPSTREAM}/v1/models`)
return res.json()
}
// Webhook callback registry
type WebhookCallback = (payload: any) => void | Promise<void>
const webhookCallbacks: WebhookCallback[] = []
export function onWebhook(callback: WebhookCallback) {
webhookCallbacks.push(callback)
}
export function emitWebhook(payload: any) {
for (const cb of webhookCallbacks) {
const result = cb(payload)
if (result && typeof result.catch === 'function') {
result.catch((err: Error) => logger.error(err, 'Webhook callback error'))
}
}
}