dsh-duet 0.1.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/HEROICONS-LICENSE.txt +24 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +77 -0
- package/deepseek_harness_duplex_control.patch.yml +3 -0
- package/deepseek_harness_duplex_control_plugin.html +392 -0
- package/deepseek_harness_duplex_control_plugin.mjs +1105 -0
- package/deepseek_harness_duplex_focus_client/lib/client.js +466 -0
- package/deepseek_harness_voice_audio.mjs +135 -0
- package/deepseek_harness_voice_browser.mjs +343 -0
- package/deepseek_harness_voice_catalog.mjs +56 -0
- package/deepseek_harness_voice_composer.mjs +125 -0
- package/deepseek_harness_voice_consent.mjs +63 -0
- package/deepseek_harness_voice_feedback.mjs +48 -0
- package/deepseek_harness_voice_feedback_files.mjs +55 -0
- package/deepseek_harness_voice_feedback_store.mjs +51 -0
- package/deepseek_harness_voice_interactions.mjs +32 -0
- package/deepseek_harness_voice_microphone.mjs +59 -0
- package/deepseek_harness_voice_notices.mjs +54 -0
- package/deepseek_harness_voice_proxy.mjs +223 -0
- package/deepseek_harness_voice_rpc.mjs +104 -0
- package/deepseek_harness_voice_service_info.mjs +45 -0
- package/deepseek_harness_voice_settings.mjs +95 -0
- package/deepseek_harness_voice_shortcuts.mjs +69 -0
- package/deepseek_harness_voice_state.mjs +171 -0
- package/deepseek_harness_voice_trace.mjs +107 -0
- package/deepseek_harness_voice_tutorial.mjs +265 -0
- package/deepseek_harness_voice_tutorial_adapter.mjs +95 -0
- package/deepseek_harness_voice_tutorial_request.mjs +16 -0
- package/package.json +57 -0
- package/tutorial-audio/broadcast.wav +0 -0
- package/tutorial-audio/clear.wav +0 -0
- package/tutorial-audio/edit.wav +0 -0
- package/tutorial-audio/input.wav +0 -0
- package/tutorial-audio/manifest.json +60 -0
- package/tutorial-audio/modes_broadcast.wav +0 -0
- package/tutorial-audio/modes_interaction.wav +0 -0
- package/tutorial-audio/reinput.wav +0 -0
- package/tutorial-audio/send.wav +0 -0
- package/tutorial-audio/switch.wav +0 -0
|
@@ -0,0 +1,1105 @@
|
|
|
1
|
+
/** DeepSeek Harness plugin that exposes the duplex control console on the official WebUI host. */
|
|
2
|
+
|
|
3
|
+
import { readFile } from 'node:fs/promises'
|
|
4
|
+
import { randomUUID } from 'node:crypto'
|
|
5
|
+
import { registerVoiceProxy, voiceConfig } from './deepseek_harness_voice_proxy.mjs'
|
|
6
|
+
import { VoiceSettings, settingsWriteAllowed } from './deepseek_harness_voice_settings.mjs'
|
|
7
|
+
import { ServiceNotices } from './deepseek_harness_voice_notices.mjs'
|
|
8
|
+
import { ServiceInfo } from './deepseek_harness_voice_service_info.mjs'
|
|
9
|
+
import { VoiceTrace } from './deepseek_harness_voice_trace.mjs'
|
|
10
|
+
import { FeedbackService } from './deepseek_harness_voice_feedback_store.mjs'
|
|
11
|
+
import { RemoteFeedback } from './deepseek_harness_voice_feedback_files.mjs'
|
|
12
|
+
import { PLUGIN_VERSION } from './deepseek_harness_voice_state.mjs'
|
|
13
|
+
import { buildSessionCatalog } from './deepseek_harness_voice_catalog.mjs'
|
|
14
|
+
|
|
15
|
+
const ROUTE = '/duplex-control'
|
|
16
|
+
const PAGE_ROUTE = '/duet'
|
|
17
|
+
const MAX_BODY_BYTES = 100_000
|
|
18
|
+
const MAX_JOBS = 500
|
|
19
|
+
const MAX_COMPOSER_REQUESTS = 500
|
|
20
|
+
const COMPOSER_RPC_TIMEOUT_MS = 5_000
|
|
21
|
+
// Long polling refreshes liveness every <=20s even when background timers slow.
|
|
22
|
+
// This remains a finite lease, not a claim that a frozen/closed tab is usable.
|
|
23
|
+
const BROWSER_CLIENT_STALE_SECONDS = 45
|
|
24
|
+
const DUPLEX_RUNTIME_STALE_SECONDS = 3
|
|
25
|
+
const HTML_URL = new URL('./deepseek_harness_duplex_control_plugin.html', import.meta.url)
|
|
26
|
+
|
|
27
|
+
export const name = 'dsh-duet'
|
|
28
|
+
export const inject = [
|
|
29
|
+
'webServer',
|
|
30
|
+
'connection',
|
|
31
|
+
'sessionController',
|
|
32
|
+
'workspaceController',
|
|
33
|
+
'workspaceRegistry',
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
function nowSeconds() {
|
|
37
|
+
return Date.now() / 1000
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function increasedForkTitle(title) {
|
|
41
|
+
const ascii = /^(.*?)\((\d+)\)$/u.exec(title)
|
|
42
|
+
if (ascii?.[1] !== undefined && ascii[2] !== undefined) {
|
|
43
|
+
return `${ascii[1]}(${BigInt(ascii[2]) + 1n})`
|
|
44
|
+
}
|
|
45
|
+
const fullWidth = /^(.*?)((\d+))$/u.exec(title)
|
|
46
|
+
if (fullWidth?.[1] !== undefined && fullWidth[2] !== undefined) {
|
|
47
|
+
return `${fullWidth[1]}(${BigInt(fullWidth[2]) + 1n})`
|
|
48
|
+
}
|
|
49
|
+
return `${title} (1)`
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function publicJob(job) {
|
|
53
|
+
const { turn: _turn, rpcId: _rpcId, ...value } = job
|
|
54
|
+
return { ...value }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function publicComposerRequest(request) {
|
|
58
|
+
return {
|
|
59
|
+
id: request.id,
|
|
60
|
+
sequence: request.sequence,
|
|
61
|
+
type: request.type,
|
|
62
|
+
session_id: request.session_id,
|
|
63
|
+
expected_revision: request.expected_revision,
|
|
64
|
+
expected_hash: request.expected_hash,
|
|
65
|
+
require_focus: request.require_focus,
|
|
66
|
+
overwrite: request.overwrite,
|
|
67
|
+
text: request.text,
|
|
68
|
+
claimed_by: request.claimed_by || null,
|
|
69
|
+
created_at: request.created_at,
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function publicInteraction(interaction) {
|
|
74
|
+
const {
|
|
75
|
+
resolve: _resolve,
|
|
76
|
+
reject: _reject,
|
|
77
|
+
signal: _signal,
|
|
78
|
+
on_abort: _onAbort,
|
|
79
|
+
...value
|
|
80
|
+
} = interaction
|
|
81
|
+
return { ...value }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function codedError(code, message, status = 409) {
|
|
85
|
+
const error = new Error(message)
|
|
86
|
+
error.code = code
|
|
87
|
+
error.status = status
|
|
88
|
+
return error
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function assistantText(event) {
|
|
92
|
+
const content = event?.data?.message?.content
|
|
93
|
+
if (!Array.isArray(content)) return ''
|
|
94
|
+
return content
|
|
95
|
+
.filter(block => block?.type === 'text' && typeof block.text === 'string')
|
|
96
|
+
.map(block => block.text)
|
|
97
|
+
.join('\n')
|
|
98
|
+
.trim()
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function userText(event) {
|
|
102
|
+
const content = event?.data?.content
|
|
103
|
+
if (!Array.isArray(content)) return ''
|
|
104
|
+
return content
|
|
105
|
+
.filter(block => block?.type === 'text' && typeof block.text === 'string')
|
|
106
|
+
.map(block => block.text)
|
|
107
|
+
.join('\n')
|
|
108
|
+
.trim()
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function sendJson(res, status, value) {
|
|
112
|
+
const body = JSON.stringify(value)
|
|
113
|
+
res.writeHead(status, {
|
|
114
|
+
'content-type': 'application/json; charset=utf-8',
|
|
115
|
+
'cache-control': 'no-store',
|
|
116
|
+
'content-length': Buffer.byteLength(body),
|
|
117
|
+
})
|
|
118
|
+
res.end(body)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function sendError(res, status, message) {
|
|
122
|
+
sendJson(res, status, { detail: message })
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function readJson(req) {
|
|
126
|
+
let size = 0
|
|
127
|
+
const chunks = []
|
|
128
|
+
for await (const chunk of req) {
|
|
129
|
+
size += chunk.length
|
|
130
|
+
if (size > MAX_BODY_BYTES) throw new Error('request body is too large')
|
|
131
|
+
chunks.push(chunk)
|
|
132
|
+
}
|
|
133
|
+
if (chunks.length === 0) return {}
|
|
134
|
+
const value = JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
135
|
+
if (value === null || Array.isArray(value) || typeof value !== 'object') {
|
|
136
|
+
throw new Error('request body must be a JSON object')
|
|
137
|
+
}
|
|
138
|
+
return value
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function apply(ctx, options = {}) {
|
|
142
|
+
const jobs = new Map()
|
|
143
|
+
const jobOrder = []
|
|
144
|
+
const composerRequests = new Map()
|
|
145
|
+
const composerPollWaiters = new Set()
|
|
146
|
+
const composerRequestOrder = []
|
|
147
|
+
const currentTurn = new Map()
|
|
148
|
+
const jobByTurn = new Map()
|
|
149
|
+
const pendingInteractions = new Map()
|
|
150
|
+
const browserClients = new Map()
|
|
151
|
+
const focusEpoch = randomUUID()
|
|
152
|
+
let activeSessionId
|
|
153
|
+
let activeSessionInitialized = false
|
|
154
|
+
// A wall-clock baseline keeps browser clients from an older host process
|
|
155
|
+
// compatible: their in-memory lastRevision must never shadow a restarted host.
|
|
156
|
+
let focusRevision = Date.now()
|
|
157
|
+
let completionSequence = 0
|
|
158
|
+
let composerRequestSequence = 0
|
|
159
|
+
let lastDuplexRuntimeSeenAt = 0
|
|
160
|
+
let lastNativeInteractionsSeenAt = -Infinity
|
|
161
|
+
const hostAbort = new AbortController()
|
|
162
|
+
|
|
163
|
+
const voice = voiceConfig()
|
|
164
|
+
const settings = new VoiceSettings(voice, { path: options.settingsPath, debug: options.debug === true || process.env.DUPLEX_CONTROL_DEBUG === '1' })
|
|
165
|
+
Object.assign(voice, settings.effective())
|
|
166
|
+
const audit = new VoiceTrace({ kind: 'host', plugin_version: PLUGIN_VERSION, pid: process.pid },
|
|
167
|
+
{ ...options.traceOptions, secrets: [voice.authorization] })
|
|
168
|
+
ctx.effect(() => () => { void audit.close({ reason: 'plugin_dispose' }) })
|
|
169
|
+
const notices = new ServiceNotices(() => settings.effective())
|
|
170
|
+
const serviceInfo = new ServiceInfo(() => settings.effective())
|
|
171
|
+
const feedbackStore = options.feedbackStore ?? (options.feedbackDisabled ? null : new RemoteFeedback(()=>settings.effective(),{keyPath:options.feedbackIdentityPath}))
|
|
172
|
+
const feedback = new FeedbackService(feedbackStore)
|
|
173
|
+
let voiceProxy
|
|
174
|
+
ctx.effect(() => { voiceProxy = registerVoiceProxy(ctx, voice, feedback); return voiceProxy })
|
|
175
|
+
|
|
176
|
+
ctx.effect(() => () => { hostAbort.abort() })
|
|
177
|
+
|
|
178
|
+
const duplexRuntimeActive = () => (
|
|
179
|
+
nowSeconds() - lastDuplexRuntimeSeenAt <= DUPLEX_RUNTIME_STALE_SECONDS
|
|
180
|
+
)
|
|
181
|
+
// A background tab may throttle its heartbeat. Once the native UI capability
|
|
182
|
+
// is known, never steal its requests again during this Host lifetime.
|
|
183
|
+
const nativeInteractionsActive = () => Number.isFinite(lastNativeInteractionsSeenAt)
|
|
184
|
+
|
|
185
|
+
const rememberInteraction = (interaction) => {
|
|
186
|
+
audit.event('interaction.created', publicInteraction(interaction))
|
|
187
|
+
pendingInteractions.set(interaction.id, interaction)
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const pendingInteraction = (value, signal) => new Promise((resolve, reject) => {
|
|
191
|
+
const interaction = { ...value, resolve, reject, signal, on_abort: undefined }
|
|
192
|
+
if (signal !== undefined) {
|
|
193
|
+
const onAbort = () => {
|
|
194
|
+
if (!pendingInteractions.delete(interaction.id)) return
|
|
195
|
+
audit.event('interaction.aborted', { id: interaction.id, reason: String(signal.reason) })
|
|
196
|
+
reject(signal.reason || codedError('interaction_cancelled', 'Harness interaction cancelled'))
|
|
197
|
+
}
|
|
198
|
+
interaction.on_abort = onAbort
|
|
199
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
200
|
+
}
|
|
201
|
+
rememberInteraction(interaction)
|
|
202
|
+
})
|
|
203
|
+
|
|
204
|
+
const finishInteraction = (interaction, settle) => {
|
|
205
|
+
pendingInteractions.delete(interaction.id)
|
|
206
|
+
if (interaction.signal !== undefined && interaction.on_abort !== undefined) {
|
|
207
|
+
interaction.signal.removeEventListener('abort', interaction.on_abort)
|
|
208
|
+
}
|
|
209
|
+
settle()
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
ctx.on('approval/request', function (request, next) {
|
|
213
|
+
if (!duplexRuntimeActive() || nativeInteractionsActive()) return next()
|
|
214
|
+
// IDs are opaque and URL-safe.
|
|
215
|
+
const id = `approval_${randomUUID().replaceAll('-', '')}`
|
|
216
|
+
return pendingInteraction({
|
|
217
|
+
id,
|
|
218
|
+
kind: 'approval',
|
|
219
|
+
session_id: String(request.agent?.session?.id || activeSessionId || ''),
|
|
220
|
+
approval_id: id.slice('approval_'.length),
|
|
221
|
+
tool_name: String(request.toolName || ''),
|
|
222
|
+
call_id: String(request.callId || ''),
|
|
223
|
+
reason: String(request.reason || ''),
|
|
224
|
+
created_at: nowSeconds(),
|
|
225
|
+
}, request.signal)
|
|
226
|
+
}, { prepend: true })
|
|
227
|
+
|
|
228
|
+
ctx.on('user-questions/request', function (request, next) {
|
|
229
|
+
if (!duplexRuntimeActive() || nativeInteractionsActive()) return next()
|
|
230
|
+
const questions = Array.isArray(request.questions) ? request.questions : []
|
|
231
|
+
const planReview = questions.some(question => question?.intent?.kind === 'plan-review')
|
|
232
|
+
const id = `question_${randomUUID().replaceAll('-', '')}`
|
|
233
|
+
return pendingInteraction({
|
|
234
|
+
id,
|
|
235
|
+
kind: planReview ? 'plan_review' : 'question',
|
|
236
|
+
session_id: String(request.agent?.session?.id || activeSessionId || ''),
|
|
237
|
+
questions,
|
|
238
|
+
created_at: nowSeconds(),
|
|
239
|
+
}, request.signal)
|
|
240
|
+
}, { prepend: true })
|
|
241
|
+
|
|
242
|
+
ctx.effect(() => () => {
|
|
243
|
+
for (const interaction of pendingInteractions.values()) {
|
|
244
|
+
finishInteraction(interaction, () => {
|
|
245
|
+
interaction.reject(codedError('plugin_stopped', 'Duplex control plugin stopped'))
|
|
246
|
+
})
|
|
247
|
+
}
|
|
248
|
+
})
|
|
249
|
+
|
|
250
|
+
const removeComposerRequest = (request) => {
|
|
251
|
+
clearTimeout(request.timer)
|
|
252
|
+
composerRequests.delete(request.id)
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const requestComposer = (type, payload) => new Promise((resolve, reject) => {
|
|
256
|
+
const id = randomUUID().replaceAll('-', '')
|
|
257
|
+
composerRequestSequence += 1
|
|
258
|
+
const request = {
|
|
259
|
+
id,
|
|
260
|
+
sequence: composerRequestSequence,
|
|
261
|
+
type,
|
|
262
|
+
session_id: String(payload.session_id || ''),
|
|
263
|
+
expected_revision: payload.expected_revision,
|
|
264
|
+
expected_hash: payload.expected_hash,
|
|
265
|
+
require_focus: payload.require_focus === true,
|
|
266
|
+
overwrite: type === 'set' && payload.overwrite === true,
|
|
267
|
+
text: payload.text,
|
|
268
|
+
claimed_by: '',
|
|
269
|
+
created_at: nowSeconds(),
|
|
270
|
+
resolve,
|
|
271
|
+
reject,
|
|
272
|
+
timer: undefined,
|
|
273
|
+
}
|
|
274
|
+
request.timer = setTimeout(() => {
|
|
275
|
+
if (!composerRequests.has(id)) return
|
|
276
|
+
removeComposerRequest(request)
|
|
277
|
+
reject(codedError(
|
|
278
|
+
'composer_client_unavailable',
|
|
279
|
+
'没有可用的 DeepSeek Harness 主页面来执行输入框操作',
|
|
280
|
+
503,
|
|
281
|
+
))
|
|
282
|
+
}, COMPOSER_RPC_TIMEOUT_MS)
|
|
283
|
+
composerRequests.set(id, request)
|
|
284
|
+
composerRequestOrder.push(id)
|
|
285
|
+
for (const wake of [...composerPollWaiters]) wake()
|
|
286
|
+
while (composerRequestOrder.length > MAX_COMPOSER_REQUESTS) {
|
|
287
|
+
const staleId = composerRequestOrder.shift()
|
|
288
|
+
const stale = composerRequests.get(staleId)
|
|
289
|
+
if (stale === undefined) continue
|
|
290
|
+
removeComposerRequest(stale)
|
|
291
|
+
stale.reject(codedError('composer_request_evicted', '输入框请求队列已满', 503))
|
|
292
|
+
}
|
|
293
|
+
})
|
|
294
|
+
|
|
295
|
+
const listSessions = async ({forCatalog = false} = {}) => {
|
|
296
|
+
const { items } = await ctx.sessionController.list({}, hostAbort.signal)
|
|
297
|
+
const catalog = buildSessionCatalog(items, {
|
|
298
|
+
archivedIds: ctx.workspaceRegistry.archivedSessionIds,
|
|
299
|
+
workspaces: ctx.workspaceRegistry.list?.() || [],
|
|
300
|
+
activeId: activeSessionId,
|
|
301
|
+
includeBlank: !forCatalog,
|
|
302
|
+
})
|
|
303
|
+
if (!activeSessionInitialized) {
|
|
304
|
+
activeSessionId = catalog[0]?.session_id
|
|
305
|
+
activeSessionInitialized = true
|
|
306
|
+
}
|
|
307
|
+
return catalog.map(item => ({...item, active:item.session_id === activeSessionId}))
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const rememberJob = (job) => {
|
|
311
|
+
jobs.set(job.id, job)
|
|
312
|
+
jobOrder.push(job.id)
|
|
313
|
+
while (jobOrder.length > MAX_JOBS) jobs.delete(jobOrder.shift())
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const enqueueTask = async (sessionId, task, origin = 'duplex_control') => {
|
|
317
|
+
const normalizedTask = String(task || '')
|
|
318
|
+
if (!normalizedTask.trim()) throw codedError('empty_task', 'Harness task is empty', 400)
|
|
319
|
+
const id = randomUUID().replaceAll('-', '')
|
|
320
|
+
const job = {
|
|
321
|
+
id,
|
|
322
|
+
origin,
|
|
323
|
+
session_id: sessionId,
|
|
324
|
+
task: normalizedTask,
|
|
325
|
+
status: 'queued',
|
|
326
|
+
result: '',
|
|
327
|
+
error: '',
|
|
328
|
+
created_at: nowSeconds(),
|
|
329
|
+
started_at: null,
|
|
330
|
+
completed_at: null,
|
|
331
|
+
completion_seq: null,
|
|
332
|
+
turn: undefined,
|
|
333
|
+
rpcId: `duplex-job-${id}`,
|
|
334
|
+
}
|
|
335
|
+
rememberJob(job)
|
|
336
|
+
try {
|
|
337
|
+
await ctx.sessionController.prompt({
|
|
338
|
+
requestId: job.rpcId,
|
|
339
|
+
sessionId,
|
|
340
|
+
mode: 'queue',
|
|
341
|
+
content: [{ type: 'text', text: normalizedTask }],
|
|
342
|
+
}, hostAbort.signal)
|
|
343
|
+
} catch (error) {
|
|
344
|
+
job.status = 'failed'
|
|
345
|
+
job.error = error instanceof Error ? error.message : String(error)
|
|
346
|
+
job.completed_at = nowSeconds()
|
|
347
|
+
completionSequence += 1
|
|
348
|
+
job.completion_seq = completionSequence
|
|
349
|
+
throw error
|
|
350
|
+
}
|
|
351
|
+
selectSession(sessionId)
|
|
352
|
+
return job
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const selectSession = (sessionId, focus = true) => {
|
|
356
|
+
if (activeSessionInitialized && activeSessionId === sessionId) return false
|
|
357
|
+
activeSessionId = sessionId
|
|
358
|
+
activeSessionInitialized = true
|
|
359
|
+
if (focus) focusRevision += 1
|
|
360
|
+
return true
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const browserClientStatus = () => {
|
|
364
|
+
const now = nowSeconds()
|
|
365
|
+
for (const [clientId, client] of browserClients) {
|
|
366
|
+
if (now - client.last_seen_at > BROWSER_CLIENT_STALE_SECONDS) {
|
|
367
|
+
browserClients.delete(clientId)
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
const liveClients = [...browserClients.values()]
|
|
371
|
+
.sort((left, right) => right.last_seen_at - left.last_seen_at)
|
|
372
|
+
const latest = liveClients[0]
|
|
373
|
+
const browserSessionId = latest?.session_id || null
|
|
374
|
+
return {
|
|
375
|
+
browser_client_connected: liveClients.length > 0,
|
|
376
|
+
browser_client_count: liveClients.length,
|
|
377
|
+
browser_focus_session_id: browserSessionId,
|
|
378
|
+
browser_focus_matches: liveClients.length > 0
|
|
379
|
+
&& browserSessionId !== null
|
|
380
|
+
&& browserSessionId === (activeSessionId || null),
|
|
381
|
+
browser_client_last_seen_at: latest?.last_seen_at || null,
|
|
382
|
+
browser_client_visibility: latest?.visibility || null,
|
|
383
|
+
browser_client_stale_after_seconds: BROWSER_CLIENT_STALE_SECONDS,
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const turnKey = (sessionId, turn) => `${sessionId}:${String(turn)}`
|
|
388
|
+
|
|
389
|
+
const completeJob = (job, event) => {
|
|
390
|
+
job.completed_at = nowSeconds()
|
|
391
|
+
if (event.data.reason?.kind === 'aborted') {
|
|
392
|
+
job.status = 'failed'
|
|
393
|
+
job.error = 'Harness turn was aborted, not completed'
|
|
394
|
+
} else if (event.data.reason?.kind === 'error') {
|
|
395
|
+
job.status = 'failed'
|
|
396
|
+
job.error = String(event.data.reason.error || 'Harness turn failed')
|
|
397
|
+
} else if (!job.result) {
|
|
398
|
+
job.status = 'failed'
|
|
399
|
+
job.error = `Harness turn ended without a final text response (${event.data.reason?.kind || 'unknown'})`
|
|
400
|
+
} else {
|
|
401
|
+
job.status = 'succeeded'
|
|
402
|
+
}
|
|
403
|
+
completionSequence += 1
|
|
404
|
+
job.completion_seq = completionSequence
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
ctx.on('session/event', (session, event) => {
|
|
408
|
+
if (['turn/start', 'turn/end', 'user/message'].includes(event.type)) {
|
|
409
|
+
audit.event('dsh.session_event', { session_id: session.id, event })
|
|
410
|
+
}
|
|
411
|
+
const sessionId = String(session.id)
|
|
412
|
+
if (event.type === 'turn/start') {
|
|
413
|
+
currentTurn.set(sessionId, event.data.turn)
|
|
414
|
+
return
|
|
415
|
+
}
|
|
416
|
+
if (event.type === 'user/message') {
|
|
417
|
+
const rpcId = event.data?.source?.rpcId
|
|
418
|
+
const turn = currentTurn.get(sessionId)
|
|
419
|
+
if (turn === undefined) return
|
|
420
|
+
let job
|
|
421
|
+
if (typeof rpcId === 'string' && rpcId.startsWith('duplex-job-')) {
|
|
422
|
+
job = jobs.get(rpcId.slice('duplex-job-'.length))
|
|
423
|
+
} else if (event.data?.source?.kind === 'user') {
|
|
424
|
+
const key = turnKey(sessionId, turn)
|
|
425
|
+
const existing = jobByTurn.get(key)
|
|
426
|
+
job = existing === undefined ? undefined : jobs.get(existing)
|
|
427
|
+
if (job === undefined) {
|
|
428
|
+
const id = randomUUID().replaceAll('-', '')
|
|
429
|
+
job = {
|
|
430
|
+
id,
|
|
431
|
+
origin: 'harness_ui',
|
|
432
|
+
session_id: sessionId,
|
|
433
|
+
task: userText(event),
|
|
434
|
+
status: 'running',
|
|
435
|
+
result: '',
|
|
436
|
+
error: '',
|
|
437
|
+
created_at: event.time / 1000,
|
|
438
|
+
started_at: nowSeconds(),
|
|
439
|
+
completed_at: null,
|
|
440
|
+
completion_seq: null,
|
|
441
|
+
turn,
|
|
442
|
+
rpcId: typeof rpcId === 'string' ? rpcId : '',
|
|
443
|
+
}
|
|
444
|
+
rememberJob(job)
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
if (job === undefined) return
|
|
448
|
+
job.turn = turn
|
|
449
|
+
job.status = 'running'
|
|
450
|
+
job.started_at ??= nowSeconds()
|
|
451
|
+
jobByTurn.set(turnKey(sessionId, turn), job.id)
|
|
452
|
+
return
|
|
453
|
+
}
|
|
454
|
+
if (event.type === 'assistant/message') {
|
|
455
|
+
const id = jobByTurn.get(turnKey(sessionId, event.data.turn))
|
|
456
|
+
const job = id === undefined ? undefined : jobs.get(id)
|
|
457
|
+
if (job === undefined) return
|
|
458
|
+
const text = assistantText(event)
|
|
459
|
+
if (text) job.result = text
|
|
460
|
+
return
|
|
461
|
+
}
|
|
462
|
+
if (event.type !== 'turn/end') return
|
|
463
|
+
const key = turnKey(sessionId, event.data.turn)
|
|
464
|
+
const id = jobByTurn.get(key)
|
|
465
|
+
const job = id === undefined ? undefined : jobs.get(id)
|
|
466
|
+
currentTurn.delete(sessionId)
|
|
467
|
+
jobByTurn.delete(key)
|
|
468
|
+
if (job === undefined) return
|
|
469
|
+
completeJob(job, event)
|
|
470
|
+
})
|
|
471
|
+
|
|
472
|
+
const handleApi = async (req, res, pathname) => {
|
|
473
|
+
if(req.method==='POST' && pathname===`${ROUTE}/api/feedback`){
|
|
474
|
+
if(!settingsWriteAllowed(req)){sendError(res,403,'same-origin feedback request required');return}
|
|
475
|
+
try {sendJson(res,201,await feedback.submit(req,await readJson(req)))}
|
|
476
|
+
catch(error){
|
|
477
|
+
const code=String(error.message||'')
|
|
478
|
+
const invalid=code.startsWith('invalid_feedback')
|
|
479
|
+
sendJson(res,invalid?400:code==='feedback_session_unavailable'?409:503,
|
|
480
|
+
{persisted:false,error_code:invalid?code:code==='feedback_session_unavailable'?code:'feedback_unavailable'})
|
|
481
|
+
}
|
|
482
|
+
return
|
|
483
|
+
}
|
|
484
|
+
if (req.method === 'POST' && pathname === `${ROUTE}/api/voice/diagnostic`) {
|
|
485
|
+
if (!settingsWriteAllowed(req)) { sendError(res, 403, 'same-origin diagnostic request required'); return }
|
|
486
|
+
const body = await readJson(req)
|
|
487
|
+
if (JSON.stringify(body).length > 24000) { sendError(res, 413, 'diagnostic too large'); return }
|
|
488
|
+
audit.event('client.diagnostic', body)
|
|
489
|
+
sendJson(res, 200, { ok: true, logging: audit.snapshot() }); return
|
|
490
|
+
}
|
|
491
|
+
if (req.method === 'GET' && pathname === `${ROUTE}/api/voice/service-info`) {
|
|
492
|
+
sendJson(res, 200, await serviceInfo.get())
|
|
493
|
+
return
|
|
494
|
+
}
|
|
495
|
+
if (req.method === 'GET' && pathname === `${ROUTE}/api/voice/config`) {
|
|
496
|
+
try{feedbackStore?.ensureIdentity?.(req,res)}catch{sendJson(res,503,{error_code:'feedback_identity_unavailable'});return}
|
|
497
|
+
sendJson(res, 200, { ...settings.public(), plugin_version: PLUGIN_VERSION, feedback_enabled: feedback.enabled, connection: voiceProxy?.snapshot?.() || { online: 0, tts_only: 0 } })
|
|
498
|
+
return
|
|
499
|
+
}
|
|
500
|
+
if (req.method === 'PUT' && pathname === `${ROUTE}/api/voice/config`) {
|
|
501
|
+
if (!settingsWriteAllowed(req)) { sendError(res, 403, 'same-origin settings request required'); return }
|
|
502
|
+
try {
|
|
503
|
+
const result = await settings.save(await readJson(req))
|
|
504
|
+
Object.assign(voice, settings.effective())
|
|
505
|
+
feedback.sessions.clear() // Never send an old rating to a newly selected backend.
|
|
506
|
+
audit.secrets.push(voice.authorization)
|
|
507
|
+
notices.invalidate()
|
|
508
|
+
serviceInfo.invalidate()
|
|
509
|
+
voiceProxy?.closeConnections?.('voice_settings_changed')
|
|
510
|
+
sendJson(res, 200, result)
|
|
511
|
+
} catch (error) { sendError(res, 400, error.message) }
|
|
512
|
+
return
|
|
513
|
+
}
|
|
514
|
+
if (req.method === 'GET' && pathname === `${ROUTE}/api/announcements`) {
|
|
515
|
+
sendJson(res, 200, await notices.get())
|
|
516
|
+
return
|
|
517
|
+
}
|
|
518
|
+
if (req.method === 'GET' && pathname === `${ROUTE}/api/health`) {
|
|
519
|
+
sendJson(res, 200, {
|
|
520
|
+
ok: true,
|
|
521
|
+
service: 'deepseek-harness-duplex-control-plugin',
|
|
522
|
+
active_session_id: activeSessionId || null,
|
|
523
|
+
focus_epoch: focusEpoch,
|
|
524
|
+
focus_revision: focusRevision,
|
|
525
|
+
job_count: jobs.size,
|
|
526
|
+
result_cursor: completionSequence,
|
|
527
|
+
composer_rpc_version: 'harness_browser_composer_rpc_v1',
|
|
528
|
+
plugin_version: PLUGIN_VERSION,
|
|
529
|
+
diagnostic_logging: audit.snapshot(),
|
|
530
|
+
direct_state_version: 'harness_direct_v7_input_status_edit_recovery',
|
|
531
|
+
composer_state_fields: ['session_name', 'text'],
|
|
532
|
+
pending_composer_request_count: composerRequests.size,
|
|
533
|
+
interaction_rpc_version: 'harness_pending_interaction_rpc_v1',
|
|
534
|
+
pending_interaction_count: pendingInteractions.size,
|
|
535
|
+
duplex_runtime_connected: duplexRuntimeActive(),
|
|
536
|
+
duplex_runtime_last_seen_at: lastDuplexRuntimeSeenAt || null,
|
|
537
|
+
duplex_runtime_stale_after_seconds: DUPLEX_RUNTIME_STALE_SECONDS,
|
|
538
|
+
browser_client_status_version: 'harness_browser_client_status_v1',
|
|
539
|
+
...browserClientStatus(),
|
|
540
|
+
})
|
|
541
|
+
return
|
|
542
|
+
}
|
|
543
|
+
if (req.method === 'GET' && pathname === `${ROUTE}/api/interactions`) {
|
|
544
|
+
const interactions = [...pendingInteractions.values()]
|
|
545
|
+
.sort((left, right) => left.created_at - right.created_at)
|
|
546
|
+
.map(publicInteraction)
|
|
547
|
+
sendJson(res, 200, { interactions })
|
|
548
|
+
return
|
|
549
|
+
}
|
|
550
|
+
const respondInteraction = pathname.match(
|
|
551
|
+
new RegExp(`^${ROUTE}/api/interactions/([^/]+)/respond$`),
|
|
552
|
+
)
|
|
553
|
+
if (req.method === 'POST' && respondInteraction !== null) {
|
|
554
|
+
const interactionId = decodeURIComponent(respondInteraction[1])
|
|
555
|
+
const interaction = pendingInteractions.get(interactionId)
|
|
556
|
+
if (interaction === undefined) {
|
|
557
|
+
sendError(res, 404, 'pending interaction not found')
|
|
558
|
+
return
|
|
559
|
+
}
|
|
560
|
+
const body = await readJson(req)
|
|
561
|
+
audit.event('interaction.respond', { interaction_id: interactionId, body })
|
|
562
|
+
let result
|
|
563
|
+
if (interaction.kind === 'approval') {
|
|
564
|
+
const outcome = String(body.outcome || '')
|
|
565
|
+
if (!['allowed-once', 'rejected'].includes(outcome)) {
|
|
566
|
+
sendError(res, 400, 'approval outcome must be allowed-once or rejected')
|
|
567
|
+
return
|
|
568
|
+
}
|
|
569
|
+
result = {
|
|
570
|
+
ok: true,
|
|
571
|
+
value: {
|
|
572
|
+
sessionId: interaction.session_id,
|
|
573
|
+
approvalId: interaction.approval_id,
|
|
574
|
+
outcome,
|
|
575
|
+
},
|
|
576
|
+
}
|
|
577
|
+
} else if (body.cancelled === true) {
|
|
578
|
+
result = {
|
|
579
|
+
ok: false,
|
|
580
|
+
error: { code: 'cancelled', message: 'cancelled by user', details: {} },
|
|
581
|
+
}
|
|
582
|
+
} else {
|
|
583
|
+
if (!Array.isArray(body.answers)) {
|
|
584
|
+
sendError(res, 400, 'question answers must be an array')
|
|
585
|
+
return
|
|
586
|
+
}
|
|
587
|
+
result = {
|
|
588
|
+
ok: true,
|
|
589
|
+
value: {
|
|
590
|
+
sessionId: interaction.session_id,
|
|
591
|
+
answer: { answers: body.answers },
|
|
592
|
+
},
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
if (interaction.kind === 'approval') {
|
|
596
|
+
finishInteraction(interaction, () => { interaction.resolve(result.value.outcome) })
|
|
597
|
+
} else if (body.cancelled === true) {
|
|
598
|
+
finishInteraction(interaction, () => {
|
|
599
|
+
interaction.reject(codedError('ASK_CANCELLED', 'cancelled by user'))
|
|
600
|
+
})
|
|
601
|
+
} else {
|
|
602
|
+
finishInteraction(interaction, () => {
|
|
603
|
+
interaction.resolve(result.value.answer)
|
|
604
|
+
})
|
|
605
|
+
}
|
|
606
|
+
sendJson(res, 200, { ok: true, interaction_id: interactionId })
|
|
607
|
+
return
|
|
608
|
+
}
|
|
609
|
+
if (req.method === 'GET' && pathname === `${ROUTE}/api/focus`) {
|
|
610
|
+
sendJson(res, 200, {
|
|
611
|
+
session_id: activeSessionId || null,
|
|
612
|
+
focus_epoch: focusEpoch,
|
|
613
|
+
revision: focusRevision,
|
|
614
|
+
})
|
|
615
|
+
return
|
|
616
|
+
}
|
|
617
|
+
if (req.method === 'POST' && pathname === `${ROUTE}/api/browser-clients/heartbeat`) {
|
|
618
|
+
const body = await readJson(req)
|
|
619
|
+
const clientId = String(body.client_id || '').trim()
|
|
620
|
+
if (!clientId) {
|
|
621
|
+
sendError(res, 400, 'client_id is required')
|
|
622
|
+
return
|
|
623
|
+
}
|
|
624
|
+
const sessionId = body.session_id === null || body.session_id === undefined
|
|
625
|
+
? null
|
|
626
|
+
: String(body.session_id)
|
|
627
|
+
browserClients.set(clientId, {
|
|
628
|
+
client_id: clientId,
|
|
629
|
+
session_id: sessionId,
|
|
630
|
+
visibility: String(body.visibility || 'unknown'),
|
|
631
|
+
last_seen_at: nowSeconds(),
|
|
632
|
+
})
|
|
633
|
+
sendJson(res, 200, {
|
|
634
|
+
ok: true,
|
|
635
|
+
focus_epoch: focusEpoch,
|
|
636
|
+
focus_revision: focusRevision,
|
|
637
|
+
active_session_id: activeSessionId || null,
|
|
638
|
+
})
|
|
639
|
+
return
|
|
640
|
+
}
|
|
641
|
+
if (req.method === 'GET' && pathname === `${ROUTE}/api/composer/requests`) {
|
|
642
|
+
const url = new URL(req.url || '/', 'http://localhost')
|
|
643
|
+
const clientId = url.searchParams.get('client_id')
|
|
644
|
+
const touch = () => {
|
|
645
|
+
if (!clientId) return
|
|
646
|
+
browserClients.set(clientId, {
|
|
647
|
+
client_id: clientId,
|
|
648
|
+
session_id: url.searchParams.get('session_id') || null,
|
|
649
|
+
visibility: url.searchParams.get('visibility') || 'unknown',
|
|
650
|
+
last_seen_at: nowSeconds(),
|
|
651
|
+
})
|
|
652
|
+
}
|
|
653
|
+
touch()
|
|
654
|
+
if (url.searchParams.get('wait') === '1'
|
|
655
|
+
&& ![...composerRequests.values()].some(request => !request.claimed_by)) {
|
|
656
|
+
await new Promise(resolve => {
|
|
657
|
+
let timer
|
|
658
|
+
const done = () => {
|
|
659
|
+
clearTimeout(timer)
|
|
660
|
+
composerPollWaiters.delete(done)
|
|
661
|
+
res.off?.('close', done)
|
|
662
|
+
hostAbort.signal.removeEventListener('abort', done)
|
|
663
|
+
resolve()
|
|
664
|
+
}
|
|
665
|
+
composerPollWaiters.add(done)
|
|
666
|
+
res.once?.('close', done)
|
|
667
|
+
hostAbort.signal.addEventListener('abort', done, { once: true })
|
|
668
|
+
timer = setTimeout(done, 20_000)
|
|
669
|
+
})
|
|
670
|
+
}
|
|
671
|
+
if (res.destroyed || hostAbort.signal.aborted) return
|
|
672
|
+
const pending = composerRequestOrder
|
|
673
|
+
.map(id => composerRequests.get(id))
|
|
674
|
+
.filter(request => request !== undefined && !request.claimed_by)
|
|
675
|
+
.slice(0, 20)
|
|
676
|
+
.map(publicComposerRequest)
|
|
677
|
+
sendJson(res, 200, {
|
|
678
|
+
requests: pending,
|
|
679
|
+
next_cursor: composerRequestSequence,
|
|
680
|
+
long_poll_supported: true,
|
|
681
|
+
})
|
|
682
|
+
return
|
|
683
|
+
}
|
|
684
|
+
const claimComposer = pathname.match(
|
|
685
|
+
new RegExp(`^${ROUTE}/api/composer/requests/([^/]+)/claim$`),
|
|
686
|
+
)
|
|
687
|
+
if (req.method === 'POST' && claimComposer !== null) {
|
|
688
|
+
const requestId = decodeURIComponent(claimComposer[1])
|
|
689
|
+
const body = await readJson(req)
|
|
690
|
+
const clientId = String(body.client_id || '').trim()
|
|
691
|
+
if (!clientId) {
|
|
692
|
+
sendError(res, 400, 'client_id is required')
|
|
693
|
+
return
|
|
694
|
+
}
|
|
695
|
+
const request = composerRequests.get(requestId)
|
|
696
|
+
if (request === undefined) {
|
|
697
|
+
sendError(res, 404, 'composer request not found')
|
|
698
|
+
return
|
|
699
|
+
}
|
|
700
|
+
if (request.claimed_by && request.claimed_by !== clientId) {
|
|
701
|
+
sendError(res, 409, 'composer request is already claimed')
|
|
702
|
+
return
|
|
703
|
+
}
|
|
704
|
+
request.claimed_by = clientId
|
|
705
|
+
sendJson(res, 200, { request: publicComposerRequest(request) })
|
|
706
|
+
return
|
|
707
|
+
}
|
|
708
|
+
const completeComposer = pathname.match(
|
|
709
|
+
new RegExp(`^${ROUTE}/api/composer/requests/([^/]+)/complete$`),
|
|
710
|
+
)
|
|
711
|
+
if (req.method === 'POST' && completeComposer !== null) {
|
|
712
|
+
const requestId = decodeURIComponent(completeComposer[1])
|
|
713
|
+
const body = await readJson(req)
|
|
714
|
+
const clientId = String(body.client_id || '').trim()
|
|
715
|
+
const request = composerRequests.get(requestId)
|
|
716
|
+
if (request === undefined) {
|
|
717
|
+
sendError(res, 404, 'composer request not found')
|
|
718
|
+
return
|
|
719
|
+
}
|
|
720
|
+
if (!clientId || request.claimed_by !== clientId) {
|
|
721
|
+
sendError(res, 409, 'composer request is not owned by this client')
|
|
722
|
+
return
|
|
723
|
+
}
|
|
724
|
+
removeComposerRequest(request)
|
|
725
|
+
if (body.ok) {
|
|
726
|
+
request.resolve(body.composer)
|
|
727
|
+
} else {
|
|
728
|
+
request.reject(codedError(
|
|
729
|
+
String(body.error_code || 'composer_operation_failed'),
|
|
730
|
+
String(body.error || 'Harness composer operation failed'),
|
|
731
|
+
Number(body.status || 409),
|
|
732
|
+
))
|
|
733
|
+
}
|
|
734
|
+
sendJson(res, 200, { ok: true })
|
|
735
|
+
return
|
|
736
|
+
}
|
|
737
|
+
if (req.method === 'POST' && pathname === `${ROUTE}/api/focus`) {
|
|
738
|
+
const body = await readJson(req)
|
|
739
|
+
const sessionId = body.session_id === null || body.session_id === undefined
|
|
740
|
+
? undefined
|
|
741
|
+
: String(body.session_id)
|
|
742
|
+
if (sessionId !== undefined) {
|
|
743
|
+
const sessions = await listSessions()
|
|
744
|
+
if (!sessions.some(session => session.session_id === sessionId)) {
|
|
745
|
+
sendError(res, 404, 'Harness session not found')
|
|
746
|
+
return
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
selectSession(sessionId)
|
|
750
|
+
sendJson(res, 200, {
|
|
751
|
+
ok: true,
|
|
752
|
+
active_session_id: activeSessionId || null,
|
|
753
|
+
focus_epoch: focusEpoch,
|
|
754
|
+
focus_revision: focusRevision,
|
|
755
|
+
})
|
|
756
|
+
return
|
|
757
|
+
}
|
|
758
|
+
if (req.method === 'GET' && pathname === `${ROUTE}/api/sessions`) {
|
|
759
|
+
sendJson(res, 200, { sessions: await listSessions({forCatalog:true}) })
|
|
760
|
+
return
|
|
761
|
+
}
|
|
762
|
+
const composer = pathname.match(new RegExp(`^${ROUTE}/api/sessions/([^/]+)/composer$`))
|
|
763
|
+
if (composer !== null && ['GET', 'PUT'].includes(req.method)) {
|
|
764
|
+
const sessionId = decodeURIComponent(composer[1])
|
|
765
|
+
const sessions = await listSessions()
|
|
766
|
+
if (!sessions.some(session => session.session_id === sessionId)) {
|
|
767
|
+
sendError(res, 404, 'Harness session not found')
|
|
768
|
+
return
|
|
769
|
+
}
|
|
770
|
+
if (req.method === 'GET') {
|
|
771
|
+
const requireFocus = new URL(req.url, 'http://localhost').searchParams.get('require_focus') === 'true'
|
|
772
|
+
if (requireFocus && sessionId !== activeSessionId) {
|
|
773
|
+
throw codedError('focus_conflict', '当前聚焦会话已变化,请重新查询输入框')
|
|
774
|
+
}
|
|
775
|
+
const state = await requestComposer('get', { session_id: sessionId, require_focus: requireFocus })
|
|
776
|
+
if (requireFocus && sessionId !== activeSessionId) {
|
|
777
|
+
throw codedError('focus_conflict', '当前聚焦会话已变化,请重新查询输入框')
|
|
778
|
+
}
|
|
779
|
+
sendJson(res, 200, { composer: {
|
|
780
|
+
...state,
|
|
781
|
+
...(requireFocus ? { session_name: sessions.find(item => item.session_id === sessionId)?.label || '' } : {}),
|
|
782
|
+
} })
|
|
783
|
+
return
|
|
784
|
+
}
|
|
785
|
+
const body = await readJson(req)
|
|
786
|
+
if (body.overwrite !== true && (!Number.isInteger(body.expected_revision) || body.expected_revision < 0)) {
|
|
787
|
+
sendError(res, 400, 'expected_revision must be a non-negative integer')
|
|
788
|
+
return
|
|
789
|
+
}
|
|
790
|
+
if (body.overwrite !== true && !/^[0-9a-f]{64}$/u.test(String(body.expected_hash || ''))) {
|
|
791
|
+
sendError(res, 400, 'expected_hash must be a lowercase SHA256 digest')
|
|
792
|
+
return
|
|
793
|
+
}
|
|
794
|
+
if (typeof body.text !== 'string') {
|
|
795
|
+
sendError(res, 400, 'composer text must be a string')
|
|
796
|
+
return
|
|
797
|
+
}
|
|
798
|
+
if (body.require_focus === true && sessionId !== activeSessionId) {
|
|
799
|
+
throw codedError('focus_conflict', '当前聚焦会话已变化,请重新查询输入框')
|
|
800
|
+
}
|
|
801
|
+
const state = await requestComposer('set', {
|
|
802
|
+
session_id: sessionId,
|
|
803
|
+
expected_revision: body.expected_revision,
|
|
804
|
+
expected_hash: body.expected_hash,
|
|
805
|
+
text: body.text,
|
|
806
|
+
require_focus: body.require_focus,
|
|
807
|
+
overwrite: body.overwrite === true,
|
|
808
|
+
})
|
|
809
|
+
sendJson(res, 200, { composer: state })
|
|
810
|
+
return
|
|
811
|
+
}
|
|
812
|
+
const submitComposer = pathname.match(
|
|
813
|
+
new RegExp(`^${ROUTE}/api/sessions/([^/]+)/composer/submit$`),
|
|
814
|
+
)
|
|
815
|
+
if (req.method === 'POST' && submitComposer !== null) {
|
|
816
|
+
const sessionId = decodeURIComponent(submitComposer[1])
|
|
817
|
+
const body = await readJson(req)
|
|
818
|
+
const expectedRevision = body.expected_revision
|
|
819
|
+
const expectedHash = String(body.expected_hash || '')
|
|
820
|
+
if (!Number.isInteger(expectedRevision) || expectedRevision < 0) {
|
|
821
|
+
sendError(res, 400, 'expected_revision must be a non-negative integer')
|
|
822
|
+
return
|
|
823
|
+
}
|
|
824
|
+
if (!/^[0-9a-f]{64}$/u.test(expectedHash)) {
|
|
825
|
+
sendError(res, 400, 'expected_hash must be a lowercase SHA256 digest')
|
|
826
|
+
return
|
|
827
|
+
}
|
|
828
|
+
const sessions = await listSessions()
|
|
829
|
+
if (!sessions.some(session => session.session_id === sessionId)) {
|
|
830
|
+
sendError(res, 404, 'Harness session not found')
|
|
831
|
+
return
|
|
832
|
+
}
|
|
833
|
+
const consumed = await requestComposer('consume', {
|
|
834
|
+
session_id: sessionId,
|
|
835
|
+
expected_revision: expectedRevision,
|
|
836
|
+
expected_hash: expectedHash,
|
|
837
|
+
})
|
|
838
|
+
if (
|
|
839
|
+
consumed.consumed_revision !== expectedRevision
|
|
840
|
+
|| consumed.consumed_hash !== expectedHash
|
|
841
|
+
) {
|
|
842
|
+
throw codedError('draft_conflict', '输入框已被修改,请确认最新内容后重试')
|
|
843
|
+
}
|
|
844
|
+
const task = String(consumed.consumed_text || '')
|
|
845
|
+
if (!task.trim()) throw codedError('empty_draft', '当前输入框为空,不能发送', 400)
|
|
846
|
+
let job
|
|
847
|
+
try {
|
|
848
|
+
job = await enqueueTask(sessionId, task)
|
|
849
|
+
} catch (error) {
|
|
850
|
+
try {
|
|
851
|
+
await requestComposer('set', {
|
|
852
|
+
session_id: sessionId,
|
|
853
|
+
expected_revision: consumed.revision,
|
|
854
|
+
expected_hash: consumed.hash,
|
|
855
|
+
text: task,
|
|
856
|
+
})
|
|
857
|
+
} catch (restoreError) {
|
|
858
|
+
error.restore_error = {
|
|
859
|
+
code: String(restoreError?.code || 'composer_restore_failed'),
|
|
860
|
+
message: restoreError instanceof Error ? restoreError.message : String(restoreError),
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
throw error
|
|
864
|
+
}
|
|
865
|
+
sendJson(res, 202, {
|
|
866
|
+
job: publicJob(job),
|
|
867
|
+
requirement: {
|
|
868
|
+
revision: expectedRevision,
|
|
869
|
+
hash: expectedHash,
|
|
870
|
+
state: 'submitted',
|
|
871
|
+
},
|
|
872
|
+
composer: consumed,
|
|
873
|
+
})
|
|
874
|
+
return
|
|
875
|
+
}
|
|
876
|
+
if (req.method === 'POST' && pathname === `${ROUTE}/api/sessions`) {
|
|
877
|
+
const body = await readJson(req)
|
|
878
|
+
const name = String(body.name || '').trim()
|
|
879
|
+
const cwd = String(body.cwd || process.cwd()).trim()
|
|
880
|
+
// Current DSH only enables the blank-session composer for a session
|
|
881
|
+
// owned by a registered workspace. cwd alone creates an orphan session.
|
|
882
|
+
let workspaceId
|
|
883
|
+
if (typeof ctx.workspaceController.create === 'function') {
|
|
884
|
+
const resolved = await ctx.workspaceController.create({ path: cwd })
|
|
885
|
+
workspaceId = resolved.workspace?.workspaceId
|
|
886
|
+
if (typeof workspaceId !== 'string' || !workspaceId) {
|
|
887
|
+
throw codedError('workspace_resolution_failed', 'DSH did not resolve a workspace', 502)
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
const created = await ctx.sessionController.create(workspaceId ? { workspaceId } : { cwd })
|
|
891
|
+
selectSession(created.sessionId)
|
|
892
|
+
if (name) {
|
|
893
|
+
await ctx.sessionController.rename({ sessionId: created.sessionId, title: name })
|
|
894
|
+
}
|
|
895
|
+
sendJson(res, 201, { session: { session_id: created.sessionId, label: name || created.sessionId, active: true } })
|
|
896
|
+
return
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
const activate = pathname.match(new RegExp(`^${ROUTE}/api/sessions/([^/]+)/activate$`))
|
|
900
|
+
if (req.method === 'POST' && activate !== null) {
|
|
901
|
+
const sessionId = decodeURIComponent(activate[1])
|
|
902
|
+
const sessions = await listSessions()
|
|
903
|
+
if (!sessions.some(session => session.session_id === sessionId)) {
|
|
904
|
+
sendError(res, 404, 'Harness session not found')
|
|
905
|
+
return
|
|
906
|
+
}
|
|
907
|
+
selectSession(sessionId)
|
|
908
|
+
sendJson(res, 200, {
|
|
909
|
+
ok: true,
|
|
910
|
+
active_session_id: sessionId,
|
|
911
|
+
focus_epoch: focusEpoch,
|
|
912
|
+
focus_revision: focusRevision,
|
|
913
|
+
})
|
|
914
|
+
return
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
const rename = pathname.match(new RegExp(`^${ROUTE}/api/sessions/([^/]+)/rename$`))
|
|
918
|
+
if (req.method === 'POST' && rename !== null) {
|
|
919
|
+
const sessionId = decodeURIComponent(rename[1])
|
|
920
|
+
const body = await readJson(req)
|
|
921
|
+
const title = String(body.title || '').trim()
|
|
922
|
+
if (!title) {
|
|
923
|
+
sendError(res, 400, 'Harness session title is empty')
|
|
924
|
+
return
|
|
925
|
+
}
|
|
926
|
+
const sessions = await listSessions()
|
|
927
|
+
if (!sessions.some(session => session.session_id === sessionId)) {
|
|
928
|
+
sendError(res, 404, 'Harness session not found')
|
|
929
|
+
return
|
|
930
|
+
}
|
|
931
|
+
const result = await ctx.sessionController.rename({ sessionId, title })
|
|
932
|
+
sendJson(res, 200, {
|
|
933
|
+
ok: true,
|
|
934
|
+
session: { session_id: sessionId, label: result.title },
|
|
935
|
+
})
|
|
936
|
+
return
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
const fork = pathname.match(new RegExp(`^${ROUTE}/api/sessions/([^/]+)/fork$`))
|
|
940
|
+
if (req.method === 'POST' && fork !== null) {
|
|
941
|
+
const sessionId = decodeURIComponent(fork[1])
|
|
942
|
+
const sessions = await listSessions()
|
|
943
|
+
const source = sessions.find(session => session.session_id === sessionId)
|
|
944
|
+
if (source === undefined) {
|
|
945
|
+
sendError(res, 404, 'Harness session not found')
|
|
946
|
+
return
|
|
947
|
+
}
|
|
948
|
+
let created
|
|
949
|
+
try {
|
|
950
|
+
created = await ctx.sessionController.fork({ sessionId })
|
|
951
|
+
} catch (error) {
|
|
952
|
+
if (error?.code === 'session/fork-unavailable') {
|
|
953
|
+
throw codedError(error.code, '当前会话还没有可分叉的完整轮次,请等一轮完成后再分叉')
|
|
954
|
+
}
|
|
955
|
+
throw error
|
|
956
|
+
}
|
|
957
|
+
const title = increasedForkTitle(source.label)
|
|
958
|
+
const renamed = await ctx.sessionController.rename({
|
|
959
|
+
sessionId: created.sessionId,
|
|
960
|
+
title,
|
|
961
|
+
})
|
|
962
|
+
selectSession(created.sessionId)
|
|
963
|
+
sendJson(res, 201, {
|
|
964
|
+
ok: true,
|
|
965
|
+
session: {
|
|
966
|
+
session_id: created.sessionId,
|
|
967
|
+
label: renamed.title,
|
|
968
|
+
active: true,
|
|
969
|
+
parent_session_id: sessionId,
|
|
970
|
+
},
|
|
971
|
+
focus_revision: focusRevision,
|
|
972
|
+
})
|
|
973
|
+
return
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
const archive = pathname.match(new RegExp(`^${ROUTE}/api/sessions/([^/]+)/archive$`))
|
|
977
|
+
if (req.method === 'POST' && archive !== null) {
|
|
978
|
+
const sessionId = decodeURIComponent(archive[1])
|
|
979
|
+
const sessions = await listSessions()
|
|
980
|
+
if (!sessions.some(session => session.session_id === sessionId)) {
|
|
981
|
+
sendError(res, 404, 'Harness session not found')
|
|
982
|
+
return
|
|
983
|
+
}
|
|
984
|
+
const wasActive = activeSessionId === sessionId
|
|
985
|
+
const result = await ctx.workspaceController.archiveSession({ sessionId })
|
|
986
|
+
if (wasActive) {
|
|
987
|
+
const remaining = await listSessions()
|
|
988
|
+
selectSession(remaining[0]?.session_id)
|
|
989
|
+
}
|
|
990
|
+
sendJson(res, 200, {
|
|
991
|
+
ok: true,
|
|
992
|
+
archived_session_id: sessionId,
|
|
993
|
+
active_session_id: activeSessionId || null,
|
|
994
|
+
focus_revision: focusRevision,
|
|
995
|
+
archived_session_count: result.archivedSessionIds.length,
|
|
996
|
+
})
|
|
997
|
+
return
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
const submit = pathname.match(new RegExp(`^${ROUTE}/api/sessions/([^/]+)/tasks$`))
|
|
1001
|
+
if (req.method === 'POST' && submit !== null) {
|
|
1002
|
+
const sessionId = decodeURIComponent(submit[1])
|
|
1003
|
+
const body = await readJson(req)
|
|
1004
|
+
const task = String(body.task || '').trim()
|
|
1005
|
+
if (!task) {
|
|
1006
|
+
sendError(res, 400, 'Harness task is empty')
|
|
1007
|
+
return
|
|
1008
|
+
}
|
|
1009
|
+
const job = await enqueueTask(sessionId, task)
|
|
1010
|
+
sendJson(res, 202, { job: publicJob(job) })
|
|
1011
|
+
return
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
if (req.method === 'GET' && pathname === `${ROUTE}/api/jobs`) {
|
|
1015
|
+
const values = jobOrder.slice().reverse().map(id => publicJob(jobs.get(id))).filter(Boolean)
|
|
1016
|
+
sendJson(res, 200, { jobs: values })
|
|
1017
|
+
return
|
|
1018
|
+
}
|
|
1019
|
+
if (req.method === 'GET' && pathname === `${ROUTE}/api/results`) {
|
|
1020
|
+
const url = new URL(req.url || '/', 'http://localhost')
|
|
1021
|
+
const after = Math.max(0, Number.parseInt(url.searchParams.get('after') || '0', 10) || 0)
|
|
1022
|
+
const limit = Math.max(1, Math.min(200, Number.parseInt(url.searchParams.get('limit') || '100', 10) || 100))
|
|
1023
|
+
const completed = jobOrder
|
|
1024
|
+
.map(id => jobs.get(id))
|
|
1025
|
+
.filter(job => job?.completion_seq > after)
|
|
1026
|
+
.sort((left, right) => left.completion_seq - right.completion_seq)
|
|
1027
|
+
const selected = completed.slice(0, limit)
|
|
1028
|
+
const nextCursor = selected.length === 0 ? after : selected[selected.length - 1].completion_seq
|
|
1029
|
+
sendJson(res, 200, {
|
|
1030
|
+
results: selected.map(publicJob),
|
|
1031
|
+
next_cursor: nextCursor,
|
|
1032
|
+
current_cursor: completionSequence,
|
|
1033
|
+
has_more: completed.length > selected.length,
|
|
1034
|
+
})
|
|
1035
|
+
return
|
|
1036
|
+
}
|
|
1037
|
+
const getJob = pathname.match(new RegExp(`^${ROUTE}/api/jobs/([^/]+)$`))
|
|
1038
|
+
if (req.method === 'GET' && getJob !== null) {
|
|
1039
|
+
const job = jobs.get(decodeURIComponent(getJob[1]))
|
|
1040
|
+
if (job === undefined) {
|
|
1041
|
+
sendError(res, 404, 'job not found')
|
|
1042
|
+
return
|
|
1043
|
+
}
|
|
1044
|
+
sendJson(res, 200, { job: publicJob(job) })
|
|
1045
|
+
return
|
|
1046
|
+
}
|
|
1047
|
+
sendError(res, 404, 'not found')
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
const handler = async (req, res) => {
|
|
1051
|
+
const pathname = new URL(req.url || '/', 'http://localhost').pathname
|
|
1052
|
+
try {
|
|
1053
|
+
if ([PAGE_ROUTE, `${PAGE_ROUTE}/`, ROUTE, `${ROUTE}/`, `${ROUTE}/api/voice/config`, `${ROUTE}/api/voice/service-info`, `${ROUTE}/api/voice/diagnostic`, `${ROUTE}/api/announcements`].includes(pathname)) {
|
|
1054
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
1055
|
+
if (rejection) { sendError(res, rejection, '请先打开并登录 DSH 主页面'); return }
|
|
1056
|
+
}
|
|
1057
|
+
const tutorialAudio = pathname.match(/^\/duplex-control\/tutorial-audio\/(modes_broadcast|modes_interaction|broadcast|input|edit|clear|reinput|send|switch)\.wav$/)
|
|
1058
|
+
if (req.method === 'GET' && tutorialAudio) {
|
|
1059
|
+
const rejection = ctx.connection.requestRejection(req)
|
|
1060
|
+
if (rejection) { sendError(res, rejection, '请先打开并登录 DSH 主页面'); return }
|
|
1061
|
+
const body = await readFile(new URL(`./tutorial-audio/${tutorialAudio[1]}.wav`, import.meta.url))
|
|
1062
|
+
res.writeHead(200, { 'content-type': 'audio/wav', 'cache-control': 'private, max-age=3600', 'content-length': body.length })
|
|
1063
|
+
res.end(body)
|
|
1064
|
+
return
|
|
1065
|
+
}
|
|
1066
|
+
const asset = pathname.match(/^\/duplex-control\/(deepseek_harness_voice_(?:state|audio|microphone|shortcuts|catalog|browser|rpc|composer|interactions|tutorial|tutorial_adapter|tutorial_request|feedback|consent)\.mjs)$/)
|
|
1067
|
+
if (req.method === 'GET' && asset) {
|
|
1068
|
+
const body = await readFile(new URL(`./${asset[1]}`, import.meta.url))
|
|
1069
|
+
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
|
|
1070
|
+
res.end(body)
|
|
1071
|
+
return
|
|
1072
|
+
}
|
|
1073
|
+
if (String(req.headers?.['x-duplex-control-client'] || '').trim()) {
|
|
1074
|
+
lastDuplexRuntimeSeenAt = nowSeconds()
|
|
1075
|
+
}
|
|
1076
|
+
if (req.headers?.['x-duet-native-interactions'] === '1') lastNativeInteractionsSeenAt = nowSeconds()
|
|
1077
|
+
if ((pathname === ROUTE || pathname === `${ROUTE}/`) && req.method === 'GET') {
|
|
1078
|
+
res.writeHead(308, {location: `${PAGE_ROUTE}/`, 'cache-control':'no-store'})
|
|
1079
|
+
res.end()
|
|
1080
|
+
return
|
|
1081
|
+
}
|
|
1082
|
+
if ((pathname === PAGE_ROUTE || pathname === `${PAGE_ROUTE}/`) && req.method === 'GET') {
|
|
1083
|
+
const body = await readFile(HTML_URL)
|
|
1084
|
+
res.writeHead(200, {
|
|
1085
|
+
'content-type': 'text/html; charset=utf-8',
|
|
1086
|
+
'cache-control': 'no-store',
|
|
1087
|
+
'content-length': body.length,
|
|
1088
|
+
})
|
|
1089
|
+
res.end(body)
|
|
1090
|
+
return
|
|
1091
|
+
}
|
|
1092
|
+
await handleApi(req, res, pathname)
|
|
1093
|
+
} catch (error) {
|
|
1094
|
+
audit.event('host.api_error', { method: req.method, path: pathname, message: error.message, stack: error.stack })
|
|
1095
|
+
const status = Number.isInteger(error?.status) ? error.status : 500
|
|
1096
|
+
sendJson(res, status, {
|
|
1097
|
+
detail: error instanceof Error ? error.message : String(error),
|
|
1098
|
+
error_code: String(error?.code || 'internal_error'),
|
|
1099
|
+
})
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: ROUTE, handler }))
|
|
1104
|
+
ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: PAGE_ROUTE, handler }))
|
|
1105
|
+
}
|