dsh-duet 0.1.3 → 0.1.5

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.
@@ -0,0 +1,186 @@
1
+ /** Fixed bootstrap, bounded discovery, and connection-scoped endpoint selection. */
2
+ import {isIP} from 'node:net'
3
+ import {lookup} from 'node:dns/promises'
4
+ import {readFileSync, statSync} from 'node:fs'
5
+ import {mkdir, writeFile, rename, unlink} from 'node:fs/promises'
6
+ import {dirname} from 'node:path'
7
+ import {defaultStateFile} from './storage-paths.mjs'
8
+ import {randomUUID} from 'node:crypto'
9
+ import {connectionGuidance,normalizeGuidance} from '../shared/connection-guidance.mjs'
10
+ import {DEFAULT_DUET_URL, PUBLIC_TRIAL_AUTHORIZATION, isPublicTrialEndpoint} from './service-defaults.mjs'
11
+
12
+ export function endpointHTTP(endpoint, path) {
13
+ const url=new URL(endpoint)
14
+ if(!['http:','https:','ws:','wss:'].includes(url.protocol))throw Error('invalid_endpoint_protocol')
15
+ url.protocol=['wss:','https:'].includes(url.protocol)?'https:':'http:'
16
+ url.pathname=url.pathname.replace(/\/ws\/?$/,'').replace(/\/$/,'')+path
17
+ url.search=''
18
+ return url.toString()
19
+ }
20
+ export const DISCOVERY_INTERVAL_MS=24*60*60*1000
21
+ function recommendationURL(value) {
22
+ if(typeof value!=='string'||!value||value.length>2048) throw Error('invalid_recommended_endpoint')
23
+ const url=new URL(value.includes('://')?value:'ws://'+value)
24
+ if(url.protocol==='http:')url.protocol='ws:'
25
+ if(url.protocol==='https:')url.protocol='wss:'
26
+ const host=url.hostname.replace(/^\[|\]$/g,'')
27
+ if(!['ws:','wss:'].includes(url.protocol)||url.username||url.password||url.hash
28
+ ||!['','/','/ws'].includes(url.pathname)||!['','80','443'].includes(url.port)
29
+ ||[...url.searchParams].some(([k,v])=>k!=='protocol'||v!=='realtime_v2')
30
+ ||(!isIP(host)&&(!host.includes('.')||/\.(local|localhost|internal|test|invalid)\.?$/i.test(host)))) throw Error('invalid_recommended_endpoint')
31
+ url.pathname='/ws';url.search='?protocol=realtime_v2'
32
+ return url
33
+ }
34
+ function pinnedCandidate(url, addresses) {
35
+ const host=url.hostname.replace(/^\[|\]$/g,'')
36
+ if(!Array.isArray(addresses)||!addresses.length||addresses.length>32
37
+ ||addresses.some(row=>![4,6].includes(row.family)||isIP(row.address)!==row.family
38
+ ||(isIP(host)&&host!==row.address))) throw Error('invalid_endpoint_address')
39
+ // Freeze DNS for the WS connection, not just for validation.
40
+ const pinnedLookup=(_host, options, callback)=>{
41
+ if(typeof options==='function'){callback=options;options={}}
42
+ if(options?.all)callback(null,addresses)
43
+ else callback(null,addresses[0].address,addresses[0].family)
44
+ }
45
+ return {url:url.toString(),addresses,lookup:pinnedLookup}
46
+ }
47
+ export async function recommendedEndpoint(value, resolve=lookup) {
48
+ const url=recommendationURL(value),host=url.hostname.replace(/^\[|\]$/g,'')
49
+ const addresses=isIP(host)?[{address:host,family:isIP(host)}]:await resolve(host,{all:true})
50
+ return pinnedCandidate(url,addresses)
51
+ }
52
+
53
+ export class EndpointDiscovery {
54
+ constructor(getConfig,{fetchImpl=fetch,resolve=lookup,now=Date.now,changed=()=>{},
55
+ cachePath=defaultStateFile('endpoint-discovery.json')}={}) {
56
+ this.getConfig=getConfig;this.fetchImpl=(...args)=>fetchImpl(...args);this.resolve=resolve;this.now=now;this.changed=changed
57
+ this.cache={candidate:null,reason:'discovery_unavailable',hint:connectionGuidance(null)};this.lastAttemptAt=null;this.cachePath=cachePath
58
+ this.inflight=null;this.selected=new Map();this.active=null;this.failedUntil=0
59
+ try {
60
+ if(cachePath&&statSync(cachePath).size<=8192){
61
+ const data=JSON.parse(readFileSync(cachePath,'utf8'))
62
+ if(data.schema_version!==1||data.bootstrap_endpoint!==DEFAULT_DUET_URL
63
+ ||!Number.isFinite(data.last_attempt_at)||data.last_attempt_at<0)throw Error('invalid_cache')
64
+ const candidate=data.candidate?pinnedCandidate(recommendationURL(data.candidate.url),data.candidate.addresses):null
65
+ this.cache={candidate,reason:candidate?'recommended':'no_recommendation',hint:normalizeGuidance(data.connection_hint)}
66
+ this.lastAttemptAt=data.last_attempt_at
67
+ }
68
+ }catch{ /* A missing/corrupt cache must not prevent startup. */ }
69
+ }
70
+ invalidate(){this.selected.clear();this.active=null;this.failedUntil=0}
71
+ async persist(){
72
+ if(!this.cachePath)return
73
+ const temp=`${this.cachePath}.${randomUUID()}.tmp`
74
+ const candidate=this.cache.candidate
75
+ const data={schema_version:1,bootstrap_endpoint:DEFAULT_DUET_URL,last_attempt_at:this.lastAttemptAt,
76
+ candidate:candidate?{url:candidate.url,addresses:candidate.addresses}:null,connection_hint:this.cache.hint}
77
+ try {
78
+ await mkdir(dirname(this.cachePath),{recursive:true,mode:0o700})
79
+ await writeFile(temp,JSON.stringify(data)+'\n',{mode:0o600,flag:'wx'})
80
+ await rename(temp,this.cachePath)
81
+ }catch{ /* Read-only/full disks must not block connecting. */ }
82
+ finally{await unlink(temp).catch(()=>{})}
83
+ }
84
+ refreshIfDue(){
85
+ if(!Object.values(this.getConfig().endpoints).some(isPublicTrialEndpoint))return null
86
+ if(this.inflight)return this.inflight
87
+ const now=this.now()
88
+ if(this.lastAttemptAt!==null&&now>=this.lastAttemptAt&&now-this.lastAttemptAt<DISCOVERY_INTERVAL_MS)return null
89
+ this.lastAttemptAt=now
90
+ const work=(async()=>{
91
+ // Persist attempts as well as successes: an outage must not cause a request on every restart.
92
+ await this.persist()
93
+ try {
94
+ const response=await this.fetchImpl(endpointHTTP(DEFAULT_DUET_URL,'/api/connection-info'),{
95
+ headers:{Authorization:PUBLIC_TRIAL_AUTHORIZATION},redirect:'error',signal:AbortSignal.timeout(2500)})
96
+ if(!response.ok)throw Error('discovery_unavailable')
97
+ const reader=response.body.getReader();let bytes=0,body='';const decoder=new TextDecoder()
98
+ try{while(true){const {done,value:chunk}=await reader.read();if(done)break;bytes+=chunk.length;if(bytes>4096)throw Error('discovery_too_large');body+=decoder.decode(chunk,{stream:true})}body+=decoder.decode()}
99
+ finally{await reader.cancel().catch(()=>{})}
100
+ const data=JSON.parse(body)
101
+ if(data.schema_version!==1||typeof data.recommended_endpoint!=='string')throw Error('invalid_discovery')
102
+ let timer,candidate
103
+ try {
104
+ candidate=data.recommended_endpoint?await Promise.race([
105
+ recommendedEndpoint(data.recommended_endpoint,this.resolve),
106
+ new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('dns_timeout')),1500);timer.unref?.()}),
107
+ ]):null
108
+ }finally{clearTimeout(timer)}
109
+ this.cache={candidate,reason:candidate?'recommended':'no_recommendation',hint:connectionGuidance(data.connection_hint,data.revision)}
110
+ await this.persist()
111
+ }catch{ /* Keep the last known recommendation, even when it is older than a day. */ }
112
+ return this.cache
113
+ })()
114
+ this.inflight=work
115
+ void work.finally(()=>{if(this.inflight===work)this.inflight=null})
116
+ return work
117
+ }
118
+ async plan(mode){
119
+ const config=this.getConfig(), target=config.endpoints[mode]
120
+ if(!isPublicTrialEndpoint(target))return [{url:target,config,selection:'custom',reason:''}]
121
+ this.refreshIfDue()
122
+ const fallback={url:DEFAULT_DUET_URL,config:{...config,authorization:PUBLIC_TRIAL_AUTHORIZATION},selection:'default',reason:''}
123
+ if(this.failedUntil>this.now())return [{...fallback,selection:'fallback',reason:'recommended_cooldown'}]
124
+ const recommendation=this.cache
125
+ if(!recommendation.candidate||recommendation.candidate.url===DEFAULT_DUET_URL)return [{...fallback,reason:recommendation.reason}]
126
+ return [{...recommendation.candidate,config:fallback.config,selection:'recommended',reason:''},fallback]
127
+ }
128
+ used(mode,route,notify=true){this.selected.set(mode,route);this.active=route;if(notify)this.changed()}
129
+ failed(){this.failedUntil=this.now()+60000}
130
+ metadata(route,reason=''){
131
+ return {bootstrap_endpoint:route.selection==='custom'?'':DEFAULT_DUET_URL,
132
+ selected_endpoint:route.url,selection:reason?'fallback':route.selection,fallback_reason:reason||route.reason||'',
133
+ connection_hint:route.selection==='custom'?connectionGuidance(null):normalizeGuidance(this.cache.hint)}
134
+ }
135
+ async effective(mode=null){
136
+ const route=(mode?this.selected.get(mode):this.active)||(await this.plan(mode||'online'))[0]
137
+ return {...route.config,endpoints:{online:route.url,tts_only:route.url}}
138
+ }
139
+ async fetch(url,options={}){
140
+ // These callers are read-only metadata endpoints. Never replay a feedback POST.
141
+ try {
142
+ const response=await this.fetchImpl(url,options)
143
+ if(response.status<500||options.method&&options.method!=='GET')return response
144
+ throw Error('endpoint_http_unavailable')
145
+ }catch(error){
146
+ if(options.method&&options.method!=='GET')throw error
147
+ const configured=this.getConfig()
148
+ if(!isPublicTrialEndpoint(configured.endpoints.online)||new URL(url).origin===new URL(endpointHTTP(DEFAULT_DUET_URL,'/')).origin)throw error
149
+ this.failed()
150
+ const target=new URL(url),fallback=new URL(endpointHTTP(DEFAULT_DUET_URL,'/'))
151
+ target.protocol=fallback.protocol;target.host=fallback.host
152
+ const route={url:DEFAULT_DUET_URL,config:{...configured,authorization:PUBLIC_TRIAL_AUTHORIZATION},selection:'fallback',reason:'metadata_network_failed'}
153
+ this.used('online',route,false)
154
+ return this.fetchImpl(target,options)
155
+ }
156
+ }
157
+ }
158
+
159
+ /** Retry only transport/handshake failures, before any session/audio/task is sent. */
160
+ export async function connectEndpoint(WebSocket, routes, {signal, trace, timeout=6000}={}) {
161
+ let fallbackReason=''
162
+ for(let i=0;i<routes.length;i++){
163
+ signal?.throwIfAborted()
164
+ const route=routes[i]
165
+ try {
166
+ const socket=await new Promise((resolve,reject)=>{
167
+ const socket=new WebSocket(route.url,{handshakeTimeout:timeout,maxPayload:16000000,
168
+ ...(route.lookup?{lookup:route.lookup}:{}),...(route.config.authorization?{headers:{Authorization:route.config.authorization}}:{})})
169
+ const abort=()=>{socket.terminate();reject(Error('connection_cancelled'))}
170
+ signal?.addEventListener('abort',abort,{once:true})
171
+ let settled=false
172
+ const finish=(error)=>{if(settled)return;settled=true;signal?.removeEventListener('abort',abort);if(error){socket.terminate();reject(error)}else resolve(socket)}
173
+ socket.once('open',()=>finish())
174
+ socket.on('error',()=>finish(Error('network_error')))
175
+ socket.once('close',()=>finish(Error('handshake_closed')))
176
+ socket.once('unexpected-response',(_request,response)=>{response.resume();finish(Object.assign(Error('http_'+response.statusCode),{status:response.statusCode}))})
177
+ })
178
+ return {socket,route,fallbackReason}
179
+ }catch(error){
180
+ trace?.event('endpoint.attempt_failed',{endpoint:route.url,reason:error.message})
181
+ if(signal?.aborted||[401,403,426,429,503].includes(error.status)||i===routes.length-1)throw error
182
+ fallbackReason=error.message
183
+ }
184
+ }
185
+ throw Error('no_endpoint_available')
186
+ }
@@ -1,14 +1,14 @@
1
1
  /** Submit feedback with a stable, locally managed user identity. */
