dsh-duet 0.1.2 → 0.1.4

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.
@@ -1,7 +1,10 @@
1
1
  /** Same-origin voice relay; endpoint and compatibility policy belong to the DSH host. */
2
2
  import { createRequire } from 'node:module'
3
3
  import { DuetTrace } from './trace.mjs'
4
+ import { PLUGIN_VERSION } from '../shared/state.mjs'
4
5
  import { duetEnv } from './environment.mjs'
6
+ import { EndpointDiscovery, connectEndpoint } from './endpoint-discovery.mjs'
7
+ import {sessionMetadata} from './session-metadata.mjs'
5
8
  import { DEFAULT_DUET_URL, publicServiceAuthorization } from './service-defaults.mjs'
6
9
  export { DEFAULT_DUET_URL } from './service-defaults.mjs'
7
10
  const require = createRequire(import.meta.url)
@@ -44,7 +47,7 @@ export function externalWithState(message, _state) {
44
47
  ...(source === undefined ? {} : { source: { ...source } }) }
45
48
  }
46
49
 
47
- export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, canUseVoice = () => true) {
50
+ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, canUseVoice = () => true, discovery = new EndpointDiscovery(() => config)) {
48
51
  if (!['http', 'client_rpc_v1'].includes(config.control_transport || 'http')) throw new Error('invalid_harness_transport')
49
52
  if (!compatibleVersion(config.min_version, config.min_version, config.max_version_exclusive)) throw new Error('invalid_plugin_version_policy')
50
53
  for (const target of Object.values(config.endpoints)) {
@@ -71,6 +74,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
71
74
  front.on('error', () => {})
72
75
  const params = new URL(req.url, 'http://localhost').searchParams
73
76
  const trace = new DuetTrace({ mode: params.get('mode'), plugin_version: params.get('plugin_version'),
77
+ host_plugin_version: PLUGIN_VERSION, page_id: (params.get('page_id') || '').slice(0, 64),
74
78
  client_trace_id: (params.get('client_trace_id') || '').slice(0, 64),
75
79
  backend_origin: new URL(config.endpoints[params.get('mode')] || config.endpoints.online).origin,
76
80
  control_transport: config.control_transport }, { ...config.traceOptions, secrets: [config.authorization] })
@@ -78,7 +82,8 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
78
82
  trace.event('browser.closed', { code, reason: reason.toString() })
79
83
  const timer = setTimeout(() => { void trace.close() }, 1500); timer.unref()
80
84
  })
81
- let back, feedbackTicket = null
85
+ let back, feedbackTicket = null, connectionRoute, selectedConfig
86
+ const opening = new AbortController()
82
87
  front.once('close', () => feedback?.close(feedbackTicket))
83
88
  let state = null
84
89
  let initialized = false
