dsh-duet 0.1.9 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +145 -10
- 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 +81 -33
- package/src/client/composer-bridge.mjs +5 -2
- package/src/client/composer.mjs +3 -3
- 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/interactions.mjs +5 -1
- package/src/client/notice.mjs +1 -0
- package/src/client/rpc.mjs +23 -5
- package/src/client/settings.html +78 -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/host/assets.mjs +12 -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 +67 -4
- package/src/host/proxy.mjs +16 -6
- package/src/host/settings-migration.mjs +2 -1
- package/src/host/settings.mjs +19 -4
- package/src/host/stop-task.mjs +37 -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 +1 -1
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,8 +15,11 @@ 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'
|
|
22
|
+
import { StopTasks } from './stop-task.mjs'
|
|
19
23
|
|
|
20
24
|
const ROUTE = '/duplex-control'
|
|
21
25
|
const PAGE_ROUTE = '/duet'
|
|
@@ -165,6 +169,7 @@ export function apply(ctx, options = {}) {
|
|
|
165
169
|
const composerPollWaiters = new Set()
|
|
166
170
|
const composerRequestOrder = []
|
|
167
171
|
const currentTurn = new Map()
|
|
172
|
+
const stopTasks = new StopTasks(request => ctx.sessionController.cancel(request))
|
|
168
173
|
const jobByTurn = new Map()
|
|
169
174
|
const pendingInteractions = new Map()
|
|
170
175
|
const browserClients = new Map()
|
|
@@ -183,7 +188,9 @@ export function apply(ctx, options = {}) {
|
|
|
183
188
|
|
|
184
189
|
const voice = duetConfig()
|
|
185
190
|
const settings = new DuetSettings(voice, { path: options.settingsPath, debug: options.debug === true || duetEnv('DEBUG') === '1' })
|
|
191
|
+
ctx.effect(() => { const avatar=registerAvatarHost(ctx);return ()=>avatar.close() })
|
|
186
192
|
Object.assign(voice, settings.effective())
|
|
193
|
+
voice.nickname = () => settings.public().nickname
|
|
187
194
|
const audit = new DuetTrace({ kind: 'host', plugin_version: PLUGIN_VERSION, pid: process.pid },
|
|
188
195
|
{ ...options.traceOptions, secrets: [voice.authorization] })
|
|
189
196
|
ctx.effect(() => () => { void audit.close({ reason: 'plugin_dispose' }) })
|
|
@@ -193,6 +200,8 @@ export function apply(ctx, options = {}) {
|
|
|
193
200
|
discovery.refreshIfDue()
|
|
194
201
|
const feedbackStore = options.feedbackStore ?? (options.feedbackDisabled ? null : new RemoteFeedback(()=>discovery.effective(),{keyPath:options.feedbackIdentityPath}))
|
|
195
202
|
const feedback = new FeedbackService(feedbackStore)
|
|
203
|
+
const avatarActivity = new AvatarActivityOutbox(()=>discovery.effective(), options.avatarActivityOptions)
|
|
204
|
+
ctx.effect(()=>()=>avatarActivity.close())
|
|
196
205
|
let duetProxy
|
|
197
206
|
ctx.effect(() => { duetProxy = registerDuetProxy(ctx, voice, feedback, () => (ctx.workspaceRegistry.list?.() || []).length > 0, discovery); return duetProxy })
|
|
198
207
|
|
|
@@ -414,10 +423,11 @@ export function apply(ctx, options = {}) {
|
|
|
414
423
|
const turnKey = (sessionId, turn) => `${sessionId}:${String(turn)}`
|
|
415
424
|
|
|
416
425
|
const completeJob = (job, event) => {
|
|
426
|
+
job.turn_end_reason = ['completed','aborted','error'].includes(event.data.reason?.kind) ? event.data.reason.kind : 'unknown'
|
|
417
427
|
job.completed_at = nowSeconds()
|
|
418
428
|
if (event.data.reason?.kind === 'aborted') {
|
|
419
429
|
job.status = 'failed'
|
|
420
|
-
job.error = '
|
|
430
|
+
job.error = '任务执行已终止,未完成。'
|
|
421
431
|
} else if (event.data.reason?.kind === 'error') {
|
|
422
432
|
job.status = 'failed'
|
|
423
433
|
job.error = taskErrorText(event.data.reason.error)
|
|
@@ -441,6 +451,7 @@ export function apply(ctx, options = {}) {
|
|
|
441
451
|
const sessionId = String(session.id)
|
|
442
452
|
if (event.type === 'turn/start') {
|
|
443
453
|
currentTurn.set(sessionId, event.data.turn)
|
|
454
|
+
stopTasks.start(sessionId, event.data.turn)
|
|
444
455
|
return
|
|
445
456
|
}
|
|
446
457
|
if (event.type === 'user/message') {
|
|
@@ -490,10 +501,11 @@ export function apply(ctx, options = {}) {
|
|
|
490
501
|
return
|
|
491
502
|
}
|
|
492
503
|
if (event.type !== 'turn/end') return
|
|
504
|
+
stopTasks.end(sessionId, event.data.turn)
|
|
493
505
|
const key = turnKey(sessionId, event.data.turn)
|
|
494
506
|
const id = jobByTurn.get(key)
|
|
495
507
|
const job = id === undefined ? undefined : jobs.get(id)
|
|
496
|
-
currentTurn.delete(sessionId)
|
|
508
|
+
if (currentTurn.get(sessionId) === event.data.turn) currentTurn.delete(sessionId)
|
|
497
509
|
jobByTurn.delete(key)
|
|
498
510
|
if (job === undefined) return
|
|
499
511
|
completeJob(job, event)
|
|
@@ -526,6 +538,33 @@ export function apply(ctx, options = {}) {
|
|
|
526
538
|
})
|
|
527
539
|
|
|
528
540
|
const handleApi = async (req, res, pathname) => {
|
|
541
|
+
if(req.method==='POST'&&pathname===`${ROUTE}/api/avatar/activity`){
|
|
542
|
+
const rejection=ctx.connection.requestRejection(req)
|
|
543
|
+
if(rejection){sendError(res,rejection,'DSH connection required');return}
|
|
544
|
+
if(!identityWriteAllowed(req)){sendError(res,403,'same-origin activity request required');return}
|
|
545
|
+
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)))}
|
|
546
|
+
catch{sendError(res,400,'invalid_avatar_activity')}return
|
|
547
|
+
}
|
|
548
|
+
if (req.method === 'POST' && pathname === `${ROUTE}/api/duet/nickname`) {
|
|
549
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
550
|
+
if (rejection) { sendError(res, rejection, '请先打开并登录 DSH 主页面'); return }
|
|
551
|
+
const boundRPC = req.headers['x-duplex-control-client'] === 'realtime-client-rpc-v1' && browserOwner(req)
|
|
552
|
+
if (!identityWriteAllowed(req) && !boundRPC) { sendError(res, 403, 'same-origin nickname request required'); return }
|
|
553
|
+
try {
|
|
554
|
+
const body = await readJson(req)
|
|
555
|
+
const result = await settings.renameNickname(body.nickname, body.revision)
|
|
556
|
+
// Nicknames do not retarget or close an active voice connection.
|
|
557
|
+
sendJson(res, 200, {ok:true, nickname:result.nickname, revision:result.revision,
|
|
558
|
+
action_response:'<action_response>rename_duet:ok</action_response>'})
|
|
559
|
+
} catch (error) {
|
|
560
|
+
const reason = error.message === NICKNAME_LIMIT ? NICKNAME_LIMIT
|
|
561
|
+
: error.message === 'settings_revision_conflict' ? '设置已更新,请刷新后重试' : '昵称保存失败,请重试'
|
|
562
|
+
sendJson(res, 200, {ok:false, reason,
|
|
563
|
+
error_code:error.message === NICKNAME_LIMIT ? 'invalid_nickname' : 'nickname_save_failed',
|
|
564
|
+
action_response:`<action_response>rename_duet:failed:${reason}</action_response>`})
|
|
565
|
+
}
|
|
566
|
+
return
|
|
567
|
+
}
|
|
529
568
|
if(req.method==='POST' && pathname===`${ROUTE}/api/feedback`){
|
|
530
569
|
const rejection = ctx.connection.requestRejection(req)
|
|
531
570
|
if(rejection){sendError(res,rejection,'请先打开并登录 DSH 主页面');return}
|
|
@@ -560,6 +599,7 @@ export function apply(ctx, options = {}) {
|
|
|
560
599
|
else feedbackStore?.ensureIdentity?.(req,res)
|
|
561
600
|
} catch {sendJson(res,503,{error_code:'feedback_identity_unavailable'});return}
|
|
562
601
|
sendJson(res, 200, { ...settings.public(), plugin_version: PLUGIN_VERSION, feedback_enabled: feedback.enabled,
|
|
602
|
+
avatar: { web_only: duetEnv('AVATAR_WEB_ONLY') === '1' },
|
|
563
603
|
...(identity?{feedback_identity:identity}:{}), connection: duetProxy?.snapshot?.() || { online: 0, tts_only: 0 } })
|
|
564
604
|
return
|
|
565
605
|
}
|
|
@@ -832,7 +872,30 @@ export function apply(ctx, options = {}) {
|
|
|
832
872
|
// A page owns its focus. Do not remove blank sessions using host focus
|
|
833
873
|
// before that page can select its own current blank session.
|
|
834
874
|
const pageCatalog = browserOwner(req) || req.headers['x-duet-catalog-scope'] === 'page'
|
|
835
|
-
sendJson(res, 200, { sessions: await listSessions({forCatalog:!pageCatalog})
|
|
875
|
+
sendJson(res, 200, { sessions: await listSessions({forCatalog:!pageCatalog}),
|
|
876
|
+
duet_nickname: settings.public().nickname,
|
|
877
|
+
duet_rpc_capabilities: ['rename_duet_v1', ...(typeof ctx.sessionController.cancel === 'function' ? ['stop_task_v1'] : [])] })
|
|
878
|
+
return
|
|
879
|
+
}
|
|
880
|
+
const stopRoute = pathname.match(new RegExp(`^${ROUTE}/api/sessions/([^/]+)/(execution|cancel)$`))
|
|
881
|
+
if (stopRoute && ((req.method === 'GET' && stopRoute[2] === 'execution')
|
|
882
|
+
|| (req.method === 'POST' && stopRoute[2] === 'cancel'))) {
|
|
883
|
+
const owner = browserOwner(req)
|
|
884
|
+
if (!owner) throw codedError('stop_task_owner_required', '停止操作需要连接所属页面')
|
|
885
|
+
if (typeof ctx.sessionController.cancel !== 'function') {
|
|
886
|
+
throw codedError('harness_stop_task_upgrade_required', '请升级 DSH 和 duet 插件后使用停止任务')
|
|
887
|
+
}
|
|
888
|
+
const sessionId = decodeURIComponent(stopRoute[1])
|
|
889
|
+
const body = req.method === 'POST' ? await readJson(req) : null
|
|
890
|
+
if (req.method === 'POST' && (!body || typeof body !== 'object' || Array.isArray(body)
|
|
891
|
+
|| Object.keys(body).some(k => !['execution_id', 'require_focus'].includes(k))
|
|
892
|
+
|| typeof body.require_focus !== 'boolean')) throw codedError('invalid_stop_request', '无效停止请求', 400)
|
|
893
|
+
const sessions = await listSessions()
|
|
894
|
+
if (!sessions.some(s => s.session_id === sessionId)) throw codedError('session_not_found', '会话不存在')
|
|
895
|
+
// Focus checks run in the owning browser; Host never substitutes global focus.
|
|
896
|
+
sendJson(res, 200, body
|
|
897
|
+
? await stopTasks.request(sessionId, body.execution_id, owner)
|
|
898
|
+
: { execution: stopTasks.snapshot(sessionId) })
|
|
836
899
|
return
|
|
837
900
|
}
|
|
838
901
|
const composer = pathname.match(new RegExp(`^${ROUTE}/api/sessions/([^/]+)/composer$`))
|
|
@@ -1165,7 +1228,7 @@ export function apply(ctx, options = {}) {
|
|
|
1165
1228
|
const asset = publicAsset(pathname)
|
|
1166
1229
|
if (req.method === 'GET' && asset) {
|
|
1167
1230
|
const body = asset.body ?? await readFile(asset.url)
|
|
1168
|
-
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
|
|
1231
|
+
res.writeHead(200, { 'content-type': asset.contentType || 'text/javascript; charset=utf-8', 'cache-control': asset.cacheControl || (asset.contentType ? 'private, max-age=3600' : 'no-store') })
|
|
1169
1232
|
res.end(body)
|
|
1170
1233
|
return
|
|
1171
1234
|
}
|
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) {
|
|
@@ -111,7 +113,8 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
111
113
|
try{anonymousUserId=feedback?.user(req)}catch{ /* Identity is optional, not admission. */ }
|
|
112
114
|
const clientMetadata=sessionMetadata(params,mode,anonymousUserId)
|
|
113
115
|
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}
|
|
116
|
+
page_id:clientMetadata.page_id, plugin_version:clientMetadata.version, host_version:PLUGIN_VERSION, mode},
|
|
117
|
+
diagnosticOutbox.fetcher, diagnosticOutbox)
|
|
115
118
|
reporters.set(clientMetadata.client_trace_id, {diagnostics, page_id:clientMetadata.page_id, user:anonymousUserId})
|
|
116
119
|
// Allow keepalive HTTP diagnostics to arrive after the browser socket closed.
|
|
117
120
|
front.once('close', () => { const timer=setTimeout(()=>reporters.delete(clientMetadata.client_trace_id),30000); timer.unref() })
|
|
@@ -171,10 +174,17 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
171
174
|
if (message.type === 'session.update') {
|
|
172
175
|
if (initialized) throw new Error('voice_mode_requires_reconnect')
|
|
173
176
|
initialized = true
|
|
177
|
+
let nickname = null
|
|
178
|
+
try { nickname = normalizeNickname(config.nickname?.()) } catch { /* Default identity. */ }
|
|
174
179
|
forward(JSON.stringify({ type: 'session.update',
|
|
175
|
-
client: {...clientMetadata, diagnostics_protocol:DIAGNOSTICS_PROTOCOL
|
|
180
|
+
client: {...clientMetadata, diagnostics_protocol:DIAGNOSTICS_PROTOCOL,
|
|
181
|
+
...(message.client?.audio_text_protocol === 'audio_text_delta_v1'
|
|
182
|
+
? {audio_text_protocol:'audio_text_delta_v1'} : {}),
|
|
183
|
+
...(message.client?.audio_stop_protocol === 'audio_stop_candidates_v1'
|
|
184
|
+
? {audio_stop_protocol:'audio_stop_candidates_v1'} : {})},
|
|
176
185
|
session: {
|
|
177
186
|
type: 'realtime', preset_id: 'server_default',
|
|
187
|
+
duet_nickname: nickname,
|
|
178
188
|
io_mode:mode === 'tts_only'?'external_only':'online',
|
|
179
189
|
...(clientRPC ? { harness: { transport: 'client_rpc_v1' } } : {}),
|
|
180
190
|
audio: { input: { format: { type: 'audio/pcm', rate: 16000 } } },
|
|
@@ -282,7 +292,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
|
|
|
282
292
|
})
|
|
283
293
|
},
|
|
284
294
|
})
|
|
285
|
-
const dispose = () => { stop(); for (const socket of server.clients) socket.close(1001); server.close() }
|
|
295
|
+
const dispose = () => { stop(); for (const socket of server.clients) socket.close(1001); server.close(); diagnosticOutbox.dispose() }
|
|
286
296
|
dispose.snapshot = () => ({
|
|
287
297
|
online: [...connections.values()].filter(c => c.mode === 'online' && c.ready).length,
|
|
288
298
|
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' })
|
package/src/host/settings.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { randomUUID } from 'node:crypto'
|
|
|
7
7
|
import { duetEnv } from './environment.mjs'
|
|
8
8
|
import { publicServiceAuthorization, isPublicTrialEndpoint } from './service-defaults.mjs'
|
|
9
9
|
import { migrateRetiredSettings } from './settings-migration.mjs'
|
|
10
|
+
import { normalizeNickname } from '../shared/nickname.mjs'
|
|
10
11
|
|
|
11
12
|
export function normalizeBackendURL(value) {
|
|
12
13
|
if (typeof value !== 'string' || value.length > 2048) throw new Error('invalid_backend_url')
|
|
@@ -45,14 +46,16 @@ export class DuetSettings {
|
|
|
45
46
|
|
|
46
47
|
validate(data) {
|
|
47
48
|
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('invalid_voice_settings')
|
|
49
|
+
if (data.backend_url === undefined && data.nickname != null) return {nickname:normalizeNickname(data.nickname)}
|
|
48
50
|
const backend_url = validateBackendURL(data.backend_url, data.insecure_origin)
|
|
49
51
|
const url = new URL(backend_url)
|
|
50
52
|
const insecure_origin = url.protocol === 'ws:' && url.origin === data.insecure_origin ? url.origin : null
|
|
51
|
-
return { backend_url, ...(insecure_origin ? { insecure_origin } : {})
|
|
53
|
+
return { backend_url, ...(insecure_origin ? { insecure_origin } : {}),
|
|
54
|
+
...(data.nickname != null ? {nickname:normalizeNickname(data.nickname)} : {}) }
|
|
52
55
|
}
|
|
53
56
|
|
|
54
57
|
effective() {
|
|
55
|
-
const endpoints = this.saved ? { online: this.saved.backend_url, tts_only: this.saved.backend_url } : this.base.endpoints
|
|
58
|
+
const endpoints = this.saved?.backend_url ? { online: this.saved.backend_url, tts_only: this.saved.backend_url } : this.base.endpoints
|
|
56
59
|
return { ...this.base, endpoints, authorization: publicServiceAuthorization(endpoints) }
|
|
57
60
|
}
|
|
58
61
|
|
|
@@ -67,9 +70,10 @@ export class DuetSettings {
|
|
|
67
70
|
return {
|
|
68
71
|
min_version: config.min_version, max_version_exclusive: config.max_version_exclusive,
|
|
69
72
|
modes: Object.keys(config.endpoints), endpoints,
|
|
70
|
-
backend_url: endpoints.online, config_source: this.saved ? 'plugin_settings' : 'environment_or_default',
|
|
73
|
+
backend_url: endpoints.online, config_source: this.saved?.backend_url ? 'plugin_settings' : 'environment_or_default',
|
|
71
74
|
auth_configured: Boolean(config.authorization),
|
|
72
75
|
debug: this.debug, revision: this.revision,
|
|
76
|
+
nickname: this.saved?.nickname ?? null,
|
|
73
77
|
insecure_transport: new URL(config.endpoints.online).protocol !== 'wss:',
|
|
74
78
|
}
|
|
75
79
|
}
|
|
@@ -81,7 +85,14 @@ export class DuetSettings {
|
|
|
81
85
|
const normalized = normalizeBackendURL(input.backend_url)
|
|
82
86
|
const insecureOrigin = input.allow_insecure_http === true ? new URL(normalized).origin : this.saved?.insecure_origin
|
|
83
87
|
const url = validateBackendURL(normalized, insecureOrigin)
|
|
84
|
-
const next = this.validate({ backend_url: url, insecure_origin: insecureOrigin
|
|
88
|
+
const next = this.validate({ backend_url: url, insecure_origin: insecureOrigin,
|
|
89
|
+
nickname: input.nickname === undefined ? this.saved?.nickname : input.nickname })
|
|
90
|
+
return this.persist(next, input.revision)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async persist(next, revision) {
|
|
94
|
+
if (this.writing) throw new Error('settings_write_in_progress')
|
|
95
|
+
if (revision !== this.revision) throw new Error('settings_revision_conflict')
|
|
85
96
|
this.writing = true
|
|
86
97
|
const temp = `${this.path}.${randomUUID()}.tmp`
|
|
87
98
|
try {
|
|
@@ -93,6 +104,10 @@ export class DuetSettings {
|
|
|
93
104
|
return this.public()
|
|
94
105
|
} finally { this.writing = false; await unlink(temp).catch(() => {}) }
|
|
95
106
|
}
|
|
107
|
+
|
|
108
|
+
async renameNickname(nickname, revision = this.revision) {
|
|
109
|
+
return this.persist({...this.saved, nickname:normalizeNickname(nickname)}, revision)
|
|
110
|
+
}
|
|
96
111
|
}
|
|
97
112
|
|
|
98
113
|
export function settingsWriteAllowed(req, { verifiedLocalIdentity = false } = {}) {
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
const fail = code => { const error = new Error(code); error.code = code; error.status = 409; throw error }
|
|
4
|
+
|
|
5
|
+
/** Bind cancellation to one observed execution, never a later turn in the session. */
|
|
6
|
+
export class StopTasks {
|
|
7
|
+
constructor(cancel) { this.cancel = cancel; this.live = new Map(); this.receipts = new Map() }
|
|
8
|
+
start(sessionId, turn) {
|
|
9
|
+
if (this.live.get(sessionId)?.turn === turn) return
|
|
10
|
+
this.live.set(sessionId, { execution_id: randomUUID(), turn })
|
|
11
|
+
}
|
|
12
|
+
end(sessionId, turn) {
|
|
13
|
+
if (this.live.get(sessionId)?.turn === turn) this.live.delete(sessionId)
|
|
14
|
+
}
|
|
15
|
+
snapshot(sessionId) {
|
|
16
|
+
const execution = this.live.get(sessionId)
|
|
17
|
+
if (!execution) fail('no_running_task')
|
|
18
|
+
return { session_id: sessionId, execution_id: execution.execution_id }
|
|
19
|
+
}
|
|
20
|
+
request(sessionId, executionId, owner) {
|
|
21
|
+
if (!owner) fail('stop_task_owner_required')
|
|
22
|
+
if (typeof executionId !== 'string' || !/^[a-f0-9-]{36}$/.test(executionId)) fail('invalid_execution_id')
|
|
23
|
+
const key = `${owner}:${sessionId}:${executionId}`
|
|
24
|
+
if (this.receipts.has(key)) return this.receipts.get(key)
|
|
25
|
+
if (this.live.get(sessionId)?.execution_id !== executionId) fail('execution_changed')
|
|
26
|
+
// DSH's public Host cancel is synchronous: no await between identity check
|
|
27
|
+
// and cancellation. Do not retry rejected/unknown outcomes automatically.
|
|
28
|
+
const result = this.cancel({ sessionId })
|
|
29
|
+
const pending = Promise.resolve(result).then(value => {
|
|
30
|
+
if (value?.accepted !== true) fail('stop_not_accepted')
|
|
31
|
+
return { accepted: true, session_id: sessionId, execution_id: executionId }
|
|
32
|
+
})
|
|
33
|
+
this.receipts.set(key, pending)
|
|
34
|
+
while (this.receipts.size > 500) this.receipts.delete(this.receipts.keys().next().value)
|
|
35
|
+
return pending
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export const AVATAR_ACTIVITY_PROTOCOL='avatar_activity_v1'
|
|
2
|
+
export const AVATAR_ACTIVITY_HOUR=3600000
|
|
3
|
+
const sizes=['small','medium','large']
|
|
4
|
+
const id=v=>typeof v==='string'&&/^[a-zA-Z0-9_-]{1,64}$/.test(v)
|
|
5
|
+
const finite=(v,min,max)=>Number.isFinite(v)&&v>=min&&v<=max
|
|
6
|
+
const resolution=v=>v&&finite(v.width,1,1000000)&&finite(v.height,1,1000000)?{width:v.width,height:v.height}:null
|
|
7
|
+
export function avatarGeometry(v){
|
|
8
|
+
if(!v||!['desktop_physical','viewport_css'].includes(v.space))return null
|
|
9
|
+
const total=resolution(v.total_resolution),p=v.avatar_position
|
|
10
|
+
if(!total||!p||!finite(p.x,-1000000,1000000)||!finite(p.y,-1000000,1000000)||!resolution(p))return null
|
|
11
|
+
const out={space:v.space,total_resolution:total,avatar_position:{x:p.x,y:p.y,width:p.width,height:p.height}}
|
|
12
|
+
if(v.space==='desktop_physical'){
|
|
13
|
+
if(!v.desktop_origin||!finite(v.desktop_origin.x,-1000000,1000000)||!finite(v.desktop_origin.y,-1000000,1000000)||!finite(v.scale,0.25,16))return null
|
|
14
|
+
out.desktop_origin={x:v.desktop_origin.x,y:v.desktop_origin.y};out.scale=v.scale
|
|
15
|
+
}else{const viewport=resolution(v.viewport_resolution);if(!viewport)return null;out.viewport_resolution=viewport}
|
|
16
|
+
return out
|
|
17
|
+
}
|
|
18
|
+
export function avatarActivity(v){
|
|
19
|
+
if(!v||v.protocol!==AVATAR_ACTIVITY_PROTOCOL||!['avatar.started','avatar.stopped','avatar.hourly'].includes(v.event)||!id(v.event_id)||!id(v.instance_id)||!Number.isSafeInteger(v.sequence)||v.sequence<0||v.sequence>1000000)throw Error('invalid_avatar_activity')
|
|
20
|
+
if(!['web','desktop'].includes(v.presentation)||!sizes.includes(v.size)||!sizes.includes(v.bubble_size)||typeof v.notifications_enabled!=='boolean'||!finite(v.timestamp_ms,0,1e15)||!finite(v.uptime_ms,0,1e12))throw Error('invalid_avatar_activity')
|
|
21
|
+
for(const key of ['pending_count','notification_count'])if(v[key]!==null&&(!Number.isSafeInteger(v[key])||v[key]<0||v[key]>100000))throw Error('invalid_avatar_activity')
|
|
22
|
+
const position=v.position===null?null:avatarGeometry(v.position);if(v.position!==null&&!position)throw Error('invalid_avatar_position')
|
|
23
|
+
const out={protocol:AVATAR_ACTIVITY_PROTOCOL,event:v.event,event_id:v.event_id,instance_id:v.instance_id,sequence:v.sequence,timestamp_ms:v.timestamp_ms,uptime_ms:v.uptime_ms,presentation:v.presentation,size:v.size,bubble_size:v.bubble_size,notifications_enabled:v.notifications_enabled,pending_count:v.pending_count,notification_count:v.notification_count,position}
|
|
24
|
+
if(v.event==='avatar.stopped')out.reason=['disabled','pagehide','unmount','restart','unavailable'].includes(v.reason)?v.reason:'unavailable'
|
|
25
|
+
return out
|
|
26
|
+
}
|
|
27
|
+
export class AvatarActivityClock {
|
|
28
|
+
constructor({snapshot,send,now=Date.now,uuid=()=>crypto.randomUUID()}){Object.assign(this,{snapshot,send,now,uuid});this.active=null}
|
|
29
|
+
start(presentation){if(this.active?.presentation===presentation)return;if(this.active)this.stop('restart');const now=this.now();this.active={id:this.uuid(),presentation,start:now,next:now+AVATAR_ACTIVITY_HOUR,sequence:0};this.emit('avatar.started')}
|
|
30
|
+
emit(event,reason){const a=this.active;if(!a)return;const now=this.now();try{this.send(avatarActivity({...this.snapshot(),protocol:AVATAR_ACTIVITY_PROTOCOL,event,event_id:this.uuid(),instance_id:a.id,sequence:a.sequence++,timestamp_ms:now,uptime_ms:Math.max(0,now-a.start),presentation:a.presentation,reason}))}catch{}}
|
|
31
|
+
tick(){if(this.active&&this.now()>=this.active.next){this.active.next=this.now()+AVATAR_ACTIVITY_HOUR;this.emit('avatar.hourly')}}
|
|
32
|
+
stop(reason){if(!this.active)return;this.emit('avatar.stopped',reason);this.active=null}
|
|
33
|
+
}
|