2
2
  import {createHmac,randomBytes,timingSafeEqual} from 'node:crypto'
3
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'
4
+ import {dirname} from 'node:path'
5
+ import {defaultStateFile} from './storage-paths.mjs'
6
6
 
7
7
  const COOKIE='duplex_feedback_user'
8
8
  export class RemoteFeedback {
9
9
  constructor(getConfig,{keyPath,fetchImpl=fetch}={}){
10
10
  this.getConfig=getConfig;this.fetch=fetchImpl
11
- this.keyPath=keyPath||join(process.env.DSH_HOME||join(homedir(),'.dsh'),'duplex-control','feedback-identity.key')
11
+ this.keyPath=keyPath||defaultStateFile('feedback-identity.key')
12
12
  this.key=null
13
13
  }
14
14
  identityKey(){
@@ -40,8 +40,8 @@ export class RemoteFeedback {
40
40
  res.setHeader('Set-Cookie',`${COOKIE}=${signed}; Path=/duplex-control; HttpOnly; SameSite=Strict; Max-Age=31536000${secure?'; Secure':''}`)
41
41
  return 'anon_'+id
42
42
  }
43
- async insert(record){
44
- const config=this.getConfig(),url=new URL(config.endpoints.online)
43
+ async insert(record,{config:connectionConfig}={}){
44
+ const config=connectionConfig||await this.getConfig(),url=new URL(config.endpoints.online)
45
45
  url.protocol=url.protocol==='wss:'?'https:':'http:'
46
46
  url.pathname=url.pathname.replace(/\/ws\/?$/,'').replace(/\/$/,'')+'/feedback';url.search=''
47
47
  const response=await this.fetch(url,{method:'POST',redirect:'error',signal:AbortSignal.timeout(10000),
@@ -17,13 +17,13 @@ export class FeedbackService {
17
17
  return user
18
18
  }
19
19
  prune() { for(const [key,s] of this.sessions)if(this.now()-s.opened>86400000)this.sessions.delete(key) }
20
- open(req, sessionId, mode) {
20
+ open(req, sessionId, mode, connectionConfig) {
21
21
  if(!this.enabled)return null
22
22
  this.prune()
23
23
  if(this.sessions.size>=2048||typeof sessionId!=='string'||!sessionId||sessionId.length>256)return null
24
24
  try {
25
25
  const ticket=randomUUID()
26
- this.sessions.set(ticket,{user:this.user(req),sessionId,mode,opened:this.now(),closed:false})
26
+ this.sessions.set(ticket,{user:this.user(req),sessionId,mode,opened:this.now(),closed:false,connectionConfig})
27
27
  return ticket
28
28
  } catch { return null } // Feedback availability must not break voice.
29
29
  }
@@ -45,7 +45,7 @@ export class FeedbackService {
45
45
  const record={request_id:input.request_id,user_id:user,kind:input.kind,text:text.trim(),
46
46
  rating:session?input.rating:null,session_id:session?.sessionId??null,mode:session?.mode??null,
47
47
  created_at:new Date(this.now()).toISOString()}
48
- const saved=await this.store.insert(record)
48
+ const saved=await this.store.insert(record,{config:session?.connectionConfig})
49
49
  return {persisted:true,request_id:input.request_id,...(saved?.archive_id?{archive_id:saved.archive_id}:{})}
50
50
  }
51
51
  }
@@ -12,10 +12,10 @@ export class ServiceNotices {
12
12
  if (this.cached && Date.now() < this.cached.expires) return this.cached.value
13
13
  if (this.inflight) return this.inflight
14
14
  const epoch = this.epoch
15
- const config = this.getConfig()
16
15
  const work = async () => {
17
16
  let value
18
17
  try {
18
+ const config = await this.getConfig()
19
19
  const url = new URL(config.endpoints.online)
20
20
  url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'
21
21
  url.pathname = url.pathname.replace(/\/ws\/?$/, '').replace(/\/$/, '') + '/announcements'
@@ -13,6 +13,7 @@ import { PLUGIN_VERSION } from '../shared/state.mjs'
13
13
  import { buildSessionCatalog } from '../shared/catalog.mjs'
14
14
  import { publicAsset } from './assets.mjs'
15
15
  import { duetEnv } from './environment.mjs'
16
+ import { EndpointDiscovery } from './endpoint-discovery.mjs'
16
17
 
17
18
  const ROUTE = '/duplex-control'
18
19
  const PAGE_ROUTE = '/duet'
@@ -68,6 +69,7 @@ function publicComposerRequest(request) {
68
69
  overwrite: request.overwrite,
69
70
  text: request.text,
70
71
  claimed_by: request.claimed_by || null,
72
+ target_client_id: request.target_client_id || null,
71
73
  created_at: request.created_at,
72
74
  }
73
75
  }
@@ -90,6 +92,15 @@ function codedError(code, message, status = 409) {
90
92
  return error
91
93
  }
92
94
 
95
+ function browserOwner(req) {
96
+ const id = req.headers['x-duet-browser-client']
97
+ if (id === undefined) return null // Legacy callers remain separate from bound requests.
98
+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)) {
99
+ throw codedError('invalid_browser_owner', 'Invalid browser connection identity', 400)
100
+ }
101
+ return id
102
+ }
103
+
93
104
  function assistantText(event) {
94
105
  const content = event?.data?.message?.content
95
106
  if (!Array.isArray(content)) return ''
@@ -168,12 +179,14 @@ export function apply(ctx, options = {}) {
168
179
  const audit = new DuetTrace({ kind: 'host', plugin_version: PLUGIN_VERSION, pid: process.pid },
169
180
  { ...options.traceOptions, secrets: [voice.authorization] })
170
181
  ctx.effect(() => () => { void audit.close({ reason: 'plugin_dispose' }) })
171
- const notices = new ServiceNotices(() => settings.effective())
172
- const serviceInfo = new ServiceInfo(() => settings.effective())
173
- const feedbackStore = options.feedbackStore ?? (options.feedbackDisabled ? null : new RemoteFeedback(()=>settings.effective(),{keyPath:options.feedbackIdentityPath}))
182
+ const discovery = new EndpointDiscovery(() => settings.effective(), {...options.endpointDiscoveryOptions, changed: () => {notices.invalidate();serviceInfo.invalidate()}})
183
+ const notices = new ServiceNotices(() => discovery.effective(), (url,options) => discovery.fetch(url,options))
184
+ const serviceInfo = new ServiceInfo(() => discovery.effective(), (url,options) => discovery.fetch(url,options))
185
+ discovery.refreshIfDue()
186
+ const feedbackStore = options.feedbackStore ?? (options.feedbackDisabled ? null : new RemoteFeedback(()=>discovery.effective(),{keyPath:options.feedbackIdentityPath}))
174
187
  const feedback = new FeedbackService(feedbackStore)
175
188
  let duetProxy
176
- ctx.effect(() => { duetProxy = registerDuetProxy(ctx, voice, feedback, () => (ctx.workspaceRegistry.list?.() || []).length > 0); return duetProxy })
189
+ ctx.effect(() => { duetProxy = registerDuetProxy(ctx, voice, feedback, () => (ctx.workspaceRegistry.list?.() || []).length > 0, discovery); return duetProxy })
177
190
 
178
191
  ctx.effect(() => () => { hostAbort.abort() })
179
192
 
@@ -268,6 +281,7 @@ export function apply(ctx, options = {}) {
268
281
  overwrite: type === 'set' && payload.overwrite === true,
269
282
  text: payload.text,
270
283
  claimed_by: '',
284
+ target_client_id: payload.target_client_id || null,
271
285
  created_at: nowSeconds(),
272
286
  resolve,
273
287
  reject,
@@ -315,7 +329,7 @@ export function apply(ctx, options = {}) {
315
329
  while (jobOrder.length > MAX_JOBS) jobs.delete(jobOrder.shift())
316
330
  }
317
331
 
318
- const enqueueTask = async (sessionId, task, origin = 'duplex_control') => {
332
+ const enqueueTask = async (sessionId, task, origin = 'duplex_control', syncFocus = true) => {
319
333
  const normalizedTask = String(task || '')
320
334
  if (!normalizedTask.trim()) throw codedError('empty_task', 'Harness task is empty', 400)
321
335
  const id = randomUUID().replaceAll('-', '')
@@ -350,7 +364,7 @@ export function apply(ctx, options = {}) {
350
364
  job.completion_seq = completionSequence
351
365
  throw error
352
366
  }
353
- selectSession(sessionId)
367
+ if (syncFocus) selectSession(sessionId)
354
368
  return job
355
369
  }
356
370
 
@@ -504,6 +518,7 @@ export function apply(ctx, options = {}) {
504
518
  try {
505
519
  const result = await settings.save(await readJson(req))
506
520
  Object.assign(voice, settings.effective())
521
+ discovery.invalidate()
507
522
  feedback.sessions.clear() // Never send an old rating to a newly selected backend.
508
523
  audit.secrets.push(voice.authorization)
509
524
  notices.invalidate()
@@ -654,7 +669,8 @@ export function apply(ctx, options = {}) {
654
669
  }
655
670
  touch()
656
671
  if (url.searchParams.get('wait') === '1'
657
- && ![...composerRequests.values()].some(request => !request.claimed_by)) {
672
+ && ![...composerRequests.values()].some(request => !request.claimed_by
673
+ && (!request.target_client_id || request.target_client_id === clientId))) {
658
674
  await new Promise(resolve => {
659
675
  let timer
660
676
  const done = () => {
@@ -673,7 +689,8 @@ export function apply(ctx, options = {}) {
673
689
  if (res.destroyed || hostAbort.signal.aborted) return
674
690
  const pending = composerRequestOrder
675
691
  .map(id => composerRequests.get(id))
676
- .filter(request => request !== undefined && !request.claimed_by)
692
+ .filter(request => request !== undefined && !request.claimed_by
693
+ && (!request.target_client_id || request.target_client_id === clientId))
677
694
  .slice(0, 20)
678
695
  .map(publicComposerRequest)
679
696
  sendJson(res, 200, {
@@ -699,6 +716,10 @@ export function apply(ctx, options = {}) {
699
716
  sendError(res, 404, 'composer request not found')
700
717
  return
701
718
  }
719
+ if (request.target_client_id && request.target_client_id !== clientId) {
720
+ sendError(res, 409, 'composer request belongs to a different browser connection')
721
+ return
722
+ }
702
723
  if (request.claimed_by && request.claimed_by !== clientId) {
703
724
  sendError(res, 409, 'composer request is already claimed')
704
725
  return
@@ -763,6 +784,7 @@ export function apply(ctx, options = {}) {
763
784
  }
764
785
  const composer = pathname.match(new RegExp(`^${ROUTE}/api/sessions/([^/]+)/composer$`))
765
786
  if (composer !== null && ['GET', 'PUT'].includes(req.method)) {
787
+ const target_client_id = browserOwner(req)
766
788
  const sessionId = decodeURIComponent(composer[1])
767
789
  const sessions = await listSessions()
768
790
  if (!sessions.some(session => session.session_id === sessionId)) {
@@ -771,11 +793,11 @@ export function apply(ctx, options = {}) {
771
793
  }
772
794
  if (req.method === 'GET') {
773
795
  const requireFocus = new URL(req.url, 'http://localhost').searchParams.get('require_focus') === 'true'
774
- if (requireFocus && sessionId !== activeSessionId) {
796
+ if (requireFocus && !target_client_id && sessionId !== activeSessionId) {
775
797
  throw codedError('focus_conflict', '当前聚焦会话已变化,请重新查询输入框')
776
798
  }
777
- const state = await requestComposer('get', { session_id: sessionId, require_focus: requireFocus })
778
- if (requireFocus && sessionId !== activeSessionId) {
799
+ const state = await requestComposer('get', { session_id: sessionId, require_focus: requireFocus, target_client_id })
800
+ if (requireFocus && !target_client_id && sessionId !== activeSessionId) {
779
801
  throw codedError('focus_conflict', '当前聚焦会话已变化,请重新查询输入框')
780
802
  }
781
803
  sendJson(res, 200, { composer: {
@@ -797,10 +819,11 @@ export function apply(ctx, options = {}) {
797
819
  sendError(res, 400, 'composer text must be a string')
798
820
  return
799
821
  }
800
- if (body.require_focus === true && sessionId !== activeSessionId) {
822
+ if (body.require_focus === true && !target_client_id && sessionId !== activeSessionId) {
801
823
  throw codedError('focus_conflict', '当前聚焦会话已变化,请重新查询输入框')
802
824
  }
803
825
  const state = await requestComposer('set', {
826
+ target_client_id,
804
827
  session_id: sessionId,
805
828
  expected_revision: body.expected_revision,
806
829
  expected_hash: body.expected_hash,
@@ -815,6 +838,7 @@ export function apply(ctx, options = {}) {
815
838
  new RegExp(`^${ROUTE}/api/sessions/([^/]+)/composer/submit$`),
816
839
  )
817
840
  if (req.method === 'POST' && submitComposer !== null) {
841
+ const target_client_id = browserOwner(req)
818
842
  const sessionId = decodeURIComponent(submitComposer[1])
819
843
  const body = await readJson(req)
820
844
  const expectedRevision = body.expected_revision
@@ -833,6 +857,8 @@ export function apply(ctx, options = {}) {
833
857
  return
834
858
  }
835
859
  const consumed = await requestComposer('consume', {
860
+ target_client_id,
861
+ require_focus: Boolean(target_client_id),
836
862
  session_id: sessionId,
837
863
  expected_revision: expectedRevision,
838
864
  expected_hash: expectedHash,
@@ -847,10 +873,11 @@ export function apply(ctx, options = {}) {
847
873
  if (!task.trim()) throw codedError('empty_draft', '当前输入框为空,不能发送', 400)
848
874
  let job
849
875
  try {
850
- job = await enqueueTask(sessionId, task)
876
+ job = await enqueueTask(sessionId, task, 'duplex_control', !target_client_id)
851
877
  } catch (error) {
852
878
  try {
853
879
  await requestComposer('set', {
880
+ target_client_id,
854
881
  session_id: sessionId,
855
882
  expected_revision: consumed.revision,
856
883
  expected_hash: consumed.hash,
@@ -890,7 +917,7 @@ export function apply(ctx, options = {}) {
890
917
  }
891
918
  }
892
919
  const created = await ctx.sessionController.create(workspaceId ? { workspaceId } : { cwd })
893
- selectSession(created.sessionId)
920
+ if (!browserOwner(req)) selectSession(created.sessionId)
894
921
  if (name) {
895
922
  await ctx.sessionController.rename({ sessionId: created.sessionId, title: name })
896
923
  }
@@ -906,7 +933,7 @@ export function apply(ctx, options = {}) {
906
933
  sendError(res, 404, 'Harness session not found')
907
934
  return
908
935
  }
909
- selectSession(sessionId)
936
+ if (!browserOwner(req)) selectSession(sessionId)
910
937
  sendJson(res, 200, {
911
938
  ok: true,
912
939
  active_session_id: sessionId,
@@ -961,7 +988,7 @@ export function apply(ctx, options = {}) {
961
988
  sessionId: created.sessionId,
962
989
  title,
963
990
  })
964
- selectSession(created.sessionId)
991
+ if (!browserOwner(req)) selectSession(created.sessionId)
965
992
  sendJson(res, 201, {
966
993
  ok: true,
967
994
  session: {
@@ -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
  }