@@ -86,6 +91,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
86
91
  const fail = code => {
87
92
  if (terminal) return
88
93
  terminal = true
94
+ opening.abort()
89
95
  trace.event('proxy.failed', { code })
90
96
  if (front.readyState === WebSocket.OPEN) front.send(JSON.stringify({ type: 'error', error: { code } }))
91
97
  front.close(code === 'capacity_exhausted' ? 1013 : 1008)
@@ -94,6 +100,10 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
94
100
  const mode = params.get('mode')
95
101
  if (!compatibleVersion(params.get('plugin_version'), config.min_version, config.max_version_exclusive)) { fail('plugin_upgrade_required'); return }
96
102
  if (!['online', 'tts_only'].includes(mode)) { fail('invalid_voice_mode'); return }
103
+ let anonymousUserId
104
+ try{anonymousUserId=feedback?.user(req)}catch{ /* Identity is optional, not admission. */ }
105
+ const clientMetadata=sessionMetadata(params,mode,anonymousUserId)
106
+ trace.event('session.metadata',clientMetadata)
97
107
  if (!canUseVoice()) { fail('workspace_required'); return }
98
108
  connections.set(front, { mode, ready: false, trace })
99
109
  front.on('close', () => connections.delete(front))
@@ -101,18 +111,23 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
101
111
  if (!target) { fail('voice_mode_unavailable'); return }
102
112
  const clientRPC = mode === 'online' && config.control_transport === 'client_rpc_v1'
103
113
  const rpcRequests = new Map()
104
- back = new WebSocket(target, { handshakeTimeout: 15000, maxPayload: 16_000_000,
105
- ...(config.authorization ? { headers: { Authorization: config.authorization } } : {}),
106
- })
107
114
  const pending = []
108
115
  const startup = setTimeout(() => fail('voice_start_timeout'), 20000)
109
- const forward = (data, binary = false) => {
116
+ let hintReporting=false,hintReported=false
117
+ const sendUpstream = (data, binary) => {
118
+ if (!binary) {
119
+ const message = JSON.parse(data.toString())
120
+ if (message.type === 'session.update') data = JSON.stringify({...message,
121
+ client: {...message.client, connection_route: connectionRoute}})
122
+ }
110
123
  trace.frame('upstream.send', data, binary)
111
- if (back.readyState === WebSocket.OPEN) back.send(data, { binary })
124
+ back.send(data, {binary})
125
+ }
126
+ const forward = (data, binary = false) => {
127
+ if (back?.readyState === WebSocket.OPEN) sendUpstream(data, binary)
112
128
  else if (pending.length < 8) pending.push([data, binary])
113
129
  else fail('voice_not_ready')
114
130
  }
115
- back.on('open', () => { for (const [data, binary] of pending.splice(0)) back.send(data, { binary }) })
116
131
  front.on('message', (raw, binary) => {
117
132
  if (terminal) return
118
133
  trace.frame('browser.receive', raw, binary)
@@ -124,6 +139,13 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
124
139
  }
125
140
  const message = JSON.parse(raw.toString())
126
141
  if (message.type === 'client.diagnostic') return // captured locally, never fed to model
142
+ if (message.type === 'client.connection_hint') {
143
+ if(hintReporting&&!hintReported&&mode==='online'&&connections.get(front)?.ready){
144
+ hintReported=true
145
+ forward(JSON.stringify({type:'client.connection_hint',connection_hint:connectionRoute.connection_hint}))
146
+ }
147
+ return
148
+ }
127
149
  if (message.type === 'harness.state') {
128
150
  if (!message.state || typeof message.state !== 'object' || JSON.stringify(message.state).length > 100_000) throw new Error('invalid_harness_state')
129
151
  state = message.state
@@ -135,10 +157,11 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
135
157
  if (initialized) throw new Error('voice_mode_requires_reconnect')
136
158
  initialized = true
137
159
  forward(JSON.stringify({ type: 'session.update',
138
- client: { name: 'dsh-duet', version: params.get('plugin_version'), protocol_major: 1 },
160
+ client: clientMetadata,
139
161
  session: {
140
162
  type: 'realtime', preset_id: 'server_default',
141
- ...(mode === 'tts_only' ? { io_mode: 'external_only' } : clientRPC ? { io_mode: 'online', harness: { transport: 'client_rpc_v1' } } : {}),
163
+ io_mode:mode === 'tts_only'?'external_only':'online',
164
+ ...(clientRPC ? { harness: { transport: 'client_rpc_v1' } } : {}),
142
165
  audio: { input: { format: { type: 'audio/pcm', rate: 16000 } } },
143
166
  debug: { enabled: false, slot_grid: false },
144
167
  } }))
@@ -164,6 +187,16 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
164
187
  } else throw new Error('unsupported_voice_event')
165
188
  } catch (error) { fail(error.message || 'invalid_voice_event') }
166
189
  })
