dsh-duet 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.
Files changed (40) hide show
  1. package/HEROICONS-LICENSE.txt +24 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +77 -0
  5. package/deepseek_harness_duplex_control.patch.yml +3 -0
  6. package/deepseek_harness_duplex_control_plugin.html +392 -0
  7. package/deepseek_harness_duplex_control_plugin.mjs +1105 -0
  8. package/deepseek_harness_duplex_focus_client/lib/client.js +466 -0
  9. package/deepseek_harness_voice_audio.mjs +135 -0
  10. package/deepseek_harness_voice_browser.mjs +343 -0
  11. package/deepseek_harness_voice_catalog.mjs +56 -0
  12. package/deepseek_harness_voice_composer.mjs +125 -0
  13. package/deepseek_harness_voice_consent.mjs +63 -0
  14. package/deepseek_harness_voice_feedback.mjs +48 -0
  15. package/deepseek_harness_voice_feedback_files.mjs +55 -0
  16. package/deepseek_harness_voice_feedback_store.mjs +51 -0
  17. package/deepseek_harness_voice_interactions.mjs +32 -0
  18. package/deepseek_harness_voice_microphone.mjs +59 -0
  19. package/deepseek_harness_voice_notices.mjs +54 -0
  20. package/deepseek_harness_voice_proxy.mjs +223 -0
  21. package/deepseek_harness_voice_rpc.mjs +104 -0
  22. package/deepseek_harness_voice_service_info.mjs +45 -0
  23. package/deepseek_harness_voice_settings.mjs +95 -0
  24. package/deepseek_harness_voice_shortcuts.mjs +69 -0
  25. package/deepseek_harness_voice_state.mjs +171 -0
  26. package/deepseek_harness_voice_trace.mjs +107 -0
  27. package/deepseek_harness_voice_tutorial.mjs +265 -0
  28. package/deepseek_harness_voice_tutorial_adapter.mjs +95 -0
  29. package/deepseek_harness_voice_tutorial_request.mjs +16 -0
  30. package/package.json +57 -0
  31. package/tutorial-audio/broadcast.wav +0 -0
  32. package/tutorial-audio/clear.wav +0 -0
  33. package/tutorial-audio/edit.wav +0 -0
  34. package/tutorial-audio/input.wav +0 -0
  35. package/tutorial-audio/manifest.json +60 -0
  36. package/tutorial-audio/modes_broadcast.wav +0 -0
  37. package/tutorial-audio/modes_interaction.wav +0 -0
  38. package/tutorial-audio/reinput.wav +0 -0
  39. package/tutorial-audio/send.wav +0 -0
  40. package/tutorial-audio/switch.wav +0 -0
