dsh-duet 0.1.10 → 0.2.1
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 +19 -1
- package/assets/avatar/THREE-LICENSE.txt +21 -0
- package/assets/avatar/character.glb +0 -0
- package/assets/avatar/desktop/character.glb +0 -0
- package/assets/avatar/desktop/companion.mjs +18 -0
- package/assets/avatar/desktop/index.html +33 -0
- package/assets/avatar/desktop/manifest.json +10 -0
- package/assets/avatar/desktop/portrait.png +0 -0
- package/assets/avatar/desktop/renderer.mjs +4230 -0
- package/assets/avatar/portrait.png +0 -0
- package/assets/avatar/renderer.mjs +4230 -0
- package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/Info.plist +36 -0
- package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/MacOS/duet-avatar +0 -0
- package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/Resources/duet companion.icns +0 -0
- package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/_CodeSignature/CodeResources +128 -0
- package/desktop/bin/darwin-arm64/manifest.json +14 -0
- package/desktop/bin/win32-x64/duet-avatar.exe +0 -0
- package/desktop/bin/win32-x64/manifest.json +11 -0
- package/package.json +17 -5
- package/src/avatar/companion.html +33 -0
- package/src/avatar/companion.mjs +210 -0
- package/src/avatar/idle.mjs +9 -0
- package/src/avatar/lipsync.mjs +13 -0
- package/src/avatar/motion.mjs +93 -0
- package/src/avatar/renderer.mjs +90 -0
- package/src/avatar/surface.mjs +45 -0
- package/src/avatar/toolbar.mjs +49 -0
- package/src/client/audio.mjs +68 -3
- package/src/client/avatar-surfaces.mjs +83 -0
- package/src/client/avatar-tasks.mjs +68 -0
- package/src/client/avatar.mjs +218 -0
- package/src/client/browser.mjs +83 -35
- package/src/client/composer-bridge.mjs +5 -2
- package/src/client/connection-hint.mjs +2 -1
- package/src/client/consent.mjs +3 -1
- package/src/client/controls-layout.mjs +21 -9
- package/src/client/entry.js +26 -3
- package/src/client/feedback.mjs +19 -4
- package/src/client/identity.mjs +2 -2
- package/src/client/input-effect.mjs +51 -0
- package/src/client/notice.mjs +20 -4
- package/src/client/rpc.mjs +2 -1
- package/src/client/settings.html +124 -4
- package/src/client/transport.mjs +2 -2
- package/src/client/tutorial-adapter.mjs +4 -4
- package/src/client/tutorial.mjs +5 -3
- package/src/client/voices.mjs +137 -0
- package/src/host/assets.mjs +13 -0
- package/src/host/avatar-activity.mjs +24 -0
- package/src/host/avatar-assets.mjs +18 -0
- package/src/host/avatar.mjs +130 -0
- package/src/host/diagnostics.mjs +111 -7
- package/src/host/feedback-files.mjs +5 -1
- package/src/host/plugin.mjs +59 -4
- package/src/host/proxy.mjs +41 -6
- package/src/host/settings-migration.mjs +2 -1
- package/src/host/settings.mjs +19 -4
- package/src/host/voices.mjs +205 -0
- package/src/shared/avatar-activity.mjs +33 -0
- package/src/shared/avatar-menu-ui.mjs +85 -0
- package/src/shared/avatar-menu.mjs +83 -0
- package/src/shared/avatar-surface.mjs +24 -0
- package/src/shared/avatar-ui.mjs +91 -0
- package/src/shared/avatar.mjs +125 -0
- package/src/shared/nickname.mjs +13 -0
- package/src/shared/state.mjs +15 -4
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import {mkdir,readdir,readFile,writeFile,rename,unlink,lstat} from 'node:fs/promises'
|
|
2
|
+
import {join} from 'node:path'
|
|
3
|
+
import {createHash} from 'node:crypto'
|
|
4
|
+
import {defaultStateFile} from './storage-paths.mjs'
|
|
5
|
+
import {avatarActivity} from '../shared/avatar-activity.mjs'
|
|
6
|
+
import {PLUGIN_VERSION} from '../shared/state.mjs'
|
|
7
|
+
export class AvatarActivityOutbox {
|
|
8
|
+
constructor(getConfig,{root=defaultStateFile('avatar-activity'),fetcher=fetch,now=Date.now}={}){
|
|
9
|
+
Object.assign(this,{getConfig,root,fetcher,now});this.records=new Map();this.closed=false;this.chain=Promise.resolve();this.ready=this.load().catch(error=>{this.loadError=error});this.timer=setInterval(()=>void this.flush(),60000);this.timer.unref?.()
|
|
10
|
+
}
|
|
11
|
+
async load(){await mkdir(this.root,{recursive:true,mode:0o700});if((await lstat(this.root)).isSymbolicLink())throw Error('invalid_activity_store');for(const name of (await readdir(this.root)).filter(n=>/^[a-f0-9]{64}\.json$/.test(n)).slice(0,512)){try{const path=join(this.root,name),stat=await lstat(path);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>16384)continue;const item=JSON.parse(await readFile(path,'utf8'));avatarActivity(item.record);const url=new URL(item.url);if(!['http:','https:'].includes(url.protocol)||url.pathname!=='/avatar-events'||url.username||url.password||url.search||url.hash)continue;if(!Number.isFinite(item.expires)||item.expires>this.now()+86400000||item.expires<=this.now()){await unlink(path);continue}if(typeof item.authorization!=='string'||item.authorization.length>8192||!/^anon_[a-f0-9]{32}$/.test(item.record.user_id))continue;this.records.set(name,item)}catch{}}}
|
|
12
|
+
enqueue(value,user){const work=this.chain.then(async()=>{
|
|
13
|
+
await this.ready;if(this.loadError)throw this.loadError;const event=avatarActivity(value);if(!/^anon_[a-f0-9]{32}$/.test(user))throw Error('invalid_activity_user')
|
|
14
|
+
const name=createHash('sha256').update(user+':'+event.event_id).digest('hex')+'.json';if(this.records.has(name))return
|
|
15
|
+
if(this.records.size>=512)throw Error('activity_queue_full')
|
|
16
|
+
const config=await this.getConfig(),url=new URL(config.endpoints.online);url.protocol=url.protocol==='wss:'?'https:':'http:';url.pathname='/avatar-events';url.search='';url.hash=''
|
|
17
|
+
const item={url:url.href,authorization:config.authorization||'',expires:this.now()+86400000,record:{...event,user_id:user,plugin_version:PLUGIN_VERSION}}
|
|
18
|
+
const path=join(this.root,name),temp=path+'.tmp';await writeFile(temp,JSON.stringify(item),{mode:0o600});await rename(temp,path);this.records.set(name,item)
|
|
19
|
+
});this.chain=work.catch(()=>{});return work.then(()=>{void this.flush();return{accepted:true}})}
|
|
20
|
+
async flush(){await this.ready;if(this.loadError||this.closed||this.busy)return;this.busy=true;try{for(const [name,item]of this.records){if(this.closed)break;let done=item.expires<=this.now();if(!done){try{const response=await this.fetcher(item.url,{method:'POST',redirect:'error',signal:AbortSignal.timeout(5000),headers:{'Content-Type':'application/json',...(item.authorization?{Authorization:item.authorization}:{})},body:JSON.stringify(item.record)});if(response.ok){const result=await response.json();done=result.persisted===true&&result.event_id===item.record.event_id}else await response.body?.cancel()}catch{}}
|
|
21
|
+
if(done){await unlink(join(this.root,name)).catch(()=>{});this.records.delete(name)}else break
|
|
22
|
+
}}finally{this.busy=false}}
|
|
23
|
+
close(){this.closed=true;clearInterval(this.timer)}
|
|
24
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import {readFileSync,realpathSync,statSync} from 'node:fs'
|
|
2
|
+
import {join,dirname} from 'node:path'
|
|
3
|
+
import {fileURLToPath} from 'node:url'
|
|
4
|
+
import {createHash} from 'node:crypto'
|
|
5
|
+
import {AVATAR_UI_PROTOCOL} from '../shared/avatar-surface.mjs'
|
|
6
|
+
export const desktopAssetsPath=fileURLToPath(new URL('../../assets/avatar/desktop/',import.meta.url))
|
|
7
|
+
export const DESKTOP_ASSET_FILES=['index.html','companion.mjs','renderer.mjs','character.glb','portrait.png']
|
|
8
|
+
/** Verify the distributed local UI before starting a privileged native webview. */
|
|
9
|
+
export function verifyDesktopAssets(path=desktopAssetsPath) {
|
|
10
|
+
const root=realpathSync(path),manifest=JSON.parse(readFileSync(join(root,'manifest.json'),'utf8'))
|
|
11
|
+
if(manifest.protocol!==AVATAR_UI_PROTOCOL||JSON.stringify(Object.keys(manifest.files||{}).sort())!==JSON.stringify([...DESKTOP_ASSET_FILES].sort()))throw Error('desktop_assets_incompatible')
|
|
12
|
+
for(const file of DESKTOP_ASSET_FILES){
|
|
13
|
+
const resolved=realpathSync(join(root,file))
|
|
14
|
+
if(dirname(resolved)!==root||statSync(resolved).size>64*1024*1024)throw Error('desktop_assets_invalid')
|
|
15
|
+
if(createHash('sha256').update(readFileSync(resolved)).digest('hex')!==manifest.files[file])throw Error('desktop_assets_damaged')
|
|
16
|
+
}
|
|
17
|
+
return root
|
|
18
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { WebSocketServer } from 'ws'
|
|
2
|
+
import { spawn } from 'node:child_process'
|
|
3
|
+
import { accessSync, constants } from 'node:fs'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto'
|
|
6
|
+
import { AVATAR_SIZES, avatarSize, avatarFrame, avatarInputEffect, AvatarHeartbeat } from '../shared/avatar.mjs'
|
|
7
|
+
import { AVATAR_UI_PROTOCOL, avatarSurface, avatarSurfaceAction } from '../shared/avatar-surface.mjs'
|
|
8
|
+
import {verifyDesktopAssets,desktopAssetsPath} from './avatar-assets.mjs'
|
|
9
|
+
import {avatarMenuAction,avatarLocalState,avatarMenuResult} from '../shared/avatar-menu.mjs'
|
|
10
|
+
import {avatarGeometry} from '../shared/avatar-activity.mjs'
|
|
11
|
+
|
|
12
|
+
export function avatarBinary(platform = process.platform, arch = process.arch) {
|
|
13
|
+
if (!['darwin-arm64','win32-x64'].includes(`${platform}-${arch}`)) return null
|
|
14
|
+
const file=platform==='darwin'?'duet-avatar.app/Contents/MacOS/duet-avatar':`duet-avatar${platform==='win32'?'.exe':''}`
|
|
15
|
+
return fileURLToPath(new URL(`../../desktop/bin/${platform}-${arch}/${file}`,import.meta.url))
|
|
16
|
+
}
|
|
17
|
+
export function sameSecret(a, b) {
|
|
18
|
+
const x=Buffer.from(String(a)),y=Buffer.from(String(b))
|
|
19
|
+
return x.length===y.length && timingSafeEqual(x,y)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Private, loopback-only IPC. The companion never receives DSH/server credentials. */
|
|
23
|
+
export async function launchAvatar({onCommand,onExit,signal,size,ownerKind='browser'}, {spawnImpl=spawn, binary=avatarBinary(), env=process.env, assets=desktopAssetsPath}={}) {
|
|
24
|
+
if(!binary)throw Error('desktop_platform_unsupported')
|
|
25
|
+
if(process.platform==='linux'&&!env.DISPLAY&&!env.WAYLAND_DISPLAY)throw Error('desktop_display_unavailable')
|
|
26
|
+
try{accessSync(binary,constants.X_OK)}catch{throw Error('desktop_helper_missing')}
|
|
27
|
+
const assetsPath=verifyDesktopAssets(assets)
|
|
28
|
+
const token=randomBytes(32).toString('hex')
|
|
29
|
+
const ipc=new WebSocketServer({host:'127.0.0.1',port:0,maxPayload:2048,
|
|
30
|
+
verifyClient:({req})=>sameSecret(req.headers['sec-websocket-protocol'],`duet-avatar-${token}`)})
|
|
31
|
+
await new Promise((resolve,reject)=>{ipc.once('listening',resolve);ipc.once('error',reject)})
|
|
32
|
+
let child,peer,closed=false,ready=false,timeout,killTimer,abort
|
|
33
|
+
const stop=()=>{
|
|
34
|
+
if(closed)return
|
|
35
|
+
closed=true;clearTimeout(timeout)
|
|
36
|
+
signal?.removeEventListener('abort',abort)
|
|
37
|
+
for(const ws of ipc.clients)ws.terminate()
|
|
38
|
+
ipc.close()
|
|
39
|
+
if(child&&child.exitCode===null){child.kill();killTimer=setTimeout(()=>{if(child.exitCode===null)child.kill('SIGKILL')},2000);killTimer.unref()}
|
|
40
|
+
}
|
|
41
|
+
const initialized=new Promise((resolve,reject)=>{
|
|
42
|
+
const fail=code=>{if(closed)return;stop();if(!ready)reject(Error(code));else onExit(code)}
|
|
43
|
+
abort=()=>fail('desktop_cancelled')
|
|
44
|
+
signal?.addEventListener('abort',abort,{once:true})
|
|
45
|
+
if(signal?.aborted){abort();return}
|
|
46
|
+
ipc.on('connection',ws=>{
|
|
47
|
+
if(peer){ws.close(1008);return}peer=ws
|
|
48
|
+
ws.on('error',()=>{})
|
|
49
|
+
ws.on('message',raw=>{
|
|
50
|
+
try{
|
|
51
|
+
const msg=JSON.parse(raw)
|
|
52
|
+
if(msg.type==='ready'&&!ready){if(msg.protocol!==AVATAR_UI_PROTOCOL){fail('desktop_helper_upgrade_required');return}ready=true;clearTimeout(timeout);resolve()}
|
|
53
|
+
else if(ready&&msg.type==='surface_action')onCommand(avatarSurfaceAction(msg))
|
|
54
|
+
else if(ready&&msg.type==='menu_action')onCommand(avatarMenuAction(msg))
|
|
55
|
+
else if(ready&&msg.type==='avatar_geometry')onCommand({type:'avatar_geometry',position:avatarGeometry(msg.position)})
|
|
56
|
+
else if(ready&&msg.type==='mode'&&['online','tts_only'].includes(msg.mode))onCommand(msg)
|
|
57
|
+
else if(ready&&msg.type==='size'&&Object.hasOwn(AVATAR_SIZES,msg.size))onCommand({type:'size',size:msg.size})
|
|
58
|
+
else if(msg.type==='hide')onCommand({type:'hide'})
|
|
59
|
+
else if(msg.type==='failed')fail('desktop_renderer_failed')
|
|
60
|
+
else if(msg.type!=='alive')ws.close(1008)
|
|
61
|
+
}catch{ws.close(1008)}
|
|
62
|
+
})
|
|
63
|
+
ws.on('close',()=>fail('desktop_closed'))
|
|
64
|
+
})
|
|
65
|
+
ipc.on('error',()=>fail('desktop_ipc_failed'))
|
|
66
|
+
try{
|
|
67
|
+
// No shell, user-supplied executable, detached daemon, inherited credentials, or CLI token.
|
|
68
|
+
const safeEnv=Object.fromEntries(['PATH','HOME','USERPROFILE','LOCALAPPDATA','APPDATA','SYSTEMROOT','WINDIR','TEMP','TMP','TMPDIR','DISPLAY','WAYLAND_DISPLAY','XDG_RUNTIME_DIR','DBUS_SESSION_BUS_ADDRESS','LANG','LC_ALL'].filter(k=>env[k]).map(k=>[k,env[k]]))
|
|
69
|
+
child=spawnImpl(binary,[],{stdio:'ignore',windowsHide:true,env:{...safeEnv,
|
|
70
|
+
DUET_AVATAR_ASSETS:assetsPath,DUET_AVATAR_IPC:`ws://127.0.0.1:${ipc.address().port}`,DUET_AVATAR_TOKEN:token,DUET_AVATAR_SIZE:avatarSize(size),
|
|
71
|
+
DUET_AVATAR_OWNER_KIND:['desktop','chrome','edge','firefox','safari','browser'].includes(ownerKind)?ownerKind:'browser'}})
|
|
72
|
+
child.once('error',()=>fail('desktop_launch_failed'))
|
|
73
|
+
child.once('exit',code=>{clearTimeout(killTimer);fail(code===78?'desktop_webview2_missing':'desktop_closed')})
|
|
74
|
+
timeout=setTimeout(()=>fail('desktop_start_timeout'),20000);timeout.unref()
|
|
75
|
+
}catch{fail('desktop_launch_failed')}
|
|
76
|
+
})
|
|
77
|
+
await initialized
|
|
78
|
+
return {close:stop,send(frame){if(peer?.readyState===1&&peer.bufferedAmount<16000)peer.send(JSON.stringify(frame))}}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Exactly one owning DSH page per Host; other pages cannot drive its companion. */
|
|
82
|
+
export function registerAvatarHost(ctx, {launch=launchAvatar}={}) {
|
|
83
|
+
const server=new WebSocketServer({noServer:true,maxPayload:65536}),clients=new Set()
|
|
84
|
+
let owner=null,closed=false
|
|
85
|
+
const unregister=ctx.webServer.registerUpgrade({path:'/duet/avatar/ws',handler(req,socket,head){
|
|
86
|
+
let allowed=!req.headers.origin
|
|
87
|
+
try{if(req.headers.origin)allowed=new URL(req.headers.origin).host===req.headers.host}catch{}
|
|
88
|
+
if(closed||!allowed||ctx.connection.requestRejection(req)||clients.size>=8){socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n');return}
|
|
89
|
+
server.handleUpgrade(req,socket,head,ws=>{
|
|
90
|
+
clients.add(ws);let helper,starting=false,ended=false,frames=0,second=Date.now(),alive=Date.now()
|
|
91
|
+
const lifetime=new AbortController()
|
|
92
|
+
const send=value=>{if(ws.readyState===1&&ws.bufferedAmount<16000)ws.send(JSON.stringify(value))}
|
|
93
|
+
const cleanup=()=>{ended=true;lifetime.abort();helper?.close();helper=null;if(owner===ws)owner=null}
|
|
94
|
+
// Background pages may be scheduled only once a minute. The Host keeps
|
|
95
|
+
// its native child alive independently while the owning page is present.
|
|
96
|
+
const liveness=new AvatarHeartbeat(15000,Date.now(),120000)
|
|
97
|
+
const heartbeat=setInterval(()=>{
|
|
98
|
+
if(liveness.expired())ws.terminate()
|
|
99
|
+
else helper?.send({type:'alive'})
|
|
100
|
+
},15000);heartbeat.unref()
|
|
101
|
+
ws.on('error',()=>{})
|
|
102
|
+
ws.on('message',async raw=>{
|
|
103
|
+
try{
|
|
104
|
+
alive=Date.now();liveness.touch(alive);if(alive-second>1000){second=alive;frames=0}if(++frames>40)throw Error('rate')
|
|
105
|
+
const msg=JSON.parse(raw)
|
|
106
|
+
if(msg.type==='start'&&!starting&&!helper){
|
|
107
|
+
if(owner&&owner!==ws){send({type:'fallback',reason:'desktop_in_use'});return}
|
|
108
|
+
owner=ws;starting=true
|
|
109
|
+
try{
|
|
110
|
+
const created=await launch({signal:lifetime.signal,size:avatarSize(msg.size),ownerKind:msg.owner_kind,onCommand:send,onExit:reason=>{helper=null;if(owner===ws)owner=null;send({type:'fallback',reason})}})
|
|
111
|
+
if(ended||closed||owner!==ws){created.close();return}
|
|
112
|
+
helper=created;send({type:'desktop_ready'})
|
|
113
|
+
}catch(error){if(owner===ws)owner=null;send({type:'fallback',reason:error.message})}
|
|
114
|
+
finally{starting=false}
|
|
115
|
+
}else if(msg.type==='frame'&&owner===ws){helper?.send(avatarFrame(msg))}
|
|
116
|
+
else if(msg.type==='surface'&&owner===ws){helper?.send(avatarSurface(msg))}
|
|
117
|
+
else if(msg.type==='owner_focus'&&owner===ws){helper?.send({type:'owner_focus'})}
|
|
118
|
+
else if(msg.type==='local_state'&&owner===ws){helper?.send(avatarLocalState(msg))}
|
|
119
|
+
else if(msg.type==='menu_result'&&owner===ws){helper?.send(avatarMenuResult(msg))}
|
|
120
|
+
else if(msg.type==='input_effect'&&owner===ws){helper?.send(avatarInputEffect(msg))}
|
|
121
|
+
else if(msg.type==='clear_input_effect'&&owner===ws){helper?.send({type:'clear_input_effect'})}
|
|
122
|
+
else if(msg.type==='alive')send({type:'alive'})
|
|
123
|
+
else throw Error('message')
|
|
124
|
+
}catch{ws.close(1008,'invalid_avatar_message')}
|
|
125
|
+
})
|
|
126
|
+
ws.on('close',()=>{clearInterval(heartbeat);clients.delete(ws);cleanup()})
|
|
127
|
+
})
|
|
128
|
+
}})
|
|
129
|
+
return {close(){closed=true;unregister();for(const ws of clients)ws.terminate();server.close()}}
|
|
130
|
+
}
|
package/src/host/diagnostics.mjs
CHANGED
|
@@ -1,16 +1,102 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { mkdirSync, readdirSync, lstatSync, readFileSync, writeFileSync, renameSync, unlinkSync } from 'node:fs'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { duetHome } from './storage-paths.mjs'
|
|
2
5
|
import { diagnosticPayload, DIAGNOSTICS_PROTOCOL } from '../shared/diagnostics.mjs'
|
|
3
6
|
|
|
7
|
+
const TTL = 6 * 60 * 60 * 1000
|
|
8
|
+
const ownerAlive = pid => {
|
|
9
|
+
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
10
|
+
try { process.kill(pid, 0); return true } catch (error) { return error.code === 'EPERM' }
|
|
11
|
+
}
|
|
12
|
+
/** Private, bounded outbox. Tickets/authorization never enter trace or public assets. */
|
|
13
|
+
export class DiagnosticOutbox {
|
|
14
|
+
constructor({root = join(duetHome(), 'diagnostic-outbox'), fetcher = fetch, now = Date.now,
|
|
15
|
+
isOwnerAlive = ownerAlive} = {}) {
|
|
16
|
+
this.root = root; this.fetcher = fetcher; this.now = now; this.active = new Set(); this.inflight = 0
|
|
17
|
+
this.closed = false
|
|
18
|
+
try {
|
|
19
|
+
mkdirSync(root, {recursive:true, mode:0o700})
|
|
20
|
+
if (lstatSync(root).isSymbolicLink()) throw Error('unsafe_outbox')
|
|
21
|
+
let index = 0
|
|
22
|
+
for (const name of readdirSync(root).filter(n => /^[a-f0-9-]{36}\.json$/.test(n))) {
|
|
23
|
+
const path = join(root, name)
|
|
24
|
+
try {
|
|
25
|
+
const stat = lstatSync(path)
|
|
26
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 65536) continue
|
|
27
|
+
const value = JSON.parse(readFileSync(path, 'utf8'))
|
|
28
|
+
if (!(value.expires > now() && value.expires <= now() + TTL) || index >= 128) {
|
|
29
|
+
unlinkSync(path); continue
|
|
30
|
+
}
|
|
31
|
+
// Another DSH profile/process may still append to this connection.
|
|
32
|
+
if (isOwnerAlive(value.owner_pid)) continue
|
|
33
|
+
const url = new URL(value.target)
|
|
34
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password ||
|
|
35
|
+
url.pathname !== '/client-diagnostics' || url.search || url.hash ||
|
|
36
|
+
typeof value.ticket !== 'string' || value.ticket.length > 4096 ||
|
|
37
|
+
typeof value.authorization !== 'string' || value.authorization.length > 8192 ||
|
|
38
|
+
!Array.isArray(value.pending) || value.pending.length > 96) throw Error('invalid_outbox')
|
|
39
|
+
const d = new ConnectionDiagnostics({}, fetcher, this)
|
|
40
|
+
d.id = name.slice(0, -5); d.target = value.target; d.ticket = value.ticket
|
|
41
|
+
d.authorization = value.authorization; d.expires = value.expires
|
|
42
|
+
// Reapply the whitelist while retaining the original idempotency ID and sequence.
|
|
43
|
+
d.pending = value.pending.map(r => ({...diagnosticPayload(r), sequence:r.sequence}))
|
|
44
|
+
.filter(r => r.event && r.event_id && Number.isInteger(r.sequence) && r.sequence >= 0 && r.sequence < 96)
|
|
45
|
+
d.count = 96 // Recovered instances only replay; never manufacture new events.
|
|
46
|
+
this.save(d); d.schedule(index++ * 2000)
|
|
47
|
+
} catch { /* Corrupt evidence must not prevent plugin startup. */ }
|
|
48
|
+
}
|
|
49
|
+
} catch { this.unavailable = true }
|
|
50
|
+
}
|
|
51
|
+
save(d) {
|
|
52
|
+
// Socket close callbacks can arrive during plugin disposal: still persist them.
|
|
53
|
+
if (!d.target) return
|
|
54
|
+
const path = join(this.root, d.id + '.json')
|
|
55
|
+
if (!d.pending.length || d.expires <= this.now()) {
|
|
56
|
+
this.active.delete(d)
|
|
57
|
+
try { unlinkSync(path) } catch { /* already delivered or unavailable */ }
|
|
58
|
+
return
|
|
59
|
+
}
|
|
60
|
+
this.active.add(d)
|
|
61
|
+
if (this.unavailable) return
|
|
62
|
+
let temp
|
|
63
|
+
try {
|
|
64
|
+
if (readdirSync(this.root).filter(n => n.endsWith('.json')).length >= 128) {
|
|
65
|
+
try { lstatSync(path) } catch { return }
|
|
66
|
+
}
|
|
67
|
+
const body = JSON.stringify({target:d.target, ticket:d.ticket, authorization:d.authorization || '',
|
|
68
|
+
expires:d.expires, pending:d.pending, owner_pid:process.pid})
|
|
69
|
+
if (Buffer.byteLength(body) > 65536) return
|
|
70
|
+
temp = path + '.' + randomUUID() + '.tmp'
|
|
71
|
+
writeFileSync(temp, body, {mode:0o600, flag:'wx'}); renameSync(temp, path)
|
|
72
|
+
} catch {
|
|
73
|
+
if (!this.warned) { this.warned = true; console.warn('[duet] Diagnostic outbox unavailable; retrying in memory.') }
|
|
74
|
+
} finally { if (temp) try { unlinkSync(temp) } catch { /* renamed */ } }
|
|
75
|
+
}
|
|
76
|
+
dispose() {
|
|
77
|
+
this.closed = true
|
|
78
|
+
for (const d of this.active) { clearTimeout(d.timer); d.controller?.abort() }
|
|
79
|
+
this.active.clear()
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
4
83
|
/** Bounded, asynchronous batches. Telemetry failure never closes a voice socket. */
|
|
5
84
|
export class ConnectionDiagnostics {
|
|
6
|
-
constructor(metadata, fetcher = fetch) {
|
|
85
|
+
constructor(metadata, fetcher = fetch, outbox = null) {
|
|
7
86
|
this.metadata = metadata; this.fetcher = fetcher
|
|
8
87
|
this.pending = []; this.seen = new Set(); this.count = 0; this.attempts = 0
|
|
88
|
+
this.outbox = outbox; this.id = randomUUID(); this.expires = (outbox?.now() ?? Date.now()) + TTL
|
|
9
89
|
}
|
|
10
90
|
add(value) {
|
|
11
91
|
const row = diagnosticPayload({...value, ...this.metadata, event_id: value.event_id || randomUUID()})
|
|
12
92
|
if (!row || this.seen.has(row.event_id) || this.count >= 96) return
|
|
93
|
+
const terminal = /close|failed|error|pagehide/.test(row.event)
|
|
94
|
+
if (!terminal && this.count >= 80) return // Reserve room for the actual ending.
|
|
95
|
+
const now = this.outbox?.now() ?? Date.now()
|
|
96
|
+
if (this.expires <= now) this.pending = []
|
|
97
|
+
if (!this.pending.length) this.expires = now + TTL // Retain queued events, not session age.
|
|
13
98
|
this.seen.add(row.event_id); row.sequence=this.count++; this.pending.push(row)
|
|
99
|
+
this.outbox?.save(this)
|
|
14
100
|
this.schedule()
|
|
15
101
|
}
|
|
16
102
|
offer(offer, config, endpoint) {
|
|
@@ -18,28 +104,46 @@ export class ConnectionDiagnostics {
|
|
|
18
104
|
const url = new URL(endpoint); url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'
|
|
19
105
|
url.pathname = '/client-diagnostics'; url.search = ''; url.hash = ''
|
|
20
106
|
this.target = url.href; this.ticket = offer.ticket; this.authorization = config.authorization
|
|
107
|
+
this.outbox?.save(this)
|
|
21
108
|
this.schedule()
|
|
22
109
|
}
|
|
23
110
|
schedule(delay = 150) {
|
|
24
|
-
if (!this.target || !this.pending.length || this.timer || this.busy
|
|
111
|
+
if (this.outbox?.closed || !this.target || !this.pending.length || this.timer || this.busy) return
|
|
112
|
+
if ((this.outbox?.now() ?? Date.now()) >= this.expires) {
|
|
113
|
+
this.pending = []; this.outbox?.save(this); return
|
|
114
|
+
}
|
|
25
115
|
this.timer = setTimeout(() => { this.timer = null; void this.flush() }, delay); this.timer.unref?.()
|
|
26
116
|
}
|
|
27
117
|
async flush() {
|
|
28
|
-
if (this.busy || !this.target || !this.pending.length) return
|
|
118
|
+
if (this.outbox?.closed || this.busy || !this.target || !this.pending.length) return
|
|
119
|
+
if ((this.outbox?.now() ?? Date.now()) >= this.expires) {
|
|
120
|
+
this.pending = []; this.outbox?.save(this); return
|
|
121
|
+
}
|
|
122
|
+
if (this.outbox && this.outbox.inflight >= 2) { this.schedule(1000); return }
|
|
29
123
|
this.busy = true; this.attempts++
|
|
124
|
+
if (this.outbox) this.outbox.inflight++
|
|
125
|
+
this.controller = new AbortController()
|
|
126
|
+
const timeout = setTimeout(() => this.controller.abort(), 3000); timeout.unref?.()
|
|
30
127
|
const rows = this.pending.slice(0, 16)
|
|
31
128
|
let failed = false
|
|
32
129
|
try {
|
|
33
130
|
const response = await this.fetcher(this.target, { method: 'POST', redirect: 'error',
|
|
34
131
|
headers: {'Content-Type':'application/json', ...(this.authorization ? {Authorization:this.authorization} : {})},
|
|
35
132
|
body: JSON.stringify({protocol:DIAGNOSTICS_PROTOCOL, ticket:this.ticket, events:rows}),
|
|
36
|
-
signal:
|
|
133
|
+
signal: this.controller.signal })
|
|
134
|
+
if ([400, 401, 403, 413].includes(response.status)) {
|
|
135
|
+
await response.body?.cancel(); this.pending = []; return
|
|
136
|
+
}
|
|
37
137
|
if (!response.ok) throw Error('diagnostic_upload_failed')
|
|
38
138
|
await response.body?.cancel()
|
|
39
139
|
this.pending.splice(0, rows.length); this.failures = 0
|
|
40
140
|
} catch { failed = true; this.failures = (this.failures || 0) + 1 }
|
|
41
|
-
finally {
|
|
42
|
-
|
|
43
|
-
|
|
141
|
+
finally {
|
|
142
|
+
clearTimeout(timeout); this.busy = false
|
|
143
|
+
if (this.outbox) this.outbox.inflight--
|
|
144
|
+
this.outbox?.save(this)
|
|
145
|
+
}
|
|
146
|
+
// Backoff through transient outages; bound lifetime, rate, storage and concurrency.
|
|
147
|
+
this.schedule(failed ? Math.min(60000, 1000 * 2 ** Math.min(this.failures - 1, 6)) : 150)
|
|
44
148
|
}
|
|
45
149
|
}
|
|
@@ -20,7 +20,11 @@ export class RemoteFeedback {
|
|
|
20
20
|
const fd=openSync(tmp,'wx',0o600)
|
|
21
21
|
try{writeFileSync(fd,randomBytes(32));fsyncSync(fd)}finally{closeSync(fd)}
|
|
22
22
|
try{linkSync(tmp,this.keyPath)}catch(e){if(e.code!=='EEXIST')throw e}finally{unlinkSync(tmp)}
|
|
23
|
-
|
|
23
|
+
// Windows cannot flush this read-only directory handle (EPERM). The key
|
|
24
|
+
// file itself was already flushed above; keep directory durability on POSIX.
|
|
25
|
+
if(process.platform!=='win32'){
|
|
26
|
+
const d=openSync(dirname(this.keyPath),'r');try{fsyncSync(d)}finally{closeSync(d)}
|
|
27
|
+
}
|
|
24
28
|
}
|
|
25
29
|
const key=readFileSync(this.keyPath);if(key.length!==32)throw Error('feedback_identity_key_invalid')
|
|
26
30
|
this.key=key;return key
|
package/src/host/plugin.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { readFile } from 'node:fs/promises'
|
|
|
4
4
|
import { randomUUID } from 'node:crypto'
|
|
5
5
|
import { registerDuetProxy, duetConfig } from './proxy.mjs'
|
|
6
6
|
import { DuetSettings, settingsWriteAllowed } from './settings.mjs'
|
|
7
|
+
import { NICKNAME_LIMIT } from '../shared/nickname.mjs'
|
|
7
8
|
import { IDENTITY_TRANSPORT_HEADER, IDENTITY_TRANSPORT } from '../shared/identity.mjs'
|
|
8
9
|
import { ServiceNotices } from './notices.mjs'
|
|
9
10
|
import { ServiceInfo } from './service-info.mjs'
|
|
@@ -14,9 +15,12 @@ import { PLUGIN_VERSION } from '../shared/state.mjs'
|
|
|
14
15
|
import { buildSessionCatalog, sessionLabel } from '../shared/catalog.mjs'
|
|
15
16
|
import { broadcastText, taskErrorText } from '../shared/result-notification.mjs'
|
|
16
17
|
import { publicAsset } from './assets.mjs'
|
|
18
|
+
import { registerAvatarHost } from './avatar.mjs'
|
|
19
|
+
import { AvatarActivityOutbox } from './avatar-activity.mjs'
|
|
17
20
|
import { duetEnv } from './environment.mjs'
|
|
18
21
|
import { EndpointDiscovery } from './endpoint-discovery.mjs'
|
|
19
22
|
import { StopTasks } from './stop-task.mjs'
|
|
23
|
+
import { DuetVoices } from './voices.mjs'
|
|
20
24
|
|
|
21
25
|
const ROUTE = '/duplex-control'
|
|
22
26
|
const PAGE_ROUTE = '/duet'
|
|
@@ -138,12 +142,12 @@ function sendError(res, status, message) {
|
|
|
138
142
|
sendJson(res, status, { detail: message })
|
|
139
143
|
}
|
|
140
144
|
|
|
141
|
-
async function readJson(req) {
|
|
145
|
+
async function readJson(req, maximum = MAX_BODY_BYTES) {
|
|
142
146
|
let size = 0
|
|
143
147
|
const chunks = []
|
|
144
148
|
for await (const chunk of req) {
|
|
145
149
|
size += chunk.length
|
|
146
|
-
if (size >
|
|
150
|
+
if (size > maximum) throw new Error('request body is too large')
|
|
147
151
|
chunks.push(chunk)
|
|
148
152
|
}
|
|
149
153
|
if (chunks.length === 0) return {}
|
|
@@ -185,16 +189,26 @@ export function apply(ctx, options = {}) {
|
|
|
185
189
|
|
|
186
190
|
const voice = duetConfig()
|
|
187
191
|
const settings = new DuetSettings(voice, { path: options.settingsPath, debug: options.debug === true || duetEnv('DEBUG') === '1' })
|
|
192
|
+
ctx.effect(() => { const avatar=registerAvatarHost(ctx);return ()=>avatar.close() })
|
|
188
193
|
Object.assign(voice, settings.effective())
|
|
194
|
+
voice.nickname = () => settings.public().nickname
|
|
189
195
|
const audit = new DuetTrace({ kind: 'host', plugin_version: PLUGIN_VERSION, pid: process.pid },
|
|
190
196
|
{ ...options.traceOptions, secrets: [voice.authorization] })
|
|
191
197
|
ctx.effect(() => () => { void audit.close({ reason: 'plugin_dispose' }) })
|
|
192
198
|
const discovery = new EndpointDiscovery(() => settings.effective(), {...options.endpointDiscoveryOptions, changed: () => {notices.invalidate();serviceInfo.invalidate()}})
|
|
199
|
+
const voices = new DuetVoices(() => discovery.effective(), {scope:()=>settings.effective().endpoints.online,...options.voiceOptions})
|
|
200
|
+
voice.prepareVoice = () => voices.prepare()
|
|
201
|
+
voice.respondVoiceChallenge = challenge => voices.respondChallenge(challenge)
|
|
202
|
+
voice.applyVoicePolicy = policy => voices.applyPolicy(policy)
|
|
203
|
+
voice.applyVoiceIssue = issue => voices.applyIssue(issue)
|
|
204
|
+
ctx.effect(() => () => voices.close())
|
|
193
205
|
const notices = new ServiceNotices(() => discovery.effective(), (url,options) => discovery.fetch(url,options))
|
|
194
206
|
const serviceInfo = new ServiceInfo(() => discovery.effective(), (url,options) => discovery.fetch(url,options))
|
|
195
207
|
discovery.refreshIfDue()
|
|
196
208
|
const feedbackStore = options.feedbackStore ?? (options.feedbackDisabled ? null : new RemoteFeedback(()=>discovery.effective(),{keyPath:options.feedbackIdentityPath}))
|
|
197
209
|
const feedback = new FeedbackService(feedbackStore)
|
|
210
|
+
const avatarActivity = new AvatarActivityOutbox(()=>discovery.effective(), options.avatarActivityOptions)
|
|
211
|
+
ctx.effect(()=>()=>avatarActivity.close())
|
|
198
212
|
let duetProxy
|
|
199
213
|
ctx.effect(() => { duetProxy = registerDuetProxy(ctx, voice, feedback, () => (ctx.workspaceRegistry.list?.() || []).length > 0, discovery); return duetProxy })
|
|
200
214
|
|
|
@@ -416,6 +430,7 @@ export function apply(ctx, options = {}) {
|
|
|
416
430
|
const turnKey = (sessionId, turn) => `${sessionId}:${String(turn)}`
|
|
417
431
|
|
|
418
432
|
const completeJob = (job, event) => {
|
|
433
|
+
job.turn_end_reason = ['completed','aborted','error'].includes(event.data.reason?.kind) ? event.data.reason.kind : 'unknown'
|
|
419
434
|
job.completed_at = nowSeconds()
|
|
420
435
|
if (event.data.reason?.kind === 'aborted') {
|
|
421
436
|
job.status = 'failed'
|
|
@@ -530,6 +545,44 @@ export function apply(ctx, options = {}) {
|
|
|
530
545
|
})
|
|
531
546
|
|
|
532
547
|
const handleApi = async (req, res, pathname) => {
|
|
548
|
+
if(pathname===`${ROUTE}/api/voices`){
|
|
549
|
+
const rejection=ctx.connection.requestRejection(req)
|
|
550
|
+
if(rejection){sendError(res,rejection,'DSH connection required');return}
|
|
551
|
+
try {
|
|
552
|
+
if(req.method==='GET'){sendJson(res,200,await voices.refreshAvailability());return}
|
|
553
|
+
if(req.method!=='POST'){sendError(res,405,'method_not_allowed');return}
|
|
554
|
+
if(!identityWriteAllowed(req)){sendError(res,403,'same-origin voice request required');return}
|
|
555
|
+
sendJson(res,200,await voices.update(await readJson(req,14*1024*1024)))
|
|
556
|
+
}catch(error){sendError(res,400,/^[a-z_]+$/.test(error.message)?error.message:'voice_request_failed')}
|
|
557
|
+
return
|
|
558
|
+
}
|
|
559
|
+
if(req.method==='POST'&&pathname===`${ROUTE}/api/avatar/activity`){
|
|
560
|
+
const rejection=ctx.connection.requestRejection(req)
|
|
561
|
+
if(rejection){sendError(res,rejection,'DSH connection required');return}
|
|
562
|
+
if(!identityWriteAllowed(req)){sendError(res,403,'same-origin activity request required');return}
|
|
563
|
+
try{const value=await readJson(req);if(JSON.stringify(value).length>4096){sendError(res,413,'activity too large');return}sendJson(res,202,await avatarActivity.enqueue(value,feedback.user(req)))}
|
|
564
|
+
catch{sendError(res,400,'invalid_avatar_activity')}return
|
|
565
|
+
}
|
|
566
|
+
if (req.method === 'POST' && pathname === `${ROUTE}/api/duet/nickname`) {
|
|
567
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
568
|
+
if (rejection) { sendError(res, rejection, '请先打开并登录 DSH 主页面'); return }
|
|
569
|
+
const boundRPC = req.headers['x-duplex-control-client'] === 'realtime-client-rpc-v1' && browserOwner(req)
|
|
570
|
+
if (!identityWriteAllowed(req) && !boundRPC) { sendError(res, 403, 'same-origin nickname request required'); return }
|
|
571
|
+
try {
|
|
572
|
+
const body = await readJson(req)
|
|
573
|
+
const result = await settings.renameNickname(body.nickname, body.revision)
|
|
574
|
+
// Nicknames do not retarget or close an active voice connection.
|
|
575
|
+
sendJson(res, 200, {ok:true, nickname:result.nickname, revision:result.revision,
|
|
576
|
+
action_response:'<action_response>rename_duet:ok</action_response>'})
|
|
577
|
+
} catch (error) {
|
|
578
|
+
const reason = error.message === NICKNAME_LIMIT ? NICKNAME_LIMIT
|
|
579
|
+
: error.message === 'settings_revision_conflict' ? '设置已更新,请刷新后重试' : '昵称保存失败,请重试'
|
|
580
|
+
sendJson(res, 200, {ok:false, reason,
|
|
581
|
+
error_code:error.message === NICKNAME_LIMIT ? 'invalid_nickname' : 'nickname_save_failed',
|
|
582
|
+
action_response:`<action_response>rename_duet:failed:${reason}</action_response>`})
|
|
583
|
+
}
|
|
584
|
+
return
|
|
585
|
+
}
|
|
533
586
|
if(req.method==='POST' && pathname===`${ROUTE}/api/feedback`){
|
|
534
587
|
const rejection = ctx.connection.requestRejection(req)
|
|
535
588
|
if(rejection){sendError(res,rejection,'请先打开并登录 DSH 主页面');return}
|
|
@@ -564,6 +617,7 @@ export function apply(ctx, options = {}) {
|
|
|
564
617
|
else feedbackStore?.ensureIdentity?.(req,res)
|
|
565
618
|
} catch {sendJson(res,503,{error_code:'feedback_identity_unavailable'});return}
|
|
566
619
|
sendJson(res, 200, { ...settings.public(), plugin_version: PLUGIN_VERSION, feedback_enabled: feedback.enabled,
|
|
620
|
+
avatar: { web_only: duetEnv('AVATAR_WEB_ONLY') === '1' },
|
|
567
621
|
...(identity?{feedback_identity:identity}:{}), connection: duetProxy?.snapshot?.() || { online: 0, tts_only: 0 } })
|
|
568
622
|
return
|
|
569
623
|
}
|
|
@@ -837,7 +891,8 @@ export function apply(ctx, options = {}) {
|
|
|
837
891
|
// before that page can select its own current blank session.
|
|
838
892
|
const pageCatalog = browserOwner(req) || req.headers['x-duet-catalog-scope'] === 'page'
|
|
839
893
|
sendJson(res, 200, { sessions: await listSessions({forCatalog:!pageCatalog}),
|
|
840
|
-
|
|
894
|
+
duet_nickname: settings.public().nickname,
|
|
895
|
+
duet_rpc_capabilities: ['rename_duet_v1', ...(typeof ctx.sessionController.cancel === 'function' ? ['stop_task_v1'] : [])] })
|
|
841
896
|
return
|
|
842
897
|
}
|
|
843
898
|
const stopRoute = pathname.match(new RegExp(`^${ROUTE}/api/sessions/([^/]+)/(execution|cancel)$`))
|
|
@@ -1191,7 +1246,7 @@ export function apply(ctx, options = {}) {
|
|
|
1191
1246
|
const asset = publicAsset(pathname)
|
|
1192
1247
|
if (req.method === 'GET' && asset) {
|
|
1193
1248
|
const body = asset.body ?? await readFile(asset.url)
|
|
1194
|
-
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
|
|
1249
|
+
res.writeHead(200, { 'content-type': asset.contentType || 'text/javascript; charset=utf-8', 'cache-control': asset.cacheControl || (asset.contentType ? 'private, max-age=3600' : 'no-store') })
|
|
1195
1250
|
res.end(body)
|
|
1196
1251
|
return
|
|
1197
1252
|
}
|
package/src/host/proxy.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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 { ConnectionDiagnostics } from './diagnostics.mjs'
|
|
4
|
+
import { ConnectionDiagnostics, DiagnosticOutbox } from './diagnostics.mjs'
|
|
5
5
|
import { DIAGNOSTICS_PROTOCOL } from '../shared/diagnostics.mjs'
|
|
6
6
|
import { PLUGIN_VERSION } from '../shared/state.mjs'
|
|
7
7
|
import { duetEnv } from './environment.mjs'
|
|
@@ -10,11 +10,12 @@ import {sessionMetadata} from './session-metadata.mjs'
|
|
|
10
10
|
import {VOICE_PROTOCOL} from '../shared/identity.mjs'
|
|
11
11
|
import { broadcastText } from '../shared/result-notification.mjs'
|
|
12
12
|
import { sessionLabel } from '../shared/catalog.mjs'
|
|
13
|
+
import { normalizeNickname } from '../shared/nickname.mjs'
|
|
13
14
|
import { DEFAULT_DUET_URL, publicServiceAuthorization } from './service-defaults.mjs'
|
|
14
15
|
export { DEFAULT_DUET_URL } from './service-defaults.mjs'
|
|
15
16
|
const require = createRequire(import.meta.url)
|
|
16
17
|
|
|
17
|
-
export function compatibleVersion(version, min = '0.1.0', maxExclusive = '0.
|
|
18
|
+
export function compatibleVersion(version, min = '0.1.0', maxExclusive = '0.3.0') {
|
|
18
19
|
const parse = v => /^\d+\.\d+\.\d+$/.test(v || '') ? v.split('.').map(Number) : null
|
|
19
20
|
const compare = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]
|
|
20
21
|
const v = parse(version), low = parse(min), high = parse(maxExclusive)
|
|
@@ -28,7 +29,7 @@ export function duetConfig(env = process.env) {
|
|
|
28
29
|
}
|
|
29
30
|
return {
|
|
30
31
|
min_version: duetEnv('MIN_VERSION', env) || '0.1.0',
|
|
31
|
-
max_version_exclusive: duetEnv('MAX_VERSION_EXCLUSIVE', env) || '0.
|
|
32
|
+
max_version_exclusive: duetEnv('MAX_VERSION_EXCLUSIVE', env) || '0.3.0',
|
|
32
33
|
control_transport: duetEnv('CONTROL_TRANSPORT', env) || 'client_rpc_v1',
|
|
33
34
|
authorization: publicServiceAuthorization(endpoints),
|
|
34
35
|
endpoints,
|
|
@@ -63,6 +64,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
63
64
|
handleProtocols: protocols => protocols.has(VOICE_PROTOCOL) ? VOICE_PROTOCOL : false })
|
|
64
65
|
const connections = new Map()
|
|
65
66
|
const reporters = new Map()
|
|
67
|
+
const diagnosticOutbox = new DiagnosticOutbox(config.diagnosticOptions)
|
|
66
68
|
const stop = ctx.webServer.registerUpgrade({
|
|
67
69
|
path: '/duplex-control/voice/ws',
|
|
68
70
|
handler(req, socket, head) {
|
|
@@ -89,6 +91,8 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
89
91
|
const timer = setTimeout(() => { void trace.close() }, 1500); timer.unref()
|
|
90
92
|
})
|
|
91
93
|
let back, feedbackTicket = null, connectionRoute, selectedConfig, diagnostics
|
|
94
|
+
let chosenVoice = 'default'
|
|
95
|
+
let voiceChallengeStarted = false
|
|
92
96
|
const opening = new AbortController()
|
|
93
97
|
front.once('close', () => feedback?.close(feedbackTicket))
|
|
94
98
|
let state = null
|
|
@@ -111,7 +115,8 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
111
115
|
try{anonymousUserId=feedback?.user(req)}catch{ /* Identity is optional, not admission. */ }
|
|
112
116
|
const clientMetadata=sessionMetadata(params,mode,anonymousUserId)
|
|
113
117
|
diagnostics = new ConnectionDiagnostics({client_trace_id:clientMetadata.client_trace_id,
|
|
114
|
-
page_id:clientMetadata.page_id, plugin_version:clientMetadata.version, host_version:PLUGIN_VERSION, mode}
|
|
118
|
+
page_id:clientMetadata.page_id, plugin_version:clientMetadata.version, host_version:PLUGIN_VERSION, mode},
|
|
119
|
+
diagnosticOutbox.fetcher, diagnosticOutbox)
|
|
115
120
|
reporters.set(clientMetadata.client_trace_id, {diagnostics, page_id:clientMetadata.page_id, user:anonymousUserId})
|
|
116
121
|
// Allow keepalive HTTP diagnostics to arrive after the browser socket closed.
|
|
117
122
|
front.once('close', () => { const timer=setTimeout(()=>reporters.delete(clientMetadata.client_trace_id),30000); timer.unref() })
|
|
@@ -132,7 +137,9 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
132
137
|
if (!binary) {
|
|
133
138
|
const message = JSON.parse(data.toString())
|
|
134
139
|
if (message.type === 'session.update') data = JSON.stringify({...message,
|
|
135
|
-
|
|
140
|
+
session: {...message.session, ...(chosenVoice!=='default'?{voice_id:chosenVoice}:{})},
|
|
141
|
+
client: {...message.client, connection_route: connectionRoute,
|
|
142
|
+
...(chosenVoice!=='default'?{voice_possession_protocol:'voice_possession_v1'}:{})}})
|
|
136
143
|
}
|
|
137
144
|
trace.frame('upstream.send', data, binary)
|
|
138
145
|
back.send(data, {binary})
|
|
@@ -171,12 +178,17 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
171
178
|
if (message.type === 'session.update') {
|
|
172
179
|
if (initialized) throw new Error('voice_mode_requires_reconnect')
|
|
173
180
|
initialized = true
|
|
181
|
+
let nickname = null
|
|
182
|
+
try { nickname = normalizeNickname(config.nickname?.()) } catch { /* Default identity. */ }
|
|
174
183
|
forward(JSON.stringify({ type: 'session.update',
|
|
175
184
|
client: {...clientMetadata, diagnostics_protocol:DIAGNOSTICS_PROTOCOL,
|
|
185
|
+
...(message.client?.audio_text_protocol === 'audio_text_delta_v1'
|
|
186
|
+
? {audio_text_protocol:'audio_text_delta_v1'} : {}),
|
|
176
187
|
...(message.client?.audio_stop_protocol === 'audio_stop_candidates_v1'
|
|
177
188
|
? {audio_stop_protocol:'audio_stop_candidates_v1'} : {})},
|
|
178
189
|
session: {
|
|
179
190
|
type: 'realtime', preset_id: 'server_default',
|
|
191
|
+
duet_nickname: nickname,
|
|
180
192
|
io_mode:mode === 'tts_only'?'external_only':'online',
|
|
181
193
|
...(clientRPC ? { harness: { transport: 'client_rpc_v1' } } : {}),
|
|
182
194
|
audio: { input: { format: { type: 'audio/pcm', rate: 16000 } } },
|
|
@@ -210,6 +222,8 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
210
222
|
} catch (error) { fail(error.message || 'invalid_voice_event') }
|
|
211
223
|
})
|
|
212
224
|
void (async () => {
|
|
225
|
+
chosenVoice = await config.prepareVoice?.() || 'default'
|
|
226
|
+
if (opening.signal.aborted || front.readyState !== WebSocket.OPEN) return
|
|
213
227
|
const routes = await discovery.plan(mode)
|
|
214
228
|
const selected = await connectEndpoint(WebSocket, routes, {signal: opening.signal, trace})
|
|
215
229
|
if (opening.signal.aborted || front.readyState !== WebSocket.OPEN) { selected.socket.close(); return }
|
|
@@ -223,6 +237,27 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
223
237
|
if (!binary) {
|
|
224
238
|
try {
|
|
225
239
|
const offer = JSON.parse(data.toString())
|
|
240
|
+
if(offer.type==='voice.unavailable'&&offer.selected==='default'){
|
|
241
|
+
chosenVoice='default'
|
|
242
|
+
Promise.resolve(config.applyVoiceIssue?.(offer)).catch(()=>{
|
|
243
|
+
trace.event('voice.issue_persist_failed',{code:'voice_links_unavailable'})
|
|
244
|
+
})
|
|
245
|
+
}
|
|
246
|
+
if(offer.type==='voice.policy'&&offer.enabled===false&&offer.selected==='default'){
|
|
247
|
+
chosenVoice='default'
|
|
248
|
+
// Queue persistence before forwarding: the reconnect waits for it.
|
|
249
|
+
Promise.resolve(config.applyVoicePolicy?.(offer)).catch(()=>{
|
|
250
|
+
trace.event('voice.policy_persist_failed', {code:'voice_links_unavailable'})
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
if (offer.type === 'voice.challenge') {
|
|
254
|
+
if(chosenVoice==='default'||voiceChallengeStarted||!config.respondVoiceChallenge){fail('voice_proof_invalid');return}
|
|
255
|
+
voiceChallengeStarted=true
|
|
256
|
+
Promise.resolve(config.respondVoiceChallenge(offer.challenge)).then(proof=>{
|
|
257
|
+
if(!terminal&&back.readyState===WebSocket.OPEN)back.send(JSON.stringify({type:'voice.proof',...proof}))
|
|
258
|
+
}).catch(()=>fail('voice_proof_invalid'))
|
|
259
|
+
return // Original-file proof and nonce never enter browser/trace.
|
|
260
|
+
}
|
|
226
261
|
if (offer.type === 'client.diagnostics.ready') {
|
|
227
262
|
diagnostics.offer(offer, selectedConfig, selected.route.url)
|
|
228
263
|
return
|
|
@@ -284,7 +319,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
284
319
|
})
|
|
285
320
|
},
|
|
286
321
|
})
|
|
287
|
-
const dispose = () => { stop(); for (const socket of server.clients) socket.close(1001); server.close() }
|
|
322
|
+
const dispose = () => { stop(); for (const socket of server.clients) socket.close(1001); server.close(); diagnosticOutbox.dispose() }
|
|
288
323
|
dispose.snapshot = () => ({
|
|
289
324
|
online: [...connections.values()].filter(c => c.mode === 'online' && c.ready).length,
|
|
290
325
|
tts_only: [...connections.values()].filter(c => c.mode === 'tts_only' && c.ready).length,
|
|
@@ -14,7 +14,8 @@ export function migrateRetiredSettings(data, path) {
|
|
|
14
14
|
if (!retired.includes(url.hostname) || !['ws:', 'wss:', 'http:', 'https:'].includes(url.protocol)
|
|
15
15
|
|| url.port || url.username || url.password || url.hash || !['/', '/ws'].includes(url.pathname)
|
|
16
16
|
|| [...url.searchParams].some(([k,v]) => k !== 'protocol' || v !== 'realtime_v2')) return data
|
|
17
|
-
const next = { backend_url: DEFAULT_DUET_URL
|
|
17
|
+
const next = { backend_url: DEFAULT_DUET_URL,
|
|
18
|
+
...(data.nickname != null ? {nickname:data.nickname} : {}) }
|
|
18
19
|
const temp = `${path}.${randomUUID()}.tmp`
|
|
19
20
|
try {
|
|
20
21
|
writeFileSync(temp, JSON.stringify(next) + '\n', { mode: 0o600, flag: 'wx' })
|