@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
package/agents/huizi.md CHANGED
@@ -74,6 +74,7 @@ summaries.jsonl 对话摘要池——每行一条 {"date","level","summary"},l
74
74
  "priority": "high", // high / normal / low
75
75
  "waiting_on": null, // followup 等待回复时填:"老板的回复"
76
76
  "cron_expr": null, // recurring 的提醒节奏,标准五段 cron(见下方「cron 写入规则」);其余 kind 为 null
77
+ "end_date": null, // recurring 专属:提醒有效期至(YYYY-MM-DD 本地时间,含当日);null=永久有效
77
78
  "metric_label": null, // recurring 可选量化字段名:"练习分钟数"
78
79
  "last_reminded": "2026-11-24",// 上次提醒日期(防重复打扰)
79
80
  "log": [ // 执行/跟进历史,recurring 打卡记录也在此追加
@@ -108,7 +109,8 @@ summaries.jsonl 对话摘要池——每行一条 {"date","level","summary"},l
108
109
  - **现算状态**:统计每个 recurring 的近 7 天执行次数、连续未做天数;数一遍 open/waiting 的未完成事项
109
110
  - **扫描该提醒的**:凡 status ∈ {open, waiting} 且"今天该提"的,主动提起(paused 不扫描)。判据按 kind:
110
111
  - `once`:due_date 临近(≤2 天)或已过期
111
- - `recurring`:cron_expr 到点(按「cron 写入规则」的五段语义,对照本地时间判断今天/此刻是否命中),且今天尚未记录打卡
112
+ - `recurring`:cron_expr 到点(按「cron 写入规则」的五段语义,对照本地时间判断今天/此刻是否命中),且今天尚未记录打卡,且未过有效期(end_date 为空或 今天 ≤ end_date)
113
+ - **已过有效期的临时 recurring**(今天 > end_date 且 status 仍 open/waiting):不再提醒,但主动向用户确认一次:"那个临时提醒到期了,要关掉吗?"用户确认后才置 dropped,不擅自关闭
112
114
  - `followup`:距 last_reminded ≥ 1 天(waiting 状态只轻问一句"有动静了吗",不催)
113
115
 
114
116
  **首次使用/冷启动**(todos.jsonl 与 summaries.jsonl 均读不到或为空):先自我介绍一句——你能帮用户记事(一次性待办)、跟事(状态跟进)、养习惯(周期打卡),用户随时说"帮我记着 X / 提醒我 X / 跟进 X"即可——然后邀请用户交给你第一件事,不干等。此时尚未创建任何文件,等用户交付第一个事项时再一并创建。
@@ -134,7 +136,7 @@ summaries.jsonl 对话摘要池——每行一条 {"date","level","summary"},l
134
136
 
135
137
  ### 3. 用户交付新事项(创建 todo)
136
138
 
137
- 用户说"帮我记着 X / 提醒我 X / 跟进 X"时,用 bash 追加一条新 todo 并回显:"记下啦,周五前把方案发给老板,我会记着的。"判断 kind:一次性的→once;"每天/每周"这类周期性的→recurring(按「cron 写入规则」转换并填 cron_expr);"等某人回复/盯着某进展"→followup(补 waiting_on)。追加前若文件不存在,先创建目录与空文件。定时器由常驻调度器自动监听文件生效,你只管把 cron_expr 写对。
139
+ 用户说"帮我记着 X / 提醒我 X / 跟进 X"时,用 bash 追加一条新 todo 并回显:"记下啦,周五前把方案发给老板,我会记着的。"判断 kind:一次性的→once;"每天/每周"这类周期性的→recurring(按「cron 写入规则」转换并填 cron_expr);"等某人回复/盯着某进展"→followup(补 waiting_on)。**周期性任务若带时间限定("仅今天""到周五为止")→ 填 end_date(提醒有效期,含当日);无限期习惯则 end_date 留 null**。追加前若文件不存在,先创建目录与空文件。定时器由常驻调度器自动监听文件生效,你只管把 cron_expr 写对。
138
140
 
139
141
  ### 4. 用户查询(读事实)
140
142
 
package/bin/index.js ADDED
@@ -0,0 +1,605 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * huizi —— 惠子 agent 统一入口(bin/ 仅 index.js,对齐其他子工程)。
4
+ *
5
+ * 形态:交互消息与定时敲门是同一动作(敲门 = 模拟用户发一条消息)。
6
+ * 调度器(--scheduler)与 CLI 同入口分派:`node bin --scheduler` 启动常驻调度器。
7
+ *
8
+ * 用法:
9
+ * huizi 问候启动:发起会话(惠子按规程打招呼/加载记忆)
10
+ * huizi <message> 模拟用户发消息给惠子(交互与定时共用)
11
+ * huizi --knock 敲门模式:让惠子按规程扫描今天该提醒的事项
12
+ * huizi --knock-todo <id> 精确敲门:只提醒指定 todo(调度器子进程用,豁免 ensureScheduler)
13
+ * huizi --scheduler 前台启动常驻定时器调度器(node-cron,Ctrl+C 退出)
14
+ * huizi --gui-start|--gui-stop|--gui-status|--gui-restart|--gui-logs
15
+ * GUI 服务管理(后台启动/停止/状态/重启/日志)
16
+ * huizi --scheduler-status 查看定时器调度器状态与各任务下次提醒时间
17
+ * huizi --status 免会话速查:直接读 todos.jsonl 打印活跃清单(不启动 LLM 会话)
18
+ *
19
+ * 目录机制(独立包设计):
20
+ * - 数据目录 = XDG ~/.config/huizi/(getXdgConfigDir,任意位置启动同一份记忆)
21
+ * - agent 定义 = 包内 agents/huizi.md,启动时 hash 对比同步到 <数据目录>/.opencode/agents/
22
+ * (包内是唯一事实源;同步前备份旧版为 .huizi-agent.bak)
23
+ * - 会话 cwd = 数据目录 → opencode 项目级发现 .opencode/agents/huizi.md,无需 OPENCODE_CONFIG_DIR
24
+ * - 首次启动若存在旧目录 ~/.config/harness/agents/huizi/,自动迁移数据
25
+ *
26
+ * 会话锁:O_EXCL 原子创建;敲门撞锁排队 pending.jsonl,绝不并发写坏 JSONL。
27
+ */
28
+ import { spawn, spawnSync } from 'node:child_process'
29
+ import { createHash } from 'node:crypto'
30
+ import {
31
+ closeSync, cpSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, watchFile, writeFileSync,
32
+ } from 'node:fs'
33
+ import path from 'node:path'
34
+ import { fileURLToPath } from 'node:url'
35
+ import { getXdgConfigDir } from '@wwkit/shared'
36
+ import { getConfigPath, mergeBuiltinConfig, loadConfig } from '../src/config.js'
37
+ import { deliver } from '../src/output/index.js'
38
+ import { SessionLock } from '../src/session-lock.js'
39
+ import { TodosStore } from '../src/todos-store.js'
40
+ import { SessionRunner } from '../src/session-runner.js'
41
+ import { SCHEDULER_START_WAIT_MS, GUI_PORT, GREET_MSG } from '../src/constants.js'
42
+ import { PidFile } from '../src/pid-file.js'
43
+ import cron from 'node-cron'
44
+ import { CronExpressionParser } from 'cron-parser'
45
+
46
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
47
+ const PKG_ROOT = path.resolve(__dirname, '..')
48
+ const DATA_DIR = getXdgConfigDir('huizi')
49
+ const AGENT_SRC = path.join(PKG_ROOT, 'agents', 'huizi.md')
50
+ const AGENT_DIR = path.join(DATA_DIR, '.opencode', 'agents')
51
+ const AGENT_DST = path.join(AGENT_DIR, 'huizi.md')
52
+ const AGENT_BAK = path.join(AGENT_DIR, '.huizi-agent.bak')
53
+ const LEGACY_DIR = path.join(getXdgConfigDir('harness'), 'agents', 'huizi')
54
+ const LOCK_FILE = path.join(DATA_DIR, 'session.lock')
55
+ const PENDING_FILE = path.join(DATA_DIR, 'pending.jsonl')
56
+ const SCHED_PID_FILE = path.join(DATA_DIR, 'scheduler.pid')
57
+ const GUI_LOG_FILE = path.join(DATA_DIR, 'gui.log')
58
+ const guiPid = new PidFile(DATA_DIR, 'gui')
59
+ const SELF = path.resolve(__dirname, 'index.js') // 调度器/后台 GUI spawn 自身(--knock-todo / --gui)
60
+ const TODOS_FILE = path.join(DATA_DIR, 'todos.jsonl')
61
+ const KNOCK_LOG = path.join(DATA_DIR, 'knock.log')
62
+ const RELOAD_DEBOUNCE_MS = 2000
63
+
64
+ const KNOCK_MSG = '到点了,请按你的记忆操作规程扫描今天该提醒我的事项。若有排队消息(pending.jsonl),一并处理。'
65
+
66
+ // ─── 初始化:数据迁移 + agent 定义同步 ───
67
+
68
+ function migrateLegacyData() {
69
+ // 旧 harness 命名空间数据一次性搬移(新目录已有数据则不动)
70
+ if (!existsSync(LEGACY_DIR)) return
71
+ const hasNewData = ['todos.jsonl', 'summaries.jsonl', 'archive.jsonl'].some((f) =>
72
+ existsSync(path.join(DATA_DIR, f)),
73
+ )
74
+ if (hasNewData) return
75
+ mkdirSync(DATA_DIR, { recursive: true })
76
+ for (const f of ['todos.jsonl', 'summaries.jsonl', 'archive.jsonl', 'pending.jsonl', 'knock.log']) {
77
+ const src = path.join(LEGACY_DIR, f)
78
+ if (existsSync(src)) renameSync(src, path.join(DATA_DIR, f))
79
+ }
80
+ console.error(`(已迁移旧数据:${LEGACY_DIR} → ${DATA_DIR})`)
81
+ }
82
+
83
+ function syncAgentDef() {
84
+ const src = readFileSync(AGENT_SRC)
85
+ const srcHash = createHash('sha256').update(src).digest('hex')
86
+ if (existsSync(AGENT_DST)) {
87
+ const dstHash = createHash('sha256').update(readFileSync(AGENT_DST)).digest('hex')
88
+ if (dstHash === srcHash) return
89
+ cpSync(AGENT_DST, AGENT_BAK) // 用户可能本地改过,留备份
90
+ }
91
+ mkdirSync(AGENT_DIR, { recursive: true })
92
+ writeFileSync(AGENT_DST, src)
93
+ // opencode 项目级发现需要 config 文件激活 .opencode/ 目录
94
+ const cfg = path.join(DATA_DIR, '.opencode', 'opencode.jsonc')
95
+ if (!existsSync(cfg)) {
96
+ writeFileSync(cfg, '{\n "$schema": "https://opencode.ai/config.json",\n}\n')
97
+ }
98
+ }
99
+
100
+ function initOnce() {
101
+ migrateLegacyData()
102
+ syncAgentDef()
103
+ // 配置兜底:postinstall 可能被跳过(如 monorepo 内联安装),首次调用补齐 config
104
+ try {
105
+ if (mergeBuiltinConfig()) {
106
+ console.error(`(配置已初始化/补齐:${getConfigPath()})`)
107
+ }
108
+ } catch {
109
+ // 配置失败不阻断会话——TTS 等功能读不到配置会各自降级
110
+ }
111
+ }
112
+
113
+ /** 显式升级:config 补齐(保用户值)+ agent 定义强制同步(包内为准) */
114
+ function runUpgrade() {
115
+ let changed = false
116
+ try {
117
+ if (mergeBuiltinConfig()) {
118
+ console.log(`✓ 配置已补齐(保留你的已有值):${getConfigPath()}`)
119
+ changed = true
120
+ } else {
121
+ console.log(`✓ 配置无变化:${getConfigPath()}`)
122
+ }
123
+ } catch (e) {
124
+ console.error(`✗ 配置升级失败:${e.message}`)
125
+ return 1
126
+ }
127
+ try {
128
+ syncAgentDef()
129
+ console.log(`✓ agent 定义已同步(包内为准):${AGENT_DST}`)
130
+ changed = true
131
+ } catch (e) {
132
+ console.error(`✗ agent 定义同步失败:${e.message}`)
133
+ return 1
134
+ }
135
+ if (changed) console.log('升级完成。')
136
+ return 0
137
+ }
138
+
139
+ // ─── 参数解析 ───
140
+
141
+ function parseArgs(argv) {
142
+ const args = argv.slice(2)
143
+ if (args.includes('--scheduler')) return { mode: 'scheduler' }
144
+ if (args.includes('--knock')) return { mode: 'knock' }
145
+ if (args.includes('--knock-todo')) {
146
+ const idx = args.indexOf('--knock-todo')
147
+ const id = args[idx + 1]
148
+ return id && !id.startsWith('-') ? { mode: 'knock-todo', id } : { mode: 'help' }
149
+ }
150
+ if (args.includes('--upgrade')) return { mode: 'upgrade' }
151
+ if (args.includes('--gui')) return { mode: 'gui' }
152
+ if (args.includes('--gui-start')) return { mode: 'gui-start' }
153
+ if (args.includes('--gui-stop')) return { mode: 'gui-stop' }
154
+ if (args.includes('--gui-status')) return { mode: 'gui-status' }
155
+ if (args.includes('--gui-restart')) return { mode: 'gui-restart' }
156
+ if (args.includes('--gui-logs')) {
157
+ const idx = args.indexOf('--gui-logs')
158
+ const n = Number(args[idx + 1])
159
+ return { mode: 'gui-logs', lines: Number.isInteger(n) && n > 0 ? n : 50 }
160
+ }
161
+ if (args.includes('--scheduler-status')) return { mode: 'scheduler-status' }
162
+ if (args.includes('--status')) return { mode: 'status' }
163
+ if (args.includes('--help') || args.includes('-h')) return { mode: 'help' }
164
+ const msg = args.filter((a) => !a.startsWith('-')).join(' ').trim()
165
+ // 无参 = 问候启动(统一机制:与 GUI 首屏同一行为——发起一次会话,惠子按规程打招呼)
166
+ return msg ? { mode: 'message', msg } : { mode: 'greet' }
167
+ }
168
+
169
+ // ─── 会话锁:SessionLock 类(cli/gui/knock 共享,见 src/session-lock.js) ───
170
+ const sessionLock = new SessionLock(DATA_DIR)
171
+
172
+ // ─── 敲门排队 ───
173
+
174
+ function enqueuePending(msg) {
175
+ mkdirSync(DATA_DIR, { recursive: true })
176
+ const line = JSON.stringify({ msg, ts: new Date().toISOString() }) + '\n'
177
+ writeFileSync(PENDING_FILE, line, { flag: 'a' })
178
+ }
179
+
180
+ // ─── 调度器保障 ───
181
+
182
+ const todosStore = new TodosStore(DATA_DIR)
183
+
184
+ function schedulerAlive() {
185
+ if (!existsSync(SCHED_PID_FILE)) return false
186
+ try {
187
+ const pid = Number(readFileSync(SCHED_PID_FILE, 'utf8').trim())
188
+ process.kill(pid, 0)
189
+ return true
190
+ } catch {
191
+ return false
192
+ }
193
+ }
194
+
195
+ function ensureScheduler() {
196
+ if (schedulerAlive()) return
197
+ rmSync(SCHED_PID_FILE, { force: true })
198
+ const child = spawn(process.execPath, [SELF, '--scheduler'], { stdio: 'ignore', detached: true })
199
+ child.unref()
200
+ const deadline = Date.now() + SCHEDULER_START_WAIT_MS
201
+ while (Date.now() < deadline) {
202
+ if (schedulerAlive()) {
203
+ console.error(`(定时器调度器未运行,已自动拉起 pid=${readFileSync(SCHED_PID_FILE, 'utf8').trim()})`)
204
+ return
205
+ }
206
+ spawnSync('sleep', ['0.2'])
207
+ }
208
+ console.error(
209
+ '定时器启动失败:惠子的提醒功能不可用。请手工运行 huizi --scheduler 或用 pm2 守护(pm2 start bin/index.js --name huizi -- --scheduler && pm2 save && pm2 startup)',
210
+ )
211
+ process.exit(1)
212
+ }
213
+
214
+ function runSchedulerStatus() {
215
+ const alive = schedulerAlive()
216
+ const pid = alive ? readFileSync(SCHED_PID_FILE, 'utf8').trim() : null
217
+ console.log(`调度器:${alive ? `运行中(pid ${pid})` : '未运行'}`)
218
+ let count = 0
219
+ for (const t of todosStore.schedulableView()) {
220
+ if (t.expired) {
221
+ console.log(`- [${t.status}] ${t.title}(${t.id})cron=${t.cron_expr} 已过有效期(end_date=${t.end_date}),待确认关闭`)
222
+ continue
223
+ }
224
+ count++
225
+ const end = t.end_date ? ` 有效期至 ${t.end_date}(含当日)` : ''
226
+ console.log(`- [${t.status}] ${t.title}(${t.id})cron=${t.cron_expr} 下次=${t.next ?? '(表达式非法)'}${end}`)
227
+ }
228
+ if (count === 0) console.log('(没有在调度的周期任务)')
229
+ return 0
230
+ }
231
+
232
+ // ─── 模式实现 ───
233
+
234
+ function pm2GuardsScheduler() {
235
+ try {
236
+ const out = spawnSync('pm2', ['jlist'], { encoding: 'utf8', timeout: 5000 })
237
+ if (out.status !== 0 || !out.stdout) return false
238
+ const list = JSON.parse(out.stdout)
239
+ return Array.isArray(list) && list.some((p) => p.name === 'huizi')
240
+ } catch {
241
+ return false
242
+ }
243
+ }
244
+
245
+ function runStatus() {
246
+ if (!existsSync(path.join(DATA_DIR, 'todos.jsonl'))) {
247
+ console.log('(惠子还没有任何记录——数据目录不存在,先和她说句话吧)')
248
+ return 0
249
+ }
250
+ const actives = todosStore.active()
251
+ if (actives.length === 0) {
252
+ console.log('(没有在跟进的事)')
253
+ return 0
254
+ }
255
+ console.log(`惠子正在跟进 ${actives.length} 件事:`)
256
+ for (const t of actives) {
257
+ const due = t.due_date ? `,期限 ${t.due_date}` : ''
258
+ const wait = t.waiting_on ? `,在等:${t.waiting_on}` : ''
259
+ const cron = t.cron_expr ? `,节奏 ${t.cron_expr}` : ''
260
+ console.log(`- [${t.kind}/${t.status}] ${t.title}${due}${wait}${cron}`)
261
+ }
262
+ if (!pm2GuardsScheduler()) {
263
+ console.log(
264
+ '\n提示:定时器未用 pm2 守护,若你长时间不与惠子交互,期间的定时提醒可能丢失。建议:pm2 start bin/index.js --name huizi -- --scheduler && pm2 save && pm2 startup',
265
+ )
266
+ }
267
+ return 0
268
+ }
269
+
270
+ function runSession(msg, { source = 'interactive' } = {}) {
271
+ if (!sessionLock.acquire()) {
272
+ if (source === 'knock') {
273
+ enqueuePending('定时提醒(排队):请按规程扫描今天该提醒的事项')
274
+ console.log('惠子正在会话中,敲门消息已排队(pending.jsonl),下轮会话处理')
275
+ return 0
276
+ }
277
+ console.error('惠子正在会话中,请稍后再试')
278
+ return 1
279
+ }
280
+ const runner = new SessionRunner(DATA_DIR)
281
+ try {
282
+ const { code, reply, stdout } = runner.runSync(msg)
283
+ // 输出通道架构:会话输出由 deliver 按通道分派(print 兜底,tts/dingtalk/ui 叠加)
284
+ if (code === 0 && reply) {
285
+ deliver(reply, { source, tty: Boolean(process.stdout.isTTY), config: loadConfig() })
286
+ } else if (stdout) {
287
+ process.stdout.write(stdout) // 失败会话:保留原始输出供排障
288
+ }
289
+ return code
290
+ } catch (e) {
291
+ console.error(`启动 opencode 失败:${e.message}`)
292
+ return 1
293
+ } finally {
294
+ sessionLock.release()
295
+ }
296
+ }
297
+
298
+ function guiPort() {
299
+ return Number(process.env.HUIZI_GUI_PORT) || GUI_PORT
300
+ }
301
+
302
+ function runGui() {
303
+ // GUI 常驻服务:只绑 127.0.0.1(写死);远程预览用 ssh -L
304
+ // 写 pid 文件供 --gui-status/stop 管理;退出时清理
305
+ const port = guiPort()
306
+ if (!guiPid.write({ port })) {
307
+ const cur = guiPid.read()
308
+ console.error(`GUI 已在运行(pid ${cur?.pid},端口 ${cur?.port})`)
309
+ return 0
310
+ }
311
+ const cleanup = () => guiPid.remove()
312
+ process.on('exit', cleanup)
313
+ // 动态 import 完成前不退出——由 startGui 的 listen 回调保持进程存活
314
+ import('../src/gui/server.js')
315
+ .then(({ startGui }) => {
316
+ const { shutdown } = startGui({ port, dataDir: DATA_DIR })
317
+ // SIGTERM/SIGINT:先终止会话子进程(防遗留占用锁),再清理 pid 文件退出
318
+ const onSignal = () => {
319
+ shutdown()
320
+ cleanup()
321
+ process.exit(0)
322
+ }
323
+ process.on('SIGINT', onSignal)
324
+ process.on('SIGTERM', onSignal)
325
+ })
326
+ .catch((e) => {
327
+ cleanup()
328
+ console.error(`GUI 启动失败:${e.message}`)
329
+ process.exit(1)
330
+ })
331
+ return 'HOLD' // main 见此值不 process.exit,让事件循环接管
332
+ }
333
+
334
+ /** 探测 GUI 就绪(GET /api/health,最多 waitMs) */
335
+ async function waitGuiReady(port, waitMs = SCHEDULER_START_WAIT_MS * 2) {
336
+ const deadline = Date.now() + waitMs
337
+ while (Date.now() < deadline) {
338
+ try {
339
+ const r = await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(800) })
340
+ if (r.ok) return true
341
+ } catch {}
342
+ await new Promise((r) => setTimeout(r, 200))
343
+ }
344
+ return false
345
+ }
346
+
347
+ async function runGuiStart() {
348
+ const cur = guiPid.read()
349
+ if (guiPid.alive()) {
350
+ console.log(`GUI 已在运行(pid ${cur.pid},端口 ${cur.port}):http://127.0.0.1:${cur.port}`)
351
+ return 0
352
+ }
353
+ const port = guiPort()
354
+ mkdirSync(DATA_DIR, { recursive: true })
355
+ const { openSync: openLog, closeSync: closeLog } = await import('node:fs')
356
+ const logFd = openLog(GUI_LOG_FILE, 'a')
357
+ const child = spawn(process.execPath, [SELF, '--gui'], {
358
+ detached: true,
359
+ stdio: ['ignore', logFd, logFd],
360
+ env: { ...process.env, HUIZI_GUI_PORT: String(port) },
361
+ })
362
+ child.unref()
363
+ closeLog(logFd)
364
+ if (await waitGuiReady(port)) {
365
+ console.log(`GUI 已启动:http://127.0.0.1:${port}(日志 ${GUI_LOG_FILE})`)
366
+ return 0
367
+ }
368
+ console.error(`GUI 启动失败或超时:请查看日志 ${GUI_LOG_FILE}(端口 ${port} 可能被占用,可用 HUIZI_GUI_PORT 改端口)`)
369
+ return 1
370
+ }
371
+
372
+ async function runGuiStop() {
373
+ const meta = guiPid.read()
374
+ if (!meta || !guiPid.alive()) {
375
+ guiPid.remove()
376
+ console.log('GUI 未运行')
377
+ return 0
378
+ }
379
+ if (!PidFile.stopPid(meta.pid)) {
380
+ console.error(`停止 GUI 失败(pid ${meta.pid})`)
381
+ return 1
382
+ }
383
+ const exited = await PidFile.waitExit(meta.pid)
384
+ guiPid.remove()
385
+ if (!exited) {
386
+ console.error(`GUI 未在超时内退出(pid ${meta.pid} 可能仍在运行)`)
387
+ return 1
388
+ }
389
+ console.log(`GUI 已停止(pid ${meta.pid})`)
390
+ return 0
391
+ }
392
+
393
+ async function runGuiStatus() {
394
+ const meta = guiPid.read()
395
+ if (!meta || !guiPid.alive()) {
396
+ if (meta) guiPid.remove() // 陈旧 pid 清理
397
+ console.log(`GUI 未运行(默认端口 ${guiPort()};启动:huizi --gui-start)`)
398
+ return 0
399
+ }
400
+ let healthy = false
401
+ try {
402
+ const r = await fetch(`http://127.0.0.1:${meta.port}/api/health`, { signal: AbortSignal.timeout(1500) })
403
+ healthy = r.ok
404
+ } catch {}
405
+ console.log(`GUI 运行中:pid ${meta.pid},端口 ${meta.port},health ${healthy ? '正常' : '无响应'}`)
406
+ console.log(`地址:http://127.0.0.1:${meta.port}`)
407
+ if (schedulerAlive()) {
408
+ console.log(`调度器:运行中(pid ${readFileSync(SCHED_PID_FILE, 'utf8').trim()})`)
409
+ } else {
410
+ console.log('调度器:未运行(提示:huizi --status 会自动拉起)')
411
+ }
412
+ return 0
413
+ }
414
+
415
+ async function runGuiRestart() {
416
+ const stopCode = await runGuiStop()
417
+ if (stopCode !== 0) return stopCode
418
+ return runGuiStart()
419
+ }
420
+
421
+ function runGuiLogs(lines) {
422
+ if (!existsSync(GUI_LOG_FILE)) {
423
+ console.log(`(无日志文件:${GUI_LOG_FILE}——前台模式不落盘,请用 --gui-start 启动)`)
424
+ return 0
425
+ }
426
+ const all = readFileSync(GUI_LOG_FILE, 'utf8').split('\n')
427
+ console.log(all.slice(Math.max(0, all.length - lines - 1)).join('\n').trimEnd())
428
+ return 0
429
+ }
430
+
431
+ // ─── 常驻调度器(--scheduler 分派;原 bin/huizi-scheduler.js 合并于此) ───
432
+
433
+ let schedTasks = [] // node-cron ScheduledTask[]
434
+
435
+ function schedIsAlive(pid) {
436
+ try {
437
+ process.kill(pid, 0)
438
+ return true
439
+ } catch {
440
+ return false
441
+ }
442
+ }
443
+
444
+ function schedAcquireSingleton() {
445
+ mkdirSync(DATA_DIR, { recursive: true })
446
+ if (existsSync(SCHED_PID_FILE)) {
447
+ const old = Number(readFileSync(SCHED_PID_FILE, 'utf8').trim())
448
+ if (Number.isInteger(old) && schedIsAlive(old)) {
449
+ console.error(`huizi-scheduler 已在运行(pid ${old}),本进程退出`)
450
+ process.exit(0)
451
+ }
452
+ rmSync(SCHED_PID_FILE, { force: true }) // 陈旧 pid,清理
453
+ }
454
+ try {
455
+ const fd = openSync(SCHED_PID_FILE, 'wx') // 原子创建,防双开竞态
456
+ writeFileSync(fd, String(process.pid))
457
+ closeSync(fd)
458
+ } catch {
459
+ console.error('huizi-scheduler 已在运行(锁竞争失败),本进程退出')
460
+ process.exit(0)
461
+ }
462
+ }
463
+
464
+ function schedDestroyAll() {
465
+ for (const t of schedTasks) t.stop()
466
+ schedTasks = []
467
+ }
468
+
469
+ function schedLogKnock(entry) {
470
+ try {
471
+ writeFileSync(KNOCK_LOG, JSON.stringify(entry) + '\n', { flag: 'a' })
472
+ } catch {
473
+ // 日志失败不阻塞敲门本身
474
+ }
475
+ }
476
+
477
+ function schedReload() {
478
+ schedDestroyAll()
479
+ let count = 0
480
+ for (const todo of new TodosStore(DATA_DIR).schedulable()) {
481
+ const expr = String(todo.cron_expr).trim()
482
+ if (!cron.validate(expr)) continue // 非法 cron 跳过(不致命)
483
+ const id = todo.id
484
+ const task = cron.schedule(expr, () => {
485
+ const ts = new Date().toISOString()
486
+ console.log(`[knock] ${ts} todo ${id}(${todo.title})到点`)
487
+ schedLogKnock({ ts, todo_id: id, title: todo.title, result: 'spawned' })
488
+ spawn(process.execPath, [SELF, '--knock-todo', id], {
489
+ stdio: 'ignore',
490
+ detached: true,
491
+ }).unref()
492
+ })
493
+ schedTasks.push(task)
494
+ count++
495
+ try {
496
+ const next = CronExpressionParser.parse(expr).next().toISOString()
497
+ console.log(`[job] ${id}(${todo.title})cron=${expr} next=${next}`)
498
+ } catch {
499
+ console.log(`[job] ${id}(${todo.title})cron=${expr}`)
500
+ }
501
+ }
502
+ console.log(`[reload] 已注册 ${count} 条定时提醒`)
503
+ }
504
+
505
+ function schedWatchTodos() {
506
+ if (!existsSync(TODOS_FILE)) {
507
+ mkdirSync(path.dirname(TODOS_FILE), { recursive: true })
508
+ }
509
+ let timer = null
510
+ watchFile(TODOS_FILE, { interval: 1000 }, () => {
511
+ clearTimeout(timer)
512
+ timer = setTimeout(schedReload, RELOAD_DEBOUNCE_MS)
513
+ })
514
+ }
515
+
516
+ function schedRelease() {
517
+ try {
518
+ if (Number(readFileSync(SCHED_PID_FILE, 'utf8').trim()) === process.pid) {
519
+ rmSync(SCHED_PID_FILE, { force: true })
520
+ }
521
+ } catch {
522
+ // 已不在
523
+ }
524
+ }
525
+
526
+ function runScheduler() {
527
+ schedAcquireSingleton()
528
+ schedReload()
529
+ schedWatchTodos()
530
+ console.log(`[start] huizi-scheduler pid=${process.pid},监听 ${TODOS_FILE}`)
531
+ process.on('SIGINT', () => {
532
+ schedDestroyAll()
533
+ schedRelease()
534
+ process.exit(0)
535
+ })
536
+ process.on('SIGTERM', () => {
537
+ schedDestroyAll()
538
+ schedRelease()
539
+ process.exit(0)
540
+ })
541
+ setInterval(() => {}, 60_000) // 保活
542
+ return 'HOLD' // 常驻模式,事件循环接管
543
+ }
544
+
545
+ function printHelp() {
546
+ console.log(`huizi —— 惠子 agent 统一入口
547
+
548
+ 用法:
549
+ huizi 问候启动(发一句"你好",惠子按规程回应)
550
+ huizi <message> 模拟用户发消息给惠子(交互与定时共用)
551
+ huizi --knock 敲门模式:让惠子扫描该提醒的事项
552
+ huizi --knock-todo <id> 精确敲门:只提醒指定 todo(调度器内部用)
553
+ huizi --scheduler 前台启动常驻定时器调度器(node-cron,Ctrl+C 退出)
554
+ huizi --gui 前台启动浏览器 UI(调试用,Ctrl+C 退出)
555
+ huizi --gui-start 后台启动 UI(日志 <data>/gui.log,就绪后返回)
556
+ huizi --gui-stop 停止 UI(幂等)
557
+ huizi --gui-status 查看 UI 状态(pid/端口/health/调度器)
558
+ huizi --gui-restart 重启 UI
559
+ huizi --gui-logs [n] 查看最近 n 行 UI 日志(默认 50)
560
+ huizi --upgrade 升级:补齐配置(保留用户值)+ 同步 agent 定义
561
+ huizi --scheduler-status 查看定时器状态与各任务下次提醒时间
562
+ huizi --status 免会话速查:打印活跃 todo 清单(不启动 LLM)
563
+ huizi --help | -h 显示本帮助
564
+
565
+ 数据目录:~/.config/huizi/(XDG,任意位置启动同一份记忆)
566
+ agent 定义:包内 agents/huizi.md 启动时自动同步到数据目录 .opencode/agents/
567
+ 定时器:huizi-scheduler 常驻调度(跨系统)。每次 huizi 执行前自动检查,
568
+ 未运行则拉起,失败则报错退出。守护建议:pm2 start bin/index.js --name huizi -- --scheduler`)
569
+ return 0
570
+ }
571
+
572
+ // ─── main ───
573
+
574
+ const opts = parseArgs(process.argv)
575
+ // help 零副作用:不迁移不同步不写配置;其余模式在锁之前完成初始化
576
+ if (opts.mode !== 'help') initOnce()
577
+ process.chdir(DATA_DIR) // 父进程 cwd 与 spawn cwd 保持一致(opencode 部分解析依赖父 cwd)
578
+
579
+ // help/status/scheduler-status 是只读操作,不拉调度器;
580
+ // knock-todo 是调度器子进程,豁免检查(防递归拉起);scheduler 自身豁免
581
+ const GUI_MODES = ['gui', 'gui-start', 'gui-stop', 'gui-status', 'gui-restart', 'gui-logs']
582
+ if (!['help', 'knock-todo', 'upgrade', 'scheduler', ...GUI_MODES].includes(opts.mode)) ensureScheduler()
583
+
584
+ async function main() {
585
+ let code = 1
586
+ if (opts.mode === 'help') code = printHelp()
587
+ else if (opts.mode === 'scheduler') code = runScheduler()
588
+ else if (opts.mode === 'greet') code = runSession(GREET_MSG, { source: 'interactive' })
589
+ else if (opts.mode === 'status') code = runStatus()
590
+ else if (opts.mode === 'upgrade') code = runUpgrade()
591
+ else if (opts.mode === 'gui') code = runGui()
592
+ else if (opts.mode === 'gui-start') code = await runGuiStart()
593
+ else if (opts.mode === 'gui-stop') code = await runGuiStop()
594
+ else if (opts.mode === 'gui-status') code = await runGuiStatus()
595
+ else if (opts.mode === 'gui-restart') code = await runGuiRestart()
596
+ else if (opts.mode === 'gui-logs') code = runGuiLogs(opts.lines)
597
+ else if (opts.mode === 'scheduler-status') code = runSchedulerStatus()
598
+ else if (opts.mode === 'knock') code = runSession(KNOCK_MSG, { source: 'knock' })
599
+ else if (opts.mode === 'knock-todo')
600
+ code = runSession(`定时提醒:todo ${opts.id} 到点了,请按你的记忆操作规程提醒我这件事(todo id: ${opts.id})。若有排队消息(pending.jsonl),一并处理。`, { source: 'knock' })
601
+ else code = runSession(opts.msg)
602
+
603
+ if (code !== 'HOLD') process.exit(code) // HOLD=常驻模式(scheduler/gui),事件循环接管
604
+ }
605
+ main()
@@ -48,7 +48,7 @@ cron 触发(task_type=xxx)
48
48
  1. **会话无状态,状态全在记忆库**——调度器崩溃重启不丢逻辑,任何入口共享同一记忆。