190
+ void (async () => {
191
+ const routes = await discovery.plan(mode)
192
+ const selected = await connectEndpoint(WebSocket, routes, {signal: opening.signal, trace})
193
+ if (opening.signal.aborted || front.readyState !== WebSocket.OPEN) { selected.socket.close(); return }
194
+ back = selected.socket
195
+ if (selected.fallbackReason) discovery.failed()
196
+ discovery.used(mode, selected.route)
197
+ connectionRoute = {...discovery.metadata(selected.route, selected.fallbackReason), attempted_endpoint:routes[0].url}
198
+ selectedConfig = {...selected.route.config, endpoints: {online:selected.route.url,tts_only:selected.route.url}}
199
+ trace.event('endpoint.selected', connectionRoute)
167
200
  back.on('message', (data, binary) => {
168
201
  trace.frame('upstream.receive', data, binary)
169
202
  if (!binary) {
@@ -174,15 +207,15 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
174
207
  rpcRequests.set(event.request_id, event.connection_id)
175
208
  }
176
209
  if (event.type === 'session.created') {
210
+ hintReporting=event.connection_hint_reporting===true
177
211
  if (clientRPC && event.session?.config?.harness_control_transport !== 'client_rpc_v1') { fail('harness_rpc_backend_upgrade_required'); return }
178
212
  if (mode === 'tts_only' && event.session?.config?.external_message_protocol !== 'harness_result_v2') { fail('harness_result_backend_upgrade_required'); return }
179
213
  const connection = connections.get(front)
180
214
  if (connection) connection.ready = true
181
215
  clearTimeout(startup)
182
- if(!feedbackTicket)feedbackTicket=feedback?.open(req,event.session?.id,mode)
183
- if(feedbackTicket){
184
- data=JSON.stringify({...event,feedback_session_ticket:feedbackTicket})
185
- }
216
+ if(!feedbackTicket)feedbackTicket=feedback?.open(req,event.session?.id,mode,selectedConfig)
217
+ data=JSON.stringify({...event, connection_route: connectionRoute,
218
+ ...(feedbackTicket?{feedback_session_ticket:feedbackTicket}:{})})
186
219
  }
187
220
  } catch { /* Upstream framing is passed through. */ }
188
221
  }
@@ -200,11 +233,15 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
200
233
  if (code === 1013) fail('capacity_exhausted')
201
234
  else front.close(code === 1000 ? 1000 : 1011)
202
235
  })
203
- front.on('error', error => { trace.event('browser.error', { message: error.message }); back.close() })
236
+ for (const [data, binary] of pending.splice(0)) sendUpstream(data, binary)
237
+ })().catch(error => {
238
+ if (!opening.signal.aborted) fail([429,503].includes(error.status)?'capacity_exhausted':error.status===426?'plugin_upgrade_required':'voice_upstream_unavailable')
239
+ })
240
+ front.on('error', error => { trace.event('browser.error', { message: error.message }); opening.abort(); back?.close() })
204
241
  front.on('close', (code, reason) => {
205
242
  trace.event('rpc.pending_at_close', { request_ids: [...rpcRequests.keys()] })
206
- clearTimeout(startup); back.close()
207
- const timer = setTimeout(() => back.terminate(), 1000)
243
+ opening.abort(); clearTimeout(startup); back?.close()
244
+ const timer = setTimeout(() => back?.terminate(), 1000)
208
245
  timer.unref()
209
246
  })
210
247
  })
@@ -2,11 +2,19 @@
2
2
  export const DEFAULT_DUET_URL = 'ws://duet-router.1781574661016173.ap-southeast-1.pai-eas.aliyuncs.com/ws?protocol=realtime_v2'
3
3
  export const PUBLIC_TRIAL_AUTHORIZATION = "ZTZhZWI4YzA3ODcyZWI2NzZhZjU4MDk3NGE3NGUxODQ2MjgxYWVjYQ=="
4
4
 
