mino-voice-notes 0.0.0-stage → 0.1.0

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.
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # mino-voice-notes
2
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.
3
+ 「语音笔记」:录音 → 分段 → 本机转写 → 纪要 → 本地分享页。
4
+
5
+ ## 能力面
6
+
7
+ - 「今日」面板的「语音」tab(注册进 `today.page.voice` 座位,mino-today 未装时安静缺席):录音控制 + 笔记列表 + 详情(转写/纪要/分段回放/分享)
8
+ - 6 个模型工具:`vnote_start` / `vnote_stop` / `vnote_list` / `vnote_get` / `vnote_update` / `vnote_share`
9
+ - 自有路由:`/mino-voice-notes/api/{start,segment,stop,list,note,update,share,delete,audio}` + `/mino-voice-notes/s/<shareId>` 只读分享页
10
+ - 服务缝:`ctx.get('mino-voice-notes')` → `{start,stop,status}`(meeting-detect 等消费方走这里,不走工具名)
11
+
12
+ ## 解耦边界
13
+
14
+ | 环节 | 缝 |
15
+ |---|---|
16
+ | 采集 | 自有 client 半:`getUserMedia` → AudioContext 16kHz mono → PCM16 → WAV(官方 voice-input 同款路径)→ `api/segment` 每 15s 分段上传 |
17
+ | 转写 | `ctx.speechToText.resolve+transcribe`(provider 由 voice-input bundle 内置的 `sensevoice-local` 提供;没装时笔记落 `failed` 并写明原因) |
18
+ | 纪要 | 模型读 `vnote_get` 转写文 → `vnote_update` 写回 `summary` → 可 `today_post` 投 feed(软依赖) |
19
+ | 存储 | 自有 `~/.mino/mino-voice-notes/`:`notes.json` 索引 + `audio/<id>/seg-*.wav` |
20
+
21
+ ## Known Limitations
22
+
23
+ - 分享页在 web 档鉴权域内(同源 token),不是公网链接。
24
+ - ScriptProcessorNode 采集(非 AudioWorklet):主线程繁忙时理论上可能丢帧;官方 voice-input 用 Worklet,后续可对齐。
25
+ - 说话人分离 deferred(需要 pyannote 类外部管线)。
26
+ - `stop` 后台转写:长录音通过 `vnote_get` 轮询拿结果(TRANSCRIBE_TIMEOUT 120s/段批量)。
@@ -0,0 +1,5 @@
1
+ # mino-voice-notes bundle patch:把双面插件行插进 web 档 roster。
2
+ # `dsh plugin --profile <name> add mino-voice-notes` 时本补丁随包并入 bundle 栈。
3
+ - insert:
4
+ - id: voice-notes
5
+ name: 'mino-voice-notes'
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "mino-voice-notes",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "「语音笔记」面板:录音→分段→本机转写→纪要→本地分享页,全官方解耦缝。",
5
+ "keywords": [
6
+ "dsh-plugin",
7
+ "voice",
8
+ "notes",
9
+ "speech"
10
+ ],
11
+ "license": "MIT",
12
+ "type": "module",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./lib/types/index.d.ts",
16
+ "default": "./lib/index.js"
17
+ },
18
+ "./client": {
19
+ "types": "./lib/types/client/index.d.ts",
20
+ "default": "./lib/client.js"
21
+ },
22
+ "./cordis.patch.yml": "./cordis.patch.yml",
23
+ "./package.json": "./package.json"
24
+ },
25
+ "files": [
26
+ "lib/**/*.js",
27
+ "lib/**/*.js.map",
28
+ "lib/**/*.d.ts",
29
+ "lib/**/*.d.ts.map",
30
+ "src",
31
+ "cordis.patch.yml",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "scripts": {
36
+ "build": "node -e \"require('node:fs').rmSync('lib',{recursive:true,force:true})\" && tsc -p tsconfig.build.json && tsdown",
37
+ "typecheck": "tsc --noEmit",
38
+ "bundle": "tsdown",
39
+ "watch": "tsdown --watch"
40
+ },
41
+ "peerDependencies": {
42
+ "@deepseek-ai/cordis": "^4.0.0",
43
+ "react": "^18.2.0"
44
+ },
45
+ "devDependencies": {
46
+ "@deepseek-ai/cordis": "4.0.5",
47
+ "@types/node": "^24.0.0",
48
+ "@types/react": "~18.3.1",
49
+ "@types/react-dom": "~18.3.1",
50
+ "lightningcss": "^1.32.0",
51
+ "react": "^18.2.0",
52
+ "react-dom": "18.2.0",
53
+ "tsdown": "^0.22.2",
54
+ "typescript": "^5.6.0"
55
+ },
56
+ "dsh": {
57
+ "engines": {
58
+ "dsh": ">=0.2.2-alpha.1 <0.3.0"
59
+ },
60
+ "bundle": {
61
+ "patch": "./cordis.patch.yml"
62
+ },
63
+ "client": {
64
+ "inject": [
65
+ "@deepseek-ai/dsh-client-locale",
66
+ "@deepseek-ai/dsh-client-ui-slots",
67
+ "@deepseek-ai/dsh-client-ui-renderer"
68
+ ],
69
+ "platform": "web"
70
+ }
71
+ }
6
72
  }