@@ -0,0 +1,95 @@
1
+ /** Host-only settings. Never return stored credentials to the browser. */
2
+ import { readFileSync } from 'node:fs'
3
+ import { mkdir, writeFile, rename, unlink } from 'node:fs/promises'
4
+ import { dirname, join } from 'node:path'
5
+ import { homedir } from 'node:os'
6
+ import { randomUUID } from 'node:crypto'
7
+
8
+ export function validateBackendURL(value, insecureOrigin = null) {
9
+ if (typeof value !== 'string' || value.length > 2048) throw new Error('invalid_backend_url')
10
+ const url = new URL(value)
11
+ if (!['ws:', 'wss:'].includes(url.protocol) || url.username || url.password || url.hash) throw new Error('invalid_backend_url')
12
+ // Credentials belong in the host-only token field, never in URLs or logs.
13
+ if ([...url.searchParams.keys()].some(k => k !== 'protocol')) throw new Error('backend_url_query_not_allowed')
14
+ if (url.protocol === 'ws:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) && url.origin !== insecureOrigin) throw new Error('backend_requires_wss')
15
+ return url.toString()
16
+ }
17
+
18
+ export class VoiceSettings {
19
+ constructor(base, { path, debug = false } = {}) {
20
+ this.base = base
21
+ this.path = path || process.env.DUPLEX_VOICE_SETTINGS_FILE || join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'duplex-control', 'voice.json')
22
+ this.debug = debug
23
+ this.saved = null
24
+ this.revision = 0
25
+ this.writing = false
26
+ try {
27
+ const data = JSON.parse(readFileSync(this.path, 'utf8'))
28
+ this.saved = this.validate(data)
29
+ } catch (error) { if (error.code !== 'ENOENT') throw new Error('invalid_voice_settings_file') }
30
+ }
31
+
32
+ validate(data) {
33
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('invalid_voice_settings')
34
+ const backend_url = validateBackendURL(data.backend_url, data.insecure_origin)
35
+ const auth_token = data.auth_token
36
+ if (typeof auth_token !== 'string' || auth_token.length > 8192 || /[\r\n\0]/.test(auth_token)) throw new Error('invalid_auth_token')
37
+ const url = new URL(backend_url)
38
+ const insecure_origin = url.protocol === 'ws:' && url.origin === data.insecure_origin ? url.origin : null
39
+ return { backend_url, auth_token: auth_token || 'test', ...(insecure_origin ? { insecure_origin } : {}) }
40
+ }
41
+
42
+ effective() {
43
+ return this.saved ? { ...this.base, endpoints: { online: this.saved.backend_url, tts_only: this.saved.backend_url }, authorization: this.saved.auth_token === 'test' ? '' : this.saved.auth_token } : this.base
44
+ }
45
+
46
+ public() {
47
+ const config = this.effective()
48
+ const endpoints = Object.fromEntries(Object.entries(config.endpoints).map(([mode, value]) => {
49
+ const url = new URL(value)
50
+ url.username = ''; url.password = ''
51
+ for (const key of [...url.searchParams.keys()]) if (key !== 'protocol') url.searchParams.delete(key)
52
+ return [mode, url.toString()]
53
+ }))
54
+ return {
55
+ min_version: config.min_version, max_version_exclusive: config.max_version_exclusive,
56
+ modes: Object.keys(config.endpoints), endpoints,
57
+ backend_url: endpoints.online, config_source: this.saved ? 'plugin_settings' : 'environment_or_default',
58
+ auth_configured: Boolean(config.authorization), token_placeholder: config.authorization ? '已保存;留空保持不变' : '请输入访问密钥',
59
+ debug: this.debug, revision: this.revision,
60
+ insecure_transport: new URL(config.endpoints.online).protocol !== 'wss:',
61
+ }
62
+ }
63
+
64
+ async save(input) {
65
+ if (this.writing) throw new Error('settings_write_in_progress')
66
+ if (!input || input.revision !== this.revision) throw new Error('settings_revision_conflict')
67
+ const current = this.effective()
68
+ // A deliberate, authenticated per-origin opt-in, never a global TLS bypass.
69
+ const insecureOrigin = input.allow_insecure_http === true ? new URL(input.backend_url).origin : this.saved?.insecure_origin
70
+ const url = validateBackendURL(input.backend_url, insecureOrigin)
71
+ // Never send a retained credential to a newly selected server.
72
+ const token = input.auth_token === '' || input.auth_token === undefined
73
+ ? url === current.endpoints.online ? current.authorization || 'test' : 'test'
74
+ : input.auth_token
75
+ const next = this.validate({ backend_url: url, auth_token: token, insecure_origin: insecureOrigin })
76
+ this.writing = true
77
+ const temp = `${this.path}.${randomUUID()}.tmp`
78
+ try {
79
+ await mkdir(dirname(this.path), { recursive: true, mode: 0o700 })
80
+ await writeFile(temp, JSON.stringify(next) + '\n', { mode: 0o600, flag: 'wx' })
81
+ await rename(temp, this.path)
82
+ this.saved = next
83
+ this.revision++
84
+ return this.public()
85
+ } finally { this.writing = false; await unlink(temp).catch(() => {}) }
86
+ }
87
+ }
88
+
89
+ export function settingsWriteAllowed(req) {
90
+ try {
91
+ return req.headers['x-duplex-settings'] === '1'
92
+ && new URL(req.headers.origin).host === req.headers.host
93
+ && String(req.headers['content-type'] || '').startsWith('application/json')
94
+ } catch { return false }
95
+ }
@@ -0,0 +1,69 @@
1
+ /** Browser-local, opt-in shortcuts. Never register OS-wide keyboard hooks. */
2
+ export const SHORTCUTS_KEY = 'dsh-duet.shortcuts.v1'
3
+ const empty = () => ({speaker:null, mic:null})
4
+ const valid = value => value && /^(Key[A-Z]|Digit[0-9]|F([1-9]|1[0-2])|Space|Enter|Arrow(Up|Down|Left|Right))$/.test(value.code)
5
+ && ['ctrl','alt','meta','shift'].every(k=>typeof value[k]==='boolean') && (value.ctrl||value.alt||value.meta)
6
+ const same = (a,b) => a && b && ['code','ctrl','alt','meta','shift'].every(k=>a[k]===b[k])
7
+ const storage = () => {try{return globalThis.localStorage}catch{return null}}
8
+ export function readShortcuts(store=storage()) {
9
+ try {
10
+ const value=JSON.parse(store?.getItem(SHORTCUTS_KEY)||'{}'), result=empty()
11
+ for(const kind of ['speaker','mic'])if(valid(value[kind]))result[kind]=value[kind]
12
+ if(same(result.speaker,result.mic))return empty()
13
+ return result
14
+ } catch {return empty()}
15
+ }
16
+ export function shortcutFromEvent(event) {
17
+ if(event.repeat||event.isComposing||event.getModifierState?.('AltGraph'))return null
18
+ const value={code:event.code,ctrl:event.ctrlKey,alt:event.altKey,meta:event.metaKey,shift:event.shiftKey}
19
+ return valid(value)?value:null
20
+ }
21
+ export function shortcutLabel(value) {
22
+ if(!value)return ''
23
+ return [value.ctrl&&'Ctrl',value.alt&&'Alt',value.meta&&'⌘',value.shift&&'Shift',
24
+ value.code.replace(/^Key|^Digit/,'').replace('Space','空格').replace('Arrow','')].filter(Boolean).join(' + ')
25
+ }
26
+ export function saveShortcut(kind,value,store=storage()) {
27
+ if(!['speaker','mic'].includes(kind)||value!==null&&!valid(value))throw Error('invalid_shortcut')
28
+ if(!store)throw Error('storage_unavailable')
29
+ const settings=readShortcuts(store)
30
+ if(value&&same(value,settings[kind==='mic'?'speaker':'mic']))throw Error('shortcut_conflict')
31
+ settings[kind]=value
32
+ store.setItem(SHORTCUTS_KEY,JSON.stringify(settings))
33
+ return settings
34
+ }
35
+ export function bindVoiceShortcuts(activate,target=window,store=storage()) {
36
+ const handler=event=>{
37
+ if(event.defaultPrevented||document.querySelector('dialog[open]'))return
38
+ const value=shortcutFromEvent(event)
39
+ if(!value)return
40
+ const settings=readShortcuts(store)
41
+ const kind=['speaker','mic'].find(k=>same(value,settings[k]))
42
+ if(!kind)return
43
+ event.preventDefault();event.stopPropagation();activate(kind)
44
+ }
45
+ target.addEventListener('keydown',handler,true)
46
+ return ()=>target.removeEventListener('keydown',handler,true)
47
+ }
48
+ export function mountShortcutSettings({speaker,mic,clearSpeaker,clearMic,status},store=storage()) {
49
+ const fields={speaker,mic}
50
+ const refresh=()=>{const settings=readShortcuts(store);for(const kind of ['speaker','mic'])fields[kind].value=shortcutLabel(settings[kind])}
51
+ const save=(kind,value)=>{
52
+ try{saveShortcut(kind,value,store);status.textContent=value?'快捷键已保存。':'快捷键已清除。'}
53
+ catch(error){status.textContent=error.message==='shortcut_conflict'?'两个模式请使用不同快捷键。':'无法保存,请允许浏览器存储后重试。'}
54
+ refresh()
55
+ }
56
+ for(const kind of ['speaker','mic'])fields[kind].onkeydown=event=>{
57
+ if(event.key==='Tab')return
58
+ event.preventDefault();event.stopPropagation()
59
+ if(event.key==='Escape'){fields[kind].blur();return}
60
+ if(['Control','Alt','Meta','Shift'].includes(event.key))return
61
+ const value=shortcutFromEvent(event)
62
+ if(!value){status.textContent='请使用 Ctrl、Alt 或 ⌘ 加其他按键。';return}
63
+ save(kind,value)
64
+ }
65
+ clearSpeaker.onclick=()=>save('speaker',null);clearMic.onclick=()=>save('mic',null)
66
+ const changed=event=>{if(event.key===SHORTCUTS_KEY||event.key===null)refresh()}
67
+ window.addEventListener('storage',changed);refresh()
68
+ return ()=>{window.removeEventListener('storage',changed);for(const field of Object.values(fields))field.onkeydown=null;clearSpeaker.onclick=clearMic.onclick=null}
69
+ }
@@ -0,0 +1,171 @@
1
+ /** Desired voice mode is independent of a temporarily suspended connection. */
2
+ export const PLUGIN_VERSION = '0.1.0'
3
+ export const IDLE_RELEASE_MS = 60_000
4
+
5
+ const safeVersion = value => typeof value === 'string' && value.length <= 32 && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value) ? value : ''
6
+ export function compatibilityNotice(code, details = {}, mode = 'online') {
7
+ const key = mode === 'tts_only' ? 'tts_only' : 'online'
8
+ const info = details.compatibility || {}
9
+ const policy = details.policy || {}
10
+ const required = safeVersion(info.modes?.[key]?.min_client_version)
11
+ || safeVersion(policy[key + '_min_client_version']) || safeVersion(policy.min_client_version)
12
+ const current = `当前插件 ${PLUGIN_VERSION}`
13
+ if (code === 'plugin_upgrade_required') {
14
+ const other = key === 'online' ? 'tts_only' : 'online'
15
+ const alternative = info.modes?.[other]?.available === true ? `;仍可手动开启${other === 'online' ? '交互' : '播报'}模式` : ''
16
+ return `${current},${required ? `此模式需要 ${required} 或更高版本` : '请升级插件后再连接'}${alternative}。`
17
+ }
18
+ if (code === 'client_protocol_unsupported') return `${current}与服务协议不兼容,请更新插件;若已是最新版,请联系服务管理员。`
19
+ if (code === 'client_version_unsupported') return `${current}暂不受服务支持,请联系服务管理员,不必反复重连。`
20
+ return null
21
+ }
22
+
23
+ export class VoiceState {
24
+ constructor({ connect, changed = () => {}, notice = () => {}, now = Date.now }) {
25
+ Object.assign(this, { connect, changed, notice, now })
26
+ this.mode = 'off'
27
+ this.connection = null
28
+ this.suspended = false
29
+ this.hidden = false
30
+ this.running = false
31
+ this.idleSince = null
32
+ this.generation = 0
33
+ this.pending = new Map()
34
+ this.sent = new Set()
35
+ this.state = null
36
+ this.ready = false
37
+ this.retiring = Promise.resolve()
38
+ this.recommendationShown = null
39
+ }
40
+
41
+ toggleMic() { return this.setMode(this.mode === 'online' ? 'off' : 'online') }
42
+ toggleSpeaker() { return this.setMode(this.mode === 'tts_only' ? 'off' : 'tts_only') }
43
+
44
+ async setMode(mode) {
45
+ if (!['off', 'tts_only', 'online'].includes(mode)) throw new Error('invalid_voice_mode')
46
+ if (mode === this.mode && !this.suspended) return
47
+ this.mode = mode
48
+ this.suspended = false
49
+ this.idleSince = null
50
+ if (mode === 'off') this.pending.clear()
51
+ // Online result polling belongs to its existing server-side Harness client.
52
+ if (mode === 'online') this.pending.clear()
53
+ await this.replaceConnection()
54
+ }
55
+
56
+ async replaceConnection() {
57
+ const generation = ++this.generation
58
+ const previous = this.connection
59
+ this.connection = null
60
+ this.ready = false
61
+ this.sent.clear()
62
+ if (previous) this.retiring = this.retiring.then(() => previous.close()).catch(() => {})
63
+ this.changed(this)
64
+ await this.retiring
65
+ if (generation !== this.generation || this.mode === 'off' || this.suspended) return
66
+ try {
67
+ this.connection = this.connect(this.mode, event => {
68
+ if (generation !== this.generation) return
69
+ this.receive(event)
70
+ })
71
+ } catch (error) { this.fail(error.message) }
72
+ }
73
+
74
+ receive(event) {
75
+ if (event.type === 'compatibility') {
76
+ const recommended = safeVersion(event.compatibility?.recommended_client_version)
77
+ const newer = recommended && recommended.split('.').reduce((result, v, i) => result || Math.sign(Number(v) - Number(PLUGIN_VERSION.split('.')[i])), 0) > 0
78
+ if (newer && this.recommendationShown !== recommended) {
79
+ this.recommendationShown = recommended
80
+ this.notice(`当前插件 ${PLUGIN_VERSION},推荐更新到 ${recommended}。当前连接可以继续使用。`, { upgrade: true })
81
+ }
82
+ } else if (event.type === 'ready') {
83
+ this.ready = true
84
+ this.connection?.sendState(this.state)
85
+ this.flush()
86
+ } else if (event.type === 'external_message.done') {
87
+ this.pending.delete(event.message_id)
88
+ this.sent.delete(event.message_id)
89
+ this.flush()
90
+ } else if (event.type === 'error') {
91
+ // A rejected model action is not a dead transport. Never execute/retry it,
92
+ // but leave the user able to clarify instead of closing their microphone.
93
+ if (event.code === 'malformed_dense_action') {
94
+ this.notice('这次操作指令格式有误,未执行。语音仍已连接,请重新说明。')
95
+ } else this.fail(event.code, event)
96
+ }
97
+ this.changed(this)
98
+ }
99
+
100
+ fail(code, details = {}) {
101
+ const compatibility = compatibilityNotice(code, details, this.mode)
102
+ if (compatibility) {
103
+ this.notice(compatibility, { upgrade: code !== 'client_version_unsupported' })
104
+ void this.setMode('off')
105
+ return
106
+ }
107
+ const policyNotices = {
108
+ microphone_unavailable: '无法使用所选麦克风,请在设置中检查设备与浏览器权限',
109
+ interaction_mode_unavailable: '交互模式暂时不可用,请稍后再试',
110
+ broadcast_mode_unavailable: '播报模式暂时不可用,请稍后再试',
111
+ client_protocol_unsupported: '插件与服务器协议不兼容,请更新插件或联系服务管理员',
112
+ client_version_unsupported: '当前插件版本暂不受服务器支持,请联系服务管理员',
113
+ }
114
+ if (policyNotices[code]) {
115
+ this.notice(policyNotices[code])
116
+ void this.setMode('off')
117
+ return
118
+ }
119
+ const busy = ['capacity_exhausted', 'server_busy', 'external_message_queue_full', 'busy'].includes(code)
120
+ const upgrade = code === 'plugin_upgrade_required'
121
+ const backendUpgrade = ['harness_result_backend_upgrade_required', 'harness_rpc_backend_upgrade_required'].includes(code)
122
+ this.notice(code === 'voice_settings_changed' ? '连接配置已更新,请重新打开语音' : upgrade ? '请升级 duet 插件后再连接' : backendUpgrade ? '语音服务器需要更新协议,请稍后再试' : busy ? '服务器忙,请稍后再试' : code === 'voice_tab_in_use' ? '另一个 Harness 页面正在使用语音' : '语音连接不可用,请稍后重试')
123
+ void this.setMode('off')
124
+ }
125
+
126
+ update({ hidden, running, state, results = [] }) {
127
+ this.hidden = hidden
128
+ this.running = running
129
+ if (JSON.stringify(state) !== JSON.stringify(this.state)) {
130
+ this.state = state
131
+ if (this.ready) this.connection?.sendState(state)
132
+ }
133
+ if (this.mode === 'tts_only') {
134
+ for (const result of results) {
135
+ if (this.pending.size >= 64) { this.fail('external_message_queue_full'); break }
136
+ this.pending.set(result.message_id, result)
137
+ }
138
+ if (this.suspended && (running || this.pending.size)) {
139
+ this.suspended = false
140
+ this.idleSince = null
141
+ void this.replaceConnection()
142
+ }
143
+ }
144
+ this.flush()
145
+ this.tick()
146
+ }
147
+
148
+ flush() {
149
+ if (!this.ready || this.mode !== 'tts_only') return
150
+ // One notification at a time; preserve the next one until generation finishes.
151
+ if (this.sent.size) return
152
+ const result = this.pending.values().next().value
153
+ if (result) {
154
+ this.sent.add(result.message_id)
155
+ this.connection.send(result)
156
+ }
157
+ }
158
+
159
+ tick() {
160
+ const idle = this.mode === 'tts_only' && this.hidden && !this.running
161
+ && !this.pending.size && !this.connection?.playing()
162
+ if (!idle) { this.idleSince = null; return }
163
+ this.idleSince ??= this.now()
164
+ if (!this.suspended && this.now() - this.idleSince >= IDLE_RELEASE_MS) {
165
+ this.suspended = true
166
+ void this.replaceConnection()
167
+ }
168
+ }
169
+
170
+ async dispose() { await this.setMode('off'); await this.retiring }
171
+ }
@@ -0,0 +1,107 @@
1
+ /** Private, append-only connection capture. Never served as a web asset. */
2
+ import { createWriteStream, mkdirSync, readdirSync, statSync } from 'node:fs'
3
+ import { homedir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import { randomUUID } from 'node:crypto'
6
+
7
+ export function redact(value, secrets = []) {
8
+ if (typeof value === 'string') {
9
+ for (const secret of secrets) if (secret) value = value.split(secret).join('[REDACTED]')
10
+ return value.replace(/([?&](?:token|api_key|access_token|authorization)=)[^&#\s]*/gi, '$1[REDACTED]')
11
+ .replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi, '$1[REDACTED]')
12
+ }
13
+ if (Array.isArray(value)) return value.map(v => redact(v, secrets))
14
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) =>
15
+ [k, /^(?:authorization|auth_token|api_key|access_token|token|cookie|set-cookie|password|secret)$/i.test(k) ? '[REDACTED]' : redact(v, secrets)]))
16
+ return value
17
+ }
18
+
19
+ const budgets = new Map()
20
+ export class VoiceTrace {
21
+ constructor(metadata, { root = process.env.DUPLEX_VOICE_TRACE_DIR || join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'duplex-control', 'traces'),
22
+ secrets = [], maxBytes = 512 * 1024 ** 2, totalBytes = 20 * 1024 ** 3, queueBytes = 8 * 1024 ** 2 } = {}) {
23
+ this.id = randomUUID(); this.start = performance.now(); this.seq = 0; this.bytes = 0
24
+ this.offset = 0; this.closed = false; this.error = null; this.secrets = secrets
25
+ this.maxBytes = maxBytes; this.queueBytes = queueBytes
26
+ try {
27
+ mkdirSync(root, { recursive: true, mode: 0o700 })
28
+ // Once per process/root; reserve bytes at enqueue time across concurrent sessions.
29
+ if (!budgets.has(root)) {
30
+ let used = 0
31
+ const folders = []
32
+ for (const dir of readdirSync(root, { withFileTypes: true })) {
33
+ if (!dir.isDirectory()) continue
34
+ if (/^\d{4}-\d{2}-\d{2}$/.test(dir.name)) {
35
+ for (const child of readdirSync(join(root, dir.name), { withFileTypes: true })) {
36
+ if (child.isDirectory()) folders.push(join(root, dir.name, child.name))
37
+ }
38
+ } else if (/^\d{4}-.*_[a-f0-9-]{36}$/.test(dir.name)) folders.push(join(root, dir.name))
39
+ }
40
+ for (const folder of folders) {
41
+ for (const name of ['events.jsonl', 'audio.bin']) {
42
+ try { used += statSync(join(folder, name)).size } catch { /* missing partial file */ }
43
+ }
44
+ }
45
+ budgets.set(root, { used })
46
+ }
47
+ this.budget = budgets.get(root); this.totalBytes = totalBytes
48
+ const date = new Date().toISOString()
49
+ const day = join(root, date.slice(0, 10))
50
+ mkdirSync(day, { recursive: true, mode: 0o700 })
51
+ this.path = join(day, date.replaceAll(':', '-') + '_' + this.id)
52
+ mkdirSync(this.path, { mode: 0o700 })
53
+ this.events = createWriteStream(join(this.path, 'events.jsonl'), { flags: 'wx', mode: 0o600 })
54
+ this.audio = createWriteStream(join(this.path, 'audio.bin'), { flags: 'wx', mode: 0o600 })
55
+ for (const stream of [this.events, this.audio]) stream.on('error', error => this.disable(error.code || 'write_failed'))
56
+ this.event('trace.started', { schema: 'duplex_voice_trace_v1', ...metadata,
57
+ input_format: 'pcm_s16le/16000/mono', limits: { maxBytes, totalBytes, queueBytes } })
58
+ } catch (error) { this.disable(error.code || 'open_failed') }
59
+ }
60
+
61
+ disable(reason) {
62
+ if (this.error) return
63
+ this.error = reason
64
+ // No payloads or credentials in stderr, and never crash audio for a logging error.
65
+ console.error(`[duplex-trace] capture incomplete trace=${this.id} reason=${reason}`)
66
+ if (this.events && !this.events.destroyed) {
67
+ this.events.end(JSON.stringify({ type: 'trace.incomplete', reason, utc: new Date().toISOString() }) + '\n')
68
+ }
69
+ this.audio?.end()
70
+ }
71
+
72
+ event(type, data, binary) {
73
+ if (this.closed || this.error) return
74
+ const record = { seq: this.seq++, utc: new Date().toISOString(), elapsed_ms: performance.now() - this.start,
75
+ type, data: redact(data, this.secrets) }
76
+ if (binary) record.blob = { file: 'audio.bin', offset: this.offset, bytes: binary.length }
77
+ const line = JSON.stringify(record) + '\n'
78
+ const size = Buffer.byteLength(line) + (binary?.length || 0)
79
+ if (this.bytes + size > this.maxBytes || this.budget.used + size > this.totalBytes) { this.disable('quota_exceeded'); return }
80
+ if (this.events.writableLength + this.audio.writableLength + size > this.queueBytes) { this.disable('disk_backpressure'); return }
81
+ this.bytes += size; this.budget.used += size
82
+ if (binary) { this.audio.write(binary); this.offset += binary.length }
83
+ this.events.write(line)
84
+ }
85
+
86
+ frame(direction, raw, binary = false) {
87
+ if (binary) { this.event(direction, { wire: 'binary' }, Buffer.from(raw)); return }
88
+ try {
89
+ const message = JSON.parse(raw.toString())
90
+ if (/audio/.test(message.type || '') && typeof message.delta === 'string') {
91
+ const data = { ...message, delta: { stored_as: 'blob', encoding: 'base64' } }
92
+ this.event(direction, data, Buffer.from(message.delta, 'base64'))
93
+ } else this.event(direction, message)
94
+ } catch { this.event(direction, { invalid_json: String(raw) }) }
95
+ }
96
+
97
+ snapshot() { return { trace_id: this.id, bytes: this.bytes, complete: !this.error, error: this.error } }
98
+
99
+ async close(data = {}) {
100
+ if (this.closed) return
101
+ this.event('trace.closed', data); this.closed = true
102
+ await Promise.all([this.events, this.audio].filter(Boolean).map(stream => new Promise(resolve => {
103
+ if (stream.closed || stream.destroyed) { resolve(); return }
104
+ stream.once('close', resolve); stream.end()
105
+ })))
106
+ }
107
+ }