@wwkit/huizi 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/agents/huizi.md +4 -2
  2. package/bin/index.js +605 -0
  3. package/docs/huizi/huizi-overview.md +1 -1
  4. package/docs/huizi/memory-loop.md +11 -1
  5. package/docs/huizi/status.md +15 -10
  6. package/package.json +28 -7
  7. package/scripts/postinstall.js +16 -0
  8. package/src/config.js +65 -0
  9. package/src/config.json5 +31 -0
  10. package/src/constants.js +10 -0
  11. package/src/gui/client/dist/assets/index-DVBRRKKn.css +1 -0
  12. package/src/gui/client/dist/assets/index-jOEH0111.js +51 -0
  13. package/src/gui/client/dist/icon.svg +4 -0
  14. package/src/gui/client/dist/index.html +15 -0
  15. package/src/gui/client/dist/manifest.json +11 -0
  16. package/src/gui/client/index.html +14 -0
  17. package/src/gui/client/public/icon.svg +4 -0
  18. package/src/gui/client/public/manifest.json +11 -0
  19. package/src/gui/client/src/App.vue +121 -0
  20. package/src/gui/client/src/api.js +37 -0
  21. package/src/gui/client/src/components/ChatPanel.vue +86 -0
  22. package/src/gui/client/src/components/CronPanel.vue +52 -0
  23. package/src/gui/client/src/components/MessageBubble.vue +46 -0
  24. package/src/gui/client/src/main.js +8 -0
  25. package/src/gui/client/src/style.css +7 -0
  26. package/src/gui/client/vite.config.js +18 -0
  27. package/src/gui/server.js +124 -0
  28. package/src/output/channels/print.js +11 -0
  29. package/src/output/channels/tts.js +50 -0
  30. package/src/output/index.js +42 -0
  31. package/src/pid-file.js +89 -0
  32. package/src/session-lock.js +70 -0
  33. package/src/session-runner.js +98 -0
  34. package/src/todos-store.js +75 -0
  35. package/src/tts.js +79 -0
  36. package/bin/huizi-scheduler.js +0 -166
  37. package/bin/huizi.js +0 -339
