@wwkit/huizi 0.0.0-stage → 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 (38) hide show
  1. package/agents/huizi.md +184 -0
  2. package/bin/index.js +605 -0
  3. package/docs/huizi/data-directory.md +31 -0
  4. package/docs/huizi/huizi-overview.md +79 -0
  5. package/docs/huizi/memory-loop.md +167 -0
  6. package/docs/huizi/status.md +67 -0
  7. package/docs/huizi/summary-management.md +84 -0
  8. package/package.json +50 -3
  9. package/scripts/postinstall.js +16 -0
  10. package/src/config.js +65 -0
  11. package/src/config.json5 +31 -0
  12. package/src/constants.js +10 -0
  13. package/src/gui/client/dist/assets/index-DVBRRKKn.css +1 -0
  14. package/src/gui/client/dist/assets/index-jOEH0111.js +51 -0
  15. package/src/gui/client/dist/icon.svg +4 -0
  16. package/src/gui/client/dist/index.html +15 -0
  17. package/src/gui/client/dist/manifest.json +11 -0
  18. package/src/gui/client/index.html +14 -0
  19. package/src/gui/client/public/icon.svg +4 -0
  20. package/src/gui/client/public/manifest.json +11 -0
  21. package/src/gui/client/src/App.vue +121 -0
  22. package/src/gui/client/src/api.js +37 -0
  23. package/src/gui/client/src/components/ChatPanel.vue +86 -0
  24. package/src/gui/client/src/components/CronPanel.vue +52 -0
  25. package/src/gui/client/src/components/MessageBubble.vue +46 -0
  26. package/src/gui/client/src/main.js +8 -0
  27. package/src/gui/client/src/style.css +7 -0
  28. package/src/gui/client/vite.config.js +18 -0
  29. package/src/gui/server.js +124 -0
  30. package/src/output/channels/print.js +11 -0
  31. package/src/output/channels/tts.js +50 -0
  32. package/src/output/index.js +42 -0
  33. package/src/pid-file.js +89 -0
  34. package/src/session-lock.js +70 -0
  35. package/src/session-runner.js +98 -0
  36. package/src/todos-store.js +75 -0
  37. package/src/tts.js +79 -0
  38. package/README.md +0 -3
