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,55 @@
1
+ /** Submit feedback with a stable, locally managed user identity. */
2
+ import {createHmac,randomBytes,timingSafeEqual} from 'node:crypto'
3
+ import {existsSync,mkdirSync,readFileSync,openSync,writeFileSync,fsyncSync,closeSync,linkSync,unlinkSync} from 'node:fs'
4
+ import {dirname,join} from 'node:path'
5
+ import {homedir} from 'node:os'
6
+
7
+ const COOKIE='duplex_feedback_user'
8
+ export class RemoteFeedback {
9
+ constructor(getConfig,{keyPath,fetchImpl=fetch}={}){
10
+ this.getConfig=getConfig;this.fetch=fetchImpl
11
+ this.keyPath=keyPath||join(process.env.DSH_HOME||join(homedir(),'.dsh'),'duplex-control','feedback-identity.key')
12
+ this.key=null
13
+ }
14
+ identityKey(){
15
+ if(this.key)return this.key
16
+ mkdirSync(dirname(this.keyPath),{recursive:true,mode:0o700})
17
+ if(!existsSync(this.keyPath)){
18
+ const tmp=this.keyPath+'.'+randomBytes(8).toString('hex')+'.tmp'
19
+ const fd=openSync(tmp,'wx',0o600)
20
+ try{writeFileSync(fd,randomBytes(32));fsyncSync(fd)}finally{closeSync(fd)}
21
+ try{linkSync(tmp,this.keyPath)}catch(e){if(e.code!=='EEXIST')throw e}finally{unlinkSync(tmp)}
22
+ const d=openSync(dirname(this.keyPath),'r');try{fsyncSync(d)}finally{closeSync(d)}
23
+ }
24
+ const key=readFileSync(this.keyPath);if(key.length!==32)throw Error('feedback_identity_key_invalid')
25
+ this.key=key;return key
26
+ }
27
+ sign(id){return createHmac('sha256',this.identityKey()).update(id).digest('hex')}
28
+ userId(req){
29
+ const cookie=String(req.headers?.cookie||'').split(';').map(x=>x.trim()).find(x=>x.startsWith(COOKIE+'='))?.slice(COOKIE.length+1)
30
+ if(!cookie||!/^([a-f0-9]{32})\.([a-f0-9]{64})$/.test(cookie))throw Error('feedback_identity_unavailable')
31
+ const [id,mac]=cookie.split('.')
32
+ if(!timingSafeEqual(Buffer.from(this.sign(id)),Buffer.from(mac)))throw Error('feedback_identity_unavailable')
33
+ return 'anon_'+id
34
+ }
35
+ ensureIdentity(req,res){
36
+ try{return this.userId(req)}catch{}
37
+ const id=randomBytes(16).toString('hex'),signed=id+'.'+this.sign(id)
38
+ // Same-origin HttpOnly cookie; identity is pseudonymous browser, not account.
39
+ const secure=req.socket?.encrypted||req.headers['x-forwarded-proto']==='https'
40
+ res.setHeader('Set-Cookie',`${COOKIE}=${signed}; Path=/duplex-control; HttpOnly; SameSite=Strict; Max-Age=31536000${secure?'; Secure':''}`)
41
+ return 'anon_'+id
42
+ }
43
+ async insert(record){
44
+ const config=this.getConfig(),url=new URL(config.endpoints.online)
45
+ url.protocol=url.protocol==='wss:'?'https:':'http:'
46
+ url.pathname=url.pathname.replace(/\/ws\/?$/,'').replace(/\/$/,'')+'/feedback';url.search=''
47
+ const response=await this.fetch(url,{method:'POST',redirect:'error',signal:AbortSignal.timeout(10000),
48
+ headers:{'Content-Type':'application/json',...(config.authorization?{Authorization:config.authorization}:{})},body:JSON.stringify(record)})
49
+ if(!response.ok)throw Error(response.status===409?'feedback_conflict':'feedback_unavailable')
50
+ const body=await response.text();if(body.length>4096)throw Error('feedback_invalid_receipt')
51
+ const result=JSON.parse(body)
52
+ if(result.persisted!==true||typeof result.archive_id!=='string')throw Error('feedback_invalid_receipt')
53
+ return result
54
+ }
55
+ }
@@ -0,0 +1,51 @@
1
+ /** Host boundary for a durable feedback adapter. No in-memory success fallback.
2
+ * Store contract: userId(req) resolves authenticated/stable identity synchronously;
3
+ * insert(record) commits durably and enforces (user_id, request_id) idempotency,
4
+ * plus one rating per (user_id, session_id). Reuse with different content conflicts.
5
+ */
6
+ import { randomUUID } from 'node:crypto'
7
+
8
+ export class FeedbackService {
9
+ constructor(store, { now = Date.now } = {}) {
10
+ this.store = store; this.now = now; this.sessions = new Map()
11
+ }
12
+ get enabled() { return Boolean(this.store?.userId && this.store?.insert) }
13
+ user(req) {
14
+ if(!this.enabled)throw Error('feedback_unavailable')
15
+ const user=this.store.userId(req)
16
+ if(typeof user!=='string'||!user||user.length>256)throw Error('feedback_identity_unavailable')
17
+ return user
18
+ }
19
+ prune() { for(const [key,s] of this.sessions)if(this.now()-s.opened>86400000)this.sessions.delete(key) }
20
+ open(req, sessionId, mode) {
21
+ if(!this.enabled)return null
22
+ this.prune()
23
+ if(this.sessions.size>=2048||typeof sessionId!=='string'||!sessionId||sessionId.length>256)return null
24
+ try {
25
+ const ticket=randomUUID()
26
+ this.sessions.set(ticket,{user:this.user(req),sessionId,mode,opened:this.now(),closed:false})
27
+ return ticket
28
+ } catch { return null } // Feedback availability must not break voice.
29
+ }
30
+ close(ticket) { const s=this.sessions.get(ticket);if(s)s.closed=true }
31
+ async submit(req, input) {
32
+ const user=this.user(req);this.prune()
33
+ if(!input||Array.isArray(input)||!['text','rating'].includes(input.kind))throw Error('invalid_feedback')
34
+ const allowed=['kind','request_id','text',...(input.kind==='rating'?['rating','session_ticket']:[])]
35
+ if(Object.keys(input).some(k=>!allowed.includes(k)))throw Error('invalid_feedback_fields')
36
+ if(typeof input.request_id!=='string'||!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(input.request_id))throw Error('invalid_feedback_id')
37
+ const text=input.text??''
38
+ if(typeof text!=='string'||text.length>5000||text.includes('\0')||(input.kind==='text'&&!text.trim()))throw Error('invalid_feedback_text')
39
+ let session
40
+ if(input.kind==='rating'){
41
+ if(!Number.isInteger(input.rating)||input.rating<1||input.rating>5)throw Error('invalid_feedback_rating')
42
+ session=this.sessions.get(input.session_ticket)
43
+ if(!session||session.user!==user||!session.closed)throw Error('feedback_session_unavailable')
44
+ }
45
+ const record={request_id:input.request_id,user_id:user,kind:input.kind,text:text.trim(),
46
+ rating:session?input.rating:null,session_id:session?.sessionId??null,mode:session?.mode??null,
47
+ created_at:new Date(this.now()).toISOString()}
48
+ const saved=await this.store.insert(record)
49
+ return {persisted:true,request_id:input.request_id,...(saved?.archive_id?{archive_id:saved.archive_id}:{})}
50
+ }
51
+ }
@@ -0,0 +1,32 @@
1
+ /** Use the same pending objects as DSH's clickable question/approval cards. */
2
+ export function nativeInteractions(ctx) {
3
+ const firstSeen = new WeakMap()
4
+ const pending = () => [...ctx.uiSession.pendingInteractions.getSnapshot().values()]
5
+ const publicValue = value => {
6
+ if (!firstSeen.has(value)) firstSeen.set(value, Date.now() / 1000)
7
+ return { id: value.key, session_id: value.sessionId, created_at: firstSeen.get(value),
8
+ kind: value.kind === 'plan-review' ? 'plan_review' : value.kind,
9
+ ...(value.kind === 'approval' ? { approval_id: value.key, tool_name: value.toolName,
10
+ call_id: value.callId || '', reason: value.reason || '' } : { questions: value.questions }) }
11
+ }
12
+ return async (request, signal) => {
13
+ signal?.throwIfAborted()
14
+ if (request.method === 'GET' && request.path === '/api/interactions') {
15
+ return { interactions: pending().filter(v => ['question', 'plan-review', 'approval'].includes(v.kind)).map(publicValue) }
16
+ }
17
+ const match = request.path.match(/^\/api\/interactions\/([^/]+)\/respond$/)
18
+ if (request.method !== 'POST' || !match) return undefined
19
+ const value = pending().find(v => v.key === decodeURIComponent(match[1]))
20
+ if (!value) throw Object.assign(Error('interaction_already_finished'), { code: 'interaction_already_finished' })
21
+ const payload = request.payload || {}
22
+ if (value.kind === 'approval') {
23
+ if (!['allowed-once', 'rejected'].includes(payload.outcome)) throw Error('invalid_approval_outcome')
24
+ await value.answer(payload.outcome)
25
+ } else if (payload.cancelled === true) await value.cancel()
26
+ else {
27
+ if (!Array.isArray(payload.answers)) throw Error('invalid_question_answers')
28
+ await value.answer({ answers: payload.answers })
29
+ }
30
+ return { ok: true, interaction_id: value.key }
31
+ }
32
+ }
@@ -0,0 +1,59 @@
1
+ /** Device identifiers belong to this browser, never to shared host settings. */
2
+ export const MICROPHONE_KEY = 'dsh-duet.microphone.v1'
3
+
4
+ function browserStorage() {
5
+ try { return globalThis.localStorage } catch { return null }
6
+ }
7
+
8
+ export function selectedMicrophone(storage = browserStorage()) {
9
+ try { return storage?.getItem(MICROPHONE_KEY) || '' } catch { return '' }
10
+ }
11
+
12
+ export function microphoneConstraints(deviceId = selectedMicrophone()) {
13
+ return { audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true,
14
+ ...(deviceId ? { deviceId: { exact: deviceId } } : {}) }, video: false }
15
+ }
16
+
17
+ export function mountMicrophoneSettings({ select, refresh, status }, media = navigator.mediaDevices, storage = browserStorage()) {
18
+ let disposed = false, revision = 0
19
+ const load = async () => {
20
+ const current = ++revision
21
+ refresh.disabled = true
22
+ try {
23
+ if (!media?.enumerateDevices) throw Error('unavailable')
24
+ const devices = (await media.enumerateDevices()).filter(d => d.kind === 'audioinput' && d.deviceId && d.deviceId !== 'default')
25
+ if (disposed || current !== revision) return
26
+ const selected = selectedMicrophone(storage)
27
+ select.replaceChildren(new Option('系统默认麦克风', ''))
28
+ devices.forEach((d, i) => select.add(new Option(d.label || `麦克风 ${i + 1}`, d.deviceId)))
29
+ const missing = selected && !devices.some(d => d.deviceId === selected)
30
+ if (missing) select.add(new Option('已选麦克风(暂不可用)', selected))
31
+ select.value = selected
32
+ select.disabled = false
33
+ status.textContent = missing ? '请连接已选麦克风,或选择其他设备。' : devices.some(d => !d.label) || !devices.length
34
+ ? '开启交互模式并允许麦克风访问后,可查看设备名称。' : ''
35
+ } catch {
36
+ if (!disposed && current === revision) { select.disabled = true; status.textContent = '暂时无法获取麦克风,请检查浏览器权限。' }
37
+ } finally { if (!disposed && current === revision) refresh.disabled = false }
38
+ }
39
+ select.onchange = () => {
40
+ ++revision
41
+ refresh.disabled = false
42
+ try {
43
+ if (!storage) throw Error('storage_unavailable')
44
+ storage.setItem(MICROPHONE_KEY, select.value)
45
+ status.textContent = '已保存,下次开启交互模式时使用。'
46
+ } catch { status.textContent = '无法保存麦克风选择,请允许浏览器存储后重试。'; select.value = selectedMicrophone(storage) }
47
+ }
48
+ refresh.onclick = () => { void load() }
49
+ const storageChanged = event => { if (event.key === MICROPHONE_KEY || event.key === null) void load() }
50
+ media?.addEventListener?.('devicechange', load)
51
+ globalThis.addEventListener?.('storage', storageChanged)
52
+ void load()
53
+ return () => {
54
+ disposed = true; ++revision
55
+ media?.removeEventListener?.('devicechange', load)
56
+ globalThis.removeEventListener?.('storage', storageChanged)
57
+ select.onchange = null; refresh.onclick = null
58
+ }
59
+ }
@@ -0,0 +1,54 @@
1
+ /** Read-only service notices; no model calls and no client-controlled proxy target. */
2
+ export class ServiceNotices {
3
+ constructor(getConfig, fetchImpl = fetch) {
4
+ this.getConfig = getConfig
5
+ this.fetch = (...args) => fetchImpl(...args)
6
+ this.cached = null
7
+ this.inflight = null
8
+ this.epoch = 0
9
+ }
10
+ invalidate() { this.epoch++; this.cached = null; this.inflight = null }
11
+ async get() {
12
+ if (this.cached && Date.now() < this.cached.expires) return this.cached.value
13
+ if (this.inflight) return this.inflight
14
+ const epoch = this.epoch
15
+ const config = this.getConfig()
16
+ const work = async () => {
17
+ let value
18
+ try {
19
+ const url = new URL(config.endpoints.online)
20
+ url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'
21
+ url.pathname = url.pathname.replace(/\/ws\/?$/, '').replace(/\/$/, '') + '/announcements'
22
+ url.search = ''
23
+ const response = await this.fetch(url, { headers: config.authorization ? { Authorization: config.authorization } : {}, redirect: 'error', signal: AbortSignal.timeout(5000) })
24
+ if (!response.ok) throw new Error('notices_unavailable')
25
+ let body = '', bytes = 0
26
+ const reader = response.body.getReader(), decoder = new TextDecoder()
27
+ try {
28
+ while (true) {
29
+ const { done, value: chunk } = await reader.read()
30
+ if (done) break
31
+ bytes += chunk.length
32
+ if (bytes > 128_000) throw new Error('notices_too_large')
33
+ body += decoder.decode(chunk, { stream: true })
34
+ }
35
+ body += decoder.decode()
36
+ } finally { await reader.cancel().catch(() => {}) }
37
+ const payload = JSON.parse(body)
38
+ if (payload.version !== 1 || !Array.isArray(payload.items) || payload.items.length > 50) throw new Error('invalid_notices')
39
+ const items = payload.items.map(item => {
40
+ if (!item || typeof item.id !== 'string' || typeof item.title !== 'string' || typeof item.body !== 'string'
41
+ || item.id.length > 128 || item.title.length > 200 || item.body.length > 4000
42
+ || typeof item.published_at !== 'string' || !Number.isFinite(Date.parse(item.published_at))
43
+ || !['info', 'update', 'warning'].includes(item.level)) throw new Error('invalid_notice')
44
+ return { id: item.id, title: item.title, body: item.body, published_at: item.published_at, level: item.level }
45
+ })
46
+ value = { status: 'ok', version: 1, items }
47
+ } catch { value = { status: 'unavailable', version: 1, items: [] } }
48
+ if (epoch === this.epoch) { this.cached = { expires: Date.now() + 60_000, value }; this.inflight = null }
49
+ return value
50
+ }
51
+ this.inflight = work()
52
+ return this.inflight
53
+ }
54
+ }
@@ -0,0 +1,223 @@
1
+ /** Same-origin voice relay; endpoint and compatibility policy belong to the DSH host. */
2
+ import { createRequire } from 'node:module'
3
+ import { VoiceTrace } from './deepseek_harness_voice_trace.mjs'
4
+ const require = createRequire(import.meta.url)
5
+ export const DEFAULT_VOICE_URL = 'ws://duet-router.1781574661016173.ap-southeast-1.pai-eas.aliyuncs.com/ws?protocol=realtime_v2'
6
+
7
+ export function compatibleVersion(version, min = '0.1.0', maxExclusive = '0.2.0') {
8
+ const parse = v => /^\d+\.\d+\.\d+$/.test(v || '') ? v.split('.').map(Number) : null
9
+ const compare = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]
10
+ const v = parse(version), low = parse(min), high = parse(maxExclusive)
11
+ return Boolean(v && low && high && compare(v, low) >= 0 && compare(v, high) < 0)
12
+ }
13
+
14
+ export function voiceConfig(env = process.env) {
15
+ return {
16
+ min_version: env.DUPLEX_PLUGIN_MIN_VERSION || '0.1.0',
17
+ max_version_exclusive: env.DUPLEX_PLUGIN_MAX_VERSION_EXCLUSIVE || '0.2.0',
18
+ control_transport: env.DUPLEX_VOICE_CONTROL_TRANSPORT || 'client_rpc_v1',
19
+ authorization: env.DUPLEX_VOICE_AUTHORIZATION || '',
20
+ endpoints: {
21
+ online: env.DUPLEX_VOICE_ONLINE_URL || env.DUPLEX_VOICE_URL || DEFAULT_VOICE_URL,
22
+ tts_only: env.DUPLEX_VOICE_TTS_ONLY_URL || env.DUPLEX_VOICE_URL || DEFAULT_VOICE_URL,
23
+ },
24
+ }
25
+ }
26
+
27
+ export function externalWithState(message, _state) {
28
+ if (message.type !== 'external_message' || typeof message.text !== 'string') throw new Error('invalid_external_message')
29
+ // Keep authoritative result metadata separate from result text and UI state.
30
+ const text = message.text
31
+ if (text.length > 8000) throw new Error('external_message_too_large')
32
+ const source = message.source
33
+ if (source !== undefined) {
34
+ const limits = { session_id: 256, session_name: 512, job_id: 256, status: 16 }
35
+ if (!source || typeof source !== 'object' || Array.isArray(source) ||
36
+ Object.keys(source).length !== 4 || Object.entries(limits).some(([key, limit]) =>
37
+ typeof source[key] !== 'string' || !source[key].trim() || source[key].length > limit || source[key].includes('\0')) ||
38
+ !['completed', 'failed'].includes(source.status)) throw new Error('invalid_external_message_source')
39
+ }
40
+ return { type: 'external_message', message_id: message.message_id, text,
41
+ ...(source === undefined ? {} : { source: { ...source } }) }
42
+ }
43
+
44
+ export function registerVoiceProxy(ctx, config = voiceConfig(), feedback = null) {
45
+ if (!['http', 'client_rpc_v1'].includes(config.control_transport || 'http')) throw new Error('invalid_harness_transport')
46
+ if (!compatibleVersion(config.min_version, config.min_version, config.max_version_exclusive)) throw new Error('invalid_plugin_version_policy')
47
+ for (const target of Object.values(config.endpoints)) {
48
+ const url = new URL(target)
49
+ if (!['ws:', 'wss:'].includes(url.protocol) || url.username || url.password || url.hash) throw new Error('invalid_voice_endpoint')
50
+ }
51
+ const { WebSocket, WebSocketServer } = require('ws')
52
+ const server = new WebSocketServer({ noServer: true, maxPayload: 1_000_000 })
53
+ const connections = new Map()
54
+ const stop = ctx.webServer.registerUpgrade({
55
+ path: '/duplex-control/voice/ws',
56
+ handler(req, socket, head) {
57
+ const rejection = ctx.connection?.requestRejection(req)
58
+ if (rejection) { socket.end(`HTTP/1.1 ${rejection} Forbidden\r\nConnection: close\r\n\r\n`); return }
59
+ // No browser-selected target URLs and no cross-origin drive-by microphone sessions.
60
+ const origin = req.headers.origin
61
+ let sameOrigin = !origin
62
+ try { if (origin) sameOrigin = new URL(origin).host === req.headers.host } catch { sameOrigin = false }
63
+ if (!sameOrigin) {
64
+ socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n')
65
+ return
66
+ }
67
+ server.handleUpgrade(req, socket, head, front => {
68
+ front.on('error', () => {})
69
+ const params = new URL(req.url, 'http://localhost').searchParams
70
+ const trace = new VoiceTrace({ mode: params.get('mode'), plugin_version: params.get('plugin_version'),
71
+ client_trace_id: (params.get('client_trace_id') || '').slice(0, 64),
72
+ backend_origin: new URL(config.endpoints[params.get('mode')] || config.endpoints.online).origin,
73
+ control_transport: config.control_transport }, { ...config.traceOptions, secrets: [config.authorization] })
74
+ front.once('close', (code, reason) => {
75
+ trace.event('browser.closed', { code, reason: reason.toString() })
76
+ const timer = setTimeout(() => { void trace.close() }, 1500); timer.unref()
77
+ })
78
+ let back, feedbackTicket = null
79
+ front.once('close', () => feedback?.close(feedbackTicket))
80
+ let state = null
81
+ let initialized = false
82
+ let terminal = false
83
+ const fail = code => {
84
+ if (terminal) return
85
+ terminal = true
86
+ trace.event('proxy.failed', { code })
87
+ if (front.readyState === WebSocket.OPEN) front.send(JSON.stringify({ type: 'error', error: { code } }))
88
+ front.close(code === 'capacity_exhausted' ? 1013 : 1008)
89
+ back?.close()
90
+ }
91
+ const mode = params.get('mode')
92
+ if (!compatibleVersion(params.get('plugin_version'), config.min_version, config.max_version_exclusive)) { fail('plugin_upgrade_required'); return }
93
+ if (!['online', 'tts_only'].includes(mode)) { fail('invalid_voice_mode'); return }
94
+ connections.set(front, { mode, ready: false, trace })
95
+ front.on('close', () => connections.delete(front))
96
+ const target = config.endpoints[mode]
97
+ if (!target) { fail('voice_mode_unavailable'); return }
98
+ const clientRPC = mode === 'online' && config.control_transport === 'client_rpc_v1'
99
+ const rpcRequests = new Map()
100
+ back = new WebSocket(target, { handshakeTimeout: 15000, maxPayload: 16_000_000,
101
+ ...(config.authorization ? { headers: { Authorization: config.authorization } } : {}),
102
+ })
103
+ const pending = []
104
+ const startup = setTimeout(() => fail('voice_start_timeout'), 20000)
105
+ const forward = (data, binary = false) => {
106
+ trace.frame('upstream.send', data, binary)
107
+ if (back.readyState === WebSocket.OPEN) back.send(data, { binary })
108
+ else if (pending.length < 8) pending.push([data, binary])
109
+ else fail('voice_not_ready')
110
+ }
111
+ back.on('open', () => { for (const [data, binary] of pending.splice(0)) back.send(data, { binary }) })
112
+ front.on('message', (raw, binary) => {
113
+ if (terminal) return
114
+ trace.frame('browser.receive', raw, binary)
115
+ try {
116
+ if (binary) {
117
+ if (mode !== 'online' || !initialized) throw new Error('input_audio_disabled')
118
+ forward(raw, true)
119
+ return
120
+ }
121
+ const message = JSON.parse(raw.toString())
122
+ if (message.type === 'client.diagnostic') return // captured locally, never fed to model
123
+ if (message.type === 'harness.state') {
124
+ if (!message.state || typeof message.state !== 'object' || JSON.stringify(message.state).length > 100_000) throw new Error('invalid_harness_state')
125
+ state = message.state
126
+ // Keep state available to host diagnostics, separate from speech.
127
+ // State-only updates never invoke a model or become a notification.
128
+ return
129
+ }
130
+ if (message.type === 'session.update') {
131
+ if (initialized) throw new Error('voice_mode_requires_reconnect')
132
+ initialized = true
133
+ forward(JSON.stringify({ type: 'session.update',
134
+ client: { name: 'dsh-duet', version: params.get('plugin_version'), protocol_major: 1 },
135
+ session: {
136
+ type: 'realtime', preset_id: 'server_default',
137
+ ...(mode === 'tts_only' ? { io_mode: 'external_only' } : clientRPC ? { io_mode: 'online', harness: { transport: 'client_rpc_v1' } } : {}),
138
+ audio: { input: { format: { type: 'audio/pcm', rate: 16000 } } },
139
+ debug: { enabled: false, slot_grid: false },
140
+ } }))
141
+ return
142
+ }
143
+ if (!initialized) throw new Error('session_not_started')
144
+ if (message.type === 'harness.composer.update') {
145
+ if (!clientRPC || raw.length > 100_000) throw new Error('invalid_composer_push')
146
+ forward(raw.toString())
147
+ return
148
+ }
149
+ if (message.type === 'harness.rpc.response') {
150
+ if (!clientRPC || rpcRequests.get(message.request_id) !== message.connection_id) throw new Error('harness_rpc_unmatched_response')
151
+ rpcRequests.delete(message.request_id)
152
+ forward(raw.toString())
153
+ return
154
+ }
155
+ if (message.type === 'external_message') {
156
+ if (mode !== 'tts_only') throw new Error('external_only_session_required')
157
+ forward(JSON.stringify(externalWithState(message, state)))
158
+ } else if (['output_audio_buffer.playback_progress', 'output_audio_buffer.cleared', 'session.close'].includes(message.type)) {
159
+ forward(raw.toString())
160
+ } else throw new Error('unsupported_voice_event')
161
+ } catch (error) { fail(error.message || 'invalid_voice_event') }
162
+ })
163
+ back.on('message', (data, binary) => {
164
+ trace.frame('upstream.receive', data, binary)
165
+ if (!binary) {
166
+ try {
167
+ const event = JSON.parse(data.toString())
168
+ if (event.type === 'harness.rpc.request') {
169
+ if (!clientRPC || rpcRequests.size >= 8) { fail('invalid_harness_rpc'); return }
170
+ rpcRequests.set(event.request_id, event.connection_id)
171
+ }
172
+ if (event.type === 'session.created') {
173
+ if (clientRPC && event.session?.config?.harness_control_transport !== 'client_rpc_v1') { fail('harness_rpc_backend_upgrade_required'); return }
174
+ if (mode === 'tts_only' && event.session?.config?.external_message_protocol !== 'harness_result_v2') { fail('harness_result_backend_upgrade_required'); return }
175
+ const connection = connections.get(front)
176
+ if (connection) connection.ready = true
177
+ clearTimeout(startup)
178
+ if(!feedbackTicket)feedbackTicket=feedback?.open(req,event.session?.id,mode)
179
+ if(feedbackTicket){
180
+ data=JSON.stringify({...event,feedback_session_ticket:feedbackTicket})
181
+ }
182
+ }
183
+ } catch { /* Upstream framing is passed through. */ }
184
+ }
185
+ if (front.readyState === WebSocket.OPEN) front.send(data, { binary })
186
+ })
187
+ back.on('error', error => { trace.event('upstream.error', { message: error.message, stack: error.stack }); fail('voice_upstream_unavailable') })
188
+ back.on('unexpected-response', (_request, response) => {
189
+ response.resume()
190
+ trace.event('upstream.handshake_failed', { status: response.statusCode })
191
+ fail([429, 503].includes(response.statusCode) ? 'capacity_exhausted' : response.statusCode === 426 ? 'plugin_upgrade_required' : 'voice_upstream_unavailable')
192
+ })
193
+ back.on('close', (code, reason) => {
194
+ trace.event('upstream.closed', { code, reason: reason.toString() })
195
+ clearTimeout(startup)
196
+ if (code === 1013) fail('capacity_exhausted')
197
+ else front.close(code === 1000 ? 1000 : 1011)
198
+ })
199
+ front.on('error', error => { trace.event('browser.error', { message: error.message }); back.close() })
200
+ front.on('close', (code, reason) => {
201
+ trace.event('rpc.pending_at_close', { request_ids: [...rpcRequests.keys()] })
202
+ clearTimeout(startup); back.close()
203
+ const timer = setTimeout(() => back.terminate(), 1000)
204
+ timer.unref()
205
+ })
206
+ })
207
+ },
208
+ })
209
+ const dispose = () => { stop(); for (const socket of server.clients) socket.close(1001); server.close() }
210
+ dispose.snapshot = () => ({
211
+ online: [...connections.values()].filter(c => c.mode === 'online' && c.ready).length,
212
+ tts_only: [...connections.values()].filter(c => c.mode === 'tts_only' && c.ready).length,
213
+ connecting: [...connections.values()].filter(c => !c.ready).length,
214
+ traces: [...connections.values()].map(c => c.trace.snapshot()),
215
+ })
216
+ dispose.closeConnections = code => {
217
+ for (const socket of connections.keys()) {
218
+ if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: 'error', error: { code } }))
219
+ socket.close(1000)
220
+ }
221
+ }
222
+ return dispose
223
+ }
@@ -0,0 +1,104 @@
1
+ /** Reverse RPC executes on this authenticated DSH origin, never a supplied URL. */
2
+ import { orderSessionCatalog, readWorkspaceView } from './deepseek_harness_voice_catalog.mjs'
3
+ const MAX_BYTES = 256_000
4
+ const READ = /^\/api\/(?:health|sessions|jobs|results|interactions|composer\/focused|sessions\/[A-Za-z0-9_-]+\/composer)$/
5
+ const WRITE = /^\/api\/(?:sessions\/[A-Za-z0-9_-]+\/(?:composer\/submit|activate|rename|fork)|interactions\/(?:(?:question|approval)(?::|%3[Aa]))?[A-Za-z0-9_-]+\/respond)$/
6
+
7
+ export function validateRPC(request) {
8
+ if (request.type !== 'harness.rpc.request' || !/^[a-f0-9]{32}$/.test(request.request_id || '')
9
+ || !/^[a-f0-9]{32}$/.test(request.connection_id || '')) throw new Error('invalid_harness_rpc')
10
+ if (!((request.method === 'GET' && READ.test(request.path))
11
+ || (request.method === 'POST' && WRITE.test(request.path))
12
+ || (request.method === 'PUT' && /^\/api\/sessions\/[A-Za-z0-9_-]+\/composer$/.test(request.path)))) throw new Error('harness_rpc_route_not_allowed')
13
+ if (new TextEncoder().encode(JSON.stringify(request)).length > MAX_BYTES) throw new Error('harness_rpc_too_large')
14
+ if (request.params != null) {
15
+ const focus = /\/composer$/.test(request.path) && JSON.stringify(request.params) === '{"require_focus":"true"}'
16
+ const results = request.path === '/api/results' && typeof request.params === 'object'
17
+ && Object.entries(request.params).every(([k, v]) => ['after', 'limit'].includes(k) && Number.isSafeInteger(v) && v >= 0)
18
+ if (!focus && !results) throw new Error('invalid_harness_rpc_params')
19
+ }
20
+ }
21
+
22
+ export class HarnessRPCExecutor {
23
+ constructor(send, fetchImpl = fetch, diagnostic = () => {}, localComposer = null) {
24
+ // Native Window.fetch rejects an RPCExecutor receiver (Illegal invocation).
25
+ // Call the captured function plainly, not as an instance method.
26
+ this.send = send; this.fetch = (...args) => fetchImpl(...args); this.closed = false
27
+ this.diagnostic = diagnostic
28
+ this.localComposer = localComposer
29
+ this.connectionId = null; this.seen = new Map(); this.retired = new Set(); this.controllers = new Set()
30
+ }
31
+
32
+ async execute(request) {
33
+ if (this.closed) return
34
+ validateRPC(request)
35
+ this.connectionId ??= request.connection_id
36
+ if (request.connection_id !== this.connectionId) throw new Error('harness_rpc_wrong_connection')
37
+ if (this.retired.has(request.request_id)) throw new Error('harness_rpc_reply_expired')
38
+ const fingerprint = JSON.stringify(request)
39
+ const previous = this.seen.get(request.request_id)
40
+ if (previous) {
41
+ if (previous.fingerprint !== fingerprint) throw new Error('harness_rpc_id_reused')
42
+ const response = await previous.promise
43
+ if (!this.closed) this.send(response)
44
+ return
45
+ }
46
+ if (this.retired.size >= 10_000 || this.controllers.size >= 8) throw new Error('harness_rpc_capacity_exhausted')
47
+ const promise = this.call(request)
48
+ // Reads are safe to repeat; keep bounded mutation replies and ID tombstones.
49
+ if (request.method !== 'GET') this.seen.set(request.request_id, { fingerprint, promise })
50
+ const response = await promise
51
+ if (!this.closed) this.send(response)
52
+ while (this.seen.size > 128) {
53
+ const id = this.seen.keys().next().value
54
+ this.seen.delete(id); this.retired.add(id)
55
+ }
56
+ }
57
+
58
+ async call(request) {
59
+ const controller = new AbortController()
60
+ this.controllers.add(controller)
61
+ const timer = setTimeout(() => controller.abort(), 12_000)
62
+ const envelope = { type: 'harness.rpc.response', connection_id: request.connection_id, request_id: request.request_id }
63
+ try {
64
+ if (this.localComposer) {
65
+ try {
66
+ const body = await this.localComposer(request, controller.signal)
67
+ if (body !== undefined) return { ...envelope, status: 200, body }
68
+ } catch (error) {
69
+ return { ...envelope, status: 409, body: { error_code: error.code || 'composer_operation_failed', detail: 'Draft changed or unavailable; read input_status again' } }
70
+ }
71
+ }
72
+ const query = request.params ? '?' + new URLSearchParams(request.params) : ''
73
+ const response = await this.fetch('/duplex-control' + request.path + query, {
74
+ method: request.method, credentials: 'same-origin', redirect: 'error',
75
+ cache: 'no-store', signal: controller.signal,
76
+ headers: { 'Content-Type': 'application/json', 'X-Duplex-Control-Client': 'realtime-client-rpc-v1',
77
+ 'X-Duet-Native-Interactions': '1' },
78
+ ...(request.method !== 'GET' ? { body: JSON.stringify(request.payload ?? {}) } : {}),
79
+ })
80
+ const text = await response.text()
81
+ if (new TextEncoder().encode(text).length > MAX_BYTES - 512) throw new Error('harness_rpc_response_too_large')
82
+ const body = JSON.parse(text)
83
+ if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error('invalid_harness_rpc_body')
84
+ if (response.status === 200 && request.path === '/api/sessions' && Array.isArray(body.sessions)) {
85
+ // Both startup prompt and nth_N resolution read this same browser-local
86
+ // order, including manual drag order; archived rows cannot consume ranks.
87
+ body.sessions = orderSessionCatalog(body.sessions, readWorkspaceView())
88
+ }
89
+ return { ...envelope, status: response.status, body }
90
+ } catch (error) {
91
+ this.diagnostic({ event: 'rpc_fetch_failed', request_id: request.request_id, path: request.path,
92
+ message: String(error?.message || error), stack: error?.stack })
93
+ return { ...envelope, status: 502, body: { error_code: 'dsh_rpc_failed_outcome_unknown', detail: 'DSH request failed; do not automatically retry mutations' } }
94
+ } finally {
95
+ clearTimeout(timer); this.controllers.delete(controller)
96
+ }
97
+ }
98
+
99
+ close() {
100
+ this.closed = true
101
+ for (const controller of this.controllers) controller.abort()
102
+ this.controllers.clear(); this.seen.clear(); this.retired.clear()
103
+ }
104
+ }
@@ -0,0 +1,45 @@
1
+ /** Read-only public model aliases from the configured voice service. */
2
+ export class ServiceInfo {
3
+ constructor(getConfig, fetchImpl = fetch) {
4
+ this.getConfig = getConfig; this.fetch = fetchImpl
5
+ this.cached = null; this.inflight = null; this.epoch = 0
6
+ }
7
+ invalidate() { this.epoch++; this.cached = null; this.inflight = null }
8
+ async get() {
9
+ if (this.cached && Date.now() < this.cached.expires) return this.cached.value
10
+ if (this.inflight) return this.inflight
11
+ const epoch = this.epoch, config = this.getConfig()
12
+ const unavailable = { status: 'unavailable', models: null }
13
+ const work = async () => {
14
+ let value = unavailable
15
+ try {
16
+ const url = new URL(config.endpoints.online)
17
+ url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'
18
+ url.pathname = url.pathname.replace(/\/ws\/?$/, '').replace(/\/$/, '') + '/api/service-info'
19
+ url.search = ''
20
+ const response = await this.fetch(url, { headers: config.authorization ? { Authorization: config.authorization } : {}, redirect: 'error', signal: AbortSignal.timeout(3000) })
21
+ if (!response.ok) throw Error('service_info_unavailable')
22
+ const reader = response.body.getReader(), decoder = new TextDecoder()
23
+ let body = '', bytes = 0
24
+ try {
25
+ while (true) {
26
+ const { done, value: chunk } = await reader.read()
27
+ if (done) break
28
+ bytes += chunk.length
29
+ if (bytes > 8192) throw Error('service_info_too_large')
30
+ body += decoder.decode(chunk, { stream: true })
31
+ }
32
+ body += decoder.decode()
33
+ } finally { await reader.cancel().catch(() => {}) }
34
+ const data = JSON.parse(body), models = data.models
35
+ if (data.schema_version !== 1 || !models || !['duplex', 'tts'].every(k => typeof models[k] === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(models[k]))) throw Error('invalid_models')
36
+ value = { status: 'ok', models: { duplex: models.duplex, tts: models.tts } }
37
+ } catch { /* An unavailable service must not display invented model names. */ }
38
+ if (epoch !== this.epoch) return unavailable
39
+ this.cached = { expires: Date.now() + 30_000, value }; this.inflight = null
40
+ return value
41
+ }
42
+ this.inflight = work()
43
+ return this.inflight
44
+ }
45
+ }