Merge branch 'dev'

# Conflicts:
#	package.json
This commit is contained in:
ekko
2026-04-16 15:21:24 +08:00
34 changed files with 1909 additions and 180 deletions
+2
View File
@@ -333,6 +333,8 @@ Unmatched `/api/hermes/*` and `/v1/*` requests are forwarded to the upstream Her
The proxy is implemented as both a route (`proxyRoutes.all('/api/hermes/{*any}', proxy)`) and a middleware (`proxyMiddleware`) registered on the main app to catch any requests that slip through route matching.
**Important:** Custom API endpoints handled locally (not proxied) must be registered **before** `hermesRoutes.routes()` in `bootstrap()`. The proxy route `proxyRoutes.all('/api/hermes/{*any}')` matches all `/api/hermes/*` paths, so any middleware registered after it will never be reached. See the `update` middleware in `index.ts` for an example.
### Hermes CLI Wrapper (`packages/server/src/services/hermes-cli.ts`)
All Hermes interactions go through `child_process.execFile('hermes', [...args])`. Each function wraps a CLI subcommand:
+2 -2
View File
@@ -132,13 +132,13 @@ Open **http://localhost:8648**
Automatically installs Node.js (if missing) and hermes-web-ui on Debian/Ubuntu/macOS:
```bash
bash <(curl -fsSL https://cdn.jsdelivr.net/gh/EKKOLearnAI/hermes-web-ui@main/scripts/setup.sh)
bash <(curl -fsSL https://raw.githubusercontent.com/EKKOLearnAI/hermes-web-ui/main/scripts/setup.sh)
```
### WSL
```bash
bash <(curl -fsSL https://cdn.jsdelivr.net/gh/EKKOLearnAI/hermes-web-ui@main/scripts/setup.sh)
bash <(curl -fsSL https://raw.githubusercontent.com/EKKOLearnAI/hermes-web-ui/main/scripts/setup.sh)
hermes-web-ui start
```
+50 -13
View File
@@ -135,23 +135,60 @@ function startDaemon(port) {
child.unref()
writePid(child.pid)
setTimeout(() => {
if (isRunning(child.pid)) {
console.log(` ✓ hermes-web-ui started (PID: ${child.pid}, port: ${port})`)
const url = token
? `http://localhost:${port}/#/?token=${token}`
: `http://localhost:${port}`
console.log(` ${url}`)
console.log(` Log: ${LOG_FILE}`)
const isWin = process.platform === 'win32'
const cmd = isWin ? `start ${url}` : process.platform === 'darwin' ? `open ${url}` : `xdg-open ${url}`
try { execSync(cmd, { stdio: 'ignore' }) } catch {}
} else {
// Poll health endpoint until server is ready (setTimeout to avoid overlapping requests)
const healthUrl = `http://127.0.0.1:${port}/health`
const maxWait = 30000
const interval = 500
let waited = 0
console.log(` ⏳ Starting hermes-web-ui (PID: ${child.pid}, port: ${port})...`)
function poll() {
waited += interval
if (!isRunning(child.pid)) {
console.log(' ✗ Failed to start hermes-web-ui')
console.log(` Check log: ${LOG_FILE}`)
removePid()
process.exit(1)
return
}
}, 500)
fetch(healthUrl).then(res => {
if (res.ok) {
const url = token
? `http://localhost:${port}/#/?token=${token}`
: `http://localhost:${port}`
console.log(` ✓ hermes-web-ui started`)
console.log(` ${url}`)
console.log(` Log: ${LOG_FILE}`)
const isWin = process.platform === 'win32'
const cmd = isWin ? `start ${url}` : process.platform === 'darwin' ? `open ${url}` : `xdg-open ${url}`
try { execSync(cmd, { stdio: 'ignore' }) } catch {}
} else if (waited < maxWait) {
setTimeout(poll, interval)
} else {
console.log(` ⚠ Server process is running but health check failed after ${maxWait / 1000}s`)
console.log(` Check log: ${LOG_FILE}`)
const url = token
? `http://localhost:${port}/#/?token=${token}`
: `http://localhost:${port}`
console.log(` ${url}`)
}
}).catch(() => {
if (waited < maxWait) {
setTimeout(poll, interval)
} else {
console.log(` ⚠ Server process is running but health check failed after ${maxWait / 1000}s`)
console.log(` Check log: ${LOG_FILE}`)
const url = token
? `http://localhost:${port}/#/?token=${token}`
: `http://localhost:${port}`
console.log(` ${url}`)
}
})
}
setTimeout(poll, interval)
}
function stopDaemon() {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hermes-web-ui",
"version": "0.2.7",
"version": "0.2.9",
"description": "Web dashboard for Hermes Agent — multi-platform AI chat, session management, scheduled jobs, usage analytics & channel configuration (Telegram, Discord, Slack, WhatsApp)",
"repository": {
"type": "git",
+122
View File
@@ -0,0 +1,122 @@
import { request, getBaseUrlValue, getApiKey } from '../client'
export interface HermesProfile {
name: string
active: boolean
model: string
gateway: string
alias: string
}
export interface HermesProfileDetail {
name: string
path: string
model: string
provider: string
gateway: string
skills: number
hasEnv: boolean
hasSoulMd: boolean
}
export async function fetchProfiles(): Promise<HermesProfile[]> {
const res = await request<{ profiles: HermesProfile[] }>('/api/hermes/profiles')
return res.profiles
}
export async function fetchProfileDetail(name: string): Promise<HermesProfileDetail> {
const res = await request<{ profile: HermesProfileDetail }>(`/api/hermes/profiles/${encodeURIComponent(name)}`)
return res.profile
}
export async function createProfile(name: string, clone?: boolean): Promise<boolean> {
try {
await request('/api/hermes/profiles', {
method: 'POST',
body: JSON.stringify({ name, clone }),
})
return true
} catch {
return false
}
}
export async function deleteProfile(name: string): Promise<boolean> {
try {
await request(`/api/hermes/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' })
return true
} catch {
return false
}
}
export async function renameProfile(name: string, newName: string): Promise<boolean> {
try {
await request(`/api/hermes/profiles/${encodeURIComponent(name)}/rename`, {
method: 'POST',
body: JSON.stringify({ new_name: newName }),
})
return true
} catch {
return false
}
}
export async function switchProfile(name: string): Promise<boolean> {
try {
await request('/api/hermes/profiles/active', {
method: 'PUT',
body: JSON.stringify({ name }),
})
return true
} catch {
return false
}
}
export async function exportProfile(name: string): Promise<boolean> {
try {
const baseUrl = getBaseUrlValue()
const token = getApiKey()
const headers: Record<string, string> = {}
if (token) headers['Authorization'] = `Bearer ${token}`
const res = await fetch(`${baseUrl}/api/hermes/profiles/${encodeURIComponent(name)}/export`, {
method: 'POST',
headers,
})
if (!res.ok) throw new Error()
const blob = await res.blob()
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `hermes-profile-${name}.tar.gz`
a.click()
URL.revokeObjectURL(url)
return true
} catch {
return false
}
}
export async function importProfile(file: File): Promise<boolean> {
try {
const baseUrl = getBaseUrlValue()
const token = getApiKey()
const headers: Record<string, string> = {}
if (token) headers['Authorization'] = `Bearer ${token}`
const formData = new FormData()
formData.append('file', file)
const res = await fetch(`${baseUrl}/api/hermes/profiles/import`, {
method: 'POST',
headers,
body: formData,
})
return res.ok
} catch {
return false
}
}
+3 -1
View File
@@ -25,8 +25,10 @@ export interface SkillFileEntry {
export interface MemoryData {
memory: string
user: string
soul: string
memory_mtime: number | null
user_mtime: number | null
soul_mtime: number | null
}
export async function fetchSkills(): Promise<SkillCategory[]> {
@@ -48,7 +50,7 @@ export async function fetchMemory(): Promise<MemoryData> {
return request<MemoryData>('/api/hermes/memory')
}
export async function saveMemory(section: 'memory' | 'user', content: string): Promise<void> {
export async function saveMemory(section: 'memory' | 'user' | 'soul', content: string): Promise<void> {
await request('/api/hermes/memory', {
method: 'POST',
body: JSON.stringify({ section, content }),
+7
View File
@@ -3,6 +3,9 @@ import { request } from '../client'
export interface HealthResponse {
status: string
version?: string
webui_version?: string
webui_latest?: string
webui_update_available?: boolean
}
// Config-based model types
@@ -45,6 +48,10 @@ export async function checkHealth(): Promise<HealthResponse> {
return request<HealthResponse>('/health')
}
export async function triggerUpdate(): Promise<{ success: boolean; message: string }> {
return request<{ success: boolean; message: string }>('/api/hermes/update', { method: 'POST' })
}
export async function fetchConfigModels(): Promise<ConfigModelsResponse> {
return request<ConfigModelsResponse>('/api/hermes/config/models')
}
@@ -0,0 +1,284 @@
<script setup lang="ts">
import { ref, computed } from 'vue'
import { NButton, NTag, NSpin, useMessage, useDialog } from 'naive-ui'
import type { HermesProfile, HermesProfileDetail } from '@/api/hermes/profiles'
import { useProfilesStore } from '@/stores/hermes/profiles'
import { useI18n } from 'vue-i18n'
const props = defineProps<{ profile: HermesProfile }>()
const emit = defineEmits<{}>()
const { t } = useI18n()
const profilesStore = useProfilesStore()
const message = useMessage()
const dialog = useDialog()
const expanded = ref(false)
const detailLoading = ref(false)
const exporting = ref(false)
const detail = ref<HermesProfileDetail | null>(null)
const isDefault = computed(() => props.profile.name === 'default')
async function toggleDetail() {
if (expanded.value) {
expanded.value = false
return
}
expanded.value = true
detailLoading.value = true
try {
detail.value = await profilesStore.fetchProfileDetail(props.profile.name)
} finally {
detailLoading.value = false
}
}
function handleSwitch() {
dialog.warning({
title: t('profiles.switchTo'),
content: t('profiles.switchConfirm', { name: props.profile.name }),
positiveText: t('common.confirm'),
negativeText: t('common.cancel'),
onPositiveClick: async () => {
profilesStore.switchProfile(props.profile.name).then(ok => {
if (ok) {
window.location.reload()
} else {
message.error(t('profiles.switchFailed'))
}
})
},
})
}
function handleDelete() {
dialog.warning({
title: t('profiles.delete'),
content: t('profiles.deleteConfirm', { name: props.profile.name }),
positiveText: t('common.delete'),
negativeText: t('common.cancel'),
onPositiveClick: async () => {
const ok = await profilesStore.deleteProfile(props.profile.name)
if (ok) {
message.success(t('profiles.deleteSuccess'))
} else {
message.error(t('profiles.deleteFailed'))
}
},
})
}
async function handleExport() {
exporting.value = true
try {
const ok = await profilesStore.exportProfile(props.profile.name)
if (ok) {
message.success(t('profiles.exportSuccess'))
} else {
message.error(t('profiles.exportFailed'))
}
} finally {
exporting.value = false
}
}
</script>
<template>
<div class="profile-card" :class="{ active: profile.active }">
<div class="card-header">
<h3 class="profile-name">{{ profile.name }}</h3>
<NTag v-if="profile.active" size="tiny" type="success" :bordered="false">
{{ t('profiles.active') }}
</NTag>
</div>
<div class="card-body">
<div class="info-row">
<span class="info-label">{{ t('profiles.model') }}</span>
<code class="info-value mono">{{ profile.model }}</code>
</div>
<div class="info-row">
<span class="info-label">{{ t('profiles.gateway') }}</span>
<code class="info-value mono">{{ profile.gateway }}</code>
</div>
</div>
<div class="card-detail-toggle" @click="toggleDetail">
<svg
width="14" height="14" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="toggle-icon"
:class="{ expanded }"
>
<polyline points="6 9 12 15 18 9" />
</svg>
<span class="toggle-text">{{ expanded ? t('common.collapse') : t('common.expand') }}</span>
</div>
<div v-if="expanded" class="card-detail">
<NSpin :show="detailLoading" size="small">
<template v-if="detail">
<div class="info-row">
<span class="info-label">{{ t('profiles.provider') }}</span>
<span class="info-value">{{ detail.provider }}</span>
</div>
<div class="info-row">
<span class="info-label">{{ t('profiles.path') }}</span>
<code class="info-value mono detail-path">{{ detail.path }}</code>
</div>
<div class="info-row">
<span class="info-label">{{ t('profiles.skills') }}</span>
<span class="info-value">{{ detail.skills }}</span>
</div>
<div class="info-row">
<span class="info-label">{{ t('profiles.hasEnv') }}</span>
<span class="info-value">{{ detail.hasEnv ? 'Yes' : 'No' }}</span>
</div>
<div class="info-row">
<span class="info-label">{{ t('profiles.hasSoulMd') }}</span>
<span class="info-value">{{ detail.hasSoulMd ? 'Yes' : 'No' }}</span>
</div>
</template>
</NSpin>
</div>
<div class="card-actions">
<NButton
v-if="!profile.active"
size="tiny"
:loading="profilesStore.switching"
quaternary
type="primary"
@click="handleSwitch"
>
{{ t('profiles.switchTo') }}
</NButton>
<NButton
size="tiny"
quaternary
type="error"
:disabled="isDefault || profile.active"
@click="handleDelete"
>
{{ t('common.delete') }}
</NButton>
<NButton size="tiny" quaternary :loading="exporting" @click="handleExport">
{{ t('profiles.export') }}
</NButton>
</div>
</div>
</template>
<style scoped lang="scss">
@use '@/styles/variables' as *;
.profile-card {
background-color: $bg-card;
border: 1px solid $border-color;
border-radius: $radius-md;
padding: 16px;
transition: border-color $transition-fast;
&:hover {
border-color: rgba($accent-primary, 0.3);
}
&.active {
border-color: rgba($success, 0.4);
}
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.profile-name {
font-size: 15px;
font-weight: 600;
color: $text-primary;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 70%;
}
.card-body {
display: flex;
flex-direction: column;
gap: 6px;
margin-bottom: 8px;
}
.card-detail-toggle {
display: flex;
align-items: center;
gap: 4px;
padding: 6px 0;
cursor: pointer;
color: $text-muted;
font-size: 12px;
user-select: none;
&:hover {
color: $text-secondary;
}
}
.toggle-icon {
transition: transform 0.2s;
&.expanded {
transform: rotate(180deg);
}
}
.card-detail {
padding: 8px 0;
border-top: 1px solid $border-light;
margin-bottom: 8px;
}
.info-row {
display: flex;
justify-content: space-between;
align-items: center;
padding: 2px 0;
}
.info-label {
font-size: 12px;
color: $text-muted;
flex-shrink: 0;
margin-right: 12px;
}
.info-value {
font-size: 12px;
color: $text-secondary;
text-align: right;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.mono {
font-family: $font-code;
font-size: 12px;
}
.detail-path {
max-width: 260px;
}
.card-actions {
display: flex;
gap: 8px;
border-top: 1px solid $border-light;
padding-top: 10px;
flex-wrap: wrap;
}
</style>
@@ -0,0 +1,88 @@
<script setup lang="ts">
import { ref } from 'vue'
import { NModal, NForm, NFormItem, NInput, NButton, NSwitch, useMessage } from 'naive-ui'
import { useProfilesStore } from '@/stores/hermes/profiles'
import { useI18n } from 'vue-i18n'
const emit = defineEmits<{
close: []
saved: []
}>()
const { t } = useI18n()
const profilesStore = useProfilesStore()
const message = useMessage()
const showModal = ref(true)
const loading = ref(false)
const name = ref('')
const clone = ref(false)
async function handleSave() {
if (!name.value.trim()) {
message.warning(t('profiles.namePlaceholder'))
return
}
loading.value = true
try {
const ok = await profilesStore.createProfile(name.value.trim(), clone.value)
if (ok) {
message.success(t('profiles.createSuccess', { name: name.value.trim() }))
emit('saved')
} else {
message.error(t('profiles.createFailed'))
}
} finally {
loading.value = false
}
}
function handleClose() {
showModal.value = false
setTimeout(() => emit('close'), 200)
}
</script>
<template>
<NModal
v-model:show="showModal"
preset="card"
:title="t('profiles.create')"
:style="{ width: 'min(420px, calc(100vw - 32px))' }"
:mask-closable="!loading"
@after-leave="emit('close')"
>
<NForm label-placement="top">
<NFormItem :label="t('profiles.name')" required>
<NInput
:value="name"
:placeholder="t('profiles.namePlaceholder')"
@input="name = $event.replace(/[^a-zA-Z0-9_-]/g, '')"
@keyup.enter="handleSave"
/>
</NFormItem>
<NFormItem :label="t('profiles.cloneFromCurrent')">
<NSwitch v-model:value="clone" />
</NFormItem>
</NForm>
<template #footer>
<div class="modal-footer">
<NButton @click="handleClose">{{ t('common.cancel') }}</NButton>
<NButton type="primary" :loading="loading" @click="handleSave">
{{ t('common.create') }}
</NButton>
</div>
</template>
</NModal>
</template>
<style scoped lang="scss">
.modal-footer {
display: flex;
justify-content: flex-end;
gap: 8px;
}
</style>
@@ -0,0 +1,105 @@
<script setup lang="ts">
import { ref } from 'vue'
import { NModal, NUpload, NButton, useMessage } from 'naive-ui'
import type { UploadFileInfo } from 'naive-ui'
import { useProfilesStore } from '@/stores/hermes/profiles'
import { useI18n } from 'vue-i18n'
const emit = defineEmits<{
close: []
saved: []
}>()
const { t } = useI18n()
const profilesStore = useProfilesStore()
const message = useMessage()
const showModal = ref(true)
const loading = ref(false)
const fileList = ref<UploadFileInfo[]>([])
const ACCEPT_TYPES = [
'.tar.gz',
'.tgz',
'.gz',
'.zip',
]
function beforeUpload({ file }: { file: UploadFileInfo }) {
const name = file.name?.toLowerCase() || ''
const valid = ACCEPT_TYPES.some(ext => name.endsWith(ext))
if (!valid) {
message.warning(t('profiles.importInvalidFile'))
return false
}
return true
}
async function handleSave() {
if (!fileList.value.length) {
message.warning(t('profiles.importSelectFile'))
return
}
loading.value = true
try {
const file = fileList.value[0].file
if (!file) {
message.error(t('profiles.importFailed'))
return
}
const ok = await profilesStore.importProfile(file)
if (ok) {
message.success(t('profiles.importSuccess'))
emit('saved')
} else {
message.error(t('profiles.importFailed'))
}
} finally {
loading.value = false
}
}
function handleClose() {
showModal.value = false
setTimeout(() => emit('close'), 200)
}
</script>
<template>
<NModal
v-model:show="showModal"
preset="card"
:title="t('profiles.import')"
:style="{ width: 'min(420px, calc(100vw - 32px))' }"
:mask-closable="!loading"
@after-leave="emit('close')"
>
<NUpload
v-model:file-list="fileList"
:max="1"
:accept="ACCEPT_TYPES.join(',')"
:disabled="loading"
@before-upload="beforeUpload"
>
<NButton>{{ t('profiles.importSelectFile') }}</NButton>
</NUpload>
<template #footer>
<div class="modal-footer">
<NButton @click="handleClose">{{ t('common.cancel') }}</NButton>
<NButton type="primary" :loading="loading" :disabled="!fileList.length" @click="handleSave">
{{ t('common.confirm') }}
</NButton>
</div>
</template>
</NModal>
</template>
<style scoped lang="scss">
.modal-footer {
display: flex;
justify-content: flex-end;
gap: 8px;
}
</style>
@@ -0,0 +1,83 @@
<script setup lang="ts">
import { ref } from 'vue'
import { NModal, NForm, NFormItem, NInput, NButton, useMessage } from 'naive-ui'
import { useProfilesStore } from '@/stores/hermes/profiles'
import { useI18n } from 'vue-i18n'
const props = defineProps<{ profileName: string }>()
const emit = defineEmits<{
close: []
saved: []
}>()
const { t } = useI18n()
const profilesStore = useProfilesStore()
const message = useMessage()
const showModal = ref(true)
const loading = ref(false)
const newName = ref('')
async function handleSave() {
if (!newName.value.trim()) {
message.warning(t('profiles.newNamePlaceholder'))
return
}
loading.value = true
try {
const ok = await profilesStore.renameProfile(props.profileName, newName.value.trim())
if (ok) {
message.success(t('profiles.renameSuccess'))
emit('saved')
} else {
message.error(t('profiles.renameFailed'))
}
} finally {
loading.value = false
}
}
function handleClose() {
showModal.value = false
setTimeout(() => emit('close'), 200)
}
</script>
<template>
<NModal
v-model:show="showModal"
preset="card"
:title="t('profiles.rename')"
:style="{ width: 'min(420px, calc(100vw - 32px))' }"
:mask-closable="!loading"
@after-leave="emit('close')"
>
<NForm label-placement="top">
<NFormItem :label="t('profiles.newName')" required>
<NInput
v-model:value="newName"
:placeholder="t('profiles.newNamePlaceholder')"
@keyup.enter="handleSave"
/>
</NFormItem>
</NForm>
<template #footer>
<div class="modal-footer">
<NButton @click="handleClose">{{ t('common.cancel') }}</NButton>
<NButton type="primary" :loading="loading" @click="handleSave">
{{ t('common.confirm') }}
</NButton>
</div>
</template>
</NModal>
</template>
<style scoped lang="scss">
.modal-footer {
display: flex;
justify-content: flex-end;
gap: 8px;
}
</style>
@@ -0,0 +1,56 @@
<script setup lang="ts">
import ProfileCard from './ProfileCard.vue'
import { useProfilesStore } from '@/stores/hermes/profiles'
import { useI18n } from 'vue-i18n'
defineEmits<{ rename: [name: string] }>()
const { t } = useI18n()
const profilesStore = useProfilesStore()
</script>
<template>
<div v-if="profilesStore.profiles.length === 0" class="empty-state">
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" class="empty-icon">
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
<circle cx="12" cy="7" r="4" />
</svg>
<p>{{ t('profiles.noProfiles') }}</p>
</div>
<div v-else class="profiles-grid">
<ProfileCard
v-for="p in profilesStore.profiles"
:key="p.name"
:profile="p"
@rename="$emit('rename', $event)"
/>
</div>
</template>
<style scoped lang="scss">
@use '@/styles/variables' as *;
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
color: $text-muted;
gap: 12px;
.empty-icon {
opacity: 0.3;
}
p {
font-size: 14px;
}
}
.profiles-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(100%, 420px), 1fr));
gap: 14px;
}
</style>
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
import { ref, reactive, onUnmounted } from 'vue'
import { NSwitch, NInput, NButton, useMessage } from 'naive-ui'
import { useI18n } from 'vue-i18n'
import { useSettingsStore } from '@/stores/hermes/settings'
@@ -11,31 +11,73 @@ const settingsStore = useSettingsStore()
const message = useMessage()
const { t } = useI18n()
async function saveChannel(platform: string, values: Record<string, any>) {
try {
await settingsStore.saveSection(platform, values)
message.success(t('settings.saved'))
} catch (err: any) {
message.error(t('settings.saveFailed'))
}
// Track saving state per platform.field
const saving = reactive<Record<string, boolean>>({})
function savingKey(platform: string, field: string) {
return `${platform}.${field}`
}
// Save credentials to .env (matching hermes gateway setup behavior)
const savingCreds = ref(false)
function isSaving(platform: string, field: string) {
return !!saving[savingKey(platform, field)]
}
async function saveCredentials(platform: string, values: Record<string, any>) {
savingCreds.value = true
// Debounce timers
const debounceTimers: Record<string, ReturnType<typeof setTimeout>> = {}
function debounceSave(platform: string, field: string, saveFn: () => Promise<void>, delay = 600) {
const key = savingKey(platform, field)
if (debounceTimers[key]) clearTimeout(debounceTimers[key])
debounceTimers[key] = setTimeout(async () => {
saving[key] = true
try {
await saveFn()
message.success(t('settings.saved'))
} catch (err: any) {
message.error(t('settings.saveFailed'))
} finally {
saving[key] = false
}
}, delay)
}
// Immediate save for switches
async function immediateSave(platform: string, field: string, saveFn: () => Promise<void>) {
const key = savingKey(platform, field)
saving[key] = true
try {
await saveCredsApi(platform, values)
await settingsStore.fetchSettings()
await saveFn()
message.success(t('settings.saved'))
} catch (err: any) {
message.error(t('settings.saveFailed'))
} finally {
savingCreds.value = false
saving[key] = false
}
}
async function saveChannel(platform: string, field: string, values: Record<string, any>) {
immediateSave(platform, field, () => settingsStore.saveSection(platform, values))
}
function debouncedSaveChannel(platform: string, field: string, values: Record<string, any>) {
debounceSave(platform, field, () => settingsStore.saveSection(platform, values))
}
// Save credentials to .env (matching hermes gateway setup behavior)
async function saveCredentials(platform: string, field: string, values: Record<string, any>) {
immediateSave(platform, field, async () => {
await saveCredsApi(platform, values)
await settingsStore.fetchSettings()
})
}
function debouncedSaveCredentials(platform: string, field: string, values: Record<string, any>) {
debounceSave(platform, field, async () => {
await saveCredsApi(platform, values)
await settingsStore.fetchSettings()
})
}
function getCreds(key: string) {
return (settingsStore.platforms[key] || {}) as Record<string, any>
}
@@ -104,6 +146,7 @@ function stopWeixinPoll() {
onUnmounted(() => {
stopWeixinPoll()
Object.values(debounceTimers).forEach(t => clearTimeout(t))
})
const platforms = [
@@ -168,133 +211,133 @@ const platforms = [
<!-- Telegram -->
<template v-if="p.key === 'telegram'">
<SettingRow :label="t('platform.botToken')" :hint="t('platform.botTokenHint')">
<NInput :value="getCreds('telegram').token || ''" clearable size="small" class="input-lg" placeholder="123456:ABC-DEF..." @update:value="v => saveCredentials('telegram', { token: v })" />
<NInput :value="getCreds('telegram').token || ''" :loading="isSaving('telegram', 'token')" clearable size="small" class="input-lg" placeholder="123456:ABC-DEF..." @update:value="v => debouncedSaveCredentials('telegram', 'token', { token: v })" />
</SettingRow>
<SettingRow :label="t('platform.requireMention')" :hint="t('platform.requireMentionGroup')">
<NSwitch :value="settingsStore.telegram.require_mention" @update:value="v => saveChannel('telegram', { require_mention: v })" />
<NSwitch :value="settingsStore.telegram.require_mention" :loading="isSaving('telegram', 'require_mention')" @update:value="v => saveChannel('telegram', 'require_mention', { require_mention: v })" />
</SettingRow>
<SettingRow :label="t('platform.reactions')" :hint="t('platform.reactionsHint')">
<NSwitch :value="settingsStore.telegram.reactions" @update:value="v => saveChannel('telegram', { reactions: v })" />
<NSwitch :value="settingsStore.telegram.reactions" :loading="isSaving('telegram', 'reactions')" @update:value="v => saveChannel('telegram', 'reactions', { reactions: v })" />
</SettingRow>
<SettingRow :label="t('platform.freeResponseChats')" :hint="t('platform.freeResponseChatsHint')">
<NInput :value="settingsStore.telegram.free_response_chats || ''" size="small" placeholder="chat_id1,chat_id2" @update:value="v => saveChannel('telegram', { free_response_chats: v })" />
<NInput :value="settingsStore.telegram.free_response_chats || ''" :loading="isSaving('telegram', 'free_response_chats')" size="small" placeholder="chat_id1,chat_id2" @update:value="v => debouncedSaveChannel('telegram', 'free_response_chats', { free_response_chats: v })" />
</SettingRow>
<SettingRow :label="t('platform.mentionPatterns')" :hint="t('platform.mentionPatternsHint')">
<NInput :value="(settingsStore.telegram.mention_patterns || []).join(', ')" size="small" placeholder="pattern1, pattern2" @update:value="v => saveChannel('telegram', { mention_patterns: v ? v.split(',').map(s => s.trim()) : [] })" />
<NInput :value="(settingsStore.telegram.mention_patterns || []).join(', ')" :loading="isSaving('telegram', 'mention_patterns')" size="small" placeholder="pattern1, pattern2" @update:value="v => debouncedSaveChannel('telegram', 'mention_patterns', { mention_patterns: v ? v.split(',').map(s => s.trim()) : [] })" />
</SettingRow>
</template>
<!-- Discord -->
<template v-if="p.key === 'discord'">
<SettingRow :label="t('platform.botToken')" :hint="t('platform.botTokenHint')">
<NInput :value="getCreds('discord').token || ''" clearable size="small" class="input-lg" placeholder="Bot token..." @update:value="v => saveCredentials('discord', { token: v })" />
<NInput :value="getCreds('discord').token || ''" :loading="isSaving('discord', 'token')" clearable size="small" class="input-lg" placeholder="Bot token..." @update:value="v => debouncedSaveCredentials('discord', 'token', { token: v })" />
</SettingRow>
<SettingRow :label="t('platform.requireMention')" :hint="t('platform.requireMentionChannel')">
<NSwitch :value="settingsStore.discord.require_mention" @update:value="v => saveChannel('discord', { require_mention: v })" />
<NSwitch :value="settingsStore.discord.require_mention" :loading="isSaving('discord', 'require_mention')" @update:value="v => saveChannel('discord', 'require_mention', { require_mention: v })" />
</SettingRow>
<SettingRow :label="t('platform.autoThread')" :hint="t('platform.autoThreadHint')">
<NSwitch :value="settingsStore.discord.auto_thread" @update:value="v => saveChannel('discord', { auto_thread: v })" />
<NSwitch :value="settingsStore.discord.auto_thread" :loading="isSaving('discord', 'auto_thread')" @update:value="v => saveChannel('discord', 'auto_thread', { auto_thread: v })" />
</SettingRow>
<SettingRow :label="t('platform.reactions')" :hint="t('platform.reactionsHint')">
<NSwitch :value="settingsStore.discord.reactions" @update:value="v => saveChannel('discord', { reactions: v })" />
<NSwitch :value="settingsStore.discord.reactions" :loading="isSaving('discord', 'reactions')" @update:value="v => saveChannel('discord', 'reactions', { reactions: v })" />
</SettingRow>
<SettingRow :label="t('platform.freeResponseChannels')" :hint="t('platform.freeResponseChannelsHint')">
<NInput :value="settingsStore.discord.free_response_channels || ''" size="small" placeholder="channel_id1,channel_id2" @update:value="v => saveChannel('discord', { free_response_channels: v })" />
<NInput :value="settingsStore.discord.free_response_channels || ''" :loading="isSaving('discord', 'free_response_channels')" size="small" placeholder="channel_id1,channel_id2" @update:value="v => debouncedSaveChannel('discord', 'free_response_channels', { free_response_channels: v })" />
</SettingRow>
<SettingRow :label="t('platform.allowedChannels')" :hint="t('platform.allowedChannelsHint')">
<NInput :value="settingsStore.discord.allowed_channels || ''" size="small" placeholder="channel_id1,channel_id2" @update:value="v => saveChannel('discord', { allowed_channels: v })" />
<NInput :value="settingsStore.discord.allowed_channels || ''" :loading="isSaving('discord', 'allowed_channels')" size="small" placeholder="channel_id1,channel_id2" @update:value="v => debouncedSaveChannel('discord', 'allowed_channels', { allowed_channels: v })" />
</SettingRow>
<SettingRow :label="t('platform.ignoredChannels')" :hint="t('platform.ignoredChannelsHint')">
<NInput :value="settingsStore.discord.ignored_channels || ''" size="small" placeholder="channel_id1,channel_id2" @update:value="v => saveChannel('discord', { ignored_channels: v })" />
<NInput :value="settingsStore.discord.ignored_channels || ''" :loading="isSaving('discord', 'ignored_channels')" size="small" placeholder="channel_id1,channel_id2" @update:value="v => debouncedSaveChannel('discord', 'ignored_channels', { ignored_channels: v })" />
</SettingRow>
<SettingRow :label="t('platform.noThreadChannels')" :hint="t('platform.noThreadChannelsHint')">
<NInput :value="settingsStore.discord.no_thread_channels || ''" size="small" placeholder="channel_id1,channel_id2" @update:value="v => saveChannel('discord', { no_thread_channels: v })" />
<NInput :value="settingsStore.discord.no_thread_channels || ''" :loading="isSaving('discord', 'no_thread_channels')" size="small" placeholder="channel_id1,channel_id2" @update:value="v => debouncedSaveChannel('discord', 'no_thread_channels', { no_thread_channels: v })" />
</SettingRow>
</template>
<!-- Slack -->
<template v-if="p.key === 'slack'">
<SettingRow :label="t('platform.botToken')" :hint="t('platform.botTokenHint')">
<NInput :value="getCreds('slack').token || ''" clearable size="small" class="input-lg" placeholder="xoxb-..." @update:value="v => saveCredentials('slack', { token: v })" />
<NInput :value="getCreds('slack').token || ''" :loading="isSaving('slack', 'token')" clearable size="small" class="input-lg" placeholder="xoxb-..." @update:value="v => debouncedSaveCredentials('slack', 'token', { token: v })" />
</SettingRow>
<SettingRow :label="t('platform.requireMention')" :hint="t('platform.requireMentionChannel')">
<NSwitch :value="settingsStore.slack.require_mention" @update:value="v => saveChannel('slack', { require_mention: v })" />
<NSwitch :value="settingsStore.slack.require_mention" :loading="isSaving('slack', 'require_mention')" @update:value="v => saveChannel('slack', 'require_mention', { require_mention: v })" />
</SettingRow>
<SettingRow :label="t('platform.allowBots')" :hint="t('platform.allowBotsHint')">
<NSwitch :value="settingsStore.slack.allow_bots" @update:value="v => saveChannel('slack', { allow_bots: v })" />
<NSwitch :value="settingsStore.slack.allow_bots" :loading="isSaving('slack', 'allow_bots')" @update:value="v => saveChannel('slack', 'allow_bots', { allow_bots: v })" />
</SettingRow>
<SettingRow :label="t('platform.freeResponseChannels')" :hint="t('platform.freeResponseChannelsHint')">
<NInput :value="settingsStore.slack.free_response_channels || ''" size="small" placeholder="channel_id1,channel_id2" @update:value="v => saveChannel('slack', { free_response_channels: v })" />
<NInput :value="settingsStore.slack.free_response_channels || ''" :loading="isSaving('slack', 'free_response_channels')" size="small" placeholder="channel_id1,channel_id2" @update:value="v => debouncedSaveChannel('slack', 'free_response_channels', { free_response_channels: v })" />
</SettingRow>
</template>
<!-- WhatsApp -->
<template v-if="p.key === 'whatsapp'">
<SettingRow :label="t('platform.waEnabled')" :hint="t('platform.waEnabledHint')">
<NSwitch :value="getCreds('whatsapp').enabled" @update:value="v => saveCredentials('whatsapp', { enabled: v })" />
<NSwitch :value="getCreds('whatsapp').enabled" :loading="isSaving('whatsapp', 'enabled')" @update:value="v => saveCredentials('whatsapp', 'enabled', { enabled: v })" />
</SettingRow>
<SettingRow :label="t('platform.requireMention')" :hint="t('platform.requireMentionGroup')">
<NSwitch :value="settingsStore.whatsapp.require_mention" @update:value="v => saveChannel('whatsapp', { require_mention: v })" />
<NSwitch :value="settingsStore.whatsapp.require_mention" :loading="isSaving('whatsapp', 'require_mention')" @update:value="v => saveChannel('whatsapp', 'require_mention', { require_mention: v })" />
</SettingRow>
<SettingRow :label="t('platform.freeResponseChats')" :hint="t('platform.freeResponseChatsHint')">
<NInput :value="settingsStore.whatsapp.free_response_chats || ''" size="small" placeholder="chat_id1,chat_id2" @update:value="v => saveChannel('whatsapp', { free_response_chats: v })" />
<NInput :value="settingsStore.whatsapp.free_response_chats || ''" :loading="isSaving('whatsapp', 'free_response_chats')" size="small" placeholder="chat_id1,chat_id2" @update:value="v => debouncedSaveChannel('whatsapp', 'free_response_chats', { free_response_chats: v })" />
</SettingRow>
<SettingRow :label="t('platform.mentionPatterns')" :hint="t('platform.mentionPatternsHint')">
<NInput :value="(settingsStore.whatsapp.mention_patterns || []).join(', ')" size="small" placeholder="pattern1, pattern2" @update:value="v => saveChannel('whatsapp', { mention_patterns: v ? v.split(',').map(s => s.trim()) : [] })" />
<NInput :value="(settingsStore.whatsapp.mention_patterns || []).join(', ')" :loading="isSaving('whatsapp', 'mention_patterns')" size="small" placeholder="pattern1, pattern2" @update:value="v => debouncedSaveChannel('whatsapp', 'mention_patterns', { mention_patterns: v ? v.split(',').map(s => s.trim()) : [] })" />
</SettingRow>
</template>
<!-- Matrix -->
<template v-if="p.key === 'matrix'">
<SettingRow :label="t('platform.accessToken')" :hint="t('platform.accessTokenHint')">
<NInput :value="getCreds('matrix').token || ''" clearable size="small" class="input-lg" placeholder="syt_..." @update:value="v => saveCredentials('matrix', { token: v })" />
<NInput :value="getCreds('matrix').token || ''" :loading="isSaving('matrix', 'token')" clearable size="small" class="input-lg" placeholder="syt_..." @update:value="v => debouncedSaveCredentials('matrix', 'token', { token: v })" />
</SettingRow>
<SettingRow :label="t('platform.homeserver')" :hint="t('platform.homeserverHint')">
<NInput :value="getCreds('matrix').extra?.homeserver || ''" clearable size="small" class="input-lg" placeholder="https://matrix.org" @update:value="v => saveCredentials('matrix', { extra: { ...getCreds('matrix').extra, homeserver: v } })" />
<NInput :value="getCreds('matrix').extra?.homeserver || ''" :loading="isSaving('matrix', 'homeserver')" clearable size="small" class="input-lg" placeholder="https://matrix.org" @update:value="v => debouncedSaveCredentials('matrix', 'homeserver', { extra: { ...getCreds('matrix').extra, homeserver: v } })" />
</SettingRow>
<SettingRow :label="t('platform.requireMention')" :hint="t('platform.requireMentionRoom')">
<NSwitch :value="settingsStore.matrix.require_mention" @update:value="v => saveChannel('matrix', { require_mention: v })" />
<NSwitch :value="settingsStore.matrix.require_mention" :loading="isSaving('matrix', 'require_mention')" @update:value="v => saveChannel('matrix', 'require_mention', { require_mention: v })" />
</SettingRow>
<SettingRow :label="t('platform.autoThread')" :hint="t('platform.autoThreadHintRoom')">
<NSwitch :value="settingsStore.matrix.auto_thread" @update:value="v => saveChannel('matrix', { auto_thread: v })" />
<NSwitch :value="settingsStore.matrix.auto_thread" :loading="isSaving('matrix', 'auto_thread')" @update:value="v => saveChannel('matrix', 'auto_thread', { auto_thread: v })" />
</SettingRow>
<SettingRow :label="t('platform.dmMentionThreads')" :hint="t('platform.dmMentionThreadsHint')">
<NSwitch :value="settingsStore.matrix.dm_mention_threads" @update:value="v => saveChannel('matrix', { dm_mention_threads: v })" />
<NSwitch :value="settingsStore.matrix.dm_mention_threads" :loading="isSaving('matrix', 'dm_mention_threads')" @update:value="v => saveChannel('matrix', 'dm_mention_threads', { dm_mention_threads: v })" />
</SettingRow>
<SettingRow :label="t('platform.freeResponseRooms')" :hint="t('platform.freeResponseRoomsHint')">
<NInput :value="settingsStore.matrix.free_response_rooms || ''" size="small" placeholder="room_id1,room_id2" @update:value="v => saveChannel('matrix', { free_response_rooms: v })" />
<NInput :value="settingsStore.matrix.free_response_rooms || ''" :loading="isSaving('matrix', 'free_response_rooms')" size="small" placeholder="room_id1,room_id2" @update:value="v => debouncedSaveChannel('matrix', 'free_response_rooms', { free_response_rooms: v })" />
</SettingRow>
</template>
<!-- Feishu -->
<template v-if="p.key === 'feishu'">
<SettingRow :label="t('platform.appId')" :hint="t('platform.appIdHint')">
<NInput :value="getCreds('feishu').extra?.app_id || ''" clearable size="small" class="input-lg" placeholder="cli_..." @update:value="v => saveCredentials('feishu', { extra: { ...getCreds('feishu').extra, app_id: v } })" />
<NInput :value="getCreds('feishu').extra?.app_id || ''" :loading="isSaving('feishu', 'app_id')" clearable size="small" class="input-lg" placeholder="cli_..." @update:value="v => debouncedSaveCredentials('feishu', 'app_id', { extra: { ...getCreds('feishu').extra, app_id: v } })" />
</SettingRow>
<SettingRow :label="t('platform.appSecret')" :hint="t('platform.appSecretHint')">
<NInput :value="getCreds('feishu').extra?.app_secret || ''" clearable size="small" class="input-lg" placeholder="App Secret" @update:value="v => saveCredentials('feishu', { extra: { ...getCreds('feishu').extra, app_secret: v } })" />
<NInput :value="getCreds('feishu').extra?.app_secret || ''" :loading="isSaving('feishu', 'app_secret')" clearable size="small" class="input-lg" placeholder="App Secret" @update:value="v => debouncedSaveCredentials('feishu', 'app_secret', { extra: { ...getCreds('feishu').extra, app_secret: v } })" />
</SettingRow>
<SettingRow :label="t('platform.requireMention')" :hint="t('platform.requireMentionGroup')">
<NSwitch :value="settingsStore.feishu.require_mention" @update:value="v => saveChannel('feishu', { require_mention: v })" />
<NSwitch :value="settingsStore.feishu.require_mention" :loading="isSaving('feishu', 'require_mention')" @update:value="v => saveChannel('feishu', 'require_mention', { require_mention: v })" />
</SettingRow>
<SettingRow :label="t('platform.freeResponseChats')" :hint="t('platform.freeResponseChatsHint')">
<NInput :value="settingsStore.feishu.free_response_chats || ''" size="small" placeholder="chat_id1,chat_id2" @update:value="v => saveChannel('feishu', { free_response_chats: v })" />
<NInput :value="settingsStore.feishu.free_response_chats || ''" :loading="isSaving('feishu', 'free_response_chats')" size="small" placeholder="chat_id1,chat_id2" @update:value="v => debouncedSaveChannel('feishu', 'free_response_chats', { free_response_chats: v })" />
</SettingRow>
</template>
<!-- DingTalk -->
<template v-if="p.key === 'dingtalk'">
<SettingRow :label="t('platform.clientId')" :hint="t('platform.clientIdHint')">
<NInput :value="getCreds('dingtalk').extra?.client_id || ''" clearable size="small" class="input-lg" placeholder="Client ID" @update:value="v => saveCredentials('dingtalk', { extra: { ...getCreds('dingtalk').extra, client_id: v } })" />
<NInput :value="getCreds('dingtalk').extra?.client_id || ''" :loading="isSaving('dingtalk', 'client_id')" clearable size="small" class="input-lg" placeholder="Client ID" @update:value="v => debouncedSaveCredentials('dingtalk', 'client_id', { extra: { ...getCreds('dingtalk').extra, client_id: v } })" />
</SettingRow>
<SettingRow :label="t('platform.clientSecret')" :hint="t('platform.clientSecretHint')">
<NInput :value="getCreds('dingtalk').extra?.client_secret || ''" clearable size="small" class="input-lg" placeholder="Client Secret" @update:value="v => saveCredentials('dingtalk', { extra: { ...getCreds('dingtalk').extra, client_secret: v } })" />
<NInput :value="getCreds('dingtalk').extra?.client_secret || ''" :loading="isSaving('dingtalk', 'client_secret')" clearable size="small" class="input-lg" placeholder="Client Secret" @update:value="v => debouncedSaveCredentials('dingtalk', 'client_secret', { extra: { ...getCreds('dingtalk').extra, client_secret: v } })" />
</SettingRow>
<SettingRow :label="t('platform.requireMention')" :hint="t('platform.requireMentionGroup')">
<NSwitch :value="settingsStore.dingtalk.require_mention" @update:value="v => saveChannel('dingtalk', { require_mention: v })" />
<NSwitch :value="settingsStore.dingtalk.require_mention" :loading="isSaving('dingtalk', 'require_mention')" @update:value="v => saveChannel('dingtalk', 'require_mention', { require_mention: v })" />
</SettingRow>
<SettingRow :label="t('platform.freeResponseChats')" :hint="t('platform.freeResponseChatsHint')">
<NInput :value="settingsStore.dingtalk.free_response_chats || ''" size="small" placeholder="chat_id1,chat_id2" @update:value="v => saveChannel('dingtalk', { free_response_chats: v })" />
<NInput :value="settingsStore.dingtalk.free_response_chats || ''" :loading="isSaving('dingtalk', 'free_response_chats')" size="small" placeholder="chat_id1,chat_id2" @update:value="v => debouncedSaveChannel('dingtalk', 'free_response_chats', { free_response_chats: v })" />
</SettingRow>
</template>
@@ -318,20 +361,20 @@ const platforms = [
</div>
</div>
<SettingRow :label="t('platform.weixinToken')" :hint="t('platform.weixinTokenHint')">
<NInput :value="getCreds('weixin').token || ''" clearable size="small" class="input-lg" placeholder="Token" @update:value="v => saveCredentials('weixin', { token: v })" />
<NInput :value="getCreds('weixin').token || ''" :loading="isSaving('weixin', 'token')" clearable size="small" class="input-lg" placeholder="Token" @update:value="v => debouncedSaveCredentials('weixin', 'token', { token: v })" />
</SettingRow>
<SettingRow :label="t('platform.accountId')" :hint="t('platform.accountIdHint')">
<NInput :value="getCreds('weixin').extra?.account_id || ''" clearable size="small" class="input-lg" placeholder="Account ID" @update:value="v => saveCredentials('weixin', { extra: { ...getCreds('weixin').extra, account_id: v } })" />
<NInput :value="getCreds('weixin').extra?.account_id || ''" :loading="isSaving('weixin', 'account_id')" clearable size="small" class="input-lg" placeholder="Account ID" @update:value="v => debouncedSaveCredentials('weixin', 'account_id', { extra: { ...getCreds('weixin').extra, account_id: v } })" />
</SettingRow>
</template>
<!-- WeCom -->
<template v-if="p.key === 'wecom'">
<SettingRow :label="t('platform.botId')" :hint="t('platform.botIdHint')">
<NInput :value="getCreds('wecom').extra?.bot_id || ''" clearable size="small" class="input-lg" placeholder="Bot ID" @update:value="v => saveCredentials('wecom', { extra: { ...getCreds('wecom').extra, bot_id: v } })" />
<NInput :value="getCreds('wecom').extra?.bot_id || ''" :loading="isSaving('wecom', 'bot_id')" clearable size="small" class="input-lg" placeholder="Bot ID" @update:value="v => debouncedSaveCredentials('wecom', 'bot_id', { extra: { ...getCreds('wecom').extra, bot_id: v } })" />
</SettingRow>
<SettingRow :label="t('platform.appSecret')" :hint="t('platform.wecomSecretHint')">
<NInput :value="getCreds('wecom').extra?.secret || ''" clearable size="small" class="input-lg" placeholder="Secret" @update:value="v => saveCredentials('wecom', { extra: { ...getCreds('wecom').extra, secret: v } })" />
<NInput :value="getCreds('wecom').extra?.secret || ''" :loading="isSaving('wecom', 'secret')" clearable size="small" class="input-lg" placeholder="Secret" @update:value="v => debouncedSaveCredentials('wecom', 'secret', { extra: { ...getCreds('wecom').extra, secret: v } })" />
</SettingRow>
</template>
</PlatformCard>
@@ -2,12 +2,15 @@
import { computed, ref, onMounted, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { useMessage } from "naive-ui";
import { useAppStore } from "@/stores/hermes/app";
import ModelSelector from "./ModelSelector.vue";
import ProfileSelector from "./ProfileSelector.vue";
import LanguageSwitch from "./LanguageSwitch.vue";
import danceVideo from "@/assets/dance.mp4";
const { t } = useI18n();
const message = useMessage();
const route = useRoute();
const router = useRouter();
const appStore = useAppStore();
@@ -63,6 +66,15 @@ onMounted(() => {
function handleNav(key: string) {
router.push({ name: key });
}
async function handleUpdate() {
const ok = await appStore.doUpdate();
if (ok) {
message.success(t('sidebar.updateSuccess'), { duration: 5000 });
} else {
message.error(t('sidebar.updateFailed'));
}
}
</script>
<template>
@@ -259,6 +271,27 @@ function handleNav(key: string) {
<span>{{ t("sidebar.usage") }}</span>
</button>
<button
class="nav-item"
:class="{ active: selectedKey === 'hermes.profiles' }"
@click="handleNav('hermes.profiles')"
>
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
<circle cx="12" cy="7" r="4" />
</svg>
<span>{{ t("sidebar.profiles") }}</span>
</button>
<button
class="nav-item"
:class="{ active: selectedKey === 'hermes.terminal' }"
@@ -304,6 +337,7 @@ function handleNav(key: string) {
</button>
</nav>
<ProfileSelector />
<ModelSelector />
<div class="sidebar-footer">
@@ -325,7 +359,10 @@ function handleNav(key: string) {
<LanguageSwitch />
</div>
<div class="version-info">
Hermes {{ appStore.serverVersion || "v0.1.0" }}
<span>Hermes Web UI v{{ appStore.serverVersion || "0.1.0" }}</span>
<a v-if="appStore.updateAvailable" class="update-hint" :class="{ loading: appStore.updating }" @click="handleUpdate">
{{ appStore.updating ? t('sidebar.updating') : t('sidebar.updateVersion', { version: appStore.latestVersion }) }}
</a>
</div>
</div>
</aside>
@@ -391,6 +428,13 @@ function handleNav(key: string) {
padding-top: 12px;
flex-direction: column;
gap: 4px;
overflow-y: auto;
min-height: 0;
scrollbar-width: none;
&::-webkit-scrollbar {
display: none;
}
}
.nav-item {
@@ -462,6 +506,31 @@ function handleNav(key: string) {
padding: 2px 12px 8px;
font-size: 11px;
color: $text-muted;
display: flex;
flex-direction: column;
gap: 2px;
}
.update-hint {
display: block;
margin-top: 4px;
padding: 5px 10px;
border-radius: $radius-sm;
background: #333333;
color: rgba(#fff, 0.7);
font-size: 11px;
text-align: center;
cursor: pointer;
transition: background $transition-fast;
&:hover {
background: #3d3d3d;
}
&.loading {
pointer-events: none;
opacity: 0.7;
}
}
@media (max-width: $breakpoint-mobile) {
@@ -0,0 +1,65 @@
<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { NSelect } from 'naive-ui'
import { useProfilesStore } from '@/stores/hermes/profiles'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const profilesStore = useProfilesStore()
const options = computed(() =>
profilesStore.profiles.map(p => ({
label: p.name,
value: p.name,
})),
)
const activeName = computed(() => profilesStore.activeProfile?.name ?? '')
function handleChange(value: string | number | Array<string | number>) {
if (typeof value === 'string' && value !== activeName.value) {
profilesStore.switchProfile(value).then(ok => {
if (ok) {
window.location.reload()
}
})
}
}
onMounted(() => {
if (profilesStore.profiles.length === 0) {
profilesStore.fetchProfiles()
}
})
</script>
<template>
<div class="profile-selector">
<div class="selector-label">{{ t('sidebar.profiles') }}</div>
<NSelect
:value="activeName"
:options="options"
:loading="profilesStore.switching"
size="small"
@update:value="handleChange"
/>
</div>
</template>
<style scoped lang="scss">
@use '@/styles/variables' as *;
.profile-selector {
padding: 0 12px;
margin-bottom: 8px;
}
.selector-label {
font-size: 11px;
font-weight: 600;
color: $text-muted;
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 6px;
}
</style>
+2
View File
@@ -1,5 +1,7 @@
/// <reference types="vite/client" />
declare const __APP_VERSION__: string
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
+58
View File
@@ -31,6 +31,9 @@ export default {
disable: 'Disable',
configured: 'Configured',
notConfigured: 'Not configured',
confirm: 'Confirm',
expand: 'Expand',
collapse: 'Collapse',
},
// Sidebar
@@ -38,6 +41,7 @@ export default {
chat: 'Chat',
jobs: 'Jobs',
models: 'Models',
profiles: 'Profiles',
skills: 'Skills',
memory: 'Memory',
logs: 'Logs',
@@ -47,6 +51,11 @@ export default {
settings: 'Settings',
connected: 'Connected',
disconnected: 'Disconnected',
updateTip: 'Run "hermes-web-ui update" in terminal to update',
updateVersion: 'Upgrade to v{version}',
updating: 'Updating...',
updateSuccess: 'Update complete, please restart the server',
updateFailed: 'Update failed',
},
// Chat
@@ -159,6 +168,9 @@ export default {
userProfile: 'User Profile',
noProfile: 'No profile yet.',
profilePlaceholder: 'Write your profile...',
soul: 'Soul',
noSoul: 'No soul configuration yet.',
soulPlaceholder: 'Write soul configuration...',
},
// Models
@@ -197,6 +209,52 @@ export default {
fetchFailed: 'Failed to fetch models',
},
// Profiles
profiles: {
title: 'Profiles',
create: 'Create Profile',
import: 'Import',
export: 'Export',
rename: 'Rename',
delete: 'Delete',
switchTo: 'Switch to',
switchConfirm: 'Switching to profile "{name}" will restart the gateway. Continue?',
switchSuccess: 'Switched to profile "{name}"',
switchFailed: 'Failed to switch profile. Gateway may need manual restart.',
createSuccess: 'Profile "{name}" created',
createFailed: 'Failed to create profile',
renameSuccess: 'Profile renamed',
renameFailed: 'Failed to rename profile',
deleteConfirm: 'Are you sure you want to delete profile "{name}"?',
deleteSuccess: 'Profile deleted',
deleteFailed: 'Failed to delete profile',
exportSuccess: 'Profile exported',
exportFailed: 'Failed to export profile',
importSuccess: 'Profile imported',
importFailed: 'Failed to import profile',
importSelectFile: 'Select archive file',
importInvalidFile: 'Please select a valid archive (.tar.gz, .tgz, .gz, .zip)',
name: 'Profile Name',
namePlaceholder: 'English letters, numbers, hyphens only',
newName: 'New Name',
newNamePlaceholder: 'Enter new name',
cloneFromCurrent: 'Clone from current profile',
archivePath: 'Archive Path',
archivePathPlaceholder: 'Server path to archive file',
importName: 'Profile Name (optional)',
importNamePlaceholder: 'Leave empty to use archive name',
active: 'Active',
model: 'Model',
gateway: 'Gateway',
alias: 'Alias',
provider: 'Provider',
path: 'Path',
skills: 'Skills',
hasEnv: 'Has .env',
hasSoulMd: 'Has soul.md',
noProfiles: 'No profiles found. Create one to get started.',
},
// Logs
logs: {
title: 'Logs',
+58
View File
@@ -31,6 +31,9 @@ export default {
disable: '禁用',
configured: '已配置',
notConfigured: '未配置',
confirm: '确定',
expand: '展开',
collapse: '收起',
},
// 侧边栏
@@ -38,6 +41,7 @@ export default {
chat: '对话',
jobs: '任务',
models: '模型',
profiles: '用户',
skills: '技能',
memory: '记忆',
logs: '日志',
@@ -47,6 +51,11 @@ export default {
settings: '设置',
connected: '已连接',
disconnected: '未连接',
updateTip: '在终端运行 "hermes-web-ui update" 即可更新',
updateVersion: '升级版本 v{version}',
updating: '正在更新...',
updateSuccess: '更新完成,请重启服务',
updateFailed: '更新失败',
},
// 对话
@@ -159,6 +168,9 @@ export default {
userProfile: '用户画像',
noProfile: '暂无画像。',
profilePlaceholder: '输入用户画像...',
soul: '灵魂',
noSoul: '暂无灵魂配置。',
soulPlaceholder: '输入灵魂配置...',
},
// 模型
@@ -197,6 +209,52 @@ export default {
fetchFailed: '获取模型失败',
},
// 配置
profiles: {
title: '配置',
create: '创建配置',
import: '导入',
export: '导出',
rename: '重命名',
delete: '删除',
switchTo: '切换到',
switchConfirm: '切换到配置 "{name}" 将重启网关,是否继续?',
switchSuccess: '已切换到配置 "{name}"',
switchFailed: '切换配置失败,网关可能需要手动重启',
createSuccess: '配置 "{name}" 已创建',
createFailed: '创建配置失败',
renameSuccess: '配置已重命名',
renameFailed: '重命名配置失败',
deleteConfirm: '确定删除配置 "{name}" 吗?',
deleteSuccess: '配置已删除',
deleteFailed: '删除配置失败',
exportSuccess: '配置已导出',
exportFailed: '导出配置失败',
importSuccess: '配置已导入',
importFailed: '导入配置失败',
importSelectFile: '选择归档文件',
importInvalidFile: '请选择有效的归档文件 (.tar.gz, .tgz, .gz, .zip)',
name: '配置名称',
namePlaceholder: '仅限英文、数字、连字符',
newName: '新名称',
newNamePlaceholder: '输入新名称',
cloneFromCurrent: '从当前配置克隆',
archivePath: '归档路径',
archivePathPlaceholder: '归档文件的服务器路径',
importName: '配置名称(可选)',
importNamePlaceholder: '留空则使用归档名称',
active: '活跃',
model: '模型',
gateway: '网关',
alias: '别名',
provider: 'Provider',
path: '路径',
skills: '技能',
hasEnv: '有 .env',
hasSoulMd: '有 soul.md',
noProfiles: '暂无配置,创建一个开始吧。',
},
// 日志
logs: {
title: '日志',
+5
View File
@@ -25,6 +25,11 @@ const router = createRouter({
name: 'hermes.models',
component: () => import('@/views/hermes/ModelsView.vue'),
},
{
path: '/hermes/profiles',
name: 'hermes.profiles',
component: () => import('@/views/hermes/ProfilesView.vue'),
},
{
path: '/hermes/logs',
name: 'hermes.logs',
+8 -14
View File
@@ -43,7 +43,7 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
{
label: 'DeepSeek',
value: 'deepseek',
base_url: 'https://api.deepseek.com/v1',
base_url: 'https://api.deepseek.com',
models: ['deepseek-chat', 'deepseek-reasoner'],
},
{
@@ -53,8 +53,8 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
models: ['glm-5', 'glm-5-turbo', 'glm-4.7', 'glm-4.5', 'glm-4.5-flash'],
},
{
label: 'Kimi Coding Plan',
value: 'kimi-coding',
label: 'Kimi for Coding',
value: 'kimi-for-coding',
base_url: 'https://api.kimi.com/coding/v1',
models: [
'kimi-for-coding',
@@ -65,12 +65,6 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
'kimi-k2-0905-preview',
],
},
{
label: 'Moonshot (Pay-as-you-go)',
value: 'moonshot',
base_url: 'https://api.moonshot.ai/v1',
models: ['kimi-k2.5', 'kimi-k2-thinking', 'kimi-k2-turbo-preview', 'kimi-k2-0905-preview'],
},
{
label: 'xAI',
value: 'xai',
@@ -91,7 +85,7 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
{
label: 'MiniMax',
value: 'minimax',
base_url: 'https://api.minimax.io/anthropic',
base_url: 'https://api.minimax.io/anthropic/v1',
models: ['MiniMax-M2.7', 'MiniMax-M2.5', 'MiniMax-M2.1', 'MiniMax-M2'],
},
{
@@ -137,7 +131,7 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
},
{
label: 'Kilo Code',
value: 'kilocode',
value: 'kilo',
base_url: 'https://api.kilo.ai/api/gateway',
models: [
'anthropic/claude-opus-4.6',
@@ -148,8 +142,8 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
],
},
{
label: 'AI Gateway',
value: 'ai-gateway',
label: 'Vercel AI Gateway',
value: 'vercel',
base_url: 'https://ai-gateway.vercel.sh/v1',
models: [
'anthropic/claude-opus-4.6',
@@ -168,7 +162,7 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
},
{
label: 'OpenCode Zen',
value: 'opencode-zen',
value: 'opencode',
base_url: 'https://opencode.ai/zen/v1',
models: [
'gpt-5.4-pro',
+28 -3
View File
@@ -1,12 +1,17 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { checkHealth, fetchAvailableModels, updateDefaultModel, type AvailableModelGroup } from '@/api/hermes/system'
import { checkHealth, fetchAvailableModels, updateDefaultModel, triggerUpdate, type AvailableModelGroup } from '@/api/hermes/system'
const WEB_UI_VERSION = __APP_VERSION__
export const useAppStore = defineStore('app', () => {
const sidebarOpen = ref(false)
const connected = ref(false)
const serverVersion = ref('')
const serverVersion = ref(WEB_UI_VERSION)
const latestVersion = ref('')
const updateAvailable = ref(false)
const updating = ref(false)
const modelGroups = ref<AvailableModelGroup[]>([])
const selectedModel = ref('')
const healthPollTimer = ref<ReturnType<typeof setInterval>>()
@@ -16,11 +21,27 @@ export const useAppStore = defineStore('app', () => {
const sessionPersistence = ref(true)
const maxTokens = ref(4096)
async function doUpdate(): Promise<boolean> {
updating.value = true
try {
const res = await triggerUpdate()
if (res.success) {
updateAvailable.value = false
await checkConnection()
}
return res.success
} finally {
updating.value = false
}
}
async function checkConnection() {
try {
const res = await checkHealth()
connected.value = res.status === 'ok'
if (res.version) serverVersion.value = res.version
if (res.webui_version) serverVersion.value = res.webui_version
if (res.webui_latest) latestVersion.value = res.webui_latest
updateAvailable.value = !!res.webui_update_available
} catch {
connected.value = false
}
@@ -75,6 +96,10 @@ export const useAppStore = defineStore('app', () => {
closeSidebar,
connected,
serverVersion,
latestVersion,
updateAvailable,
updating,
doUpdate,
modelGroups,
selectedModel,
streamEnabled,
@@ -0,0 +1,96 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import * as profilesApi from '@/api/hermes/profiles'
import type { HermesProfile, HermesProfileDetail } from '@/api/hermes/profiles'
export const useProfilesStore = defineStore('profiles', () => {
const profiles = ref<HermesProfile[]>([])
const activeProfile = ref<HermesProfile | null>(null)
const detailMap = ref<Record<string, HermesProfileDetail>>({})
const loading = ref(false)
const switching = ref(false)
async function fetchProfiles() {
loading.value = true
try {
profiles.value = await profilesApi.fetchProfiles()
activeProfile.value = profiles.value.find(p => p.active) ?? null
} catch (err) {
console.error('Failed to fetch profiles:', err)
} finally {
loading.value = false
}
}
async function fetchProfileDetail(name: string) {
if (detailMap.value[name]) return detailMap.value[name]
try {
const detail = await profilesApi.fetchProfileDetail(name)
detailMap.value[name] = detail
return detail
} catch {
return null
}
}
async function createProfile(name: string, clone?: boolean) {
const ok = await profilesApi.createProfile(name, clone)
if (ok) await fetchProfiles()
return ok
}
async function deleteProfile(name: string) {
const ok = await profilesApi.deleteProfile(name)
if (ok) {
delete detailMap.value[name]
await fetchProfiles()
}
return ok
}
async function renameProfile(name: string, newName: string) {
const ok = await profilesApi.renameProfile(name, newName)
if (ok) {
delete detailMap.value[name]
await fetchProfiles()
}
return ok
}
async function switchProfile(name: string) {
switching.value = true
try {
const ok = await profilesApi.switchProfile(name)
if (ok) await fetchProfiles()
return ok
} finally {
switching.value = false
}
}
async function exportProfile(name: string) {
return profilesApi.exportProfile(name)
}
async function importProfile(file: File) {
const ok = await profilesApi.importProfile(file)
if (ok) await fetchProfiles()
return ok
}
return {
profiles,
activeProfile,
detailMap,
loading,
switching,
fetchProfiles,
fetchProfileDetail,
createProfile,
deleteProfile,
renameProfile,
switchProfile,
exportProfile,
importProfile,
}
})
@@ -9,7 +9,7 @@ const { t } = useI18n()
const message = useMessage()
const loading = ref(false)
const data = ref<MemoryData | null>(null)
const editingSection = ref<'memory' | 'user' | null>(null)
const editingSection = ref<'memory' | 'user' | 'soul' | null>(null)
const editContent = ref('')
const saving = ref(false)
@@ -27,7 +27,7 @@ async function loadMemory() {
}
}
function startEdit(section: 'memory' | 'user') {
function startEdit(section: 'memory' | 'user' | 'soul') {
editingSection.value = section
editContent.value = data.value?.[section] || ''
}
@@ -65,9 +65,11 @@ function formatTime(ts: number | null): string {
const memoryEmpty = computed(() => !data.value?.memory?.trim())
const userEmpty = computed(() => !data.value?.user?.trim())
const soulEmpty = computed(() => !data.value?.soul?.trim())
const displayMemory = computed(() => (data.value?.memory || '').replace(/§/g, '\n\n'))
const displayUser = computed(() => (data.value?.user || '').replace(/§/g, '\n\n'))
const displaySoul = computed(() => (data.value?.soul || '').replace(/§/g, '\n\n'))
</script>
<template>
@@ -179,6 +181,53 @@ const displayUser = computed(() => (data.value?.user || '').replace(/§/g, '\n\n
</div>
</div>
</div>
<!-- Soul -->
<div class="memory-section">
<div class="section-header">
<div class="section-title-row">
<span class="section-icon">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z" />
<path d="M8 14s1.5 2 4 2 4-2 4-2" />
<line x1="9" y1="9" x2="9.01" y2="9" />
<line x1="15" y1="9" x2="15.01" y2="9" />
</svg>
</span>
<span class="section-title">{{ t('memory.soul') }}</span>
<span v-if="data?.soul_mtime" class="section-mtime">{{ formatTime(data.soul_mtime) }}</span>
</div>
<NButton v-if="editingSection !== 'soul'" size="tiny" quaternary @click="startEdit('soul')">
<template #icon>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
</svg>
</template>
{{ t('common.edit') }}
</NButton>
</div>
<!-- View mode -->
<div v-if="editingSection !== 'soul'" class="section-body">
<MarkdownRenderer v-if="!soulEmpty" :content="displaySoul" />
<p v-else class="empty-text">{{ t('memory.noSoul') }}</p>
</div>
<!-- Edit mode -->
<div v-else class="section-edit">
<textarea
v-model="editContent"
class="edit-textarea"
:placeholder="t('memory.soulPlaceholder')"
spellcheck="false"
></textarea>
<div class="edit-actions">
<NButton size="small" @click="cancelEdit">{{ t('common.cancel') }}</NButton>
<NButton size="small" type="primary" :loading="saving" @click="handleSave">{{ t('common.save') }}</NButton>
</div>
</div>
</div>
</div>
</div>
</div>
@@ -0,0 +1,120 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { NButton, NSpin } from 'naive-ui'
import { useI18n } from 'vue-i18n'
import ProfilesPanel from '@/components/hermes/profiles/ProfilesPanel.vue'
import ProfileCreateModal from '@/components/hermes/profiles/ProfileCreateModal.vue'
import ProfileRenameModal from '@/components/hermes/profiles/ProfileRenameModal.vue'
import ProfileImportModal from '@/components/hermes/profiles/ProfileImportModal.vue'
import { useProfilesStore } from '@/stores/hermes/profiles'
const { t } = useI18n()
const profilesStore = useProfilesStore()
const showCreateModal = ref(false)
const showImportModal = ref(false)
const renamingProfile = ref<string | null>(null)
onMounted(() => {
profilesStore.fetchProfiles()
})
function handleCreated() {
showCreateModal.value = false
}
function handleRenamed() {
renamingProfile.value = null
}
function handleImported() {
showImportModal.value = false
}
</script>
<template>
<div class="profiles-view">
<header class="page-header">
<h2 class="header-title">{{ t('profiles.title') }}</h2>
<div class="header-actions">
<NButton size="small" @click="showImportModal = true">
<template #icon>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="17 8 12 3 7 8" />
<line x1="12" y1="3" x2="12" y2="15" />
</svg>
</template>
{{ t('profiles.import') }}
</NButton>
<NButton type="primary" size="small" @click="showCreateModal = true">
<template #icon>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
</template>
{{ t('profiles.create') }}
</NButton>
</div>
</header>
<div class="profiles-content">
<NSpin :show="profilesStore.loading && profilesStore.profiles.length === 0">
<ProfilesPanel @rename="renamingProfile = $event" />
</NSpin>
</div>
<ProfileCreateModal
v-if="showCreateModal"
@close="showCreateModal = false"
@saved="handleCreated"
/>
<ProfileRenameModal
v-if="renamingProfile"
:profile-name="renamingProfile"
@close="renamingProfile = null"
@saved="handleRenamed"
/>
<ProfileImportModal
v-if="showImportModal"
@close="showImportModal = false"
@saved="handleImported"
/>
</div>
</template>
<style scoped lang="scss">
@use '@/styles/variables' as *;
.profiles-view {
height: calc(100 * var(--vh));
display: flex;
flex-direction: column;
}
.page-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px 20px;
border-bottom: 1px solid $border-color;
}
.header-title {
font-size: 16px;
font-weight: 600;
color: $text-primary;
}
.header-actions {
display: flex;
gap: 8px;
}
.profiles-content {
flex: 1;
overflow-y: auto;
padding: 20px;
}
</style>
+75 -4
View File
@@ -5,6 +5,7 @@ import serve from 'koa-static'
import send from 'koa-send'
import { resolve } from 'path'
import { mkdir } from 'fs/promises'
import { readFileSync } from 'fs'
import { config } from './config'
import { hermesRoutes, setupTerminalWebSocket, proxyMiddleware } from './routes/hermes'
import { uploadRoutes } from './routes/upload'
@@ -12,6 +13,43 @@ import { webhookRoutes } from './routes/webhook'
import * as hermesCli from './services/hermes-cli'
import { getToken, authMiddleware } from './services/auth'
function getLocalVersion(): string {
// production: dist/server → ../../package.json
// dev: packages/server/src → ../../../package.json
const candidates = [
resolve(__dirname, '../../package.json'),
resolve(__dirname, '../../../package.json'),
]
for (const p of candidates) {
try {
return JSON.parse(readFileSync(p, 'utf-8')).version
} catch { }
}
return '0.0.0'
}
const LOCAL_VERSION = getLocalVersion()
let cachedLatestVersion = ''
async function checkLatestVersion(): Promise<void> {
try {
const res = await fetch('https://registry.npmjs.org/hermes-web-ui/latest', {
signal: AbortSignal.timeout(5000),
})
if (res.ok) {
const data = await res.json()
const latest = data.version || ''
if (latest && latest !== cachedLatestVersion) {
cachedLatestVersion = latest
if (latest !== LOCAL_VERSION) {
console.log(`⬆ New version available: v${LOCAL_VERSION} → v${latest}`)
}
}
}
} catch { }
}
const app = new Koa()
const { restartGateway, startGateway, startGatewayBackground, getVersion } = hermesCli
@@ -40,6 +78,32 @@ export async function bootstrap() {
app.use(webhookRoutes.routes())
app.use(uploadRoutes.routes())
// update (must be before hermesRoutes which includes proxy routes)
app.use(async (ctx, next) => {
if (ctx.path === '/api/hermes/update' && ctx.method === 'POST') {
const isWin = process.platform === 'win32'
const cmd = isWin
? 'cmd /c hermes-web-ui update'
: 'hermes-web-ui update'
try {
const { execSync } = await import('child_process')
const output = execSync(cmd, {
encoding: 'utf-8',
timeout: 120000,
stdio: ['pipe', 'pipe', 'pipe'],
})
ctx.body = { success: true, message: output.trim() }
} catch (err: any) {
ctx.status = 500
ctx.body = { success: false, message: err.stderr || err.message }
}
return
}
await next()
})
app.use(hermesRoutes.routes())
app.use(proxyMiddleware)
@@ -47,7 +111,7 @@ export async function bootstrap() {
app.use(async (ctx, next) => {
if (ctx.path === '/health') {
const raw = await getVersion()
const version = raw.split('\n')[0].replace('Hermes Agent ', '') || ''
const hermesVersion = raw.split('\n')[0].replace('Hermes Agent ', '') || ''
let gatewayOk = false
try {
@@ -60,8 +124,11 @@ export async function bootstrap() {
ctx.body = {
status: gatewayOk ? 'ok' : 'error',
platform: 'hermes-agent',
version,
version: hermesVersion,
gateway: gatewayOk ? 'running' : 'stopped',
webui_version: LOCAL_VERSION,
webui_latest: cachedLatestVersion,
webui_update_available: cachedLatestVersion && cachedLatestVersion !== LOCAL_VERSION,
}
return
}
@@ -97,6 +164,10 @@ export async function bootstrap() {
// 👇 绑定退出信号
bindShutdown()
// Check for updates every 4 hours
checkLatestVersion()
setInterval(checkLatestVersion, 4 * 60 * 60 * 1000)
}
// ============================
@@ -159,10 +230,10 @@ function bindShutdown() {
// ============================
async function ensureApiServerConfig() {
const { homedir } = await import('os')
const { readFileSync, writeFileSync, existsSync, copyFileSync } = await import('fs')
const yaml = (await import('js-yaml')).default
const configPath = resolve(homedir(), '.hermes/config.yaml')
const { getActiveConfigPath } = await import('./services/hermes-profile')
const configPath = getActiveConfigPath()
const defaults: Record<string, any> = {
enabled: true,
+12 -11
View File
@@ -1,10 +1,10 @@
import Router from '@koa/router'
import { readFile, writeFile, copyFile } from 'fs/promises'
import { chmod } from 'fs/promises'
import { resolve } from 'path'
import { homedir } from 'os'
import { join } from 'path'
import YAML from 'js-yaml'
import { restartGateway } from '../../services/hermes-cli'
import { getActiveConfigPath, getActiveEnvPath, getActiveProfileDir } from '../../services/hermes-profile'
// Platform sections that require gateway restart after config change
const PLATFORM_SECTIONS = new Set([
@@ -12,8 +12,8 @@ const PLATFORM_SECTIONS = new Set([
'weixin', 'wecom', 'feishu', 'dingtalk',
])
const configPath = resolve(homedir(), '.hermes/config.yaml')
const envPath = resolve(homedir(), '.hermes/.env')
const configPath = () => getActiveConfigPath()
const envPath = () => getActiveEnvPath()
// Env var → (platform, configPath in PlatformConfig) mapping
// Matches hermes _apply_env_overrides() in gateway/config.py
@@ -81,7 +81,7 @@ function getNested(obj: Record<string, any>, path: string): any {
async function readEnvPlatforms(): Promise<Record<string, any>> {
try {
const raw = await readFile(envPath, 'utf-8')
const raw = await readFile(envPath(), 'utf-8')
const env = parseEnv(raw)
const platforms: Record<string, any> = {}
for (const [envKey, [platform, cfgPath]] of Object.entries(envPlatformMap)) {
@@ -103,7 +103,7 @@ async function readEnvPlatforms(): Promise<Record<string, any>> {
async function saveEnvValue(key: string, value: string): Promise<void> {
let raw: string
try {
raw = await readFile(envPath, 'utf-8')
raw = await readFile(envPath(), 'utf-8')
} catch {
raw = ''
}
@@ -144,25 +144,26 @@ async function saveEnvValue(key: string, value: string): Promise<void> {
// Remove trailing empty lines, keep exactly one trailing newline
let output = result.join('\n').replace(/\n{3,}/g, '\n\n').replace(/\n+$/, '') + '\n'
await writeFile(envPath, output, 'utf-8')
await writeFile(envPath(), output, 'utf-8')
// Set permissions to 0600 (owner only), matching hermes behavior
try { await chmod(envPath, 0o600) } catch { /* ignore */ }
try { await chmod(envPath(), 0o600) } catch { /* ignore */ }
}
async function readConfig(): Promise<Record<string, any>> {
const raw = await readFile(configPath, 'utf-8')
const raw = await readFile(configPath(), 'utf-8')
return (YAML.load(raw) as Record<string, any>) || {}
}
async function writeConfig(data: Record<string, any>): Promise<void> {
await copyFile(configPath, configPath + '.bak')
const cp = configPath()
await copyFile(cp, cp + '.bak')
const yamlStr = YAML.dump(data, {
lineWidth: -1,
noRefs: true,
quotingType: '"',
forceQuotes: false,
})
await writeFile(configPath, yamlStr, 'utf-8')
await writeFile(cp, yamlStr, 'utf-8')
}
export const configRoutes = new Router()
+120 -35
View File
@@ -1,8 +1,64 @@
import Router from '@koa/router'
import { readdir, readFile, stat, writeFile, mkdir, copyFile } from 'fs/promises'
import { join, resolve } from 'path'
import { homedir } from 'os'
import YAML from 'js-yaml'
import { getActiveProfileDir, getActiveConfigPath, getActiveAuthPath, getActiveEnvPath } from '../../services/hermes-profile'
import * as hermesCli from '../../services/hermes-cli'
// --- Provider env var mapping (from hermes providers.py HERMES_OVERLAYS + config.py) ---
// Maps provider key → { api_key_envs: all env var aliases for API key, base_url_env: env var for base URL }
const PROVIDER_ENV_MAP: Record<string, { api_key_env: string; base_url_env: string }> = {
openrouter: { api_key_env: 'OPENROUTER_API_KEY', base_url_env: 'OPENROUTER_BASE_URL' },
zai: { api_key_env: 'ZAI_API_KEY', base_url_env: '' },
'kimi-for-coding': { api_key_env: 'KIMI_API_KEY', base_url_env: '' },
minimax: { api_key_env: 'MINIMAX_API_KEY', base_url_env: 'MINIMAX_BASE_URL' },
'minimax-cn': { api_key_env: 'MINIMAX_API_KEY', base_url_env: 'MINIMAX_CN_BASE_URL' },
deepseek: { api_key_env: 'DEEPSEEK_API_KEY', base_url_env: 'DEEPSEEK_BASE_URL' },
alibaba: { api_key_env: 'DASHSCOPE_API_KEY', base_url_env: 'DASHSCOPE_BASE_URL' },
anthropic: { api_key_env: 'ANTHROPIC_API_KEY', base_url_env: '' },
xai: { api_key_env: 'XAI_API_KEY', base_url_env: 'XAI_BASE_URL' },
xiaomi: { api_key_env: 'XIAOMI_API_KEY', base_url_env: 'XIAOMI_BASE_URL' },
gemini: { api_key_env: 'GEMINI_API_KEY', base_url_env: '' },
kilo: { api_key_env: 'KILO_API_KEY', base_url_env: 'KILOCODE_BASE_URL' },
vercel: { api_key_env: 'AI_GATEWAY_API_KEY', base_url_env: '' },
opencode: { api_key_env: 'OPENCODE_API_KEY', base_url_env: 'OPENCODE_ZEN_BASE_URL' },
'opencode-go': { api_key_env: 'OPENCODE_API_KEY', base_url_env: 'OPENCODE_GO_BASE_URL' },
huggingface: { api_key_env: 'HF_TOKEN', base_url_env: 'HF_BASE_URL' },
}
async function saveEnvValue(key: string, value: string): Promise<void> {
const envPath = getActiveEnvPath()
let raw: string
try {
raw = await readFile(envPath, 'utf-8')
} catch {
raw = ''
}
const remove = !value
const lines = raw.split('\n')
let found = false
const result: string[] = []
for (const line of lines) {
const trimmed = line.trim()
if (trimmed.startsWith('#') && trimmed.startsWith(`# ${key}=`)) {
if (!remove) result.push(`${key}=${value}`)
found = true
} else {
const eqIdx = trimmed.indexOf('=')
if (eqIdx !== -1 && trimmed.slice(0, eqIdx).trim() === key) {
if (!remove) result.push(`${key}=${value}`)
found = true
} else {
result.push(line)
}
}
}
if (!found && !remove) {
result.push(`${key}=${value}`)
}
let output = result.join('\n').replace(/\n{3,}/g, '\n\n').replace(/\n+$/, '') + '\n'
await writeFile(envPath, output, 'utf-8')
}
// --- Auth / Credential Pool ---
@@ -18,11 +74,11 @@ interface AuthJson {
credential_pool?: Record<string, CredentialPoolEntry[]>
}
const authPath = resolve(homedir(), '.hermes', 'auth.json')
const authPath = () => getActiveAuthPath()
async function loadAuthJson(): Promise<AuthJson | null> {
try {
const raw = await readFile(authPath, 'utf-8')
const raw = await readFile(authPath(), 'utf-8')
return JSON.parse(raw) as AuthJson
} catch {
return null
@@ -30,7 +86,7 @@ async function loadAuthJson(): Promise<AuthJson | null> {
}
async function saveAuthJson(auth: AuthJson): Promise<void> {
await writeFile(authPath, JSON.stringify(auth, null, 2) + '\n', 'utf-8')
await writeFile(authPath(), JSON.stringify(auth, null, 2) + '\n', 'utf-8')
}
async function fetchProviderModels(baseUrl: string, apiKey: string): Promise<string[]> {
@@ -62,7 +118,7 @@ const PROVIDER_MODEL_CATALOG = buildProviderModelMap()
export const fsRoutes = new Router()
const hermesDir = resolve(homedir(), '.hermes')
const hermesDir = () => getActiveProfileDir()
// --- Types ---
@@ -123,29 +179,30 @@ async function safeStat(filePath: string): Promise<{ mtime: number } | null> {
// --- Config YAML helpers ---
const configPath = resolve(homedir(), '.hermes/config.yaml')
const configPath = () => getActiveConfigPath()
async function readConfigYaml(): Promise<Record<string, any>> {
const raw = await safeReadFile(configPath)
const raw = await safeReadFile(configPath())
if (!raw) return {}
return (YAML.load(raw) as Record<string, any>) || {}
}
async function writeConfigYaml(config: Record<string, any>): Promise<void> {
await copyFile(configPath, configPath + '.bak')
const cp = configPath()
await copyFile(cp, cp + '.bak')
const yamlStr = YAML.dump(config, {
lineWidth: -1,
noRefs: true,
quotingType: '"',
})
await writeFile(configPath, yamlStr, 'utf-8')
await writeFile(cp, yamlStr, 'utf-8')
}
// --- Skills Routes ---
// List all skills grouped by category
fsRoutes.get('/api/hermes/skills', async (ctx) => {
const skillsDir = join(hermesDir, 'skills')
const skillsDir = join(hermesDir(), 'skills')
try {
// Read disabled skills list from config.yaml
@@ -250,7 +307,7 @@ async function listFilesRecursive(dir: string, prefix: string): Promise<{ path:
fsRoutes.get('/api/hermes/skills/:category/:skill/files', async (ctx) => {
const { category, skill } = ctx.params
const skillDir = join(hermesDir, 'skills', category, skill)
const skillDir = join(hermesDir(), 'skills', category, skill)
try {
const allFiles = await listFilesRecursive(skillDir, '')
@@ -265,9 +322,10 @@ fsRoutes.get('/api/hermes/skills/:category/:skill/files', async (ctx) => {
// Read a specific file under skills/ (must be registered after the /files route)
fsRoutes.get('/api/hermes/skills/{*path}', async (ctx) => {
const filePath = (ctx.params as any).path
const fullPath = resolve(join(hermesDir, 'skills', filePath))
const hd = hermesDir()
const fullPath = resolve(join(hd, 'skills', filePath))
if (!fullPath.startsWith(join(hermesDir, 'skills'))) {
if (!fullPath.startsWith(join(hd, 'skills'))) {
ctx.status = 403
ctx.body = { error: 'Access denied' }
return
@@ -286,21 +344,27 @@ fsRoutes.get('/api/hermes/skills/{*path}', async (ctx) => {
// --- Memory Routes ---
fsRoutes.get('/api/hermes/memory', async (ctx) => {
const memoryPath = join(hermesDir, 'memories', 'MEMORY.md')
const userPath = join(hermesDir, 'memories', 'USER.md')
const hd = hermesDir()
const memoryPath = join(hd, 'memories', 'MEMORY.md')
const userPath = join(hd, 'memories', 'USER.md')
const soulPath = join(hd, 'SOUL.md')
const [memory, user, memoryStat, userStat] = await Promise.all([
const [memory, user, soul, memoryStat, userStat, soulStat] = await Promise.all([
safeReadFile(memoryPath),
safeReadFile(userPath),
safeReadFile(soulPath),
safeStat(memoryPath),
safeStat(userPath),
safeStat(soulPath),
])
ctx.body = {
memory: memory || '',
user: user || '',
soul: soul || '',
memory_mtime: memoryStat?.mtime || null,
user_mtime: userStat?.mtime || null,
soul_mtime: soulStat?.mtime || null,
}
})
@@ -313,14 +377,19 @@ fsRoutes.post('/api/hermes/memory', async (ctx) => {
return
}
if (section !== 'memory' && section !== 'user') {
if (section !== 'memory' && section !== 'user' && section !== 'soul') {
ctx.status = 400
ctx.body = { error: 'Section must be "memory" or "user"' }
ctx.body = { error: 'Section must be "memory", "user", or "soul"' }
return
}
const fileName = section === 'memory' ? 'MEMORY.md' : 'USER.md'
const filePath = join(hermesDir, 'memories', fileName)
let filePath: string
if (section === 'soul') {
filePath = join(hermesDir(), 'SOUL.md')
} else {
const fileName = section === 'memory' ? 'MEMORY.md' : 'USER.md'
filePath = join(hermesDir(), 'memories', fileName)
}
try {
await writeFile(filePath, content, 'utf-8')
@@ -532,26 +601,27 @@ fsRoutes.post('/api/hermes/config/providers', async (ctx) => {
}
try {
// 1. Write to config.yaml custom_providers
const config = await readConfigYaml()
if (!Array.isArray(config.custom_providers)) {
config.custom_providers = []
}
config.custom_providers.push({ name, base_url, api_key, model })
await writeConfigYaml(config)
// 2. Write to auth.json credential_pool
// Determine if this is a built-in provider or a custom one
const poolKey = providerKey
|| `custom:${name.trim().toLowerCase().replace(/ /g, '-')}`
const isBuiltin = poolKey in PROVIDER_ENV_MAP
if (!isBuiltin) {
// Custom provider: write to config.yaml custom_providers
const config = await readConfigYaml()
if (!Array.isArray(config.custom_providers)) {
config.custom_providers = []
}
config.custom_providers.push({ name, base_url, api_key, model })
await writeConfigYaml(config)
}
// Write to auth.json credential_pool (all providers)
const auth = await loadAuthJson() || { credential_pool: {} }
if (!auth.credential_pool) auth.credential_pool = {}
if (!auth.credential_pool[poolKey]) {
auth.credential_pool[poolKey] = []
}
auth.credential_pool[poolKey].push({
id: `${poolKey}-${Date.now()}`,
label: name,
@@ -559,10 +629,18 @@ fsRoutes.post('/api/hermes/config/providers', async (ctx) => {
access_token: api_key,
last_status: null,
})
await saveAuthJson(auth)
// 3. Auto-switch model to the newly added provider
// Write API key to .env (built-in providers only)
const envMapping = PROVIDER_ENV_MAP[poolKey] || PROVIDER_ENV_MAP[providerKey || '']
if (envMapping) {
await saveEnvValue(envMapping.api_key_env, api_key)
if (envMapping.base_url_env) {
await saveEnvValue(envMapping.base_url_env, base_url)
}
}
// Auto-switch model to the newly added provider
const config2 = await readConfigYaml()
if (typeof config2.model !== 'object' || config2.model === null) {
config2.model = {}
@@ -571,6 +649,13 @@ fsRoutes.post('/api/hermes/config/providers', async (ctx) => {
config2.model.provider = poolKey
await writeConfigYaml(config2)
// Restart gateway to pick up .env and config.yaml changes
try {
await hermesCli.restartGateway()
} catch (e: any) {
console.error('[Provider] Gateway restart failed:', e.message)
}
ctx.body = { success: true }
} catch (err: any) {
ctx.status = 500
+134 -15
View File
@@ -1,6 +1,41 @@
import Router from '@koa/router'
import { createReadStream, existsSync, unlinkSync, readFileSync, writeFileSync, mkdirSync, copyFileSync } from 'fs'
import { mkdir, writeFile } from 'fs/promises'
import { basename, join } from 'path'
import { tmpdir, homedir } from 'os'
import YAML from 'js-yaml'
import * as hermesCli from '../../services/hermes-cli'
const apiServerDefaults = {
enabled: true,
host: '127.0.0.1',
port: 8642,
key: '',
cors_origins: '*',
}
function ensureApiServerConfig(profilePath: string) {
const configPath = join(profilePath, 'config.yaml')
try {
if (!existsSync(configPath)) {
// Profile has no config.yaml — run hermes setup --reset to generate full defaults,
// then inject api_server config (setup itself doesn't add it)
console.log(`[Profile] No config.yaml for ${profilePath}, running setup --reset`)
return { needSetup: true, path: profilePath }
}
const content = readFileSync(configPath, 'utf-8')
const cfg = YAML.load(content) as any || {}
if (!cfg.platforms) cfg.platforms = {}
if (!cfg.platforms.api_server) {
cfg.platforms.api_server = { ...apiServerDefaults }
writeFileSync(configPath, YAML.dump(cfg), 'utf-8')
console.log(`[Profile] Ensured api_server config for: ${profilePath}`)
}
return { needSetup: false, path: profilePath }
} catch { }
return { needSetup: false, path: profilePath }
}
export const profileRoutes = new Router()
// GET /api/profiles - List all profiles
@@ -106,10 +141,10 @@ profileRoutes.put('/api/hermes/profiles/active', async (ctx) => {
}
try {
// 1. Stop gateway (try launchd/systemd first, ignore if unavailable e.g. WSL)
// 1. Stop gateway
try { await hermesCli.stopGateway() } catch { }
// 2. Kill gateway by port if still running (for WSL / background mode)
// 2. Kill gateway by port if still running
try {
const { execSync } = await import('child_process')
const isWin = process.platform === 'win32'
@@ -135,11 +170,34 @@ profileRoutes.put('/api/hermes/profiles/active', async (ctx) => {
const output = await hermesCli.useProfile(name)
await new Promise(r => setTimeout(r, 1000))
// 4. Start gateway — try launchd/systemd first, fall back to background mode
// 4. Ensure api_server config for new profile
try {
await hermesCli.restartGateway()
const detail = await hermesCli.getProfile(name)
console.log(`[Profile] detail.path = ${detail.path}`)
const result = ensureApiServerConfig(detail.path)
if (result?.needSetup) {
// No config.yaml — run setup --reset to create full default config,
// then ensure api_server is present
try { await hermesCli.setupReset() } catch { }
ensureApiServerConfig(detail.path)
}
// Create .env if target has none
const profileEnv = join(detail.path, '.env')
console.log(`[Profile] .env exists: ${existsSync(profileEnv)}, path: ${profileEnv}`)
if (!existsSync(profileEnv)) {
writeFileSync(profileEnv, '# Hermes Agent Environment Configuration\n', 'utf-8')
console.log(`[Profile] Created .env for: ${detail.path}`)
}
} catch (err: any) {
console.error(`[Profile] Ensure config failed:`, err.message)
}
// 5. Start gateway
try {
await hermesCli.startGateway()
console.log('[Profile] Gateway started')
} catch {
// Fallback for WSL / environments without launchd/systemd
// Fallback: background mode (for WSL etc.)
try {
const pid = await hermesCli.startGatewayBackground()
await new Promise(r => setTimeout(r, 3000))
@@ -156,34 +214,95 @@ profileRoutes.put('/api/hermes/profiles/active', async (ctx) => {
}
})
// POST /api/profiles/:name/export - Export profile to archive
// POST /api/profiles/:name/export - Export profile to archive and download
profileRoutes.post('/api/hermes/profiles/:name/export', async (ctx) => {
const { name } = ctx.params
const { output } = ctx.request.body as { output?: string }
const outputPath = join(tmpdir(), `hermes-profile-${name}.tar.gz`)
try {
const result = await hermesCli.exportProfile(name, output)
ctx.body = { success: true, message: result.trim() }
await hermesCli.exportProfile(name, outputPath)
if (!existsSync(outputPath)) {
ctx.status = 500
ctx.body = { error: 'Export file not found' }
return
}
const filename = basename(outputPath)
ctx.set('Content-Disposition', `attachment; filename="${filename}"`)
ctx.set('Content-Type', 'application/gzip')
ctx.body = createReadStream(outputPath)
// Clean up temp file after response ends
ctx.res.on('finish', () => {
try { unlinkSync(outputPath) } catch { }
})
} catch (err: any) {
ctx.status = 500
ctx.body = { error: err.message }
}
})
// POST /api/profiles/import - Import profile from archive
// POST /api/profiles/import - Import profile from uploaded archive
profileRoutes.post('/api/hermes/profiles/import', async (ctx) => {
const { archive, name } = ctx.request.body as { archive?: string; name?: string }
if (!archive) {
const contentType = ctx.get('content-type') || ''
if (!contentType.startsWith('multipart/form-data')) {
ctx.status = 400
ctx.body = { error: 'Missing archive path' }
ctx.body = { error: 'Expected multipart/form-data' }
return
}
const boundary = '--' + contentType.split('boundary=')[1]
if (!boundary || boundary === '--undefined') {
ctx.status = 400
ctx.body = { error: 'Missing boundary' }
return
}
const tmpDir = join(tmpdir(), 'hermes-import')
await mkdir(tmpDir, { recursive: true })
// Read raw body and parse multipart
const chunks: Buffer[] = []
for await (const chunk of ctx.req) chunks.push(chunk)
const body = Buffer.concat(chunks).toString('latin1')
const parts = body.split(boundary).slice(1, -1)
let archivePath = ''
for (const part of parts) {
const headerEnd = part.indexOf('\r\n\r\n')
if (headerEnd === -1) continue
const header = part.substring(0, headerEnd)
const data = part.substring(headerEnd + 4, part.length - 2)
const filenameMatch = header.match(/filename="([^"]+)"/)
if (!filenameMatch) continue
const filename = filenameMatch[1]
const ext = filename.includes('.') ? '.' + filename.split('.').pop() : ''
if (!['.gz', '.tar.gz', '.zip', '.tgz'].includes(ext)) continue
archivePath = join(tmpDir, filename)
await writeFile(archivePath, Buffer.from(data, 'binary'))
break
}
if (!archivePath) {
ctx.status = 400
ctx.body = { error: 'No archive file found (.gz, .zip, .tgz)' }
return
}
try {
const result = await hermesCli.importProfile(archive, name)
const result = await hermesCli.importProfile(archivePath)
// Clean up temp file
try { unlinkSync(archivePath) } catch { }
ctx.body = { success: true, message: result.trim() }
} catch (err: any) {
try { unlinkSync(archivePath) } catch { }
ctx.status = 500
ctx.body = { error: err.message }
}
+17 -5
View File
@@ -1,9 +1,16 @@
import { WebSocketServer } from 'ws'
import type { Server as HttpServer } from 'http'
import { existsSync } from 'fs'
import * as pty from 'node-pty'
import { getToken } from '../../services/auth'
let pty: any = null
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
pty = require('node-pty')
} catch {
console.warn('[Terminal] node-pty failed to load, terminal feature disabled')
}
// ─── Shell detection ────────────────────────────────────────────
function findShell(): string {
@@ -29,7 +36,7 @@ function shellName(shell: string): string {
interface PtySession {
id: string
pty: pty.IPty
pty: { pid: number; onData: (cb: (data: string) => void) => void; onExit: (cb: (e: { exitCode: number }) => void) => void; write: (data: string) => void; kill: (signal?: string) => void; resize: (cols: number, rows: number) => void }
shell: string
pid: number
createdAt: number
@@ -49,7 +56,7 @@ function generateId(): string {
function createSession(shell: string): PtySession {
const id = generateId()
let ptyProcess: pty.IPty
let ptyProcess: PtySession['pty']
try {
ptyProcess = pty.spawn(shell, [], {
name: 'xterm-color',
@@ -75,6 +82,11 @@ function createSession(shell: string): PtySession {
// ─── WebSocket server setup ─────────────────────────────────────
export function setupTerminalWebSocket(httpServer: HttpServer) {
if (!pty) {
console.warn('[Terminal] node-pty not available, skipping terminal WebSocket setup')
return
}
const wss = new WebSocketServer({ noServer: true })
const defaultShell = findShell()
@@ -111,7 +123,7 @@ export function setupTerminalWebSocket(httpServer: HttpServer) {
// ─── PTY output → WebSocket ──────────────────────────────────
function attachPtyOutput(session: PtySession) {
session.pty.onData((data) => {
session.pty.onData((data: string) => {
if (ws.readyState !== ws.OPEN) return
if (conn.activeSessionId === session.id) {
ws.send(data)
@@ -130,7 +142,7 @@ export function setupTerminalWebSocket(httpServer: HttpServer) {
}
})
session.pty.onExit(({ exitCode }) => {
session.pty.onExit(({ exitCode }: { exitCode: number }) => {
conn.outputBuffers.delete(session.id)
if (ws.readyState === ws.OPEN) {
ws.send(JSON.stringify({ type: 'exited', id: session.id, exitCode }))
+6 -5
View File
@@ -3,10 +3,10 @@ import axios from 'axios'
import { readFile, writeFile } from 'fs/promises'
import { chmod } from 'fs/promises'
import { resolve } from 'path'
import { homedir } from 'os'
import { restartGateway } from '../../services/hermes-cli'
import { getActiveEnvPath } from '../../services/hermes-profile'
const envPath = resolve(homedir(), '.hermes/.env')
const envPath = () => getActiveEnvPath()
const ILINK_BASE = 'https://ilinkai.weixin.qq.com'
export const weixinRoutes = new Router()
@@ -84,7 +84,7 @@ weixinRoutes.post('/api/hermes/weixin/save', async (ctx) => {
try {
let raw: string
try {
raw = await readFile(envPath, 'utf-8')
raw = await readFile(envPath(), 'utf-8')
} catch {
raw = ''
}
@@ -124,8 +124,9 @@ weixinRoutes.post('/api/hermes/weixin/save', async (ctx) => {
}
let output = result.join('\n').replace(/\n{3,}/g, '\n\n').replace(/\n+$/, '') + '\n'
await writeFile(envPath, output, 'utf-8')
try { await chmod(envPath, 0o600) } catch { /* ignore */ }
const ep = envPath()
await writeFile(ep, output, 'utf-8')
try { await chmod(ep, 0o600) } catch { /* ignore */ }
await restartGateway()
ctx.body = { success: true }
@@ -507,6 +507,22 @@ export async function exportProfile(name: string, outputPath?: string): Promise<
}
}
/**
* Run hermes setup --non-interactive --reset to generate default config for current profile
*/
export async function setupReset(): Promise<string> {
try {
const { stdout, stderr } = await execFileAsync('hermes', ['setup', '--non-interactive', '--reset'], {
timeout: 30000,
...execOpts,
})
return stdout || stderr
} catch (err: any) {
console.error('[Hermes CLI] setup reset failed:', err.message)
throw new Error(`Failed to reset config: ${err.message}`)
}
}
/**
* Import profile from archive
*/
@@ -0,0 +1,56 @@
import { resolve, join } from 'path'
import { homedir } from 'os'
import { readFileSync, existsSync } from 'fs'
const HERMES_BASE = resolve(homedir(), '.hermes')
/**
* Get the active profile's home directory.
* default → ~/.hermes/
* other → ~/.hermes/profiles/{name}/
*/
export function getActiveProfileDir(): string {
const activeFile = join(HERMES_BASE, 'active_profile')
try {
const name = readFileSync(activeFile, 'utf-8').trim()
if (name && name !== 'default') {
const dir = join(HERMES_BASE, 'profiles', name)
if (existsSync(dir)) return dir
}
} catch { }
return HERMES_BASE
}
/**
* Get the active profile's config.yaml path.
*/
export function getActiveConfigPath(): string {
return join(getActiveProfileDir(), 'config.yaml')
}
/**
* Get the active profile's auth.json path.
*/
export function getActiveAuthPath(): string {
return join(getActiveProfileDir(), 'auth.json')
}
/**
* Get the active profile's .env path.
*/
export function getActiveEnvPath(): string {
return join(getActiveProfileDir(), '.env')
}
/**
* Get the active profile name.
*/
export function getActiveProfileName(): string {
const activeFile = join(HERMES_BASE, 'active_profile')
try {
const name = readFileSync(activeFile, 'utf-8').trim()
return name || 'default'
} catch {
return 'default'
}
}
+8 -14
View File
@@ -43,7 +43,7 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
{
label: 'DeepSeek',
value: 'deepseek',
base_url: 'https://api.deepseek.com/v1',
base_url: 'https://api.deepseek.com',
models: ['deepseek-chat', 'deepseek-reasoner'],
},
{
@@ -53,8 +53,8 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
models: ['glm-5', 'glm-5-turbo', 'glm-4.7', 'glm-4.5', 'glm-4.5-flash'],
},
{
label: 'Kimi Coding Plan',
value: 'kimi-coding',
label: 'Kimi for Coding',
value: 'kimi-for-coding',
base_url: 'https://api.kimi.com/coding/v1',
models: [
'kimi-for-coding',
@@ -65,12 +65,6 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
'kimi-k2-0905-preview',
],
},
{
label: 'Moonshot (Pay-as-you-go)',
value: 'moonshot',
base_url: 'https://api.moonshot.ai/v1',
models: ['kimi-k2.5', 'kimi-k2-thinking', 'kimi-k2-turbo-preview', 'kimi-k2-0905-preview'],
},
{
label: 'xAI',
value: 'xai',
@@ -91,7 +85,7 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
{
label: 'MiniMax',
value: 'minimax',
base_url: 'https://api.minimax.io/anthropic',
base_url: 'https://api.minimax.io/anthropic/v1',
models: ['MiniMax-M2.7', 'MiniMax-M2.5', 'MiniMax-M2.1', 'MiniMax-M2'],
},
{
@@ -137,7 +131,7 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
},
{
label: 'Kilo Code',
value: 'kilocode',
value: 'kilo',
base_url: 'https://api.kilo.ai/api/gateway',
models: [
'anthropic/claude-opus-4.6',
@@ -148,8 +142,8 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
],
},
{
label: 'AI Gateway',
value: 'ai-gateway',
label: 'Vercel AI Gateway',
value: 'vercel',
base_url: 'https://ai-gateway.vercel.sh/v1',
models: [
'anthropic/claude-opus-4.6',
@@ -168,7 +162,7 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [
},
{
label: 'OpenCode Zen',
value: 'opencode-zen',
value: 'opencode',
base_url: 'https://opencode.ai/zen/v1',
models: [
'gpt-5.4-pro',
+4
View File
@@ -2,6 +2,7 @@ import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import type { ProxyOptions } from 'vite'
import { resolve } from 'path'
import pkg from './package.json'
const BACKEND = 'http://127.0.0.1:8648'
@@ -25,6 +26,9 @@ function createProxyConfig(): ProxyOptions {
export default defineConfig({
root: 'packages/client',
plugins: [vue()],
define: {
__APP_VERSION__: JSON.stringify(pkg.version),
},
resolve: {
alias: {
'@': resolve(__dirname, 'packages/client/src'),