@@ -0,0 +1,42 @@
1
+ /**
2
+ * 输出通道统一出口(v0.2 架构)。
3
+ *
4
+ * 会话代码只认 deliver(reply, ctx)——"惠子说了什么"与"从哪里说出去"分离。
5
+ * 通道契约(src/output/channels/<name>.js):
6
+ * - name 通道名
7
+ * - available(ctx) 此上下文是否可用(同步,绝不抛错)
8
+ * - deliver(ctx) 投递(失败自行提示,不抛错)
9
+ * - priority 同可用时先走谁(数字小先)
10
+ *
11
+ * 通道叠加而非互斥:print 永在(兜底),tts/dingtalk/ui 是叠加出口。
12
+ * config.output.channels 显式列表可覆盖自动判定(如 ['print','tts'])。
13
+ */
14
+ import { printChannel } from './channels/print.js'
15
+ import { ttsChannel } from './channels/tts.js'
16
+
17
+ const REGISTRY = [printChannel, ttsChannel] // dingtalk/ui 按版本加入
18
+
19
+ /**
20
+ * 投递惠子回复到所有可用通道。
21
+ * @param {string} reply 惠子的最终回复文本
22
+ * @param {{source: 'interactive'|'knock', tty: boolean, config: object, sessionMeta?: object}} ctx
23
+ */
24
+ export function deliver(reply, ctx) {
25
+ if (!reply) return
26
+ let channels = REGISTRY.filter((c) => c.available(ctx))
27
+ const explicit = ctx.config?.output?.channels
28
+ if (Array.isArray(explicit)) {
29
+ // 显式列表(含空数组=全部排除);undefined/null 才走自动判定
30
+ const want = new Set(explicit)
31
+ channels = REGISTRY.filter((c) => want.has(c.name))
32
+ }
33
+ channels.sort((a, b) => a.priority - b.priority)
34
+ for (const c of channels) {
35
+ try {
36
+ c.deliver({ ...ctx, reply })
37
+ } catch (e) {
38
+ // 通道失败只影响自己,不阻断其他通道与会话
39
+ process.stderr.write(`(输出通道 ${c.name} 失败:${e.message})\n`)
40
+ }
41
+ }
42
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * pid 文件管理(常驻服务单例 + 管理命令用):对齐 freetoken pids/ 与 nets frpc.pid 的既有模式。
3
+ *
4
+ * 设计要点:
5
+ * - O_EXCL 原子抢写,消除并发 start 的双实例竞态
6
+ * - alive() 用 process.kill(pid, 0) 探测存活;pid 文件损坏/进程已死视为未运行
7
+ * - stopPid() 平台分派:POSIX 用 SIGTERM,Windows 用 taskkill /PID
8
+ */
9
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
10
+ import { spawnSync } from 'node:child_process'
11
+ import path from 'node:path'
12
+
13
+ export class PidFile {
14
+ /** @param {string} dataDir 数据目录 @param {string} name 服务名(<name>.pid) */
15
+ constructor(dataDir, name) {
16
+ mkdirSync(dataDir, { recursive: true })
17
+ this.pidFile = path.join(dataDir, `${name}.pid`)
18
+ }
19
+
20
+ /** 读取 pid 元信息;不存在/损坏返回 null */
21
+ read() {
22
+ if (!existsSync(this.pidFile)) return null
23
+ try {
24
+ const meta = JSON.parse(readFileSync(this.pidFile, 'utf8'))
25
+ return Number.isInteger(meta?.pid) ? meta : null
26
+ } catch {
27
+ return null
28
+ }
29
+ }
30
+
31
+ /** 进程是否存活(pid 文件存在且进程可被信号探测) */
32
+ alive() {
33
+ const meta = this.read()
34
+ if (!meta) return false
35
+ try {
36
+ process.kill(meta.pid, 0)
37
+ return true
38
+ } catch {
39
+ return false
40
+ }
41
+ }
42
+
43
+ /** O_EXCL 原子抢写(已存在且存活 → false);返回是否抢到 */
44
+ write(meta = {}) {
45
+ if (this.alive()) return false
46
+ rmSync(this.pidFile, { force: true }) // 陈旧 pid 清理
47
+ try {
48
+ const fd = openSync(this.pidFile, 'wx')
49
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, ts: Date.now(), ...meta }))
50
+ closeSync(fd)
51
+ return true
52
+ } catch {
53
+ return false
54
+ }
55
+ }
56
+
57
+ /** 删除 pid 文件(管理命令 stop 用:不校验归属) */
58
+ remove() {
59
+ rmSync(this.pidFile, { force: true })
60
+ }
61
+
62
+ /** 发送停止信号:POSIX SIGTERM / Windows taskkill;返回是否发送成功 */
63
+ static stopPid(pid) {
64
+ try {
65
+ if (process.platform === 'win32') {
66
+ spawnSync('taskkill', ['/PID', String(pid)], { stdio: 'ignore' })
67
+ } else {
68
+ process.kill(pid, 'SIGTERM')
69
+ }
70
+ return true
71
+ } catch {
72
+ return false
73
+ }
74
+ }
75
+
76
+ /** 等待进程退出(轮询,最多 waitMs);超时返回 false */
77
+ static async waitExit(pid, waitMs = 5000) {
78
+ const deadline = Date.now() + waitMs
79
+ while (Date.now() < deadline) {
80
+ try {
81
+ process.kill(pid, 0)
82
+ } catch {
83
+ return true // 已退出
84
+ }
85
+ await new Promise((r) => setTimeout(r, 200))
86
+ }
87
+ return false
88
+ }
89
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * 会话锁(单例资源模式):同一时刻一个惠子会话——cli/gui/knock 共享一把锁。
3
+ *
4
+ * 设计要点:
5
+ * - O_EXCL 原子创建(openSync 'wx'),消除 check-then-act 竞态窗口
6
+ * - 陈旧锁自愈:TTL 超时或持锁进程已死 → 自动清理放行
7
+ * - 释放只删自己的锁(按 pid 校验),防误删他人
8
+ * - 所有会话入口(cli runSession / gui chat / 敲门)必须经此类,禁止内联锁逻辑
9
+ */
10
+ import { closeSync, existsSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
11
+ import path from 'node:path'
12
+
13
+ export const LOCK_TTL_MS = 10 * 60 * 1000 // 会话最长 10 分钟;超时视为陈旧锁
14
+
15
+ export class SessionLock {
16
+ /** @param {string} dataDir 惠子数据目录(锁文件 <dataDir>/session.lock) */
17
+ constructor(dataDir) {
18
+ this.lockFile = path.join(dataDir, 'session.lock')
19
+ }
20
+
21
+ /** 锁文件存在且持锁进程活着且未超 TTL → true(陈旧锁顺带清理) */
22
+ isHeld() {
23
+ if (!existsSync(this.lockFile)) return false
24
+ let stale = true
25
+ try {
26
+ const { pid, ts } = JSON.parse(readFileSync(this.lockFile, 'utf8'))
27
+ stale = Date.now() - ts > LOCK_TTL_MS
28
+ if (!stale) {
29
+ try {
30
+ process.kill(pid, 0)
31
+ } catch {
32
+ stale = true // 持锁进程已死
33
+ }
34
+ }
35
+ } catch {
36
+ stale = true // 锁文件损坏
37
+ }
38
+ if (stale) {
39
+ try {
40
+ rmSync(this.lockFile, { force: true })
41
+ } catch {}
42
+ return false
43
+ }
44
+ return true
45
+ }
46
+
47
+ /** 抢锁(O_EXCL 原子);已被占返回 false。isHeld 的陈旧清理在前,此处兜底竞态 */
48
+ acquire() {
49
+ if (this.isHeld()) return false
50
+ try {
51
+ const fd = openSync(this.lockFile, 'wx')
52
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, ts: Date.now() }))
53
+ closeSync(fd)
54
+ return true
55
+ } catch {
56
+ // 竞争失败:极小概率陈旧锁在 isHeld 与 open 间被替换——再判一次
57
+ return !this.isHeld() ? this.acquire() : false
58
+ }
59
+ }
60
+
61
+ /** 释放自己的锁(按 pid 校验);不是自己的不动 */
62
+ release() {
63
+ try {
64
+ const { pid } = JSON.parse(readFileSync(this.lockFile, 'utf8'))
65
+ if (pid === process.pid) rmSync(this.lockFile, { force: true })
66
+ } catch {
67
+ // 锁已不在(异常路径),无需处理
68
+ }
69
+ }
70
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * 会话执行器:opencode 调用的唯一封装(cli runSession 与 gui chat 共用)。
3
+ *
4
+ * 设计要点:
5
+ * - cwd=数据目录 + PWD 显式覆盖(opencode 是 Go 二进制,信 PWD 不信 chdir——
6
+ * 这是实测得出的平台坑,两处调用点绝不允许各写一份参数)
7
+ * - source 由调用方显式传入('interactive' | 'knock'),不靠消息内容猜——
8
+ * 消灭"字符串当协议"的脆弱耦合
9
+ * - 同步(spawnSync)与异步(execFile 回调)两种执行形态,锁语义由调用方处理
10
+ */
11
+ import { spawnSync } from 'node:child_process'
12
+ import { extractReply } from './tts.js'
13
+
14
+ export const SESSION_TIMEOUT_MS = 9.5 * 60 * 1000 // 略小于锁 TTL,保证锁先于会话过期
15
+
16
+ export class SessionRunner {
17
+ /** @param {string} dataDir 惠子数据目录(会话 cwd,opencode 项目级发现 .opencode/agents/) */
18
+ constructor(dataDir) {
19
+ this.dataDir = dataDir
20
+ }
21
+
22
+ /** 公共 spawn 参数(两形态共用) */
23
+ _common(text) {
24
+ // 清除 OPENCODE_CONFIG_DIR:opencode 从 cwd(数据目录)项目级发现 .opencode/agents/huizi.md。
25
+ // 若继承外部 OPENCODE_CONFIG_DIR(如 harness 环境),opencode 会从错误目录找 agent → 找不到 huizi。
26
+ const env = { ...process.env, PWD: this.dataDir }
27
+ delete env.OPENCODE_CONFIG_DIR
28
+ return {
29
+ cwd: this.dataDir,
30
+ env,
31
+ }
32
+ }
33
+
34
+ /** 同步执行(cli 用):返回 { code, reply };reply 为提取后的最终回复 */
35
+ runSync(text) {
36
+ const result = spawnSync(
37
+ 'opencode',
38
+ ['run', '--auto', '--pure', '--agent', 'huizi', text],
39
+ {
40
+ ...this._common(text),
41
+ stdio: ['ignore', 'pipe', 'inherit'],
42
+ encoding: 'utf8',
43
+ timeout: SESSION_TIMEOUT_MS,
44
+ },
45
+ )
46
+ if (result.error) throw result.error
47
+ const reply = extractReply(result.stdout)
48
+ return { code: result.status ?? 1, reply, stdout: result.stdout }
49
+ }
50
+
51
+ /** 异步执行(gui 用):回调 (err, { reply, stdout });返回 child 供调用方跟踪/终止 */
52
+ runAsync(text, cb) {
53
+ import('node:child_process').then(({ spawn }) => {
54
+ // 用 spawn 而非 execFile:execFile 缓冲 stdout 在非 TTY 下 opencode 会卡住(实测),
55
+ // spawn 流式收集输出可正常完成。
56
+ const child = spawn(
57
+ 'opencode',
58
+ ['run', '--auto', '--pure', '--agent', 'huizi', text],
59
+ {
60
+ ...this._common(text),
61
+ stdio: ['ignore', 'pipe', 'inherit'],
62
+ },
63
+ )
64
+ let stdout = ''
65
+ let timedOut = false
66
+ child.stdout.on('data', (d) => {
67
+ stdout += d
68
+ })
69
+ const timer = setTimeout(() => {
70
+ timedOut = true
71
+ child.kill('SIGTERM')
72
+ }, SESSION_TIMEOUT_MS)
73
+ child.on('error', (err) => {
74
+ clearTimeout(timer)
75
+ cb(err)
76
+ })
77
+ child.on('close', (code) => {
78
+ clearTimeout(timer)
79
+ if (timedOut) return cb(new Error(`会话超时(${SESSION_TIMEOUT_MS / 60000} 分钟)`))
80
+ if (code !== 0) return cb(new Error(`opencode 退出码 ${code}`))
81
+ cb(null, { reply: extractReply(stdout) || String(stdout).trim(), stdout })
82
+ })
83
+ // 暴露 child 供调用方跟踪(GUI 停止时终止会话子进程)
84
+ this._activeChild = child
85
+ })
86
+ }
87
+
88
+ /** 终止当前正在运行的会话子进程(GUI 停止时调用,防遗留会话占用锁) */
89
+ killActive() {
90
+ const child = this._activeChild
91
+ if (child && child.pid) {
92
+ try {
93
+ process.kill(child.pid, 'SIGTERM')
94
+ } catch {}
95
+ }
96
+ this._activeChild = null
97
+ }
98
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * todos 仓储(Repository 模式):todos.jsonl 解析/过滤/只读视图的唯一实现。
3
+ *
4
+ * 设计要点:
5
+ * - 任何模块(cli/scheduler/gui)要读 todos 只 import 此类,禁止再写 JSONL 解析
6
+ * - 读操作纯函数化(不缓存——文件小,每次现读最简单可靠)
7
+ * - 过滤谓词命名化:schedulable = recurring + open/waiting + cron 合法 + 未过有效期
8
+ */
9
+ import { existsSync, readFileSync } from 'node:fs'
10
+ import path from 'node:path'
11
+ import { CronExpressionParser } from 'cron-parser'
12
+
13
+ export function today() {
14
+ const d = new Date()
15
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
16
+ }
17
+
18
+ export class TodosStore {
19
+ /** @param {string} dataDir 惠子数据目录 */
20
+ constructor(dataDir) {
21
+ this.todosFile = path.join(dataDir, 'todos.jsonl')
22
+ }
23
+
24
+ /** 全量解析(坏行跳过);文件不存在返回 [] */
25
+ load() {
26
+ if (!existsSync(this.todosFile)) return []
27
+ return readFileSync(this.todosFile, 'utf8')
28
+ .split('\n')
29
+ .filter(Boolean)
30
+ .map((l) => {
31
+ try {
32
+ return JSON.parse(l)
33
+ } catch {
34
+ return null
35
+ }
36
+ })
37
+ .filter(Boolean)
38
+ }
39
+
40
+ /** 可调度谓词:recurring + open/waiting + cron 非空 + 未过有效期(end_date 含当日) */
41
+ static schedulable(t, todayStr = today()) {
42
+ if (t.kind !== 'recurring') return false
43
+ if (!['open', 'waiting'].includes(t.status)) return false
44
+ if (!t.cron_expr) return false
45
+ return !(t.end_date && todayStr > String(t.end_date))
46
+ }
47
+
48
+ /** 可调度条目(scheduler reload 与状态视图共用) */
49
+ schedulable() {
50
+ return this.load().filter((t) => TodosStore.schedulable(t))
51
+ }
52
+
53
+ /** 只读调度视图(cli --scheduler-status 与 gui /api/todos 共用):含过期提示条目 */
54
+ schedulableView() {
55
+ const todayStr = today()
56
+ return this.load()
57
+ .filter((t) => t.kind === 'recurring' && ['open', 'waiting'].includes(t.status) && t.cron_expr)
58
+ .map((t) => {
59
+ const expired = Boolean(t.end_date && todayStr > String(t.end_date))
60
+ let next = null
61
+ try {
62
+ next = CronExpressionParser.parse(String(t.cron_expr).trim()).next().toISOString()
63
+ } catch {}
64
+ return {
65
+ id: t.id, title: t.title, status: t.status, cron_expr: t.cron_expr,
66
+ end_date: t.end_date ?? null, expired, next,
67
+ }
68
+ })
69
+ }
70
+
71
+ /** 活跃条目(cli --status 用):open/waiting/paused */
72
+ active() {
73
+ return this.load().filter((t) => ['open', 'waiting', 'paused'].includes(t.status))
74
+ }
75
+ }
package/src/tts.js ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * TTS 语音合成核心(v0.2)。
3
+ * 职责收敛为"合成":文本 → 硅基流动 CosyVoice2 → wav 缓存。
4
+ * 播放与通道选择在 src/output/channels/tts.js(输出通道架构)。
5
+ * 降级原则:任何失败返回 null 不抛错——纯文字兜底由 print 通道承担。
6
+ */
7
+ import { spawnSync } from 'node:child_process'
8
+ import { existsSync, mkdirSync, statSync } from 'node:fs'
9
+ import path from 'node:path'
10
+ import { createHash } from 'node:crypto'
11
+ import { ttsConfig, getConfigDir } from './config.js'
12
+
13
+ const TTS_CACHE_DIR = path.join(getConfigDir(), 'tts-cache')
14
+
15
+ /** 探测可用的本地播放命令;无则返回 null */
16
+ export function detectPlayer() {
17
+ const candidates =
18
+ process.platform === 'darwin'
19
+ ? ['afplay']
20
+ : process.platform === 'win32'
21
+ ? []
22
+ : ['aplay', 'ffplay', 'pw-play', 'paplay', 'play']
23
+ for (const cmd of candidates) {
24
+ const r = spawnSync('which', [cmd], { encoding: 'utf8' })
25
+ if (r.status === 0 && r.stdout.trim()) return cmd
26
+ }
27
+ if (process.platform === 'win32') return 'powershell' // SoundPlayer 经 -Command 调用
28
+ return null
29
+ }
30
+
31
+ /** 从 opencode run 的 stdout 提取惠子的最终回复(去掉工具调用/状态行/代码块围栏) */
32
+ export function extractReply(stdoutText) {
33
+ if (!stdoutText) return ''
34
+ const lines = stdoutText.split('\n')
35
+ const clean = (l) => {
36
+ const s = l.replace(/\x1b\[[0-9;]*m/g, '').trim()
37
+ if (!s || s.startsWith('$') || s.startsWith('→') || s.startsWith('>') || s.startsWith('```')) return null
38
+ return s
39
+ }
40
+ const out = []
41
+ for (let i = lines.length - 1; i >= 0; i--) {
42
+ const c = clean(lines[i])
43
+ if (c === null) {
44
+ if (out.length) break // 已收集到回复段,遇工具行/围栏即止
45
+ continue // 尾部杂行跳过
46
+ }
47
+ out.unshift(c)
48
+ }
49
+ return out.join('\n').trim()
50
+ }
51
+
52
+ /** 同步合成(node 子进程内完成 fetch,保持 CLI 同步流);成功返回缓存 wav 路径,失败 null */
53
+ export function synthSync(text, configOverride) {
54
+ const cfg = ttsConfig(configOverride)
55
+ if (!cfg.enabled || !text) return null
56
+ if (!cfg.api_key || cfg.api_key.includes('{env:')) return null
57
+ const hash = createHash('sha256').update(`${cfg.model}|${cfg.voice}|${text}`).digest('hex')
58
+ mkdirSync(TTS_CACHE_DIR, { recursive: true })
59
+ const cacheFile = path.join(TTS_CACHE_DIR, `${hash}.wav`)
60
+ if (existsSync(cacheFile) && statSync(cacheFile).size > 0) return cacheFile
61
+
62
+ const script = `
63
+ const fs = require('fs')
64
+ async function main() {
65
+ const resp = await fetch(${JSON.stringify(`${cfg.api_base.replace(/\/$/, '')}/audio/speech`)}, {
66
+ method: 'POST',
67
+ headers: { Authorization: 'Bearer ' + ${JSON.stringify(cfg.api_key)}, 'Content-Type': 'application/json' },
68
+ body: JSON.stringify({ model: ${JSON.stringify(cfg.model)}, input: ${JSON.stringify(text)}, voice: ${JSON.stringify(cfg.voice)}, response_format: 'wav', sample_rate: 16000 }),
69
+ })
70
+ if (!resp.ok) { console.error('tts http ' + resp.status); process.exit(1) }
71
+ const buf = Buffer.from(await resp.arrayBuffer())
72
+ fs.writeFileSync(${JSON.stringify(cacheFile)}, buf)
73
+ }
74
+ main().catch((e) => { console.error(String(e)); process.exit(1) })
75
+ `
76
+ const r = spawnSync(process.execPath, ['-e', script], { encoding: 'utf8', timeout: 60_000 })
77
+ if (r.status !== 0) return null
78
+ return existsSync(cacheFile) ? cacheFile : null
79
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.