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.
- package/README.md +7 -6
- package/package.json +2 -2
- package/src/client/audio.mjs +37 -2
- package/src/client/browser.mjs +98 -63
- package/src/client/composer-bridge.mjs +201 -0
- package/src/client/composer.mjs +23 -0
- package/src/client/connection-hint.mjs +33 -7
- package/src/client/controls-layout.mjs +18 -0
- package/src/client/entry.js +1 -408
- package/src/client/feedback.mjs +11 -6
- package/src/client/notice.mjs +47 -0
- package/src/client/rpc.mjs +6 -2
- package/src/client/settings.html +3 -3
- package/src/client/tutorial-adapter.mjs +18 -12
- package/src/client/tutorial.mjs +15 -1
- package/src/host/assets.mjs +4 -0
- package/src/host/endpoint-discovery.mjs +185 -0
- package/src/host/feedback-files.mjs +5 -5
- package/src/host/feedback-store.mjs +3 -3
- package/src/host/notices.mjs +1 -1
- package/src/host/plugin.mjs +43 -16
- package/src/host/proxy.mjs +54 -17
- package/src/host/service-defaults.mjs +12 -4
- package/src/host/service-info.mjs +2 -1
- package/src/host/session-metadata.mjs +17 -0
- package/src/host/settings.mjs +19 -7
- package/src/host/storage-paths.mjs +28 -0
- package/src/host/trace.mjs +2 -2
- package/src/shared/connection-guidance.mjs +9 -0
- package/src/shared/state.mjs +5 -1
package/src/client/settings.html
CHANGED
|
@@ -366,7 +366,7 @@
|
|
|
366
366
|
}
|
|
367
367
|
$('openTutorial').onclick = async () => {
|
|
368
368
|
try {
|
|
369
|
-
const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.1.
|
|
369
|
+
const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.1.4');
|
|
370
370
|
requestTutorial(localStorage);
|
|
371
371
|
$('tutorialStatus').textContent = '请回到 DSH 页面继续教学。';
|
|
372
372
|
} catch { $('tutorialStatus').textContent = '暂时无法打开教学,请允许浏览器存储后重试。'; }
|
|
@@ -375,11 +375,11 @@
|
|
|
375
375
|
setInterval(() => { loadDuetConfig().catch(() => { $('duetConnection').textContent = '语音连接信息不可用'; }); }, 2000);
|
|
376
376
|
void loadNotices();
|
|
377
377
|
setInterval(loadNotices, 60000);
|
|
378
|
-
import('/duet/assets/client/shortcuts.mjs?v=0.1.
|
|
378
|
+
import('/duet/assets/client/shortcuts.mjs?v=0.1.4').then(({mountShortcutSettings}) => {
|
|
379
379
|
const dispose = mountShortcutSettings({speaker:$('speakerShortcut'),mic:$('micShortcut'),clearSpeaker:$('clearSpeakerShortcut'),clearMic:$('clearMicShortcut'),status:$('shortcutStatus')});
|
|
380
380
|
window.addEventListener('pagehide', e => {if(!e.persisted)dispose()}, {once:true});
|
|
381
381
|
}).catch(() => { $('shortcutStatus').textContent = '暂时无法加载快捷键设置,请刷新重试。'; });
|
|
382
|
-
import('/duet/assets/client/microphone.mjs?v=0.1.
|
|
382
|
+
import('/duet/assets/client/microphone.mjs?v=0.1.4').then(({mountMicrophoneSettings}) => {
|
|
383
383
|
const dispose = mountMicrophoneSettings({select:$('microphoneDevice'),refresh:$('refreshMicrophones'),status:$('microphoneStatus')});
|
|
384
384
|
window.addEventListener('pagehide', dispose, {once:true});
|
|
385
385
|
}).catch(() => { $('microphoneStatus').textContent = '暂时无法加载麦克风设置,请刷新重试。'; });
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/** DSH browser services plus existing voice connection; never opens a microphone. */
|
|
2
|
-
import { PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.
|
|
3
|
-
import { focusedSession } from './composer.mjs?v=0.1.
|
|
4
|
-
import { requireWorkspace } from './workspaces.mjs?v=0.1.
|
|
5
|
-
|
|
2
|
+
import { PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.4'
|
|
3
|
+
import { focusedSession } from './composer.mjs?v=0.1.4'
|
|
4
|
+
import { requireWorkspace, workspaceIssue } from './workspaces.mjs?v=0.1.4'
|
|
5
|
+
import { startComposerBridge } from './composer-bridge.mjs?v=0.1.4'
|
|
6
|
+
export function tutorialAdapter(ctx, state, audio, pollReady, startBridge = startComposerBridge) {
|
|
6
7
|
let narration
|
|
7
8
|
const completed = new Map()
|
|
8
9
|
const check = signal => signal.throwIfAborted()
|
|
@@ -17,10 +18,10 @@ export function tutorialAdapter(ctx, state, audio, pollReady) {
|
|
|
17
18
|
while(Date.now()<deadline){check(signal);if(await fn())return;await wait(150,signal)}
|
|
18
19
|
throw Error('等待超时,教学已停止;不会自动重新发送')
|
|
19
20
|
}
|
|
20
|
-
const api = async (path, signal, method='GET', body) => {
|
|
21
|
+
const api = async (path, signal, method='GET', body, owner) => {
|
|
21
22
|
check(signal)
|
|
22
23
|
const r=await fetch('/duplex-control/api/'+path,{method,signal,cache:'no-store',credentials:'same-origin',
|
|
23
|
-
headers:{'Content-Type':'application/json'},...(body?{body:JSON.stringify(body)}:{})})
|
|
24
|
+
headers:{'Content-Type':'application/json', 'X-Duet-Browser-Client': owner || 'tutorial-local'},...(body?{body:JSON.stringify(body)}:{})})
|
|
24
25
|
const d=await r.json();check(signal)
|
|
25
26
|
if(!r.ok)throw Error(d.detail||d.error_code||'DSH 请求失败')
|
|
26
27
|
return d
|
|
@@ -38,6 +39,7 @@ export function tutorialAdapter(ctx, state, audio, pollReady) {
|
|
|
38
39
|
return s
|
|
39
40
|
}
|
|
40
41
|
return {
|
|
42
|
+
workspaceIssue:()=>workspaceIssue(ctx),
|
|
41
43
|
mode:()=>state.mode,current,
|
|
42
44
|
observe(event){if(event.type==='external_message.done'){completed.set(event.message_id,event.status);if(completed.size>128)completed.delete(completed.keys().next().value)}},
|
|
43
45
|
unlock:()=>audio.prepare(),
|
|
@@ -56,12 +58,16 @@ export function tutorialAdapter(ctx, state, audio, pollReady) {
|
|
|
56
58
|
async write(id,text,expected,signal){check(signal);safeSnapshot(id,expected);input(id).setDraft(text)},
|
|
57
59
|
async submit(id,expected,signal){
|
|
58
60
|
safeSnapshot(id,expected)
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
61
|
+
const owner = crypto.randomUUID()
|
|
62
|
+
const stop = startBridge(ctx, owner)
|
|
63
|
+
try {
|
|
64
|
+
const {composer}=await api(`sessions/${encodeURIComponent(id)}/composer?require_focus=true`,signal,'GET',undefined,owner)
|
|
65
|
+
safeSnapshot(id,expected)
|
|
66
|
+
if(composer.text!==expected)throw Error('教学草稿不一致,未发送')
|
|
67
|
+
const {job}=await api(`sessions/${encodeURIComponent(id)}/composer/submit`,signal,'POST',{
|
|
68
|
+
expected_revision:composer.revision,expected_hash:composer.hash,
|
|
69
|
+
},owner);return job
|
|
70
|
+
} finally { stop() }
|
|
65
71
|
},
|
|
66
72
|
async enableBroadcast(signal){
|
|
67
73
|
await pollReady(signal);check(signal)
|
package/src/client/tutorial.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Opt-in walkthrough. All writes are limited to sessions created by this run. */
|
|
2
|
-
import {consumeTutorialRequest} from './tutorial-request.mjs?v=0.1.
|
|
2
|
+
import {consumeTutorialRequest} from './tutorial-request.mjs?v=0.1.4'
|
|
3
3
|
export const TUTORIAL_KEY = 'dsh-duplex-tutorial-v1'
|
|
4
4
|
export const QUESTION = '什么是语音交互?请用一句话简单解释,不使用工具。'
|
|
5
5
|
export const INPUT = '用一句话介绍语音助手。'
|
|
@@ -177,8 +177,19 @@ export function mountTutorial({ controls, adapter }) {
|
|
|
177
177
|
const owner=run
|
|
178
178
|
await owner?.stop();if(run!==owner)return
|
|
179
179
|
active=false;lockRelease?.();lockRelease=null
|
|
180
|
+
if (showWorkspaceIssue(error.message)) return
|
|
180
181
|
show('教学已暂停', `${error.message}\n不会继续发送或修改。已经提交的任务仍会保留。`, [['重新开始',welcome]])
|
|
181
182
|
}
|
|
183
|
+
const showWorkspaceIssue = issue => {
|
|
184
|
+
const messages = {
|
|
185
|
+
workspace_required: ['请先创建 workspace', '请先在 DSH 中创建一个 workspace,再回来开始教学。'],
|
|
186
|
+
workspace_loading: ['正在加载 workspace', '请稍等片刻,再试一次。'],
|
|
187
|
+
workspace_unavailable: ['暂时无法读取 workspace', '请检查 DSH 的 workspace 是否正常加载,再试一次。'],
|
|
188
|
+
}
|
|
189
|
+
if (!messages[issue]) return false
|
|
190
|
+
show(...messages[issue], [['重新检查', welcome]])
|
|
191
|
+
return true
|
|
192
|
+
}
|
|
182
193
|
const act = async (title,text,fn,next,selector,pause=0) => {
|
|
183
194
|
if(run?.busy)return
|
|
184
195
|
const owner=run
|
|
@@ -216,6 +227,7 @@ export function mountTutorial({ controls, adapter }) {
|
|
|
216
227
|
if(active)return
|
|
217
228
|
if(!consent?.sound||!consent?.chat){welcome();return}
|
|
218
229
|
closed=false
|
|
230
|
+
if(showWorkspaceIssue(adapter.workspaceIssue?.()))return
|
|
219
231
|
if(adapter.mode()!=='off'){show('先结束当前语音','请先关闭语音模式,再开始教学。',[['重新检查',welcome]]);return}
|
|
220
232
|
if(!navigator.locks){show('当前浏览器暂不支持教学','请使用新版 Chrome 或 Edge 打开 DSH。');return}
|
|
221
233
|
try {
|
|
@@ -233,11 +245,13 @@ export function mountTutorial({ controls, adapter }) {
|
|
|
233
245
|
}
|
|
234
246
|
const welcome = () => {
|
|
235
247
|
closed=false
|
|
248
|
+
if(showWorkspaceIssue(adapter.workspaceIssue?.()))return
|
|
236
249
|
const view=show('来试试用声音操作吧','我会带您体验播报模式和交互模式。\n开始前,请完成以下准备:')
|
|
237
250
|
if(!view)return
|
|
238
251
|
const check=text=>{const label=element('label'),input=element('input',null,label);input.type='checkbox';element('span',text,label);view.panel.insertBefore(label,view.footer);return input}
|
|
239
252
|
const sound=check('声音已打开'),chat=check('同意本教程通过dsh发送消息(会产生模型用量)')
|
|
240
253
|
const b=button(view.footer,'开始教学',()=>{
|
|
254
|
+
if(showWorkspaceIssue(adapter.workspaceIssue?.()))return
|
|
241
255
|
b.disabled=true
|
|
242
256
|
const consent={sound:sound.checked,chat:chat.checked}
|
|
243
257
|
// User gesture unlocks audio before either mode is demonstrated.
|
package/src/host/assets.mjs
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
/** Explicit public asset inventory. Host code and configuration are never served. */
|
|
2
2
|
const modules = {
|
|
3
3
|
state: 'shared/state', catalog: 'shared/catalog',
|
|
4
|
+
connection_guidance: 'shared/connection-guidance',
|
|
4
5
|
audio: 'client/audio', microphone: 'client/microphone', shortcuts: 'client/shortcuts',
|
|
5
6
|
browser: 'client/browser', rpc: 'client/rpc', composer: 'client/composer',
|
|
7
|
+
composer_bridge: 'client/composer-bridge',
|
|
6
8
|
interactions: 'client/interactions', tutorial: 'client/tutorial',
|
|
7
9
|
tutorial_adapter: 'client/tutorial-adapter', tutorial_request: 'client/tutorial-request',
|
|
8
10
|
feedback: 'client/feedback', consent: 'client/consent',
|
|
9
11
|
connection_hint: 'client/connection-hint',
|
|
12
|
+
controls_layout: 'client/controls-layout',
|
|
13
|
+
notice: 'client/notice',
|
|
10
14
|
workspaces: 'client/workspaces',
|
|
11
15
|
}
|
|
12
16
|
const aliases = {
|
|
@@ -0,0 +1,185 @@
|
|
|
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
|
+
url.protocol=url.protocol==='wss:'?'https:':'http:'
|
|
15
|
+
url.pathname=url.pathname.replace(/\/ws\/?$/,'').replace(/\/$/,'')+path
|
|
16
|
+
url.search=''
|
|
17
|
+
return url.toString()
|
|
18
|
+
}
|
|
19
|
+
export const DISCOVERY_INTERVAL_MS=24*60*60*1000
|
|
20
|
+
function recommendationURL(value) {
|
|
21
|
+
if(typeof value!=='string'||!value||value.length>2048) throw Error('invalid_recommended_endpoint')
|
|
22
|
+
const url=new URL(value.includes('://')?value:'ws://'+value)
|
|
23
|
+
if(url.protocol==='http:')url.protocol='ws:'
|
|
24
|
+
if(url.protocol==='https:')url.protocol='wss:'
|
|
25
|
+
const host=url.hostname.replace(/^\[|\]$/g,'')
|
|
26
|
+
if(!['ws:','wss:'].includes(url.protocol)||url.username||url.password||url.hash
|
|
27
|
+
||!['','/','/ws'].includes(url.pathname)||!['','80','443'].includes(url.port)
|
|
28
|
+
||[...url.searchParams].some(([k,v])=>k!=='protocol'||v!=='realtime_v2')
|
|
29
|
+
||(!isIP(host)&&(!host.includes('.')||/\.(local|localhost|internal|test|invalid)\.?$/i.test(host)))) throw Error('invalid_recommended_endpoint')
|
|
30
|
+
url.pathname='/ws';url.search='?protocol=realtime_v2'
|
|
31
|
+
return url
|
|
32
|
+
}
|
|
33
|
+
function pinnedCandidate(url, addresses) {
|
|
34
|
+
const host=url.hostname.replace(/^\[|\]$/g,'')
|
|
35
|
+
if(!Array.isArray(addresses)||!addresses.length||addresses.length>32
|
|
36
|
+
||addresses.some(row=>![4,6].includes(row.family)||isIP(row.address)!==row.family
|
|
37
|
+
||(isIP(host)&&host!==row.address))) throw Error('invalid_endpoint_address')
|
|
38
|
+
// Freeze DNS for the WS connection, not just for validation.
|
|
39
|
+
const pinnedLookup=(_host, options, callback)=>{
|
|
40
|
+
if(typeof options==='function'){callback=options;options={}}
|
|
41
|
+
if(options?.all)callback(null,addresses)
|
|
42
|
+
else callback(null,addresses[0].address,addresses[0].family)
|
|
43
|
+
}
|
|
44
|
+
return {url:url.toString(),addresses,lookup:pinnedLookup}
|
|
45
|
+
}
|
|
46
|
+
export async function recommendedEndpoint(value, resolve=lookup) {
|
|
47
|
+
const url=recommendationURL(value),host=url.hostname.replace(/^\[|\]$/g,'')
|
|
48
|
+
const addresses=isIP(host)?[{address:host,family:isIP(host)}]:await resolve(host,{all:true})
|
|
49
|
+
return pinnedCandidate(url,addresses)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export class EndpointDiscovery {
|
|
53
|
+
constructor(getConfig,{fetchImpl=fetch,resolve=lookup,now=Date.now,changed=()=>{},
|
|
54
|
+
cachePath=defaultStateFile('endpoint-discovery.json')}={}) {
|
|
55
|
+
this.getConfig=getConfig;this.fetchImpl=(...args)=>fetchImpl(...args);this.resolve=resolve;this.now=now;this.changed=changed
|
|
56
|
+
this.cache={candidate:null,reason:'discovery_unavailable',hint:connectionGuidance(null)};this.lastAttemptAt=null;this.cachePath=cachePath
|
|
57
|
+
this.inflight=null;this.selected=new Map();this.active=null;this.failedUntil=0
|
|
58
|
+
try {
|
|
59
|
+
if(cachePath&&statSync(cachePath).size<=8192){
|
|
60
|
+
const data=JSON.parse(readFileSync(cachePath,'utf8'))
|
|
61
|
+
if(data.schema_version!==1||data.bootstrap_endpoint!==DEFAULT_DUET_URL
|
|
62
|
+
||!Number.isFinite(data.last_attempt_at)||data.last_attempt_at<0)throw Error('invalid_cache')
|
|
63
|
+
const candidate=data.candidate?pinnedCandidate(recommendationURL(data.candidate.url),data.candidate.addresses):null
|
|
64
|
+
this.cache={candidate,reason:candidate?'recommended':'no_recommendation',hint:normalizeGuidance(data.connection_hint)}
|
|
65
|
+
this.lastAttemptAt=data.last_attempt_at
|
|
66
|
+
}
|
|
67
|
+
}catch{ /* A missing/corrupt cache must not prevent startup. */ }
|
|
68
|
+
}
|
|
69
|
+
invalidate(){this.selected.clear();this.active=null;this.failedUntil=0}
|
|
70
|
+
async persist(){
|
|
71
|
+
if(!this.cachePath)return
|
|
72
|
+
const temp=`${this.cachePath}.${randomUUID()}.tmp`
|
|
73
|
+
const candidate=this.cache.candidate
|
|
74
|
+
const data={schema_version:1,bootstrap_endpoint:DEFAULT_DUET_URL,last_attempt_at:this.lastAttemptAt,
|
|
75
|
+
candidate:candidate?{url:candidate.url,addresses:candidate.addresses}:null,connection_hint:this.cache.hint}
|
|
76
|
+
try {
|
|
77
|
+
await mkdir(dirname(this.cachePath),{recursive:true,mode:0o700})
|
|
78
|
+
await writeFile(temp,JSON.stringify(data)+'\n',{mode:0o600,flag:'wx'})
|
|
79
|
+
await rename(temp,this.cachePath)
|
|
80
|
+
}catch{ /* Read-only/full disks must not block connecting. */ }
|
|
81
|
+
finally{await unlink(temp).catch(()=>{})}
|
|
82
|
+
}
|
|
83
|
+
refreshIfDue(){
|
|
84
|
+
if(!Object.values(this.getConfig().endpoints).some(isPublicTrialEndpoint))return null
|
|
85
|
+
if(this.inflight)return this.inflight
|
|
86
|
+
const now=this.now()
|
|
87
|
+
if(this.lastAttemptAt!==null&&now>=this.lastAttemptAt&&now-this.lastAttemptAt<DISCOVERY_INTERVAL_MS)return null
|
|
88
|
+
this.lastAttemptAt=now
|
|
89
|
+
const work=(async()=>{
|
|
90
|
+
// Persist attempts as well as successes: an outage must not cause a request on every restart.
|
|
91
|
+
await this.persist()
|
|
92
|
+
try {
|
|
93
|
+
const response=await this.fetchImpl(endpointHTTP(DEFAULT_DUET_URL,'/api/connection-info'),{
|
|
94
|
+
headers:{Authorization:PUBLIC_TRIAL_AUTHORIZATION},redirect:'error',signal:AbortSignal.timeout(2500)})
|
|
95
|
+
if(!response.ok)throw Error('discovery_unavailable')
|
|
96
|
+
const reader=response.body.getReader();let bytes=0,body='';const decoder=new TextDecoder()
|
|
97
|
+
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()}
|
|
98
|
+
finally{await reader.cancel().catch(()=>{})}
|
|
99
|
+
const data=JSON.parse(body)
|
|
100
|
+
if(data.schema_version!==1||typeof data.recommended_endpoint!=='string')throw Error('invalid_discovery')
|
|
101
|
+
let timer,candidate
|
|
102
|
+
try {
|
|
103
|
+
candidate=data.recommended_endpoint?await Promise.race([
|
|
104
|
+
recommendedEndpoint(data.recommended_endpoint,this.resolve),
|
|
105
|
+
new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('dns_timeout')),1500);timer.unref?.()}),
|
|
106
|
+
]):null
|
|
107
|
+
}finally{clearTimeout(timer)}
|
|
108
|
+
this.cache={candidate,reason:candidate?'recommended':'no_recommendation',hint:connectionGuidance(data.connection_hint,data.revision)}
|
|
109
|
+
await this.persist()
|
|
110
|
+
}catch{ /* Keep the last known recommendation, even when it is older than a day. */ }
|
|
111
|
+
return this.cache
|
|
112
|
+
})()
|
|
113
|
+
this.inflight=work
|
|
114
|
+
void work.finally(()=>{if(this.inflight===work)this.inflight=null})
|
|
115
|
+
return work
|
|
116
|
+
}
|
|
117
|
+
async plan(mode){
|
|
118
|
+
const config=this.getConfig(), target=config.endpoints[mode]
|
|
119
|
+
if(!isPublicTrialEndpoint(target))return [{url:target,config,selection:'custom',reason:''}]
|
|
120
|
+
this.refreshIfDue()
|
|
121
|
+
const fallback={url:DEFAULT_DUET_URL,config:{...config,authorization:PUBLIC_TRIAL_AUTHORIZATION},selection:'default',reason:''}
|
|
122
|
+
if(this.failedUntil>this.now())return [{...fallback,selection:'fallback',reason:'recommended_cooldown'}]
|
|
123
|
+
const recommendation=this.cache
|
|
124
|
+
if(!recommendation.candidate||recommendation.candidate.url===DEFAULT_DUET_URL)return [{...fallback,reason:recommendation.reason}]
|
|
125
|
+
return [{...recommendation.candidate,config:fallback.config,selection:'recommended',reason:''},fallback]
|
|
126
|
+
}
|
|
127
|
+
used(mode,route,notify=true){this.selected.set(mode,route);this.active=route;if(notify)this.changed()}
|
|
128
|
+
failed(){this.failedUntil=this.now()+60000}
|
|
129
|
+
metadata(route,reason=''){
|
|
130
|
+
return {bootstrap_endpoint:route.selection==='custom'?'':DEFAULT_DUET_URL,
|
|
131
|
+
selected_endpoint:route.url,selection:reason?'fallback':route.selection,fallback_reason:reason||route.reason||'',
|
|
132
|
+
connection_hint:route.selection==='custom'?connectionGuidance(null):normalizeGuidance(this.cache.hint)}
|
|
133
|
+
}
|
|
134
|
+
async effective(mode=null){
|
|
135
|
+
const route=(mode?this.selected.get(mode):this.active)||(await this.plan(mode||'online'))[0]
|
|
136
|
+
return {...route.config,endpoints:{online:route.url,tts_only:route.url}}
|
|
137
|
+
}
|
|
138
|
+
async fetch(url,options={}){
|
|
139
|
+
// These callers are read-only metadata endpoints. Never replay a feedback POST.
|
|
140
|
+
try {
|
|
141
|
+
const response=await this.fetchImpl(url,options)
|
|
142
|
+
if(response.status<500||options.method&&options.method!=='GET')return response
|
|
143
|
+
throw Error('endpoint_http_unavailable')
|
|
144
|
+
}catch(error){
|
|
145
|
+
if(options.method&&options.method!=='GET')throw error
|
|
146
|
+
const configured=this.getConfig()
|
|
147
|
+
if(!isPublicTrialEndpoint(configured.endpoints.online)||new URL(url).origin===new URL(endpointHTTP(DEFAULT_DUET_URL,'/')).origin)throw error
|
|
148
|
+
this.failed()
|
|
149
|
+
const target=new URL(url),fallback=new URL(endpointHTTP(DEFAULT_DUET_URL,'/'))
|
|
150
|
+
target.protocol=fallback.protocol;target.host=fallback.host
|
|
151
|
+
const route={url:DEFAULT_DUET_URL,config:{...configured,authorization:PUBLIC_TRIAL_AUTHORIZATION},selection:'fallback',reason:'metadata_network_failed'}
|
|
152
|
+
this.used('online',route,false)
|
|
153
|
+
return this.fetchImpl(target,options)
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Retry only transport/handshake failures, before any session/audio/task is sent. */
|
|
159
|
+
export async function connectEndpoint(WebSocket, routes, {signal, trace, timeout=6000}={}) {
|
|
160
|
+
let fallbackReason=''
|
|
161
|
+
for(let i=0;i<routes.length;i++){
|
|
162
|
+
signal?.throwIfAborted()
|
|
163
|
+
const route=routes[i]
|
|
164
|
+
try {
|
|
165
|
+
const socket=await new Promise((resolve,reject)=>{
|
|
166
|
+
const socket=new WebSocket(route.url,{handshakeTimeout:timeout,maxPayload:16000000,
|
|
167
|
+
...(route.lookup?{lookup:route.lookup}:{}),...(route.config.authorization?{headers:{Authorization:route.config.authorization}}:{})})
|
|
168
|
+
const abort=()=>{socket.terminate();reject(Error('connection_cancelled'))}
|
|
169
|
+
signal?.addEventListener('abort',abort,{once:true})
|
|
170
|
+
let settled=false
|
|
171
|
+
const finish=(error)=>{if(settled)return;settled=true;signal?.removeEventListener('abort',abort);if(error){socket.terminate();reject(error)}else resolve(socket)}
|
|
172
|
+
socket.once('open',()=>finish())
|
|
173
|
+
socket.on('error',()=>finish(Error('network_error')))
|
|
174
|
+
socket.once('close',()=>finish(Error('handshake_closed')))
|
|
175
|
+
socket.once('unexpected-response',(_request,response)=>{response.resume();finish(Object.assign(Error('http_'+response.statusCode),{status:response.statusCode}))})
|
|
176
|
+
})
|
|
177
|
+
return {socket,route,fallbackReason}
|
|
178
|
+
}catch(error){
|
|
179
|
+
trace?.event('endpoint.attempt_failed',{endpoint:route.url,reason:error.message})
|
|
180
|
+
if(signal?.aborted||[401,403,426,429,503].includes(error.status)||i===routes.length-1)throw error
|
|
181
|
+
fallbackReason=error.message
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
throw Error('no_endpoint_available')
|
|
185
|
+
}
|
|
@@ -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
|
|
5
|
-
import {
|
|
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||
|
|
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
|
}
|
package/src/host/notices.mjs
CHANGED
|
@@ -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'
|
package/src/host/plugin.mjs
CHANGED
|
@@ -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
|
|
172
|
-
const
|
|
173
|
-
const
|
|
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: {
|