@@ -0,0 +1,4 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
2
+ <circle cx="64" cy="64" r="60" fill="#007aff"/>
3
+ <text x="64" y="82" font-size="56" text-anchor="middle" fill="#fff" font-family="PingFang SC, Microsoft YaHei, sans-serif">惠</text>
4
+ </svg>
@@ -0,0 +1,15 @@
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>惠子</title>
7
+ <link rel="manifest" href="/manifest.json" />
8
+ <link rel="icon" href="/icon.svg" type="image/svg+xml" />
9
+ <script type="module" crossorigin src="/assets/index-jOEH0111.js"></script>
10
+ <link rel="stylesheet" crossorigin href="/assets/index-DVBRRKKn.css">
11
+ </head>
12
+ <body>
13
+ <div id="app"></div>
14
+ </body>
15
+ </html>
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "huizi",
3
+ "short_name": "惠子",
4
+ "start_url": "/",
5
+ "display": "standalone",
6
+ "background_color": "#f5f5f7",
7
+ "theme_color": "#007aff",
8
+ "icons": [
9
+ { "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }
10
+ ]
11
+ }
@@ -0,0 +1,14 @@
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>惠子</title>
7
+ <link rel="manifest" href="/manifest.json" />
8
+ <link rel="icon" href="/icon.svg" type="image/svg+xml" />
9
+ </head>
10
+ <body>
11
+ <div id="app"></div>
12
+ <script type="module" src="/src/main.js"></script>
13
+ </body>
14
+ </html>
@@ -0,0 +1,4 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
2
+ <circle cx="64" cy="64" r="60" fill="#007aff"/>
3
+ <text x="64" y="82" font-size="56" text-anchor="middle" fill="#fff" font-family="PingFang SC, Microsoft YaHei, sans-serif">惠</text>
4
+ </svg>
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "huizi",
3
+ "short_name": "惠子",
4
+ "start_url": "/",
5
+ "display": "standalone",
6
+ "background_color": "#f5f5f7",
7
+ "theme_color": "#007aff",
8
+ "icons": [
9
+ { "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }
10
+ ]
11
+ }
@@ -0,0 +1,121 @@
1
+ <script setup>
2
+ import { ref, onMounted } from 'vue'
3
+ import { CircleCheck, CircleClose } from '@element-plus/icons-vue'
4
+ import ChatPanel from './components/ChatPanel.vue'
5
+ import CronPanel from './components/CronPanel.vue'
6
+ import { fetchGreet, fetchHealth, fetchTodos, chat } from './api.js'
7
+
8
+ const messages = ref([])
9
+ const busy = ref(false)
10
+ const notice = ref('')
11
+ const todos = ref([])
12
+ const schedulerRunning = ref(false)
13
+
14
+ const now = () => {
15
+ const d = new Date()
16
+ const p = (n) => String(n).padStart(2, '0')
17
+ return `${p(d.getHours())}:${p(d.getMinutes())}`
18
+ }
19
+
20
+ async function refreshHealth() {
21
+ try {
22
+ const h = await fetchHealth()
23
+ schedulerRunning.value = Boolean(h.schedulerRunning)
24
+ } catch {
25
+ schedulerRunning.value = false
26
+ }
27
+ }
28
+ async function refreshTodos() {
29
+ try { todos.value = await fetchTodos() } catch {}
30
+ }
31
+
32
+ /** 统一会话入口:用户消息与首屏问候都走这里(silent 不显示用户气泡) */
33
+ async function runChat(text, { silent = false } = {}) {
34
+ if (busy.value || !text) return
35
+ if (!silent) messages.value.push({ role: 'user', text, time: now() })
36
+ busy.value = true
37
+ notice.value = ''
38
+ try {
39
+ await chat(text, (status, payload) => {
40
+ if (status === 'done') messages.value.push({ role: 'huizi', text: payload.reply, audio: payload.audio, time: now() })
41
+ else if (status === 'error') notice.value = payload.message
42
+ else if (status === 'expired') notice.value = '任务结果已过期,请重发'
43
+ })
44
+ refreshTodos()
45
+ } catch (e) {
46
+ notice.value = `连接出错:${e.message}`
47
+ } finally {
48
+ busy.value = false
49
+ }
50
+ }
51
+
52
+ function play(audioUrl) {
53
+ new Audio(audioUrl).play()
54
+ }
55
+
56
+ onMounted(async () => {
57
+ refreshHealth()
58
+ refreshTodos()
59
+ // 统一启动机制:首屏自动问候(触发词由服务端供给;显示用户气泡,让用户看到问候已发出)
60
+ const greeting = await fetchGreet()
61
+ if (greeting) runChat(greeting)
62
+ })
63
+ </script>
64
+
65
+ <template>
66
+ <div class="app">
67
+ <header class="header">
68
+ <span class="brand">惠子</span>
69
+ <el-tooltip content="点击刷新" placement="bottom">
70
+ <span class="health" @click="refreshHealth">
71
+ <el-icon :class="schedulerRunning ? 'ok' : 'bad'">
72
+ <component :is="schedulerRunning ? CircleCheck : CircleClose" />
73
+ </el-icon>
74
+ {{ schedulerRunning ? '调度器正常' : '调度器未运行' }}
75
+ </span>
76
+ </el-tooltip>
77
+ </header>
78
+
79
+ <div class="body">
80
+ <aside class="side">
81
+ <CronPanel :todos="todos" />
82
+ </aside>
83
+
84
+ <main class="main">
85
+ <ChatPanel
86
+ :messages="messages"
87
+ :busy="busy"
88
+ :notice="notice"
89
+ @send="(text) => runChat(text)"
90
+ @play="play"
91
+ />
92
+ </main>
93
+ </div>
94
+ </div>
95
+ </template>
96
+
97
+ <style scoped>
98
+ .app {
99
+ height: 100%;
100
+ max-width: 1080px;
101
+ margin: 0 auto;
102
+ display: flex;
103
+ flex-direction: column;
104
+ background: #fff;
105
+ box-shadow: 0 0 24px rgba(0, 0, 0, 0.08);
106
+ }
107
+ .header {
108
+ display: flex;
109
+ align-items: center;
110
+ justify-content: space-between;
111
+ padding: 12px 16px;
112
+ border-bottom: 1px solid #eee;
113
+ }
114
+ .brand { font-size: 17px; font-weight: 600; color: #333; }
115
+ .health { display: inline-flex; align-items: center; gap: 4px; font-size: 12px; color: #888; cursor: pointer; }
116
+ .ok { color: #34c759; }
117
+ .bad { color: #ff3b30; }
118
+ .body { flex: 1; display: flex; min-height: 0; }
119
+ .side { width: 280px; flex-shrink: 0; border-right: 1px solid #eee; overflow-y: auto; }
120
+ .main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
121
+ </style>
@@ -0,0 +1,37 @@
1
+ /** GUI API 封装:/api/* 调用与 chat 异步任务轮询(与旧单页逻辑等价)。 */
2
+
3
+ const json = (r) => r.json()
4
+
5
+ export async function fetchGreet() {
6
+ try {
7
+ const { greeting } = await fetch('/api/greet').then(json)
8
+ return greeting || null
9
+ } catch {
10
+ return null
11
+ }
12
+ }
13
+
14
+ export const fetchHealth = () => fetch('/api/health').then(json)
15
+ export const fetchTodos = () => fetch('/api/todos').then(json)
16
+
17
+ /**
18
+ * 提交一次会话并轮询结果(惠子会话耗时数分钟,异步任务模式)。
19
+ * @param {string} text 消息文本
20
+ * @param {(status: 'submitted'|'done'|'error'|'expired', payload?) => void} onEvent
21
+ */
22
+ export async function chat(text, onEvent) {
23
+ const submit = await fetch('/api/chat', {
24
+ method: 'POST',
25
+ headers: { 'Content-Type': 'application/json' },
26
+ body: JSON.stringify({ text }),
27
+ }).then(json)
28
+ if (submit.error) return onEvent('error', { message: submit.error })
29
+ onEvent('submitted', { taskId: submit.taskId })
30
+ for (;;) {
31
+ await new Promise((r) => setTimeout(r, 5000))
32
+ const t = await fetch(`/api/chat/${submit.taskId}`).then(json)
33
+ if (t.status === 'done') return onEvent('done', t)
34
+ if (t.status === 'error') return onEvent('error', { message: t.error })
35
+ if (t.error === 'task not found') return onEvent('expired')
36
+ }
37
+ }
@@ -0,0 +1,86 @@
1
+ <script setup>
2
+ import { ref, watch, nextTick } from 'vue'
3
+ import { Promotion } from '@element-plus/icons-vue'
4
+ import MessageBubble from './MessageBubble.vue'
5
+
6
+ const props = defineProps({
7
+ messages: { type: Array, default: () => [] }, // [{role,text,audio?,time?}]
8
+ busy: { type: Boolean, default: false }, // 会话进行中
9
+ notice: { type: String, default: '' }, // 提示/错误(如"惠子正在会话中")
10
+ placeholder: { type: String, default: '跟惠子说点什么…' },
11
+ })
12
+ const emit = defineEmits(['send', 'play'])
13
+
14
+ const draft = ref('')
15
+ const listRef = ref(null)
16
+
17
+ function submit() {
18
+ const text = draft.value.trim()
19
+ if (!text || props.busy) return
20
+ draft.value = ''
21
+ emit('send', text)
22
+ }
23
+
24
+ function scrollToBottom() {
25
+ nextTick(() => {
26
+ // EP 2.x el-scrollbar 暴露 wrapRef;同 fallback 到 DOM 查询(防内部实现变动)
27
+ const wrap =
28
+ listRef.value?.wrapRef ??
29
+ listRef.value?.$el?.querySelector('.el-scrollbar__wrap')
30
+ if (wrap) wrap.scrollTop = wrap.scrollHeight
31
+ })
32
+ }
33
+ watch(() => props.messages.length, scrollToBottom)
34
+ </script>
35
+
36
+ <template>
37
+ <section class="chat-panel">
38
+ <el-scrollbar ref="listRef" class="list">
39
+ <el-empty v-if="messages.length === 0 && !busy" description="惠子正在路上,马上打个招呼…" :image-size="72" />
40
+ <MessageBubble
41
+ v-for="(m, i) in messages"
42
+ :key="i"
43
+ :role="m.role"
44
+ :text="m.text"
45
+ :audio="m.audio"
46
+ :time="m.time"
47
+ @play="emit('play', $event)"
48
+ />
49
+ <div v-if="busy" class="thinking">
50
+ <el-avatar :size="32" class="avatar">惠</el-avatar>
51
+ <el-skeleton :rows="1" animated class="skeleton" />
52
+ </div>
53
+ </el-scrollbar>
54
+
55
+ <el-alert v-if="notice" :title="notice" type="warning" :closable="false" class="notice" />
56
+
57
+ <div class="composer">
58
+ <el-input
59
+ v-model="draft"
60
+ :placeholder="placeholder"
61
+ :disabled="busy"
62
+ size="large"
63
+ clearable
64
+ @keyup.enter="submit"
65
+ />
66
+ <el-button
67
+ type="primary"
68
+ size="large"
69
+ :icon="Promotion"
70
+ :loading="busy"
71
+ :disabled="busy || !draft.trim()"
72
+ @click="submit"
73
+ >{{ busy ? '惠子思考中…' : '发送' }}</el-button>
74
+ </div>
75
+ </section>
76
+ </template>
77
+
78
+ <style scoped>
79
+ .chat-panel { flex: 1; display: flex; flex-direction: column; min-height: 0; }
80
+ .list { flex: 1; padding: 16px; min-height: 0; }
81
+ .thinking { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; }
82
+ .avatar { background: #007aff; color: #fff; flex-shrink: 0; }
83
+ .skeleton { flex: 1; max-width: 60%; }
84
+ .notice { margin: 0 16px 8px; }
85
+ .composer { display: flex; gap: 8px; padding: 12px 16px; border-top: 1px solid #eee; }
86
+ </style>
@@ -0,0 +1,52 @@
1
+ <script setup>
2
+ import { computed, ref } from 'vue'
3
+ import { Calendar, ArrowDown, ArrowRight } from '@element-plus/icons-vue'
4
+
5
+ const props = defineProps({
6
+ todos: { type: Array, default: () => [] }, // [{id,title,status,cron_expr,end_date,expired,next}]
7
+ })
8
+ const open = ref(false)
9
+
10
+ function formatNext(iso) {
11
+ if (!iso) return '—'
12
+ const d = new Date(iso)
13
+ const p = (n) => String(n).padStart(2, '0')
14
+ return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
15
+ }
16
+ const headerIcon = computed(() => (open.value ? ArrowDown : ArrowRight))
17
+ </script>
18
+
19
+ <template>
20
+ <section class="cron-panel">
21
+ <div class="head" @click="open = !open">
22
+ <el-icon><Calendar /></el-icon>
23
+ <span class="title">定时计划({{ todos.length }})</span>
24
+ <el-icon class="toggle"><component :is="headerIcon" /></el-icon>
25
+ </div>
26
+ <el-collapse-transition>
27
+ <div v-show="open" class="body">
28
+ <el-empty v-if="todos.length === 0" description="没有在调度的周期任务" :image-size="56" />
29
+ <div v-for="t in todos" :key="t.id" class="row">
30
+ <div class="left">
31
+ <span class="name">{{ t.title }}</span>
32
+ <el-tag size="small" type="info" class="cron">{{ t.cron_expr }}</el-tag>
33
+ <el-tag v-if="t.end_date" size="small" type="warning">有效期至 {{ t.end_date }}</el-tag>
34
+ </div>
35
+ <el-tag v-if="t.expired" size="small" type="danger">已过期,待确认关闭</el-tag>
36
+ <span v-else class="next">下次 {{ formatNext(t.next) }}</span>
37
+ </div>
38
+ </div>
39
+ </el-collapse-transition>
40
+ </section>
41
+ </template>
42
+
43
+ <style scoped>
44
+ .cron-panel { background: #fafafa; height: 100%; display: flex; flex-direction: column; }
45
+ .head { display: flex; align-items: center; gap: 6px; padding: 12px 16px; cursor: pointer; color: #666; font-size: 13px; border-bottom: 1px solid #eee; }
46
+ .title { flex: 1; }
47
+ .body { padding: 0 16px 12px; flex: 1; overflow-y: auto; }
48
+ .row { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 6px 0; border-bottom: 1px dashed #e8e8e8; font-size: 12px; }
49
+ .left { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
50
+ .name { color: #333; font-size: 13px; }
51
+ .next { color: #888; }
52
+ </style>
@@ -0,0 +1,46 @@
1
+ <script setup>
2
+ import { computed } from 'vue'
3
+ import { VideoPlay } from '@element-plus/icons-vue'
4
+
5
+ const props = defineProps({
6
+ role: { type: String, required: true }, // 'user' | 'huizi'
7
+ text: { type: String, required: true },
8
+ audio: { type: String, default: null },
9
+ time: { type: String, default: '' },
10
+ })
11
+ const emit = defineEmits(['play'])
12
+
13
+ const isUser = computed(() => props.role === 'user')
14
+ </script>
15
+
16
+ <template>
17
+ <div class="bubble-row" :class="{ user: isUser }">
18
+ <el-avatar v-if="!isUser" :size="32" class="avatar">惠</el-avatar>
19
+ <div class="bubble" :class="{ user: isUser }">
20
+ <div class="content">{{ text }}</div>
21
+ <div class="meta">
22
+ <span v-if="time" class="time">{{ time }}</span>
23
+ <el-button
24
+ v-if="audio"
25
+ link
26
+ type="primary"
27
+ size="small"
28
+ :icon="VideoPlay"
29
+ @click="emit('play', audio)"
30
+ >播放</el-button>
31
+ </div>
32
+ </div>
33
+ </div>
34
+ </template>
35
+
36
+ <style scoped>
37
+ .bubble-row { display: flex; gap: 8px; margin-bottom: 12px; align-items: flex-start; }
38
+ .bubble-row.user { justify-content: flex-end; }
39
+ .avatar { background: #007aff; color: #fff; flex-shrink: 0; }
40
+ .bubble { max-width: 78%; padding: 10px 14px; border-radius: 14px; background: #f0f0f2; color: #222; }
41
+ .bubble.user { background: #007aff; color: #fff; border-bottom-right-radius: 4px; }
42
+ .bubble:not(.user) { border-bottom-left-radius: 4px; }
43
+ .content { font-size: 14px; line-height: 1.65; white-space: pre-wrap; word-break: break-word; }
44
+ .meta { display: flex; gap: 8px; align-items: center; margin-top: 4px; }
45
+ .time { font-size: 11px; opacity: 0.6; }
46
+ </style>
@@ -0,0 +1,8 @@
1
+ import { createApp } from 'vue'
2
+ import ElementPlus from 'element-plus'
3
+ import zhCn from 'element-plus/es/locale/lang/zh-cn'
4
+ import 'element-plus/dist/index.css'
5
+ import App from './App.vue'
6
+ import './style.css'
7
+
8
+ createApp(App).use(ElementPlus, { locale: zhCn }).mount('#app')
@@ -0,0 +1,7 @@
1
+ /* 全局基础样式(组件样式在各 SFC 的 scoped 块里,避免全局污染) */
2
+ * { box-sizing: border-box; }
3
+ html, body, #app { height: 100%; margin: 0; }
4
+ body {
5
+ font-family: -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
6
+ background: #f5f5f7;
7
+ }
@@ -0,0 +1,18 @@
1
+ import { defineConfig } from 'vite'
2
+ import vue from '@vitejs/plugin-vue'
3
+ import path from 'node:path'
4
+
5
+ // 构建到 src/gui/client/dist(随包提交,Express 静态服务;改动前端须 build 后一并提交)
6
+ export default defineConfig({
7
+ plugins: [vue()],
8
+ build: {
9
+ outDir: 'dist',
10
+ emptyOutDir: true,
11
+ assetsDir: 'assets',
12
+ },
13
+ resolve: {
14
+ alias: {
15
+ '@': path.resolve(import.meta.dirname, 'src'),
16
+ },
17
+ },
18
+ })
@@ -0,0 +1,124 @@
1
+ /**
2
+ * 惠子 GUI 服务(v0.4):Node Express + Vue3 浏览器 UI。
3
+ *
4
+ * 安全边界:只绑 127.0.0.1(写死,绝不出公网)——远程预览走 ssh -L 端口转发。
5
+ * 会话语义:与 cli 完全一致(同一把锁);Express 事件循环内用 execFile 异步执行
6
+ * opencode 会话 + 请求队列(同一时刻一个会话,撞锁返回 409 提示)。
7
+ * 语音:服务端只供给 wav 文件 URL(/api/tts/:id),播放由浏览器 <audio> 完成
8
+ * ——output 架构"ui 通道只供给不越权"的兑现。
9
+ */
10
+ import express from 'express'
11
+ import { existsSync, readFileSync } from 'node:fs'
12
+ import path from 'node:path'
13
+ import { fileURLToPath } from 'node:url'
14
+ import { ttsConfig } from '../config.js'
15
+ import { synthSync } from '../tts.js'
16
+ import { SessionLock } from '../session-lock.js'
17
+ import { TodosStore } from '../todos-store.js'
18
+ import { SessionRunner } from '../session-runner.js'
19
+ import { GUI_PORT, GREET_MSG } from '../constants.js'
20
+
21
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
22
+ // 前端为 Vite 构建产物(src/gui/client/dist,随包提交);源码在 src/gui/client/src
23
+ const PUBLIC_DIR = path.join(__dirname, 'client', 'dist')
24
+
25
+ let dataDir = ''
26
+ let ttsCacheDir = ''
27
+
28
+ export function startGui({ port = GUI_PORT, dataDir: dd }) {
29
+ dataDir = dd
30
+ ttsCacheDir = path.join(dd, 'tts-cache')
31
+ const lock = new SessionLock(dd)
32
+ const store = new TodosStore(dd)
33
+ const runner = new SessionRunner(dd)
34
+ const app = express()
35
+ app.use(express.json())
36
+ app.use(express.static(PUBLIC_DIR))
37
+
38
+ // ─── chat 异步任务模式:POST 立即返回 taskId,前端轮询 GET /api/chat/:id ───
39
+ // 惠子会话耗时 5-10 分钟,同步等待式 HTTP 必然客户端超时——改为任务提交+轮询。
40
+ let taskSeq = 0
41
+ const tasks = new Map() // id → { status: 'running'|'done'|'error', reply, audio, error }
42
+
43
+ app.post('/api/chat', async (req, res) => {
44
+ const text = String(req.body?.text ?? '').trim()
45
+ if (!text) return res.status(400).json({ error: 'text is required' })
46
+ // 与 cli 同一把会话锁(SessionLock 类,陈旧自愈内建)
47
+ if (!lock.acquire()) {
48
+ return res.status(409).json({ error: '惠子正在会话中,请稍候' })
49
+ }
50
+ const id = `chat-${Date.now()}-${++taskSeq}`
51
+ tasks.set(id, { status: 'running' })
52
+ // 会话在后台执行;锁由任务结束时释放
53
+ runner.runAsync(text, (err, out) => {
54
+ if (err) {
55
+ tasks.set(id, { status: 'error', error: err.message })
56
+ } else {
57
+ let audio = null
58
+ const cfg = ttsConfig()
59
+ if (cfg.enabled && cfg.api_key && !cfg.api_key.includes('{env:')) {
60
+ const wav = synthSync(out.reply)
61
+ if (wav) audio = `/api/tts/${path.basename(wav)}`
62
+ }
63
+ tasks.set(id, { status: 'done', reply: out.reply, audio })
64
+ }
65
+ lock.release()
66
+ // 任务结果保留 30 分钟供轮询,之后清理
67
+ setTimeout(() => tasks.delete(id), 30 * 60 * 1000).unref()
68
+ })
69
+ res.json({ taskId: id })
70
+ })
71
+
72
+ // ─── GET /api/chat/:id:轮询任务结果 ───
73
+ app.get('/api/chat/:id', (req, res) => {
74
+ const t = tasks.get(req.params.id)
75
+ if (!t) return res.status(404).json({ error: 'task not found' })
76
+ res.json(t)
77
+ })
78
+
79
+ // ─── GET /api/todos:cron 计划面板(只读视图) ───
80
+ app.get('/api/todos', (req, res) => {
81
+ res.json(store.schedulableView())
82
+ })
83
+
84
+ // ─── GET /api/tts/:file:音频文件下发(浏览器播放) ───
85
+ app.get('/api/tts/:file', (req, res) => {
86
+ const file = path.basename(req.params.file) // 防路径穿越
87
+ const full = path.join(ttsCacheDir, file)
88
+ if (!existsSync(full)) return res.status(404).end()
89
+ res.setHeader('Content-Type', 'audio/wav')
90
+ res.sendFile(full)
91
+ })
92
+
93
+ // ─── GET /api/greet:问候启动触发词(与 cli 同一事实源,前端不硬编码) ───
94
+ app.get('/api/greet', (req, res) => {
95
+ res.json({ greeting: GREET_MSG })
96
+ })
97
+
98
+ // ─── GET /api/health:调度器状态 ───
99
+ app.get('/api/health', (req, res) => {
100
+ const pidFile = path.join(dataDir, 'scheduler.pid')
101
+ let schedulerRunning = false
102
+ if (existsSync(pidFile)) {
103
+ try {
104
+ process.kill(Number(readFileSync(pidFile, 'utf8').trim()), 0)
105
+ schedulerRunning = true
106
+ } catch {}
107
+ }
108
+ res.json({ schedulerRunning })
109
+ })
110
+
111
+ const server = app.listen(port, '127.0.0.1', () => {
112
+ console.log(`惠子 GUI:http://127.0.0.1:${port}(仅本机;远程预览用 ssh -L ${port}:localhost:${port})`)
113
+ })
114
+
115
+ // GUI 停止时终止正在运行的会话子进程(防遗留会话占用锁,导致新页面问候卡住)
116
+ // 返回 shutdown 供 bin/index.js 的 runGui 在收到 SIGTERM/SIGINT 时调用
117
+ const shutdown = () => {
118
+ runner.killActive()
119
+ server.close()
120
+ }
121
+ return { server, shutdown }
122
+ }
123
+
124
+
@@ -0,0 +1,11 @@
1
+ /** print 通道:回复直印 stdout——兜底通道,永不缺席(终端可看、日志可查)。 */
2
+ export const printChannel = {
3
+ name: 'print',
4
+ priority: 10,
5
+ available() {
6
+ return true
7
+ },
8
+ deliver(ctx) {
9
+ process.stdout.write(ctx.reply + '\n')
10
+ },
11
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * tts 通道:回复合成语音并本地播放(v0.2)。
3
+ * available 自判三条件:配置开启 + api_key 有效 + TTY 交互且有播放命令
4
+ * (cron 敲门旁无人,声音该走 dingtalk 通道,v0.3)。
5
+ * 合成复用 src/tts.js 的 synthSync(含缓存去重);失败提示一次,纯文字兜底由 print 通道承担。
6
+ */
7
+ import { spawnSync } from 'node:child_process'
8
+ import { detectPlayer, synthSync } from '../../tts.js'
9
+ import { ttsConfig } from '../../config.js'
10
+
11
+ function playLocal(wavFile) {
12
+ const player = detectPlayer()
13
+ if (!player) return false
14
+ if (player === 'powershell') {
15
+ spawnSync(
16
+ 'powershell',
17
+ ['-Command', `(New-Object System.Media.SoundPlayer '${wavFile}').PlaySync()`],
18
+ { timeout: 120_000 },
19
+ )
20
+ return true
21
+ }
22
+ if (player === 'ffplay') {
23
+ spawnSync('ffplay', ['-nodisp', '-autoexit', '-loglevel', 'quiet', wavFile], { timeout: 120_000 })
24
+ return true
25
+ }
26
+ spawnSync(player, [wavFile], { timeout: 120_000 })
27
+ return true
28
+ }
29
+
30
+ export const ttsChannel = {
31
+ name: 'tts',
32
+ priority: 20,
33
+ available(ctx) {
34
+ const cfg = ttsConfig(ctx.config)
35
+ if (!cfg.enabled) return false
36
+ if (cfg.channel === 'off') return false
37
+ if (!cfg.api_key || cfg.api_key.includes('{env:')) return false
38
+ if (cfg.channel === 'speaker') return detectPlayer() !== null
39
+ // auto:TTY 交互(用户在设备旁)且有播放命令;knock 场景不出声
40
+ return ctx.tty && ctx.source === 'interactive' && detectPlayer() !== null
41
+ },
42
+ deliver(ctx) {
43
+ const wav = synthSync(ctx.reply, ctx.config)
44
+ if (!wav) {
45
+ process.stderr.write('(语音合成不可用:检查 tts.api_key 或网络,本次纯文字)\n')
46
+ return
47
+ }
48
+ playLocal(wav)
49
+ },
50
+ }