5
+ export const PUBLIC_TRIAL_GATEWAY_URL = 'ws://duet-router-acc.gw-bmmaj5gve68z3gw34o.ap-southeast-1.pai-eas.aliyuncs.com/ws?protocol=realtime_v2'
6
+ export const PUBLIC_TRIAL_ACCELERATOR_URL = 'ws://47.117.104.188/ws?protocol=realtime_v2'
7
+
8
+ export function isPublicTrialEndpoint(value) {
9
+ const url = new URL(value)
10
+ return [DEFAULT_DUET_URL, PUBLIC_TRIAL_GATEWAY_URL, PUBLIC_TRIAL_ACCELERATOR_URL].some(value => {
11
+ const expected = new URL(value)
12
+ return url.origin === expected.origin && url.pathname === expected.pathname && !url.username && !url.password
13
+ })
14
+ }
15
+
5
16
  /** Never forward the trial credential to a user-selected third-party service. */
6
17
  export function publicServiceAuthorization(endpoints) {
7
18
  const urls = Object.values(endpoints)
8
- return urls.length && urls.every(value => {
9
- const url = new URL(value), expected = new URL(DEFAULT_DUET_URL)
10
- return url.origin === expected.origin && url.pathname === expected.pathname && !url.username && !url.password
11
- }) ? PUBLIC_TRIAL_AUTHORIZATION : ''
19
+ return urls.length && urls.every(isPublicTrialEndpoint) ? PUBLIC_TRIAL_AUTHORIZATION : ''
12
20
  }