@@ -0,0 +1,161 @@
1
+ /** 「语音笔记」main 页:录音控制 + 笔记列表 + 详情(转写/纪要/分享)。 */
2
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
3
+ import type { Translate } from './index.tsx'
4
+ import * as api from './api.ts'
5
+ import { startRecording, wavToBase64, type Recorder } from './recorder.ts'
6
+ import styles from './vnotes.module.css'
7
+
8
+ export interface VNotesActions {
9
+ refresh: () => void
10
+ }
11
+
12
+ export function VNotesPage({ t }: { t: Translate }) {
13
+ const [notes, setNotes] = useState<api.VNotePublic[]>([])
14
+ const [selected, setSelected] = useState<api.VNotePublic | undefined>()
15
+ const [recording, setRecording] = useState<{ id: string; seconds: number } | undefined>()
16
+ const [error, setError] = useState<string>()
17
+ const [sharePath, setSharePath] = useState<string>()
18
+ const recorderRef = useRef<Recorder | undefined>()
19
+ const seqRef = useRef(0)
20
+ const timerRef = useRef<ReturnType<typeof setInterval> | undefined>()
21
+
22
+ const refresh = useCallback(async () => {
23
+ try {
24
+ const list = await api.listNotes()
25
+ setNotes(list)
26
+ if (selected) setSelected(list.find(n => n.id === selected.id) ?? selected)
27
+ } catch { /* 列表刷新失败静默 */ }
28
+ }, [selected])
29
+
30
+ useEffect(() => {
31
+ void refresh()
32
+ const poll = setInterval(() => void refresh(), 4000)
33
+ return () => clearInterval(poll)
34
+ }, [])
35
+
36
+ const begin = async () => {
37
+ setError(undefined)
38
+ try {
39
+ const { id } = (await api.startNote()) as { id: string }
40
+ seqRef.current = 0
41
+ const rec = await startRecording(async (wav, ms) => {
42
+ const seq = seqRef.current++
43
+ await api.uploadSegment(id, seq, wavToBase64(wav), ms)
44
+ })
45
+ recorderRef.current = rec
46
+ setRecording({ id, seconds: 0 })
47
+ timerRef.current = setInterval(() => {
48
+ setRecording(r => (r ? { ...r, seconds: rec.seconds() } : r))
49
+ }, 500)
50
+ void refresh()
51
+ } catch {
52
+ setError(t('record.micDenied'))
53
+ }
54
+ }
55
+
56
+ const finish = async () => {
57
+ if (!recording) return
58
+ clearInterval(timerRef.current)
59
+ try {
60
+ await recorderRef.current?.stop()
61
+ recorderRef.current?.dispose()
62
+ recorderRef.current = undefined
63
+ await api.stopNote(recording.id)
64
+ } catch { /* 上传/收尾失败也走清理 */ }
65
+ setRecording(undefined)
66
+ void refresh()
67
+ }
68
+
69
+ const share = async (id: string) => {
70
+ try {
71
+ const data = (await api.shareNote(id)) as { path?: string }
72
+ if (data.path) {
73
+ setSharePath(data.path)
74
+ try { await navigator.clipboard.writeText(location.origin + data.path) } catch { /* 剪贴板不可用就只显示 */ }
75
+ }
76
+ } catch { /* 分享失败静默 */ }
77
+ }
78
+
79
+ const remove = async (id: string) => {
80
+ try { await api.deleteNote(id) } catch { /* 删除失败静默 */ }
81
+ if (selected?.id === id) setSelected(undefined)
82
+ void refresh()
83
+ }
84
+
85
+ const statusLabel = (s: api.VNotePublic['status']) => t(`list.status.${s}` as Parameters<Translate>[0])
86
+
87
+ // audioNotes 同款时间分桶:今天 / 昨天 / 更早。
88
+ const grouped = useMemo(() => {
89
+ const dayStart = (iso: string) => { const d = new Date(iso); return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime() }
90
+ const today = dayStart(new Date().toISOString())
91
+ const buckets: { key: 'group.today' | 'group.yesterday' | 'group.earlier'; items: api.VNotePublic[] }[] = [
92
+ { key: 'group.today', items: [] },
93
+ { key: 'group.yesterday', items: [] },
94
+ { key: 'group.earlier', items: [] },
95
+ ]
96
+ for (const n of notes) {
97
+ const d = dayStart(n.createdAt)
98
+ buckets[d >= today ? 0 : d >= today - 86_400_000 ? 1 : 2]!.items.push(n)
99
+ }
100
+ return buckets.filter(b => b.items.length > 0)
101
+ }, [notes])
102
+
103
+ return (
104
+ <div className={styles.page}>
105
+ <div className={styles.head}>
106
+ {recording ? (
107
+ <button className={`${styles.btn} ${styles.btnStop}`} onClick={() => void finish()}>
108
+ ● {t('record.recording')} {Math.floor(recording.seconds / 60)}:{String(Math.floor(recording.seconds % 60)).padStart(2, '0')} — {t('record.stop')}
109
+ </button>
110
+ ) : (
111
+ <button className={styles.btn} onClick={() => void begin()}>{t('record.start')}</button>
112
+ )}
113
+ <button className={styles.miniButton} onClick={() => void refresh()}>{t('action.refresh')}</button>
114
+ </div>
115
+ {error && <div className={styles.error}>{error}</div>}
116
+ {sharePath && <div className={styles.share}>{t('share.path')}: <a href={sharePath} target="_blank" rel="noreferrer">{sharePath}</a> · {t('share.copied')}</div>}
117
+
118
+ <div className={styles.body}>
119
+ <div className={styles.list}>
120
+ {notes.length === 0 && <div className={styles.empty}>{t('list.empty')}</div>}
121
+ {grouped.map(g => (
122
+ <div key={g.key} className={styles.group}>
123
+ <div className={styles.groupHead}>{t(g.key)}</div>
124
+ {g.items.map(n => (
125
+ <div key={n.id} className={`${styles.row} ${selected?.id === n.id ? styles.rowActive : ''}`}
126
+ onClick={() => { setSelected(n); void api.getNote(n.id).then(d => d && setSelected(d)) }}>
127
+ <div className={styles.rowTitle}>{n.title}</div>
128
+ <div className={styles.rowMeta}>
129
+ <span className={`${styles.badge} ${styles[`st_${n.status}`]}`}>{statusLabel(n.status)}</span>
130
+ <span>{n.createdAt.slice(0, 16).replace('T', ' ')}</span>
131
+ {n.audioSeconds !== undefined && <span>{n.audioSeconds.toFixed(0)}s</span>}
132
+ </div>
133
+ </div>
134
+ ))}
135
+ </div>
136
+ ))}
137
+ </div>
138
+
139
+ {selected && (
140
+ <div className={styles.detail}>
141
+ <div className={styles.detailHead}>
142
+ <h2>{selected.title}</h2>
143
+ <div>
144
+ <button className={styles.miniButton} onClick={() => void share(selected.id)}>{t('action.share')}</button>
145
+ <button className={`${styles.miniButton} ${styles.danger}`} onClick={() => void remove(selected.id)}>{t('action.delete')}</button>
146
+ </div>
147
+ </div>
148
+ {selected.error && <div className={styles.error}>{selected.error}</div>}
149
+ {selected.summary && (<><h3>{t('detail.summary')}</h3><pre className={styles.pre}>{selected.summary}</pre></>)}
150
+ <h3>{t('detail.transcript')}</h3>
151
+ <pre className={styles.pre}>{selected.transcript || t('detail.noTranscript')}</pre>
152
+ <h3>{t('detail.audio')}({selected.segments})</h3>
153
+ {Array.from({ length: selected.segments }, (_, i) => (
154
+ <audio key={i} controls preload="none" src={`/mino-voice-notes/api/audio?id=${selected.id}&seq=${i}`} className={styles.audio} />
155
+ ))}
156
+ </div>
157
+ )}
158
+ </div>
159
+ </div>
160
+ )
161
+ }
@@ -0,0 +1,45 @@
1
+ /** mino-voice-notes 客户端的 API 面:自有插件路由,同源 fetch 自动带会话鉴权。 */
2
+
3
+ export interface VNotePublic {
4
+ id: string
5
+ title: string
6
+ status: 'recording' | 'transcribing' | 'ready' | 'failed'
7
+ createdAt: string
8
+ stoppedAt?: string
9
+ segments: number
10
+ transcript?: string
11
+ summary?: string
12
+ shareId?: string
13
+ error?: string
14
+ audioSeconds?: number
15
+ }
16
+
17
+ async function post(path: string, body: Record<string, unknown>): Promise<Record<string, unknown>> {
18
+ const res = await fetch(path, {
19
+ method: 'POST',
20
+ headers: { 'content-type': 'application/json' },
21
+ body: JSON.stringify(body),
22
+ })
23
+ const data = await res.json().catch(() => ({}))
24
+ if (!res.ok) throw new Error(String((data as { error?: string }).error ?? res.status))
25
+ return data
26
+ }
27
+
28
+ export async function listNotes(): Promise<VNotePublic[]> {
29
+ const res = await fetch('/mino-voice-notes/api/list', { cache: 'no-store' })
30
+ const data = (await res.json()) as { notes?: VNotePublic[] }
31
+ return data.notes ?? []
32
+ }
33
+
34
+ export const startNote = (title?: string) => post('/mino-voice-notes/api/start', title ? { title } : {})
35
+ export const stopNote = (id: string) => post('/mino-voice-notes/api/stop', { id })
36
+ export const getNote = async (id: string): Promise<VNotePublic | undefined> => {
37
+ const res = await fetch(`/mino-voice-notes/api/note?id=${encodeURIComponent(id)}`, { cache: 'no-store' })
38
+ if (!res.ok) return undefined
39
+ const data = (await res.json()) as { note?: VNotePublic }
40
+ return data.note
41
+ }
42
+ export const shareNote = (id: string) => post('/mino-voice-notes/api/share', { id })
43
+ export const deleteNote = (id: string) => post('/mino-voice-notes/api/delete', { id })
44
+ export const uploadSegment = (id: string, seq: number, wavBase64: string, durationMs: number) =>
45
+ post('/mino-voice-notes/api/segment', { id, seq, audio: wavBase64, durationMs })
@@ -0,0 +1,49 @@
1
+ /** mino-voice-notes 客户端半:注册进 mino-today 的「语音」tab 座位。
2
+ * 与 mino-today 同款注册法(slots.inject 座位缺席则安静缺席)。
3
+ * 数据面:同源 fetch 自有路由;录音经 MediaRecorder 同款 getUserMedia+PCM16 WAV 链。
4
+ */
5
+ import type { Context } from '@deepseek-ai/cordis'
6
+ import { VNotesPage } from './VNotesPage.tsx'
7
+ import { en, zh, type CopyKey } from './locales.ts'
8
+
9
+ export const inject = ['slots', 'locale']
10
+
11
+ const NS = 'mino-voice-notes'
12
+ const SEAT = 'today.page.voice'
13
+
14
+ interface SlotsFace {
15
+ inject(key: string, callback: () => (() => void) | void): () => void
16
+ register(options: Record<string, unknown>, component: unknown): () => void
17
+ }
18
+ interface LocaleFace {
19
+ register(ns: string, dicts: Record<string, Record<string, string>>): () => void
20
+ bind(ns: string): Translate
21
+ }
22
+ export type Translate = (key: CopyKey, params?: Record<string, unknown>) => string
23
+
24
+ export function apply(ctx: Context): void {
25
+ const slots = ctx.get('slots') as SlotsFace | undefined
26
+ const locale = ctx.get('locale') as LocaleFace | undefined
27
+ if (!slots) return
28
+
29
+ let t: Translate = (key, params) => {
30
+ const dict = zh as Record<string, string>
31
+ let s = dict[key] ?? key
32
+ if (params) for (const [k, v] of Object.entries(params)) s = s.replace(`{${k}}`, String(v))
33
+ return s
34
+ }
35
+ if (locale) {
36
+ ctx.effect(() => locale.register(NS, { zh, en }), 'mino-voice-notes: dictionaries')
37
+ const bound = locale.bind(NS)
38
+ t = (key, params) => bound(key as CopyKey, params)
39
+ }
40
+
41
+ ctx.effect(() =>
42
+ slots.inject(SEAT, () =>
43
+ slots.register({
44
+ name: SEAT,
45
+ id: 'mino-voice-notes',
46
+ locale: NS,
47
+ inject: () => ({ t }),
48
+ }, VNotesPage)))
49
+ }
@@ -0,0 +1,53 @@
1
+ export type CopyKey = keyof typeof zh
2
+
3
+ export const zh = {
4
+ 'entry.label': '语音笔记',
5
+ 'page.title': '语音笔记',
6
+ 'record.start': '开始录音',
7
+ 'record.stop': '结束并转写',
8
+ 'record.recording': '录音中',
9
+ 'record.micDenied': '麦克风不可用——检查浏览器授权',
10
+ 'list.empty': '还没有语音笔记。点「开始录音」录第一段。',
11
+ 'list.status.recording': '录制中',
12
+ 'list.status.transcribing': '转写中',
13
+ 'list.status.ready': '已完成',
14
+ 'list.status.failed': '失败',
15
+ 'detail.transcript': '转写',
16
+ 'detail.summary': '纪要',
17
+ 'detail.audio': '音频分段',
18
+ 'detail.noTranscript': '(暂无)',
19
+ 'action.share': '分享',
20
+ 'action.delete': '删除',
21
+ 'action.refresh': '刷新',
22
+ 'share.copied': '链接已复制',
23
+ 'share.path': '分享页',
24
+ 'group.today': '今天',
25
+ 'group.yesterday': '昨天',
26
+ 'group.earlier': '更早',
27
+ } as const
28
+
29
+ export const en: Record<CopyKey, string> = {
30
+ 'entry.label': 'Voice Notes',
31
+ 'page.title': 'Voice Notes',
32
+ 'record.start': 'Start recording',
33
+ 'record.stop': 'Stop & transcribe',
34
+ 'record.recording': 'Recording',
35
+ 'record.micDenied': 'Microphone unavailable — check browser permission',
36
+ 'list.empty': 'No voice notes yet. Hit "Start recording" for the first one.',
37
+ 'list.status.recording': 'Recording',
38
+ 'list.status.transcribing': 'Transcribing',
39
+ 'list.status.ready': 'Ready',
40
+ 'list.status.failed': 'Failed',
41
+ 'detail.transcript': 'Transcript',
42
+ 'detail.summary': 'Summary',
43
+ 'detail.audio': 'Audio segments',
44
+ 'detail.noTranscript': '(none yet)',
45
+ 'action.share': 'Share',
46
+ 'action.delete': 'Delete',
47
+ 'action.refresh': 'Refresh',
48
+ 'share.copied': 'Link copied',
49
+ 'share.path': 'Share page',
50
+ 'group.today': 'Today',
51
+ 'group.yesterday': 'Yesterday',
52
+ 'group.earlier': 'Earlier',
53
+ }
@@ -0,0 +1,96 @@
1
+ /** 录音引擎:getUserMedia → AudioContext(16kHz mono) → ScriptProcessor → PCM16 →
2
+ * WAV 编码,每 SEGMENT_MS 冲一段回调上传。官方 voice-input 同路径(16kHz mono PCM16 WAV),
3
+ * 但用 ScriptProcessorNode(AudioWorklet 内联 worker 在 tsdown 单文件包里要多绕一层)。
4
+ */
5
+
6
+ const SAMPLE_RATE = 16000
7
+ const CHANNELS = 1
8
+ const SEGMENT_MS = 15_000
9
+ const BUFFER_SIZE = 4096
10
+
11
+ export interface Recorder {
12
+ readonly seconds: () => number
13
+ stop(): Promise<void>
14
+ dispose(): void
15
+ }
16
+
17
+ /** PCM16 WAV 封装(RIFF 头 + interleaved s16le)。 */
18
+ export function encodeWav(chunks: Float32Array[], totalSamples: number, sampleRate = SAMPLE_RATE): ArrayBuffer {
19
+ const pcm = new Int16Array(totalSamples)
20
+ let off = 0
21
+ for (const chunk of chunks) {
22
+ for (let i = 0; i < chunk.length && off + i < totalSamples; i++) {
23
+ const s = Math.max(-1, Math.min(1, chunk[i]!))
24
+ pcm[off + i] = s < 0 ? s * 0x8000 : s * 0x7fff
25
+ }
26
+ off += chunk.length
27
+ }
28
+ const buf = new ArrayBuffer(44 + totalSamples * 2)
29
+ const v = new DataView(buf)
30
+ const wstr = (o: number, s: string) => { for (let i = 0; i < s.length; i++) v.setUint8(o + i, s.charCodeAt(i)) }
31
+ wstr(0, 'RIFF'); v.setUint32(4, 36 + totalSamples * 2, true); wstr(8, 'WAVE')
32
+ wstr(12, 'fmt '); v.setUint32(16, 16, true); v.setUint16(20, 1, true)
33
+ v.setUint16(22, CHANNELS, true); v.setUint32(24, sampleRate, true)
34
+ v.setUint32(28, sampleRate * CHANNELS * 2, true); v.setUint16(32, CHANNELS * 2, true); v.setUint16(34, 16, true)
35
+ wstr(36, 'data'); v.setUint32(40, totalSamples * 2, true)
36
+ new Int16Array(buf, 44).set(pcm)
37
+ return buf
38
+ }
39
+
40
+ export function wavToBase64(buf: ArrayBuffer): string {
41
+ const bytes = new Uint8Array(buf)
42
+ let bin = ''
43
+ const CHUNK = 0x8000
44
+ for (let i = 0; i < bytes.length; i += CHUNK) bin += String.fromCharCode(...bytes.subarray(i, i + CHUNK))
45
+ return btoa(bin)
46
+ }
47
+
48
+ export async function startRecording(onSegment: (wav: ArrayBuffer, durationMs: number) => void | Promise<void>): Promise<Recorder> {
49
+ const stream = await navigator.mediaDevices.getUserMedia({
50
+ audio: { channelCount: 1, sampleRate: SAMPLE_RATE, echoCancellation: true, noiseSuppression: true },
51
+ })
52
+ const ctx = new AudioContext({ sampleRate: SAMPLE_RATE })
53
+ const source = ctx.createMediaStreamSource(stream)
54
+ const proc = ctx.createScriptProcessor(BUFFER_SIZE, CHANNELS, CHANNELS)
55
+
56
+ let chunks: Float32Array[] = []
57
+ let samples = 0
58
+ let segmentStart = performance.now()
59
+ let flushed = false
60
+ const startedAt = performance.now()
61
+
62
+ const flush = async () => {
63
+ if (!samples) return
64
+ const wav = encodeWav(chunks, samples, ctx.sampleRate)
65
+ const ms = Math.round(performance.now() - segmentStart)
66
+ chunks = []; samples = 0; segmentStart = performance.now()
67
+ await onSegment(wav, ms)
68
+ }
69
+
70
+ proc.onaudioprocess = (e) => {
71
+ if (flushed) return
72
+ const input = e.inputBuffer.getChannelData(0)
73
+ chunks.push(new Float32Array(input))
74
+ samples += input.length
75
+ if (performance.now() - segmentStart >= SEGMENT_MS) void flush()
76
+ }
77
+ source.connect(proc)
78
+ proc.connect(ctx.destination)
79
+
80
+ return {
81
+ seconds: () => (performance.now() - startedAt) / 1000,
82
+ stop: async () => {
83
+ flushed = true
84
+ proc.onaudioprocess = null
85
+ await flush()
86
+ },
87
+ dispose: () => {
88
+ flushed = true
89
+ proc.onaudioprocess = null
90
+ try { proc.disconnect() } catch { /* 已断开 */ }
91
+ try { source.disconnect() } catch { /* 已断开 */ }
92
+ for (const track of stream.getTracks()) track.stop()
93
+ void ctx.close().catch(() => {})
94
+ },
95
+ }
96
+ }
@@ -0,0 +1,145 @@
1
+ /* mino-voice-notes:内嵌「今日 · 语音」tab,复用 today 解包视觉——
2
+ 玻璃容器 + ink 色阶 + 胶囊按钮,底色透明吃 today 页渐变。 */
3
+ .page {
4
+ --vn-ink: #3c3b41;
5
+ --vn-ink-2: rgba(52, 52, 81, 0.75);
6
+ --vn-ink-3: rgba(52, 52, 81, 0.45);
7
+ --vn-ink-fill: rgba(52, 52, 81, 0.08);
8
+ --vn-ink-fill-2: rgba(52, 52, 81, 0.04);
9
+ --vn-accent: #008aff;
10
+ --vn-accent-soft: rgba(0, 138, 255, 0.1);
11
+ --vn-accent-ink: #0071dd;
12
+ --vn-glass-bg: rgba(255, 255, 255, 0.8);
13
+ --vn-glass-border: rgba(0, 0, 0, 0.1);
14
+ --vn-glass-shadow: -4px 8px 28px rgba(104, 104, 104, 0.04), 0 2px 8px rgba(100, 100, 100, 0.06);
15
+ display: flex;
16
+ flex-direction: column;
17
+ height: 100%;
18
+ padding: 8px 0;
19
+ gap: 10px;
20
+ overflow: hidden;
21
+ color: var(--vn-ink);
22
+ }
23
+ :global(body[data-ds-dark-theme]) .page {
24
+ --vn-ink: #e8e8ec;
25
+ --vn-ink-2: rgba(232, 232, 236, 0.68);
26
+ --vn-ink-3: rgba(232, 232, 236, 0.42);
27
+ --vn-ink-fill: rgba(255, 255, 255, 0.08);
28
+ --vn-ink-fill-2: rgba(255, 255, 255, 0.04);
29
+ --vn-accent: #38bdf8;
30
+ --vn-accent-soft: rgba(56, 189, 248, 0.14);
31
+ --vn-accent-ink: #66b8ff;
32
+ --vn-glass-bg: rgba(255, 255, 255, 0.07);
33
+ --vn-glass-border: rgba(255, 255, 255, 0.08);
34
+ --vn-glass-shadow: -4px 8px 28px rgba(0, 0, 0, 0.2), 0 2px 8px rgba(0, 0, 0, 0.15);
35
+ }
36
+
37
+ .head { display: flex; align-items: center; gap: 10px; }
38
+ .btn {
39
+ padding: 8px 18px;
40
+ border-radius: 999px;
41
+ border: none;
42
+ background: var(--vn-ink);
43
+ color: #fff;
44
+ font-size: 13px;
45
+ font-weight: 500;
46
+ cursor: pointer;
47
+ transition: opacity 140ms ease;
48
+ }
49
+ .btn:hover { opacity: 0.85; }
50
+ :global(body[data-ds-dark-theme]) .btn { color: #1a1a1c; }
51
+ .btnStop { background: #e5484d; color: #fff; }
52
+ .miniButton {
53
+ padding: 6px 12px;
54
+ border-radius: 999px;
55
+ border: 0.5px solid var(--vn-glass-border);
56
+ background: transparent;
57
+ font-size: 12px;
58
+ cursor: pointer;
59
+ color: var(--vn-ink-2);
60
+ }
61
+ .miniButton:hover {
62
+ color: var(--vn-accent-ink);
63
+ border-color: var(--vn-accent);
64
+ background: var(--vn-accent-soft);
65
+ }
66
+ .danger { color: #e5484d; }
67
+ .danger:hover { color: #e5484d; border-color: #e5484d; background: rgba(229, 72, 77, 0.08); }
68
+ .error { color: #e5484d; font-size: 12px; }
69
+ .share {
70
+ font-size: 12px;
71
+ background: var(--vn-ink-fill-2);
72
+ border-radius: 10px;
73
+ padding: 8px 12px;
74
+ color: var(--vn-ink-2);
75
+ }
76
+ .share a { color: var(--vn-accent-ink); }
77
+
78
+ .body { display: flex; gap: 14px; flex: 1; min-height: 0; }
79
+
80
+ /* 笔记列:软行列表(today diaryList 同款,行自圆角) */
81
+ .list {
82
+ width: 300px;
83
+ flex-shrink: 0;
84
+ overflow-y: auto;
85
+ display: flex;
86
+ flex-direction: column;
87
+ gap: 4px;
88
+ }
89
+ .empty { color: var(--vn-ink-3); font-size: 13px; padding: 28px 14px; text-align: center; }
90
+ .groupHead {
91
+ font-size: 11px;
92
+ font-weight: 500;
93
+ letter-spacing: 0.3px;
94
+ color: var(--vn-ink-3);
95
+ padding: 10px 14px 4px;
96
+ }
97
+ .row {
98
+ padding: 10px 14px;
99
+ cursor: pointer;
100
+ border: 0.5px solid transparent;
101
+ border-radius: 12px;
102
+ }
103
+ .row:hover { background: var(--vn-ink-fill-2); }
104
+ .rowActive { border-color: var(--vn-accent); background: var(--vn-accent-soft); }
105
+ .rowTitle { font-size: 13px; font-weight: 500; color: var(--vn-ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
106
+ .rowMeta { display: flex; gap: 8px; align-items: center; font-size: 11px; color: var(--vn-ink-3); margin-top: 4px; }
107
+ .badge { padding: 3px 7px; border-radius: 999px; font-size: 10px; line-height: 1; }
108
+ .st_recording { background: rgba(229, 72, 77, 0.13); color: #e5484d; }
109
+ .st_transcribing { background: rgba(255, 197, 61, 0.3); color: #8a5d00; }
110
+ .st_ready { background: rgba(48, 164, 108, 0.15); color: #30a46c; }
111
+ .st_failed { background: var(--vn-ink-fill); color: var(--vn-ink-3); }
112
+
113
+ .detail {
114
+ flex: 1;
115
+ overflow-y: auto;
116
+ border: 0.5px solid var(--vn-glass-border);
117
+ border-radius: 16px;
118
+ background: var(--vn-glass-bg);
119
+ box-shadow: var(--vn-glass-shadow);
120
+ backdrop-filter: blur(24px) saturate(1.2);
121
+ -webkit-backdrop-filter: blur(24px) saturate(1.2);
122
+ padding: 16px 18px;
123
+ }
124
+ .detailHead { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
125
+ .detailHead > div { display: flex; gap: 8px; flex: none; }
126
+ .detailHead h2 { font-size: 15px; font-weight: 500; margin: 0; color: var(--vn-ink); }
127
+ .detail h3 { font-size: 12px; font-weight: 500; color: var(--vn-ink-3); margin: 16px 0 6px; }
128
+ .pre {
129
+ white-space: pre-wrap;
130
+ font-size: 13px;
131
+ line-height: 1.7;
132
+ color: var(--vn-ink-2);
133
+ background: var(--vn-ink-fill-2);
134
+ border-radius: 12px;
135
+ padding: 10px 12px;
136
+ margin: 0;
137
+ max-height: 300px;
138
+ overflow-y: auto;
139
+ }
140
+ .audio { width: 100%; height: 32px; display: block; margin-bottom: 6px; }
141
+
142
+ @media (max-width: 640px) {
143
+ .body { flex-direction: column; overflow-y: auto; }
144
+ .list { width: 100%; max-height: 40%; flex-shrink: 0; }
145
+ }
@@ -0,0 +1,4 @@
1
+ declare module '*.module.css' {
2
+ const classes: Record<string, string>
3
+ export default classes
4
+ }
package/src/index.ts ADDED
@@ -0,0 +1,443 @@
1
+ /** mino-voice-notes 宿主半:vnote_* 模型工具 + 分段上传/分享路由 + speechToText 转写 + 服务缝。
2
+ *
3
+ * 解耦边界(全官方缝,零他插件私域):
4
+ * - 录音段:自有 client 半经 MediaRecorder/AudioWorklet 采 PCM16 WAV → POST /mino-voice-notes/api/segment
5
+ * - 转写:ctx.speechToText(resolve→transcribe 官方缝;sensevoice provider 由 voice-input bundle 内置)
6
+ * - 纪要:模型读 vnote_get 的转写文 → vnote_update 写回 summary → 可 today_post 投 feed(软依赖,不耦合)
7
+ * - 分享:/mino-voice-notes/s/<shareId> 只读页(web 档鉴权域内,本地链接)
8
+ * - 服务缝:ctx.provide('mino-voice-notes') 暴露 start/stop/getStatus 给 meeting-detect 等消费方
9
+ */
10
+ import type { Context } from '@deepseek-ai/cordis'
11
+ import {
12
+ appendSegment, deleteNote, getNote, loadNotes, newId, putNote, readSegment,
13
+ type VNote,
14
+ } from './store.ts'
15
+
16
+ export const name = 'mino-voice-notes'
17
+ export const inject = ['webServer', 'tools']
18
+
19
+ const JSON_HEADERS = { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
20
+ const MAX_TITLE = 120
21
+ const MAX_SEGMENTS = 400
22
+ const MAX_SEGMENT_BYTES = 24 * 1024 * 1024
23
+ const TRANSCRIBE_TIMEOUT_MS = 120_000
24
+
25
+ interface WebServerFace {
26
+ register(route: {
27
+ kind: 'exact' | 'prefix'
28
+ path: string
29
+ handler: (req: NodeReq, res: NodeRes) => Promise<void> | void
30
+ }): () => void
31
+ }
32
+ interface NodeReq {
33
+ url?: string
34
+ method?: string
35
+ on(event: 'data' | 'end', cb: (chunk?: unknown) => void): void
36
+ [Symbol.asyncIterator]?: () => AsyncIterableIterator<unknown>
37
+ }
38
+ interface NodeRes {
39
+ writeHead(status: number, headers?: Record<string, string>): void
40
+ end(body?: string): void
41
+ }
42
+ interface ToolsFace {
43
+ register(tool: Record<string, unknown>, options?: Record<string, unknown>): () => void
44
+ }
45
+
46
+ /** ctx.speechToText 官方缝的结构面(experimental/speech-to-text 的 resolve/transcribe 契约)。 */
47
+ interface SpeechToTextFace {
48
+ resolve(request: { audio: Uint8Array; providerId?: string; language?: string }): { provider: unknown; audio: Uint8Array; language: string }
49
+ transcribe(spec: { provider: unknown; audio: Uint8Array; language: string }, signal: AbortSignal): Promise<{ text: string; audioSeconds: number; inferenceSeconds: number }>
50
+ }
51
+
52
+ /** 提供给其他插件消费的服务缝(meeting-detect 预约/触发录音走这里,不走工具名)。 */
53
+ interface VoiceNotesService {
54
+ start(title?: string): VNote
55
+ stop(id: string): VNote | undefined
56
+ status(id: string): VNote | undefined
57
+ }
58
+
59
+ function sendJson(res: NodeRes, status: number, body: unknown): void {
60
+ res.writeHead(status, JSON_HEADERS)
61
+ res.end(JSON.stringify(body))
62
+ }
63
+ async function readBody(req: NodeReq): Promise<Record<string, unknown>> {
64
+ let raw = ''
65
+ for await (const chunk of req as AsyncIterable<unknown>) raw += String(chunk)
66
+ if (!raw) return {}
67
+ try {
68
+ const parsed = JSON.parse(raw)
69
+ return parsed && typeof parsed === 'object' ? parsed as Record<string, unknown> : {}
70
+ } catch {
71
+ return {}
72
+ }
73
+ }
74
+ const clip = (s: unknown, max: number): string | undefined => {
75
+ if (s === undefined || s === null) return undefined
76
+ const v = String(s).slice(0, max)
77
+ return v || undefined
78
+ }
79
+ const esc = (s: string): string =>
80
+ s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
81
+
82
+ function notePublic(n: VNote) {
83
+ return {
84
+ id: n.id, title: n.title, status: n.status,
85
+ createdAt: n.createdAt, stoppedAt: n.stoppedAt,
86
+ segments: n.segments.length, transcript: n.transcript,
87
+ summary: n.summary, shareId: n.shareId, error: n.error,
88
+ audioSeconds: n.audioSeconds,
89
+ }
90
+ }
91
+
92
+ function startNote(title?: string): VNote {
93
+ const now = new Date().toISOString()
94
+ const note: VNote = {
95
+ id: newId(),
96
+ title: (title || `录音 ${now.slice(0, 16).replace('T', ' ')}`).slice(0, MAX_TITLE),
97
+ status: 'recording',
98
+ createdAt: now,
99
+ updatedAt: now,
100
+ segments: [],
101
+ }
102
+ putNote(note)
103
+ return note
104
+ }
105
+
106
+ async function transcribeNote(ctx: Context, note: VNote): Promise<VNote> {
107
+ const stt = ctx.get('speechToText') as SpeechToTextFace | undefined
108
+ if (!stt?.transcribe) {
109
+ note.status = 'failed'
110
+ note.error = '没有可用的语音转写服务(装 voice-input bundle / 配 ASR provider)'
111
+ note.updatedAt = new Date().toISOString()
112
+ putNote(note)
113
+ return note
114
+ }
115
+ const segments = [...note.segments].sort((a, b) => a.seq - b.seq)
116
+ if (!segments.length) {
117
+ note.status = 'failed'
118
+ note.error = '没有音频分段'
119
+ note.updatedAt = new Date().toISOString()
120
+ putNote(note)
121
+ return note
122
+ }
123
+ const texts: string[] = []
124
+ let audioSeconds = 0
125
+ const controller = new AbortController()
126
+ const timer = setTimeout(() => controller.abort(new Error('transcribe timeout')), TRANSCRIBE_TIMEOUT_MS)
127
+ try {
128
+ for (const seg of segments) {
129
+ const wav = readSegment(note.id, seg.seq)
130
+ if (!wav) continue
131
+ const spec = stt.resolve({ audio: new Uint8Array(wav) })
132
+ const out = await stt.transcribe(spec, controller.signal)
133
+ if (out.text?.trim()) texts.push(out.text.trim())
134
+ audioSeconds += out.audioSeconds || 0
135
+ }
136
+ note.transcript = texts.join('\n')
137
+ note.audioSeconds = audioSeconds || undefined
138
+ note.status = 'ready'
139
+ note.error = undefined
140
+ } catch (error) {
141
+ note.status = 'failed'
142
+ note.error = `转写失败:${String((error as Error)?.message ?? error)}`
143
+ } finally {
144
+ clearTimeout(timer)
145
+ note.updatedAt = new Date().toISOString()
146
+ putNote(note)
147
+ }
148
+ return note
149
+ }
150
+
151
+ function stopAndTranscribe(ctx: Context, id: string): VNote | 'not_found' | 'bad_state' {
152
+ const note = getNote(id)
153
+ if (!note) return 'not_found'
154
+ if (note.status !== 'recording') return 'bad_state'
155
+ note.status = 'transcribing'
156
+ note.stoppedAt = new Date().toISOString()
157
+ note.updatedAt = note.stoppedAt
158
+ putNote(note)
159
+ // 转写走后台:长音频不阻塞工具/路由调用方;调用方轮询 vnote_get/api/note。
160
+ void transcribeNote(ctx, note).catch(() => { /* transcribeNote 内部已落 failed 状态 */ })
161
+ return note
162
+ }
163
+
164
+ const PARAM_ID = { type: 'object', additionalProperties: false, required: ['id'], properties: { id: { type: 'string', description: '笔记 id(vn_ 开头)。' } } }
165
+ const OUT_NOTE = {
166
+ type: 'object', additionalProperties: false,
167
+ properties: {
168
+ id: { type: 'string' }, title: { type: 'string' }, status: { type: 'string' },
169
+ transcript: { type: 'string' }, summary: { type: 'string' }, error: { type: 'string' },
170
+ },
171
+ }
172
+
173
+ function makeTools(ctx: Context): Record<string, unknown>[] {
174
+ return [
175
+ {
176
+ name: 'vnote_start',
177
+ description:
178
+ '开始一段语音笔记录音。返回笔记 id——客户端的「语音笔记」面板会用这个 id 上传音频分段;' +
179
+ '录完用 vnote_stop 收尾并转写。',
180
+ parameters: {
181
+ type: 'object', additionalProperties: false,
182
+ properties: { title: { type: 'string', description: '可选。给这段录音起个名(≤120字)。' } },
183
+ },
184
+ output: { schema: OUT_NOTE, render: (_a: unknown, v: { id?: string }) => [{ type: 'text', text: `开始录音 ${v?.id ?? ''}` }] },
185
+ isConcurrencySafe: () => false,
186
+ async execute(args: { title?: string }) {
187
+ const note = startNote(args.title)
188
+ return { id: note.id, title: note.title, status: note.status }
189
+ },
190
+ presentCall: (a: { title?: string }) => ({ card: 'generic', title: a?.title ? `开始录音:${a.title}` : '开始录音', kind: 'other', rawInput: a }),
191
+ },
192
+ {
193
+ name: 'vnote_stop',
194
+ description:
195
+ '结束一段录音并触发本机转写。转写在后台跑——长录音别干等,过几秒用 vnote_get 取结果。',
196
+ parameters: PARAM_ID,
197
+ output: { schema: OUT_NOTE, render: (_a: unknown, v: { status?: string }) => [{ type: 'text', text: `收尾:${v?.status ?? ''}` }] },
198
+ isConcurrencySafe: () => false,
199
+ async execute(args: { id: string }) {
200
+ const r = stopAndTranscribe(ctx, String(args.id || ''))
201
+ if (r === 'not_found') throw new Error(`找不到笔记 ${args.id}`)
202
+ if (r === 'bad_state') throw new Error('这段录音不在录制中(可能已收尾)')
203
+ return { id: r.id, title: r.title, status: r.status }
204
+ },
205
+ presentCall: () => ({ card: 'generic', title: '结束录音', kind: 'other' }),
206
+ },
207
+ {
208
+ name: 'vnote_list',
209
+ description: '列出最近的语音笔记(id/标题/状态/时长),不含转写全文——要全文用 vnote_get。',
210
+ parameters: {
211
+ type: 'object', additionalProperties: false,
212
+ properties: { limit: { type: 'integer', description: '最近多少条(默认 20)' } },
213
+ },
214
+ output: {
215
+ schema: { type: 'object', additionalProperties: false, properties: { count: { type: 'integer' }, notes: { type: 'array', items: { type: 'object', additionalProperties: true } } } },
216
+ render: (_a: unknown, v: { count?: number }) => [{ type: 'text', text: `${v?.count ?? 0} 条语音笔记` }],
217
+ },
218
+ isConcurrencySafe: () => true,
219
+ async execute(args: { limit?: number }) {
220
+ const limit = Math.min(Math.max(Number(args.limit) || 20, 1), 100)
221
+ const notes = Object.values(loadNotes())
222
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
223
+ .slice(0, limit)
224
+ .map(notePublic)
225
+ return { count: notes.length, notes }
226
+ },
227
+ presentCall: () => ({ card: 'generic', title: '看语音笔记', kind: 'other' }),
228
+ },
229
+ {
230
+ name: 'vnote_get',
231
+ description: '取一条语音笔记的完整信息:转写全文、纪要、状态。转写文可能很长。',
232
+ parameters: PARAM_ID,
233
+ output: { schema: OUT_NOTE, render: (_a: unknown, v: { status?: string }) => [{ type: 'text', text: `笔记 ${v?.status ?? ''}` }] },
234
+ isConcurrencySafe: () => true,
235
+ async execute(args: { id: string }) {
236
+ const note = getNote(String(args.id || ''))
237
+ if (!note) throw new Error(`找不到笔记 ${args.id}`)
238
+ return notePublic(note)
239
+ },
240
+ presentCall: () => ({ card: 'generic', title: '读语音笔记', kind: 'other' }),
241
+ },
242
+ {
243
+ name: 'vnote_update',
244
+ description:
245
+ '改一条语音笔记的标题或纪要。转写完之后,把读出来的要点写成 summary 存回去。',
246
+ parameters: {
247
+ type: 'object', additionalProperties: false, required: ['id'],
248
+ properties: {
249
+ id: { type: 'string', description: '笔记 id。' },
250
+ title: { type: 'string', description: '可选。新标题(≤120字)。' },
251
+ summary: { type: 'string', description: '可选。纪要文字(≤4000字)。' },
252
+ },
253
+ },
254
+ output: { schema: OUT_NOTE, render: () => [{ type: 'text', text: '已更新' }] },
255
+ isConcurrencySafe: () => false,
256
+ async execute(args: { id: string; title?: string; summary?: string }) {
257
+ const note = getNote(String(args.id || ''))
258
+ if (!note) throw new Error(`找不到笔记 ${args.id}`)
259
+ const title = clip(args.title, MAX_TITLE)
260
+ const summary = clip(args.summary, 4000)
261
+ if (title !== undefined) note.title = title
262
+ if (summary !== undefined) note.summary = summary
263
+ note.updatedAt = new Date().toISOString()
264
+ putNote(note)
265
+ return { id: note.id, title: note.title, status: note.status }
266
+ },
267
+ presentCall: () => ({ card: 'generic', title: '改语音笔记', kind: 'other' }),
268
+ },
269
+ {
270
+ name: 'vnote_share',
271
+ description: '给一条已完成的语音笔记生成本地只读分享页(转写+纪要+音频分段),返回页面路径。',
272
+ parameters: PARAM_ID,
273
+ output: {
274
+ schema: { type: 'object', additionalProperties: false, properties: { shareId: { type: 'string' }, path: { type: 'string' } } },
275
+ render: (_a: unknown, v: { path?: string }) => [{ type: 'text', text: `分享页 ${v?.path ?? ''}` }],
276
+ },
277
+ isConcurrencySafe: () => false,
278
+ async execute(args: { id: string }) {
279
+ const note = getNote(String(args.id || ''))
280
+ if (!note) throw new Error(`找不到笔记 ${args.id}`)
281
+ if (!note.shareId) {
282
+ note.shareId = Math.random().toString(36).slice(2, 10) + Date.now().toString(36)
283
+ note.updatedAt = new Date().toISOString()
284
+ putNote(note)
285
+ }
286
+ return { shareId: note.shareId, path: `/mino-voice-notes/s/${note.shareId}` }
287
+ },
288
+ presentCall: () => ({ card: 'generic', title: '分享语音笔记', kind: 'other' }),
289
+ },
290
+ ]
291
+ }
292
+
293
+ function sharePage(note: VNote): string {
294
+ const segs = note.segments.map(s =>
295
+ `<li><a href="/mino-voice-notes/api/audio?id=${encodeURIComponent(note.id)}&seq=${s.seq}">分段 ${s.seq}</a>(${(s.bytes / 1024).toFixed(0)} KB)</li>`).join('')
296
+ return `<!doctype html><html lang="zh"><head><meta charset="utf-8"><title>${esc(note.title)}</title>
297
+ <meta name="viewport" content="width=device-width,initial-scale=1">
298
+ <style>body{font-family:system-ui,sans-serif;max-width:720px;margin:32px auto;padding:0 16px;color:#222}
299
+ h1{font-size:20px}h2{font-size:15px;margin-top:28px;color:#555}
300
+ pre{white-space:pre-wrap;background:#f6f6f6;padding:14px;border-radius:8px;font-size:14px;line-height:1.7}
301
+ ul{padding-left:20px}.muted{color:#888;font-size:12px}</style></head><body>
302
+ <h1>${esc(note.title)}</h1><div class="muted">${esc(note.createdAt)} · ${note.audioSeconds ? note.audioSeconds.toFixed(1) + 's' : ''}</div>
303
+ ${note.summary ? `<h2>纪要</h2><pre>${esc(note.summary)}</pre>` : ''}
304
+ <h2>转写</h2><pre>${esc(note.transcript || '(无)')}</pre>
305
+ <h2>音频</h2><ul>${segs || '<li>无分段</li>'}</ul>
306
+ </body></html>`
307
+ }
308
+
309
+ export function apply(ctx: Context): void {
310
+ const webServer = ctx.get('webServer') as WebServerFace | undefined
311
+ const tools = ctx.get('tools') as ToolsFace | undefined
312
+
313
+ // 服务缝:其他插件(meeting-detect 等)经 ctx.get('mino-voice-notes') 消费,不走工具名。
314
+ // 与 task-board 同款守卫:宿主没有 provide 面时安静缺席。
315
+ if (typeof (ctx as { provide?: unknown }).provide === 'function') {
316
+ ;(ctx as Context & { provide: (name: string, svc: VoiceNotesService) => void }).provide('mino-voice-notes', {
317
+ start: (title?: string) => startNote(title),
318
+ stop: (id: string) => { const r = stopAndTranscribe(ctx, id); return typeof r === 'object' ? r : undefined },
319
+ status: (id: string) => getNote(id),
320
+ })
321
+ }
322
+
323
+ const route = (kind: 'exact' | 'prefix', path: string, handler: (req: NodeReq, res: NodeRes) => Promise<void> | void) => {
324
+ if (!webServer) return
325
+ ctx.effect(() =>
326
+ webServer.register({
327
+ kind, path,
328
+ handler: async (req, res) => {
329
+ try { await handler(req, res) } catch (error) {
330
+ sendJson(res, 500, { ok: false, error: String((error as Error)?.message ?? error) })
331
+ }
332
+ },
333
+ }),
334
+ )
335
+ }
336
+
337
+ route('exact', '/mino-voice-notes/api/start', async (req, res) => {
338
+ const body = await readBody(req)
339
+ const note = startNote(clip(body.title, MAX_TITLE))
340
+ sendJson(res, 200, { ok: true, id: note.id, title: note.title })
341
+ })
342
+
343
+ route('exact', '/mino-voice-notes/api/segment', async (req, res) => {
344
+ const body = await readBody(req)
345
+ const id = String(body.id || '')
346
+ const seq = Number(body.seq)
347
+ const note = getNote(id)
348
+ if (!note) return sendJson(res, 404, { ok: false, error: '找不到笔记' })
349
+ if (note.status !== 'recording') return sendJson(res, 409, { ok: false, error: '不在录制中' })
350
+ if (!Number.isInteger(seq) || seq < 0 || seq >= MAX_SEGMENTS) return sendJson(res, 400, { ok: false, error: 'seq 不对' })
351
+ if (typeof body.audio !== 'string' || !body.audio) return sendJson(res, 400, { ok: false, error: 'audio 为空' })
352
+ const wav = Buffer.from(body.audio, 'base64')
353
+ if (!wav.length || wav.length > MAX_SEGMENT_BYTES) return sendJson(res, 400, { ok: false, error: 'audio 大小不对' })
354
+ if (wav.length > 12 && wav.toString('ascii', 0, 4) !== 'RIFF') return sendJson(res, 400, { ok: false, error: 'audio 不是 WAV' })
355
+ const seg = appendSegment(id, seq, wav, Number.isFinite(+body.durationMs!) ? +body.durationMs! : undefined)
356
+ const fresh = getNote(id)!
357
+ if (!fresh.segments.some(s => s.seq === seq)) fresh.segments.push(seg)
358
+ else fresh.segments = fresh.segments.map(s => (s.seq === seq ? seg : s))
359
+ fresh.updatedAt = new Date().toISOString()
360
+ putNote(fresh)
361
+ sendJson(res, 200, { ok: true, seq, bytes: seg.bytes })
362
+ })
363
+
364
+ route('exact', '/mino-voice-notes/api/stop', async (req, res) => {
365
+ const body = await readBody(req)
366
+ const r = stopAndTranscribe(ctx, String(body.id || ''))
367
+ if (r === 'not_found') return sendJson(res, 404, { ok: false, error: '找不到笔记' })
368
+ if (r === 'bad_state') return sendJson(res, 409, { ok: false, error: '不在录制中' })
369
+ sendJson(res, 200, { ok: true, id: r.id, status: r.status })
370
+ })
371
+
372
+ route('exact', '/mino-voice-notes/api/list', async (_req, res) => {
373
+ const notes = Object.values(loadNotes())
374
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
375
+ .slice(0, 100)
376
+ .map(notePublic)
377
+ sendJson(res, 200, { ok: true, notes })
378
+ })
379
+
380
+ route('exact', '/mino-voice-notes/api/note', async (req, res) => {
381
+ const url = new URL(req.url || '', 'http://localhost')
382
+ const note = getNote(url.searchParams.get('id') || '')
383
+ if (!note) return sendJson(res, 404, { ok: false, error: '找不到笔记' })
384
+ sendJson(res, 200, { ok: true, note: notePublic(note) })
385
+ })
386
+
387
+ route('exact', '/mino-voice-notes/api/update', async (req, res) => {
388
+ const body = await readBody(req)
389
+ const note = getNote(String(body.id || ''))
390
+ if (!note) return sendJson(res, 404, { ok: false, error: '找不到笔记' })
391
+ const title = clip(body.title, MAX_TITLE)
392
+ const summary = clip(body.summary, 4000)
393
+ if (title !== undefined) note.title = title
394
+ if (summary !== undefined) note.summary = summary
395
+ note.updatedAt = new Date().toISOString()
396
+ putNote(note)
397
+ sendJson(res, 200, { ok: true })
398
+ })
399
+
400
+ route('exact', '/mino-voice-notes/api/share', async (req, res) => {
401
+ const body = await readBody(req)
402
+ const note = getNote(String(body.id || ''))
403
+ if (!note) return sendJson(res, 404, { ok: false, error: '找不到笔记' })
404
+ if (!note.shareId) {
405
+ note.shareId = Math.random().toString(36).slice(2, 10) + Date.now().toString(36)
406
+ note.updatedAt = new Date().toISOString()
407
+ putNote(note)
408
+ }
409
+ sendJson(res, 200, { ok: true, shareId: note.shareId, path: `/mino-voice-notes/s/${note.shareId}` })
410
+ })
411
+
412
+ route('exact', '/mino-voice-notes/api/delete', async (req, res) => {
413
+ const body = await readBody(req)
414
+ if (!deleteNote(String(body.id || ''))) return sendJson(res, 404, { ok: false, error: '找不到笔记' })
415
+ sendJson(res, 200, { ok: true })
416
+ })
417
+
418
+ route('exact', '/mino-voice-notes/api/audio', async (req, res) => {
419
+ const url = new URL(req.url || '', 'http://localhost')
420
+ const note = getNote(url.searchParams.get('id') || '')
421
+ const seq = Number(url.searchParams.get('seq'))
422
+ if (!note || !Number.isInteger(seq)) return sendJson(res, 404, { ok: false, error: '找不到' })
423
+ const wav = readSegment(note.id, seq)
424
+ if (!wav) return sendJson(res, 404, { ok: false, error: '找不到分段' })
425
+ res.writeHead(200, { 'content-type': 'audio/wav', 'content-length': String(wav.length), 'cache-control': 'no-store' })
426
+ res.end(wav.toString('binary'))
427
+ })
428
+
429
+ route('prefix', '/mino-voice-notes/s', async (req, res) => {
430
+ const shareId = (req.url || '').split('/mino-voice-notes/s/')[1]?.split(/[?#]/)[0] || ''
431
+ const note = Object.values(loadNotes()).find(n => n.shareId === shareId)
432
+ if (!note) {
433
+ res.writeHead(404, { 'content-type': 'text/html; charset=utf-8' })
434
+ return res.end('<!doctype html><meta charset="utf-8"><p>分享不存在或已删除。</p>')
435
+ }
436
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' })
437
+ res.end(sharePage(note))
438
+ })
439
+
440
+ if (tools) {
441
+ for (const tool of makeTools(ctx)) ctx.effect(() => tools.register(tool))
442
+ }
443
+ }
package/src/store.ts ADDED
@@ -0,0 +1,95 @@
1
+ /** mino-voice-notes 自有存储:notes.json 元数据索引 + audio/<id>/<seq>.wav 分段文件。
2
+ * 位置 `$DSH_HOME/mino-voice-notes/`(无 DSH_HOME 时 `~/.mino/mino-voice-notes/`)——
3
+ * 与 mino-today 同一落点约定,不读其他插件私有目录。
4
+ */
5
+ import { mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs'
6
+ import { join } from 'node:path'
7
+ import { homedir } from 'node:os'
8
+
9
+ const ROOT = join(process.env.DSH_HOME || join(homedir(), '.mino'), 'mino-voice-notes')
10
+ const AUDIO_DIR = join(ROOT, 'audio')
11
+ const STORE_FILE = join(ROOT, 'notes.json')
12
+
13
+ export type VNoteStatus = 'recording' | 'transcribing' | 'ready' | 'failed'
14
+
15
+ export interface VNoteSegment {
16
+ seq: number
17
+ file: string
18
+ bytes: number
19
+ durationMs?: number
20
+ }
21
+
22
+ export interface VNote {
23
+ id: string
24
+ title: string
25
+ status: VNoteStatus
26
+ createdAt: string
27
+ updatedAt: string
28
+ stoppedAt?: string
29
+ segments: VNoteSegment[]
30
+ transcript?: string
31
+ summary?: string
32
+ shareId?: string
33
+ error?: string
34
+ audioSeconds?: number
35
+ }
36
+
37
+ interface NotesFile { notes: Record<string, VNote> }
38
+
39
+ function ensureDirs(): void {
40
+ mkdirSync(AUDIO_DIR, { recursive: true })
41
+ }
42
+
43
+ export function loadNotes(): Record<string, VNote> {
44
+ try {
45
+ const raw = readFileSync(STORE_FILE, 'utf-8')
46
+ const parsed = JSON.parse(raw) as NotesFile
47
+ return parsed && typeof parsed === 'object' && parsed.notes && typeof parsed.notes === 'object' ? parsed.notes : {}
48
+ } catch {
49
+ return {}
50
+ }
51
+ }
52
+
53
+ export function saveNotes(notes: Record<string, VNote>): void {
54
+ ensureDirs()
55
+ writeFileSync(STORE_FILE, JSON.stringify({ notes }, null, 2))
56
+ }
57
+
58
+ export function getNote(id: string): VNote | undefined {
59
+ return loadNotes()[id]
60
+ }
61
+
62
+ export function putNote(note: VNote): void {
63
+ const notes = loadNotes()
64
+ notes[note.id] = note
65
+ saveNotes(notes)
66
+ }
67
+
68
+ export function deleteNote(id: string): boolean {
69
+ const notes = loadNotes()
70
+ if (!notes[id]) return false
71
+ delete notes[id]
72
+ saveNotes(notes)
73
+ try { rmSync(join(AUDIO_DIR, id), { recursive: true, force: true }) } catch { /* 音频目录缺失按无处理 */ }
74
+ return true
75
+ }
76
+
77
+ export function segmentPath(id: string, seq: number): string {
78
+ return join(AUDIO_DIR, id, `seg-${String(seq).padStart(4, '0')}.wav`)
79
+ }
80
+
81
+ export function appendSegment(id: string, seq: number, wav: Buffer, durationMs?: number): VNoteSegment {
82
+ const dir = join(AUDIO_DIR, id)
83
+ mkdirSync(dir, { recursive: true })
84
+ const file = segmentPath(id, seq)
85
+ writeFileSync(file, wav)
86
+ return { seq, file, bytes: wav.length, ...(durationMs !== undefined ? { durationMs } : {}) }
87
+ }
88
+
89
+ export function readSegment(id: string, seq: number): Buffer | undefined {
90
+ try { return readFileSync(segmentPath(id, seq)) } catch { return undefined }
91
+ }
92
+
93
+ export function newId(): string {
94
+ return `vn_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`
95
+ }