49
49
  2. **业务即配置**——新任务不改代码,只注册 task_type + 字段 schema + cron 表达式。
50
50
 
51
- ## 4. 技术选型(延续 [free-tts](../free-tts.md) 结论)
51
+ ## 4. 技术选型(延续 [free-tts](../../../harness/docs/tts/free-tts.md) 结论)
52
52
 
53
53
  | 环节 | 选型 | 理由 |
54
54
  |---|---|---|
@@ -78,10 +78,20 @@ summaries 不单设归档文件:摘要的"归档"就是压缩本身(有损
78
78
  | 创建时间 | `created_date` | 事项进入清单的时刻 | 事实,不可变 |
79
79
  | 计划结束 | `due_date` | 用户承诺的完成期限(once/followup,可空) | 计划,用户可改期 |
80
80
  | 周期节奏 | `cron_expr` | recurring 的重复提醒计划 | 计划,用户可调整 |
81
+ | **有效期至** | `end_date` | recurring 专属:周期提醒的最后有效日(**含当日**) | 计划,用户可延长/缩短 |
81
82
  | 上次提醒 | `last_reminded` | 防重复打扰的游标 | 簿记,惠子维护 |
82
83
  | 实际完成 | `closed_date` | 生命周期终点 | 事实,不可变 |
83
84
 
84
- 原则:**事实(created/closed)与计划(due/cron)与簿记(last_reminded)三类不混用**;"过期"不落字段,每次扫描用 due_date 与今天现算。
85
+ 原则:**事实(created/closed)与计划(due/cron/end_date)与簿记(last_reminded)三类不混用**;"过期"不落字段,每次扫描现算。
86
+
87
+ **end_date 的精确定义**:
88
+
89
+ - 语义:**提醒本身的有效期**,与 due_date("事情要办完的期限")是两个概念——"今天下午每整点反馈进度"里,事情的期限是今天(due 语义),提醒的期限也是今天(end 语义),但"每天练琴"没有提醒期限(end=null 永久)
90
+ - 格式/时区:`YYYY-MM-DD`,本地时间,与 cron_expr 同一基准
91
+ - 边界:`end_date=2026-11-24` → **11-24 当天的提醒照常触发**,11-25 00:00 起不再触发(判据:`今天 > end_date` 为过期)
92
+ - 过期后:调度器跳过(不敲门);惠子扫描发现已过期的临时 recurring → 主动向用户确认是否关闭(dropped),**不擅自关闭**
93
+ - 空值:`null` = 永久有效(习惯类 recurring 默认)
94
+ - 典型场景:"仅今天"→end_date=今天;"到周五为止每天"→end_date=周五;"每天练琴"→end_date=null
85
95
 
86
96
  ## 3. 三种 kind 的统一行为
87
97