@@ -8,11 +8,12 @@ export class ServiceInfo {
8
8
  async get() {
9
9
  if (this.cached && Date.now() < this.cached.expires) return this.cached.value
10
10
  if (this.inflight) return this.inflight
11
- const epoch = this.epoch, config = this.getConfig()
11
+ const epoch = this.epoch
12
12
  const unavailable = { status: 'unavailable', models: null }
13
13
  const work = async () => {
14
14
  let value = unavailable
15
15
  try {
16
+ const config = await this.getConfig()
16
17
  const url = new URL(config.endpoints.online)
17
18
  url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'
18
19
  url.pathname = url.pathname.replace(/\/ws\/?$/, '').replace(/\/$/, '') + '/api/service-info'
@@ -0,0 +1,17 @@
1
+ /** Shared, connection-scoped diagnostics for both voice modes. No account identity. */
2
+ import {randomUUID} from 'node:crypto'
3
+ import {PLUGIN_VERSION} from '../shared/state.mjs'
4
+
5
+ function identifier(value){
6
+ return typeof value==='string'&&/^[A-Za-z0-9_-]{1,64}$/.test(value)?value:''
7
+ }
8
+ export function sessionMetadata(params,mode,anonymousUserId){
9
+ if(!['online','tts_only'].includes(mode))throw Error('invalid_voice_mode')
10
+ return Object.freeze({name:'dsh-duet',version:(params.get('plugin_version')||'').slice(0,64),
11
+ protocol_major:1,metadata_version:'duet_session_v1',mode,
12
+ host_version:PLUGIN_VERSION,page_binding:'connection_owner_v1',
13
+ client_trace_id:identifier(params.get('client_trace_id'))||randomUUID(),
14
+ page_id:identifier(params.get('page_id')),
15
+ ...(typeof anonymousUserId==='string'&&/^anon_[a-f0-9]{32}$/.test(anonymousUserId)
16
+ ?{anonymous_user_id:anonymousUserId,identity_kind:'anonymous_browser'}:{})})
17
+ }
@@ -1,11 +1,22 @@
1
1
  /** Host-only endpoint settings; trial authentication comes from the package. */
2
2
  import { readFileSync } from 'node:fs'
3
3
  import { mkdir, writeFile, rename, unlink } from 'node:fs/promises'
4
- import { dirname, join } from 'node:path'
5
- import { homedir } from 'node:os'
4
+ import { dirname } from 'node:path'
5
+ import { defaultStateFile } from './storage-paths.mjs'
6
6
  import { randomUUID } from 'node:crypto'
7
7
  import { duetEnv } from './environment.mjs'
8
- import { publicServiceAuthorization } from './service-defaults.mjs'
8
+ import { publicServiceAuthorization, isPublicTrialEndpoint } from './service-defaults.mjs'
9
+
10
+ export function normalizeBackendURL(value) {
11
+ if (typeof value !== 'string' || value.length > 2048) throw new Error('invalid_backend_url')
12
+ const url = new URL(value.trim())
13
+ const baseAddress = url.pathname === '/'
14
+ if (url.protocol === 'http:') url.protocol = 'ws:'
15
+ else if (url.protocol === 'https:') url.protocol = 'wss:'
16
+ if (url.pathname === '/') url.pathname = '/ws'
17
+ if (baseAddress && !url.searchParams.has('protocol')) url.searchParams.set('protocol', 'realtime_v2')
18
+ return url.toString()
19
+ }
9
20
 
10
21
  export function validateBackendURL(value, insecureOrigin = null) {
11
22
  if (typeof value !== 'string' || value.length > 2048) throw new Error('invalid_backend_url')
@@ -13,14 +24,14 @@ export function validateBackendURL(value, insecureOrigin = null) {
13
24
  if (!['ws:', 'wss:'].includes(url.protocol) || url.username || url.password || url.hash) throw new Error('invalid_backend_url')
14
25
  // Credentials never belong in URLs or logs.
15
26
  if ([...url.searchParams.keys()].some(k => k !== 'protocol')) throw new Error('backend_url_query_not_allowed')
16
- if (url.protocol === 'ws:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) && url.origin !== insecureOrigin) throw new Error('backend_requires_wss')
27
+ if (url.protocol === 'ws:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) && url.origin !== insecureOrigin && !isPublicTrialEndpoint(url.toString())) throw new Error('backend_requires_wss')
17
28
  return url.toString()
18
29
  }
19
30
 
20
31
  export class DuetSettings {
21
32
  constructor(base, { path, debug = false } = {}) {
22
33
  this.base = base
23
- this.path = path || duetEnv('SETTINGS_FILE') || join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'duplex-control', 'voice.json')
34
+ this.path = path || duetEnv('SETTINGS_FILE') || defaultStateFile('voice.json')
24
35
  this.debug = debug
25
36
  this.saved = null
26
37
  this.revision = 0
@@ -66,8 +77,9 @@ export class DuetSettings {
66
77
  if (this.writing) throw new Error('settings_write_in_progress')
67
78
  if (!input || input.revision !== this.revision) throw new Error('settings_revision_conflict')
68
79
  // 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)
80
+ const normalized = normalizeBackendURL(input.backend_url)
81
+ const insecureOrigin = input.allow_insecure_http === true ? new URL(normalized).origin : this.saved?.insecure_origin
82
+ const url = validateBackendURL(normalized, insecureOrigin)
71
83
  const next = this.validate({ backend_url: url, insecure_origin: insecureOrigin })
72
84
  this.writing = true
73
85
  const temp = `${this.path}.${randomUUID()}.tmp`
@@ -0,0 +1,28 @@
1
+ /** Default private plugin storage; legacy files are copied once, never overwritten. */
2
+ import {existsSync,mkdirSync,copyFileSync,chmodSync,linkSync,unlinkSync} from 'node:fs'
3
+ import {join,dirname} from 'node:path'
4
+ import {homedir} from 'node:os'
5
+ import {randomUUID} from 'node:crypto'
6
+
7
+ export function duetHome(){
8
+ return join(process.env.DSH_HOME||join(homedir(),'.dsh'),'dsh-duet')
9
+ }
10
+
11
+ export function defaultStateFile(name){
12
+ const target=join(duetHome(),name)
13
+ const legacy=join(dirname(duetHome()),'duplex-control',name)
14
+ if(existsSync(target)||!existsSync(legacy))return target
15
+ const temp=`${target}.${randomUUID()}.tmp`
16
+ try {
17
+ mkdirSync(dirname(target),{recursive:true,mode:0o700})
18
+ copyFileSync(legacy,temp)
19
+ chmodSync(temp,0o600)
20
+ // Publish atomically without overwriting another process's completed migration.
21
+ try{linkSync(temp,target)}catch(error){if(error.code!=='EEXIST')throw error}
22
+ return target
23
+ }catch{
24
+ // A read-only/full disk must not discard settings or rotate the feedback identity.
25
+ console.warn('[duet] Storage migration unavailable; keeping legacy file until next startup.')
26
+ return legacy
27
+ }finally{try{unlinkSync(temp)}catch{}}
28
+ }
@@ -1,6 +1,6 @@
1
1
  /** Private, append-only connection capture. Never served as a web asset. */
2
2
  import { createWriteStream, mkdirSync, readdirSync, statSync } from 'node:fs'
3
- import { homedir } from 'node:os'
3
+ import { duetHome } from './storage-paths.mjs'
4
4
  import { join } from 'node:path'
5
5
  import { randomUUID } from 'node:crypto'
6
6
  import { duetEnv } from './environment.mjs'
@@ -19,7 +19,7 @@ export function redact(value, secrets = []) {
19
19
 
20
20
  const budgets = new Map()
21
21
  export class DuetTrace {
22
- constructor(metadata, { root = duetEnv('TRACE_DIR') || join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'duplex-control', 'traces'),
22
+ constructor(metadata, { root = duetEnv('TRACE_DIR') || join(duetHome(), 'traces'),
23
23
  secrets = [], maxBytes = 512 * 1024 ** 2, totalBytes = 20 * 1024 ** 3, queueBytes = 8 * 1024 ** 2 } = {}) {
24
24
  this.id = randomUUID(); this.start = performance.now(); this.seq = 0; this.bytes = 0
25
25
  this.offset = 0; this.closed = false; this.error = null; this.secrets = secrets
@@ -0,0 +1,9 @@
1
+ export const DEFAULT_CONNECTION_HINT='连接成功,可以试试对我说“你好”。'
2
+ export function connectionGuidance(text,revision=null){
3
+ const valid=typeof text==='string'&&text.trim().length>0&&text.length<=200&&!/[\u0000-\u001f\u007f<>]/.test(text)
4
+ return {text:valid?text.trim():DEFAULT_CONNECTION_HINT,source:valid?'router':'default',
5
+ revision:valid&&Number.isSafeInteger(revision)&&revision>=0?revision:null}
6
+ }
7
+ export function normalizeGuidance(value){
8
+ return value?.source==='router'?connectionGuidance(value.text,value.revision):connectionGuidance(null)
9
+ }
@@ -1,5 +1,5 @@
1
1
  /** Desired voice mode is independent of a temporarily suspended connection. */
2
- export const PLUGIN_VERSION = '0.1.2'
2
+ export const PLUGIN_VERSION = '0.1.4'
3
3
  export const IDLE_RELEASE_MS = 60_000
4
4
 
5
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 : ''
@@ -109,6 +109,10 @@ export class DuetState {
109
109
  workspace_loading: '正在加载 workspace,请稍后再试。',
110
110
  workspace_unavailable: '无法读取 workspace,请刷新 DSH 后重试。',
111
111
  microphone_unavailable: '无法使用所选麦克风,请在设置中检查设备与浏览器权限',
112
+ microphone_disconnected: '麦克风已断开或权限已撤销,交互模式已关闭。请检查设备后重新开启。',
113
+ audio_capture_failed: '麦克风采集异常,交互模式已关闭。请检查设备后重新开启。',
114
+ voice_start_timeout: '连接超时,请检查网络或麦克风授权后重新开启。',
115
+ harness_sync_failed: '无法继续同步 DSH 会话,语音已关闭。请检查 DSH 后重新开启。',
112
116
  interaction_mode_unavailable: '交互模式暂时不可用,请稍后再试',
113
117
  broadcast_mode_unavailable: '播报模式暂时不可用,请稍后再试',
114
118
  client_protocol_unsupported: '插件与服务器协议不兼容,请更新插件或联系服务管理员',