@kir_sleeping/dsh-relay 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +150 -2
- package/client.js +144 -0
- package/cordis.patch.yml +4 -0
- package/icon.svg +7 -0
- package/index.js +1323 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/native-dialog.js +278 -0
- package/package.json +53 -4
package/index.js
ADDED
|
@@ -0,0 +1,1323 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 外部任务入口:把本机 HTTP 请求转成 DSH agent 消息。
|
|
3
|
+
*
|
|
4
|
+
* 只做转接,不做权限准入。
|
|
5
|
+
*
|
|
6
|
+
* 所有外部会话都落在插件自己的 workspace 里:用户界面按工作区分组时能一眼分开,
|
|
7
|
+
* 工作区里的会话自动成为可被外部调用的会话,agent 关于外部调用的长期记忆也写在同一处。
|
|
8
|
+
*
|
|
9
|
+
* 端点(前缀可配置,默认 /x/relay):
|
|
10
|
+
* POST /submit 提交任务
|
|
11
|
+
* GET /result/{id} 取结果
|
|
12
|
+
* GET /sessions 列出外部会话
|
|
13
|
+
* GET /health 健康检查
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'
|
|
17
|
+
import { mkdirSync } from 'node:fs'
|
|
18
|
+
import { homedir } from 'node:os'
|
|
19
|
+
import { isAbsolute, join } from 'node:path'
|
|
20
|
+
import { confirm } from './native-dialog.js'
|
|
21
|
+
|
|
22
|
+
export const name = 'relay'
|
|
23
|
+
|
|
24
|
+
export const inject = ['webServer', 'agents', 'sessionQuery', 'workspaceRegistry', 'credentials']
|
|
25
|
+
|
|
26
|
+
/** 会话名与 source 共用的字符集;`~` 被留作 id 分隔符。 */
|
|
27
|
+
const NAME_PATTERN = /^[A-Za-z0-9_-]{1,64}$/u
|
|
28
|
+
|
|
29
|
+
const DEFAULT_TITLE = '外部任务'
|
|
30
|
+
|
|
31
|
+
const MAX_BODY_BYTES = 1024 * 1024
|
|
32
|
+
|
|
33
|
+
/** 凭证记录的 key 前缀。 */
|
|
34
|
+
const SOURCE_PREFIX = 'relay/'
|
|
35
|
+
|
|
36
|
+
const LEVELS = new Set([0, 1, 2, 3])
|
|
37
|
+
|
|
38
|
+
const DEFAULTS = {
|
|
39
|
+
pathPrefix: '/x/relay',
|
|
40
|
+
defaultSession: 'main',
|
|
41
|
+
workspacePath: join(resolveDshHome(), 'relay', 'workspace'),
|
|
42
|
+
workspaceTitle: 'Relay',
|
|
43
|
+
queueLimitMs: 600_000,
|
|
44
|
+
maxWaitMs: 3_600_000,
|
|
45
|
+
resultTtlMs: 86_400_000,
|
|
46
|
+
authTimeoutMs: 60_000,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 带对外错误码的失败,供 HTTP 层映射成具体状态码。 */
|
|
50
|
+
class RelayError extends Error {
|
|
51
|
+
constructor(code, message, status) {
|
|
52
|
+
super(message)
|
|
53
|
+
this.name = 'RelayError'
|
|
54
|
+
this.code = code
|
|
55
|
+
this.status = status
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function apply(ctx, config) {
|
|
60
|
+
const cfg = normalizeConfig(config)
|
|
61
|
+
const prefix = cfg.pathPrefix
|
|
62
|
+
|
|
63
|
+
/** id → 任务。 */
|
|
64
|
+
const tasks = new Map()
|
|
65
|
+
/** message.id → 还在等的任务。 */
|
|
66
|
+
const byMessage = new Map()
|
|
67
|
+
/** 「会话~turn」→ 任务。 */
|
|
68
|
+
const turnIndex = new Map()
|
|
69
|
+
/** 会话 → 创建中的 agent Promise,避免并发重复创建。 */
|
|
70
|
+
const agentCache = new Map()
|
|
71
|
+
/** 本进程见过并确认属于本工作区的会话。 */
|
|
72
|
+
const knownSessions = new Set()
|
|
73
|
+
/** 已向工作区登记过的会话,避免重复写盘。 */
|
|
74
|
+
const attached = new Set()
|
|
75
|
+
/** 插件独占的工作区(懒建立)。 */
|
|
76
|
+
let workspace = null
|
|
77
|
+
/** 弹窗串行链:同一时刻只允许一个系统对话框。 */
|
|
78
|
+
let dialogChain = Promise.resolve()
|
|
79
|
+
/** agent.id → 正在接收增量的任务。chunk 帧不带 turn,只能按 agent 定位。 */
|
|
80
|
+
const streamingByAgent = new Map()
|
|
81
|
+
/** 所有存活定时器,卸载时统一清掉。 */
|
|
82
|
+
const timers = new Set()
|
|
83
|
+
|
|
84
|
+
// ════════════════════════════════════════
|
|
85
|
+
// 定时器
|
|
86
|
+
// ════════════════════════════════════════
|
|
87
|
+
|
|
88
|
+
function later(callback, delay) {
|
|
89
|
+
const timer = setTimeout(() => {
|
|
90
|
+
timers.delete(timer)
|
|
91
|
+
callback()
|
|
92
|
+
}, delay)
|
|
93
|
+
timers.add(timer)
|
|
94
|
+
return timer
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function cancel(timer) {
|
|
98
|
+
if (timer !== null && timer !== undefined) {
|
|
99
|
+
clearTimeout(timer)
|
|
100
|
+
timers.delete(timer)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ════════════════════════════════════════
|
|
105
|
+
// 来源与授权
|
|
106
|
+
// ════════════════════════════════════════
|
|
107
|
+
|
|
108
|
+
function recordKey(source) {
|
|
109
|
+
return `${SOURCE_PREFIX}${source}`
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function decodePayload(record) {
|
|
113
|
+
if (!record || record.kind !== 'grant' || !record.payload || typeof record.payload !== 'object') return {}
|
|
114
|
+
return record.payload
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function readSource(source) {
|
|
118
|
+
try {
|
|
119
|
+
const payload = decodePayload(await ctx.credentials.readRecord(recordKey(source)))
|
|
120
|
+
const level = Number.isInteger(payload.level) && LEVELS.has(payload.level) ? payload.level : 1
|
|
121
|
+
const fingerprint = typeof payload.fingerprint === 'string' ? payload.fingerprint : null
|
|
122
|
+
if (payload.level === undefined && fingerprint === null) return undefined
|
|
123
|
+
return { level, fingerprint }
|
|
124
|
+
} catch {
|
|
125
|
+
return undefined
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function writeSource(source, value) {
|
|
130
|
+
await ctx.credentials.modifyRecord(recordKey(source), async () => ({
|
|
131
|
+
kind: 'grant',
|
|
132
|
+
payload: { fingerprint: value.fingerprint ?? null, level: value.level },
|
|
133
|
+
}))
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function removeSource(source) {
|
|
137
|
+
await ctx.credentials.deleteRecord(recordKey(source))
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function listSources() {
|
|
141
|
+
const rows = []
|
|
142
|
+
for (const entry of await ctx.credentials.listRecords()) {
|
|
143
|
+
const key = String(entry.key)
|
|
144
|
+
if (!key.startsWith(SOURCE_PREFIX)) continue
|
|
145
|
+
const source = key.slice(SOURCE_PREFIX.length)
|
|
146
|
+
const payload = decodePayload(await ctx.credentials.readRecord(key))
|
|
147
|
+
rows.push({
|
|
148
|
+
source,
|
|
149
|
+
level: Number.isInteger(payload.level) && LEVELS.has(payload.level) ? payload.level : 1,
|
|
150
|
+
hasFingerprint: typeof payload.fingerprint === 'string',
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
return rows.sort((left, right) => left.source.localeCompare(right.source))
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function newFingerprint() {
|
|
157
|
+
return randomBytes(32).toString('base64url')
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function sameSecret(expected, given) {
|
|
161
|
+
if (typeof expected !== 'string' || typeof given !== 'string') return false
|
|
162
|
+
const left = Buffer.from(expected, 'utf8')
|
|
163
|
+
const right = Buffer.from(given, 'utf8')
|
|
164
|
+
if (left.length !== right.length) return false
|
|
165
|
+
return timingSafeEqual(left, right)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function askUser(message, options = {}) {
|
|
169
|
+
const run = dialogChain.then(() => confirm({
|
|
170
|
+
title: 'Relay',
|
|
171
|
+
message,
|
|
172
|
+
detail: typeof options.detail === 'string' ? options.detail : '',
|
|
173
|
+
timeoutMs: Number.isFinite(options.timeoutMs) ? options.timeoutMs : cfg.authTimeoutMs,
|
|
174
|
+
}))
|
|
175
|
+
dialogChain = run.then(() => undefined, () => undefined)
|
|
176
|
+
return run
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function dialogFailure(answer) {
|
|
180
|
+
if (answer.reason === 'unavailable') {
|
|
181
|
+
return { ok: false, status: 503, code: 'ERR_AUTH_UNAVAILABLE', message: '主机上没有可用的确认窗口。' }
|
|
182
|
+
}
|
|
183
|
+
return { ok: false, status: 504, code: 'ERR_AUTH_TIMEOUT', message: '等待用户确认超时。' }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function enroll(source) {
|
|
187
|
+
const existing = await readSource(source)
|
|
188
|
+
if (existing && existing.level === 0) {
|
|
189
|
+
return { ok: false, status: 403, code: 'ERR_ACCESS_DENIED', message: '这个来源处于禁止名单。' }
|
|
190
|
+
}
|
|
191
|
+
if (existing && existing.fingerprint !== null) {
|
|
192
|
+
return { ok: false, status: 409, code: 'ERR_SOURCE_EXISTS', message: '这个来源已经接过入了。' }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const answer = await askUser(
|
|
196
|
+
`应用「${source}」请求接入 Relay,是否允许?\n\n允许后它可以向这个 agent 提交任务。你之后可以在「设置 → 外部应用」里调整它的权限级别。`,
|
|
197
|
+
)
|
|
198
|
+
if (answer.reason !== 'answered') return dialogFailure(answer)
|
|
199
|
+
if (!answer.allowed) {
|
|
200
|
+
await writeSource(source, { fingerprint: null, level: 0 })
|
|
201
|
+
return { ok: false, status: 403, code: 'ERR_ACCESS_DENIED', message: '用户拒绝了这个来源。' }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const fingerprint = newFingerprint()
|
|
205
|
+
await writeSource(source, { fingerprint, level: 1 })
|
|
206
|
+
return { ok: true, data: { source, fingerprint, level: 1 } }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function verifyCredential(source, given) {
|
|
210
|
+
const record = await readSource(source)
|
|
211
|
+
if (!record || record.fingerprint === null) return { ok: false, record: null }
|
|
212
|
+
if (!sameSecret(record.fingerprint, given)) return { ok: false, record: null }
|
|
213
|
+
return { ok: true, record }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* 验完身份后决定这条消息要不要再问一次用户。
|
|
218
|
+
*
|
|
219
|
+
* trigger 表示谁发起的,approved 表示这次调用是否被允许发生。两者独立:
|
|
220
|
+
* 用户放行一次,不等于这句话是用户说的。后台发起的消息无论如何都不会被
|
|
221
|
+
* 标记成用户发言——包括用户点过允许的情况。
|
|
222
|
+
*/
|
|
223
|
+
async function admitMessage(source, record, trigger, content) {
|
|
224
|
+
if (record.level === 0) {
|
|
225
|
+
return { ok: false, status: 403, code: 'ERR_ACCESS_DENIED', message: '这个来源处于禁止名单。' }
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const needsConfirm = record.level === 1 || (record.level === 2 && trigger !== 'user')
|
|
229
|
+
if (!needsConfirm) return { ok: true, approved: true }
|
|
230
|
+
|
|
231
|
+
const answer = await askUser(
|
|
232
|
+
trigger === 'user'
|
|
233
|
+
? `应用「${source}」请求发送一条消息,是否允许?`
|
|
234
|
+
: `应用「${source}」在后台请求处理一条消息,是否允许?`,
|
|
235
|
+
{ detail: content },
|
|
236
|
+
)
|
|
237
|
+
if (answer.reason !== 'answered') return dialogFailure(answer)
|
|
238
|
+
if (!answer.allowed) {
|
|
239
|
+
return { ok: false, status: 403, code: 'ERR_AUTH_DENIED', message: '用户拒绝了这条消息。' }
|
|
240
|
+
}
|
|
241
|
+
return { ok: true, approved: true }
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// ════════════════════════════════════════
|
|
245
|
+
// 任务结算
|
|
246
|
+
// ════════════════════════════════════════
|
|
247
|
+
|
|
248
|
+
function settle(task, state, event) {
|
|
249
|
+
if (task.state !== 'pending') return
|
|
250
|
+
task.state = state
|
|
251
|
+
task.event = event
|
|
252
|
+
cancel(task.timer)
|
|
253
|
+
task.timer = null
|
|
254
|
+
|
|
255
|
+
if (byMessage.get(task.id) === task) byMessage.delete(task.id)
|
|
256
|
+
if (task.turn !== null && turnIndex.get(turnKey(task.session, task.turn)) === task) {
|
|
257
|
+
turnIndex.delete(turnKey(task.session, task.turn))
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const waiters = Array.from(task.waiters)
|
|
261
|
+
task.waiters.clear()
|
|
262
|
+
for (const waiter of waiters) {
|
|
263
|
+
try {
|
|
264
|
+
waiter()
|
|
265
|
+
} catch {
|
|
266
|
+
/* 等待者自己的异常不能影响结算 */
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
finishStream(task)
|
|
271
|
+
|
|
272
|
+
task.ttl = later(() => {
|
|
273
|
+
if (tasks.get(task.id) === task) tasks.delete(task.id)
|
|
274
|
+
}, cfg.resultTtlMs)
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function settleFromReason(task, reason) {
|
|
278
|
+
const kind = reason && typeof reason.kind === 'string' ? reason.kind : 'unknown'
|
|
279
|
+
const base = {
|
|
280
|
+
id: task.id,
|
|
281
|
+
session: task.session,
|
|
282
|
+
source: task.source,
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (kind === 'completed') {
|
|
286
|
+
settle(task, 'final', {
|
|
287
|
+
...base,
|
|
288
|
+
type: 'final',
|
|
289
|
+
content: task.candidate === null ? '' : task.candidate,
|
|
290
|
+
})
|
|
291
|
+
return
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
if (kind === 'error') {
|
|
295
|
+
const failure = reason.error && typeof reason.error === 'object' ? reason.error : {}
|
|
296
|
+
const code = typeof failure.code === 'string' && failure.code !== 'UNKNOWN' ? failure.code : 'ERR_TASK_FAILED'
|
|
297
|
+
settle(task, 'error', {
|
|
298
|
+
...base,
|
|
299
|
+
type: 'error',
|
|
300
|
+
code,
|
|
301
|
+
message: typeof failure.message === 'string' ? failure.message : '任务执行失败。',
|
|
302
|
+
})
|
|
303
|
+
return
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
settle(task, 'error', {
|
|
307
|
+
...base,
|
|
308
|
+
type: 'error',
|
|
309
|
+
code: `ERR_TURN_${kind.toUpperCase()}`,
|
|
310
|
+
message: `任务未正常结束:${kind}。`,
|
|
311
|
+
})
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function turnKey(session, turn) {
|
|
315
|
+
return `${session}~${turn}`
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// ════════════════════════════════════════
|
|
319
|
+
// 流式输出
|
|
320
|
+
// ════════════════════════════════════════
|
|
321
|
+
|
|
322
|
+
function openStream(res, task, origin, budgetMs) {
|
|
323
|
+
res.statusCode = 200
|
|
324
|
+
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8')
|
|
325
|
+
res.setHeader('Cache-Control', 'no-cache, no-transform')
|
|
326
|
+
res.setHeader('Connection', 'keep-alive')
|
|
327
|
+
res.setHeader('X-Accel-Buffering', 'no')
|
|
328
|
+
if (origin) {
|
|
329
|
+
res.setHeader('Access-Control-Allow-Origin', origin)
|
|
330
|
+
res.setHeader('Vary', 'Origin')
|
|
331
|
+
res.setHeader('Access-Control-Allow-Private-Network', 'true')
|
|
332
|
+
}
|
|
333
|
+
if (typeof res.flushHeaders === 'function') res.flushHeaders()
|
|
334
|
+
|
|
335
|
+
const send = (event, data) => {
|
|
336
|
+
if (res.writableEnded || res.destroyed) return
|
|
337
|
+
res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
task.stream = { send, res }
|
|
341
|
+
send('accepted', { id: task.id, session: task.session, source: task.source })
|
|
342
|
+
|
|
343
|
+
task.streamTimer = later(() => {
|
|
344
|
+
task.streamTimer = null
|
|
345
|
+
if (task.stream) {
|
|
346
|
+
task.stream.send('end', { id: task.id, status: 'timeout' })
|
|
347
|
+
finishStream(task)
|
|
348
|
+
}
|
|
349
|
+
}, Math.max(1, budgetMs))
|
|
350
|
+
|
|
351
|
+
res.on('close', () => {
|
|
352
|
+
if (task.stream && task.stream.res === res) {
|
|
353
|
+
task.stream = null
|
|
354
|
+
if (task.streamTimer !== null) {
|
|
355
|
+
cancel(task.streamTimer)
|
|
356
|
+
task.streamTimer = null
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
})
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function finishStream(task) {
|
|
363
|
+
if (task.streamTimer !== null) {
|
|
364
|
+
cancel(task.streamTimer)
|
|
365
|
+
task.streamTimer = null
|
|
366
|
+
}
|
|
367
|
+
if (!task.stream) return
|
|
368
|
+
const stream = task.stream
|
|
369
|
+
task.stream = null
|
|
370
|
+
if (streamingByAgent.get(task.session) === task) streamingByAgent.delete(task.session)
|
|
371
|
+
|
|
372
|
+
if (task.state === 'final') {
|
|
373
|
+
stream.send('end', { id: task.id, status: 'completed', content: task.event.content })
|
|
374
|
+
} else if (task.state === 'expired') {
|
|
375
|
+
stream.send('error', { id: task.id, code: task.event.code, message: task.event.message })
|
|
376
|
+
stream.send('end', { id: task.id, status: 'expired' })
|
|
377
|
+
} else if (task.state === 'error') {
|
|
378
|
+
stream.send('error', { id: task.id, code: task.event.code, message: task.event.message })
|
|
379
|
+
stream.send('end', { id: task.id, status: 'error' })
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
try {
|
|
383
|
+
if (!stream.res.writableEnded && !stream.res.destroyed) stream.res.end()
|
|
384
|
+
} catch {
|
|
385
|
+
/* 客户端可能已经断开 */
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* 模型增量。
|
|
391
|
+
*
|
|
392
|
+
* chunk 帧不带 turn,只有 start 帧带,所以按 start 绑定、按 end 解绑:
|
|
393
|
+
* 开始那一刻确认这个 turn 属于我们某个在等流式的任务,之后同 agent 的增量就归它。
|
|
394
|
+
*/
|
|
395
|
+
function onAssistantStream(payload) {
|
|
396
|
+
const agent = payload && payload.agent
|
|
397
|
+
const frame = payload && payload.frame
|
|
398
|
+
if (!agent || !frame) return
|
|
399
|
+
|
|
400
|
+
if (frame.type === 'start') {
|
|
401
|
+
const task = turnIndex.get(turnKey(agent.id, frame.turn))
|
|
402
|
+
if (task && task.stream) streamingByAgent.set(agent.id, task)
|
|
403
|
+
else streamingByAgent.delete(agent.id)
|
|
404
|
+
return
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
if (frame.type === 'end') {
|
|
408
|
+
streamingByAgent.delete(agent.id)
|
|
409
|
+
return
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
if (frame.type !== 'chunk' || !frame.chunk) return
|
|
413
|
+
const task = streamingByAgent.get(agent.id)
|
|
414
|
+
if (!task || !task.stream) return
|
|
415
|
+
|
|
416
|
+
const chunk = frame.chunk
|
|
417
|
+
if (chunk.type === 'text-delta' && chunk.text) {
|
|
418
|
+
task.stream.send('content', { id: task.id, text: chunk.text })
|
|
419
|
+
return
|
|
420
|
+
}
|
|
421
|
+
if (chunk.type === 'reasoning-delta' && chunk.text) {
|
|
422
|
+
task.stream.send('reasoning', { id: task.id, text: chunk.text })
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// ════════════════════════════════════════
|
|
427
|
+
// 等待
|
|
428
|
+
// ════════════════════════════════════════
|
|
429
|
+
|
|
430
|
+
function waitFor(task, budgetMs) {
|
|
431
|
+
if (task.state !== 'pending') return Promise.resolve()
|
|
432
|
+
|
|
433
|
+
const budget = Math.max(0, Math.min(budgetMs, cfg.maxWaitMs))
|
|
434
|
+
return new Promise((resolve) => {
|
|
435
|
+
let done = false
|
|
436
|
+
const finish = () => {
|
|
437
|
+
if (done) return
|
|
438
|
+
done = true
|
|
439
|
+
cancel(timer)
|
|
440
|
+
task.waiters.delete(finish)
|
|
441
|
+
resolve()
|
|
442
|
+
}
|
|
443
|
+
const timer = later(() => {
|
|
444
|
+
task.waiters.delete(finish)
|
|
445
|
+
if (done) return
|
|
446
|
+
done = true
|
|
447
|
+
resolve()
|
|
448
|
+
}, budget)
|
|
449
|
+
task.waiters.add(finish)
|
|
450
|
+
})
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// ════════════════════════════════════════
|
|
454
|
+
// 会话
|
|
455
|
+
// ════════════════════════════════════════
|
|
456
|
+
|
|
457
|
+
async function ensureWorkspace() {
|
|
458
|
+
if (workspace) return workspace
|
|
459
|
+
mkdirSync(cfg.workspacePath, { recursive: true })
|
|
460
|
+
workspace = await ctx.workspaceRegistry.create(cfg.workspacePath, cfg.workspaceTitle)
|
|
461
|
+
return workspace
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
async function attach(sessionId) {
|
|
465
|
+
if (attached.has(sessionId)) return
|
|
466
|
+
try {
|
|
467
|
+
await workspace.attachSession(sessionId)
|
|
468
|
+
attached.add(sessionId)
|
|
469
|
+
} catch (error) {
|
|
470
|
+
console.warn(
|
|
471
|
+
`[relay] 会话 ${sessionId} 未能登记到工作区:`,
|
|
472
|
+
error && error.message ? error.message : error,
|
|
473
|
+
)
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
async function readHeader(sessionName) {
|
|
478
|
+
try {
|
|
479
|
+
const snapshot = await ctx.sessionQuery.readSession(sessionName)
|
|
480
|
+
return snapshot && snapshot.session ? snapshot.session : null
|
|
481
|
+
} catch {
|
|
482
|
+
return null
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
function modelOptions() {
|
|
487
|
+
const service = ctx.get('agentDefaultModel')
|
|
488
|
+
if (!service || typeof service.currentSelection !== 'function') return undefined
|
|
489
|
+
const selection = service.currentSelection()
|
|
490
|
+
if (!selection || typeof selection.provider !== 'string' || typeof selection.model !== 'string') return undefined
|
|
491
|
+
const options = { provider: selection.provider, model: selection.model }
|
|
492
|
+
if (typeof selection.reasoningEffort === 'string') options.reasoningEffort = selection.reasoningEffort
|
|
493
|
+
return options
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
async function createOrResume(sessionName) {
|
|
497
|
+
const agentOptions = modelOptions()
|
|
498
|
+
await ensureWorkspace()
|
|
499
|
+
|
|
500
|
+
const header = await readHeader(sessionName)
|
|
501
|
+
if (header) {
|
|
502
|
+
if (header.cwd !== workspace.path) {
|
|
503
|
+
throw new RelayError(
|
|
504
|
+
'ERR_SESSION_OUTSIDE_WORKSPACE',
|
|
505
|
+
`会话「${sessionName}」不在 Relay 工作区(${workspace.path})内,外部入口不能使用它。`,
|
|
506
|
+
409,
|
|
507
|
+
)
|
|
508
|
+
}
|
|
509
|
+
const live = ctx.agents.get(sessionName)
|
|
510
|
+
if (live) {
|
|
511
|
+
await attach(live.id)
|
|
512
|
+
return live
|
|
513
|
+
}
|
|
514
|
+
const handle = await ctx.agents.resume({
|
|
515
|
+
resumeSessionId: sessionName,
|
|
516
|
+
...(agentOptions ? { agentOptions } : {}),
|
|
517
|
+
})
|
|
518
|
+
await attach(handle.agent.id)
|
|
519
|
+
return handle.agent
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const handle = await ctx.agents.create({
|
|
523
|
+
sessionId: sessionName,
|
|
524
|
+
meta: { cwd: workspace.path },
|
|
525
|
+
...(agentOptions ? { agentOptions } : {}),
|
|
526
|
+
})
|
|
527
|
+
try {
|
|
528
|
+
const titles = ctx.get('sessionTitle')
|
|
529
|
+
if (titles && typeof titles.rename === 'function') {
|
|
530
|
+
titles.rename(handle.agent.session, DEFAULT_TITLE)
|
|
531
|
+
}
|
|
532
|
+
} catch {
|
|
533
|
+
/* 标题只是显示,失败不影响入口 */
|
|
534
|
+
}
|
|
535
|
+
await attach(handle.agent.id)
|
|
536
|
+
return handle.agent
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
async function ensureAgent(sessionName) {
|
|
540
|
+
let pending = agentCache.get(sessionName)
|
|
541
|
+
if (!pending) {
|
|
542
|
+
pending = createOrResume(sessionName)
|
|
543
|
+
agentCache.set(sessionName, pending)
|
|
544
|
+
pending.catch(() => {
|
|
545
|
+
if (agentCache.get(sessionName) === pending) agentCache.delete(sessionName)
|
|
546
|
+
})
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
const agent = await pending
|
|
550
|
+
knownSessions.add(sessionName)
|
|
551
|
+
return agent
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
// ════════════════════════════════════════
|
|
555
|
+
// 事件关联
|
|
556
|
+
// ════════════════════════════════════════
|
|
557
|
+
|
|
558
|
+
function onSessionEvent(session, event) {
|
|
559
|
+
if (!event || typeof event.type !== 'string') return
|
|
560
|
+
const sessionId = session.id
|
|
561
|
+
const data = event.data
|
|
562
|
+
if (!data || typeof data !== 'object') return
|
|
563
|
+
|
|
564
|
+
if (event.type === 'assistant/message') {
|
|
565
|
+
const task = turnIndex.get(turnKey(sessionId, data.turn))
|
|
566
|
+
if (!task || task.state !== 'pending') return
|
|
567
|
+
if (!hasToolCall(data.message)) task.candidate = extractText(data.message)
|
|
568
|
+
return
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
if (event.type === 'turn/end') {
|
|
572
|
+
const task = turnIndex.get(turnKey(sessionId, data.turn))
|
|
573
|
+
if (!task) return
|
|
574
|
+
settleFromReason(task, data.reason)
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* 消息被 agent 取走时触发,比 `user/message` 可靠:
|
|
580
|
+
* turn 在进入 step 之前就失败时不会产生 `user/message`,但一定会经过这里。
|
|
581
|
+
*/
|
|
582
|
+
function onInboxClaimed(payload) {
|
|
583
|
+
const agent = payload && payload.agent
|
|
584
|
+
const message = payload && payload.message
|
|
585
|
+
if (!agent || !message || typeof message.id !== 'string') return
|
|
586
|
+
const task = byMessage.get(message.id)
|
|
587
|
+
if (!task || task.state !== 'pending' || task.claimed) return
|
|
588
|
+
task.turn = payload.turn
|
|
589
|
+
task.claimed = true
|
|
590
|
+
turnIndex.set(turnKey(agent.id, payload.turn), task)
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
function onAgentDisposed(payload) {
|
|
594
|
+
const agent = payload && payload.agent
|
|
595
|
+
if (!agent) return
|
|
596
|
+
const sessionId = agent.id
|
|
597
|
+
agentCache.delete(sessionId)
|
|
598
|
+
for (const task of Array.from(tasks.values())) {
|
|
599
|
+
if (task.session !== sessionId || task.state !== 'pending') continue
|
|
600
|
+
settle(task, 'error', {
|
|
601
|
+
id: task.id,
|
|
602
|
+
session: task.session,
|
|
603
|
+
source: task.source,
|
|
604
|
+
type: 'error',
|
|
605
|
+
code: 'ERR_AGENT_DISPOSED',
|
|
606
|
+
message: '会话在任务完成前被关闭。',
|
|
607
|
+
})
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// ════════════════════════════════════════
|
|
612
|
+
// 消息构造
|
|
613
|
+
// ════════════════════════════════════════
|
|
614
|
+
|
|
615
|
+
function serialize(content, source, trigger, approved) {
|
|
616
|
+
return JSON.stringify({ type: 'external_request', source, trigger, approved, content })
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
function hasToolCall(message) {
|
|
620
|
+
const blocks = message && message.content
|
|
621
|
+
return Array.isArray(blocks) && blocks.some((block) => block && block.type === 'tool-call')
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
function extractText(message) {
|
|
625
|
+
const blocks = message && message.content
|
|
626
|
+
if (!Array.isArray(blocks)) return ''
|
|
627
|
+
return blocks
|
|
628
|
+
.filter((block) => block && block.type === 'text' && typeof block.text === 'string')
|
|
629
|
+
.map((block) => block.text)
|
|
630
|
+
.join('')
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// ════════════════════════════════════════
|
|
634
|
+
// id
|
|
635
|
+
// ════════════════════════════════════════
|
|
636
|
+
|
|
637
|
+
function parseId(id) {
|
|
638
|
+
const parts = String(id).split('~')
|
|
639
|
+
if (parts.length !== 3) return null
|
|
640
|
+
const [session, source] = parts
|
|
641
|
+
if (!NAME_PATTERN.test(session) || !NAME_PATTERN.test(source)) return null
|
|
642
|
+
return { session, source }
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
function buildId(session, source) {
|
|
646
|
+
return `${session}~${source}~${randomUUID()}`
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
// ════════════════════════════════════════
|
|
650
|
+
// 日志重建
|
|
651
|
+
// ════════════════════════════════════════
|
|
652
|
+
|
|
653
|
+
async function rebuild(id) {
|
|
654
|
+
const parsed = parseId(id)
|
|
655
|
+
if (!parsed) return null
|
|
656
|
+
|
|
657
|
+
let snapshot
|
|
658
|
+
try {
|
|
659
|
+
snapshot = await ctx.sessionQuery.readSession(parsed.session)
|
|
660
|
+
} catch {
|
|
661
|
+
return null
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
const events = snapshot && Array.isArray(snapshot.events) ? snapshot.events : []
|
|
665
|
+
const index = events.findIndex(
|
|
666
|
+
(event) => event && event.type === 'user/message' && event.data && event.data.id === id,
|
|
667
|
+
)
|
|
668
|
+
if (index < 0) return null
|
|
669
|
+
|
|
670
|
+
let turn = null
|
|
671
|
+
for (let i = index - 1; i >= 0; i -= 1) {
|
|
672
|
+
const event = events[i]
|
|
673
|
+
if (!event) continue
|
|
674
|
+
if (event.type === 'turn/end') return null
|
|
675
|
+
if (event.type === 'turn/start' && event.data) {
|
|
676
|
+
turn = event.data.turn
|
|
677
|
+
break
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
if (turn === null) return null
|
|
681
|
+
|
|
682
|
+
let candidate = null
|
|
683
|
+
let end = null
|
|
684
|
+
for (let i = index + 1; i < events.length; i += 1) {
|
|
685
|
+
const event = events[i]
|
|
686
|
+
if (!event) continue
|
|
687
|
+
if (event.type === 'turn/end' && event.data && event.data.turn === turn) {
|
|
688
|
+
end = event
|
|
689
|
+
break
|
|
690
|
+
}
|
|
691
|
+
if (event.type === 'assistant/message' && event.data && event.data.turn === turn && !hasToolCall(event.data.message)) {
|
|
692
|
+
candidate = extractText(event.data.message)
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
if (!end) return null
|
|
696
|
+
|
|
697
|
+
const task = {
|
|
698
|
+
id,
|
|
699
|
+
session: parsed.session,
|
|
700
|
+
source: parsed.source,
|
|
701
|
+
state: 'pending',
|
|
702
|
+
acceptedAt: typeof end.time === 'number' ? end.time : Date.now(),
|
|
703
|
+
waiters: new Set(),
|
|
704
|
+
candidate,
|
|
705
|
+
claimed: true,
|
|
706
|
+
turn,
|
|
707
|
+
timer: null,
|
|
708
|
+
ttl: null,
|
|
709
|
+
event: null,
|
|
710
|
+
stream: null,
|
|
711
|
+
streamTimer: null,
|
|
712
|
+
}
|
|
713
|
+
settleFromReason(task, end.data.reason)
|
|
714
|
+
return task
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
// ════════════════════════════════════════
|
|
718
|
+
// HTTP 工具
|
|
719
|
+
// ════════════════════════════════════════
|
|
720
|
+
|
|
721
|
+
function allowedOrigin(req) {
|
|
722
|
+
const origin = req.headers.origin
|
|
723
|
+
if (typeof origin !== 'string' || origin === '') return null
|
|
724
|
+
if (origin === 'null') return origin
|
|
725
|
+
try {
|
|
726
|
+
const url = new URL(origin)
|
|
727
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
|
|
728
|
+
const host = url.hostname
|
|
729
|
+
if (host === '127.0.0.1' || host === 'localhost' || host === '::1' || host === '[::1]') return origin
|
|
730
|
+
} catch {
|
|
731
|
+
return null
|
|
732
|
+
}
|
|
733
|
+
return null
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
function sendJson(res, status, body, origin) {
|
|
737
|
+
if (res.writableEnded || res.destroyed) return
|
|
738
|
+
const buffer = Buffer.from(JSON.stringify(body), 'utf8')
|
|
739
|
+
res.statusCode = status
|
|
740
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8')
|
|
741
|
+
res.setHeader('Content-Length', String(buffer.length))
|
|
742
|
+
res.setHeader('Cache-Control', 'no-store')
|
|
743
|
+
if (origin) {
|
|
744
|
+
res.setHeader('Access-Control-Allow-Origin', origin)
|
|
745
|
+
res.setHeader('Vary', 'Origin')
|
|
746
|
+
res.setHeader('Access-Control-Allow-Private-Network', 'true')
|
|
747
|
+
}
|
|
748
|
+
res.end(buffer)
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
function fail(res, status, code, message, origin) {
|
|
752
|
+
sendJson(res, status, { code, message }, origin)
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
function readJson(req) {
|
|
756
|
+
return new Promise((resolve, reject) => {
|
|
757
|
+
const chunks = []
|
|
758
|
+
let size = 0
|
|
759
|
+
req.on('data', (chunk) => {
|
|
760
|
+
size += chunk.length
|
|
761
|
+
if (size > MAX_BODY_BYTES) {
|
|
762
|
+
reject(new Error('request body too large'))
|
|
763
|
+
req.destroy()
|
|
764
|
+
return
|
|
765
|
+
}
|
|
766
|
+
chunks.push(chunk)
|
|
767
|
+
})
|
|
768
|
+
req.on('end', () => {
|
|
769
|
+
const raw = Buffer.concat(chunks).toString('utf8')
|
|
770
|
+
if (raw.trim() === '') {
|
|
771
|
+
resolve(null)
|
|
772
|
+
return
|
|
773
|
+
}
|
|
774
|
+
try {
|
|
775
|
+
resolve(JSON.parse(raw))
|
|
776
|
+
} catch (error) {
|
|
777
|
+
reject(error)
|
|
778
|
+
}
|
|
779
|
+
})
|
|
780
|
+
req.on('error', reject)
|
|
781
|
+
})
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// ════════════════════════════════════════
|
|
785
|
+
// 处理器
|
|
786
|
+
// ════════════════════════════════════════
|
|
787
|
+
|
|
788
|
+
function respondTask(res, task, origin) {
|
|
789
|
+
if (task.state === 'pending') {
|
|
790
|
+
sendJson(res, 202, { id: task.id, status: 'pending' }, origin)
|
|
791
|
+
return
|
|
792
|
+
}
|
|
793
|
+
if (task.state === 'expired') {
|
|
794
|
+
sendJson(res, 410, task.event, origin)
|
|
795
|
+
return
|
|
796
|
+
}
|
|
797
|
+
sendJson(res, 200, task.event, origin)
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
async function readObject(req, res, origin) {
|
|
801
|
+
let body
|
|
802
|
+
try {
|
|
803
|
+
body = await readJson(req)
|
|
804
|
+
} catch {
|
|
805
|
+
fail(res, 400, 'ERR_REQUEST_JSON', '请求体不是合法的 JSON 对象。', origin)
|
|
806
|
+
return undefined
|
|
807
|
+
}
|
|
808
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
809
|
+
fail(res, 400, 'ERR_REQUEST_JSON', '请求体必须是 JSON 对象。', origin)
|
|
810
|
+
return undefined
|
|
811
|
+
}
|
|
812
|
+
return body
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
function validSourceField(value) {
|
|
816
|
+
return typeof value === 'string' && NAME_PATTERN.test(value)
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
const LEVEL_LABEL = { 0: '禁止', 1: '每条消息都确认', 2: '信任已确认标记', 3: '完全信任' }
|
|
820
|
+
|
|
821
|
+
async function handleEnroll(req, res, origin) {
|
|
822
|
+
const body = await readObject(req, res, origin)
|
|
823
|
+
if (body === undefined) return
|
|
824
|
+
if (!validSourceField(body.source)) {
|
|
825
|
+
fail(res, 400, 'ERR_SOURCE', 'source 必须是 1-64 位字母、数字、下划线或连字符。', origin)
|
|
826
|
+
return
|
|
827
|
+
}
|
|
828
|
+
try {
|
|
829
|
+
const result = await enroll(body.source)
|
|
830
|
+
if (!result.ok) {
|
|
831
|
+
fail(res, result.status, result.code, result.message, origin)
|
|
832
|
+
return
|
|
833
|
+
}
|
|
834
|
+
sendJson(res, 200, result.data, origin)
|
|
835
|
+
} catch (error) {
|
|
836
|
+
fail(res, 500, 'ERR_INTERNAL', error && error.message ? String(error.message) : '接入失败。', origin)
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
async function handleFingerprintReset(req, res, origin) {
|
|
841
|
+
const body = await readObject(req, res, origin)
|
|
842
|
+
if (body === undefined) return
|
|
843
|
+
if (!validSourceField(body.source) || typeof body.fingerprint !== 'string') {
|
|
844
|
+
fail(res, 401, 'ERR_INPUT_FINGERPRINT', '需要 source 和当前凭证。', origin)
|
|
845
|
+
return
|
|
846
|
+
}
|
|
847
|
+
try {
|
|
848
|
+
const verified = await verifyCredential(body.source, body.fingerprint.trim())
|
|
849
|
+
if (!verified.ok) {
|
|
850
|
+
fail(res, 401, 'ERR_INPUT_FINGERPRINT', '来源与凭证不匹配。', origin)
|
|
851
|
+
return
|
|
852
|
+
}
|
|
853
|
+
const answer = await askUser(`应用「${body.source}」请求更换凭证,是否允许?`)
|
|
854
|
+
if (answer.reason !== 'answered') {
|
|
855
|
+
const failure = dialogFailure(answer)
|
|
856
|
+
fail(res, failure.status, failure.code, failure.message, origin)
|
|
857
|
+
return
|
|
858
|
+
}
|
|
859
|
+
if (!answer.allowed) {
|
|
860
|
+
fail(res, 403, 'ERR_AUTH_DENIED', '用户拒绝更换凭证。', origin)
|
|
861
|
+
return
|
|
862
|
+
}
|
|
863
|
+
const fingerprint = newFingerprint()
|
|
864
|
+
await writeSource(body.source, { fingerprint, level: verified.record.level })
|
|
865
|
+
sendJson(res, 200, { source: body.source, fingerprint }, origin)
|
|
866
|
+
} catch (error) {
|
|
867
|
+
fail(res, 500, 'ERR_INTERNAL', error && error.message ? String(error.message) : '凭证轮换失败。', origin)
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
async function handleSources(req, res, origin) {
|
|
872
|
+
try {
|
|
873
|
+
sendJson(res, 200, { sources: await listSources() }, origin)
|
|
874
|
+
} catch (error) {
|
|
875
|
+
fail(res, 500, 'ERR_INTERNAL', error && error.message ? String(error.message) : '读取来源失败。', origin)
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
async function handleLevel(req, res, origin) {
|
|
880
|
+
const body = await readObject(req, res, origin)
|
|
881
|
+
if (body === undefined) return
|
|
882
|
+
if (!validSourceField(body.source) || !LEVELS.has(body.level)) {
|
|
883
|
+
fail(res, 400, 'ERR_PERMISSION_LEVEL', 'source 或 level 不合法。', origin)
|
|
884
|
+
return
|
|
885
|
+
}
|
|
886
|
+
try {
|
|
887
|
+
const record = await readSource(body.source)
|
|
888
|
+
if (!record || record.fingerprint === null) {
|
|
889
|
+
fail(res, 409, 'ERR_SOURCE_NOT_ONBOARDED', '这个来源还没有凭证。', origin)
|
|
890
|
+
return
|
|
891
|
+
}
|
|
892
|
+
const loosening = body.level > record.level
|
|
893
|
+
if (loosening) {
|
|
894
|
+
const answer = await askUser(
|
|
895
|
+
`把应用「${body.source}」的权限从「${LEVEL_LABEL[record.level]}」改为「${LEVEL_LABEL[body.level]}」,是否允许?`,
|
|
896
|
+
)
|
|
897
|
+
if (answer.reason !== 'answered') {
|
|
898
|
+
const failure = dialogFailure(answer)
|
|
899
|
+
fail(res, failure.status, failure.code, failure.message, origin)
|
|
900
|
+
return
|
|
901
|
+
}
|
|
902
|
+
if (!answer.allowed) {
|
|
903
|
+
fail(res, 403, 'ERR_AUTH_DENIED', '用户拒绝了这次提权。', origin)
|
|
904
|
+
return
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
await writeSource(body.source, { fingerprint: record.fingerprint, level: body.level })
|
|
908
|
+
sendJson(res, 200, { source: body.source, level: body.level }, origin)
|
|
909
|
+
} catch (error) {
|
|
910
|
+
fail(res, 500, 'ERR_INTERNAL', error && error.message ? String(error.message) : '修改级别失败。', origin)
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
async function handleClear(req, res, origin) {
|
|
915
|
+
const body = await readObject(req, res, origin)
|
|
916
|
+
if (body === undefined) return
|
|
917
|
+
if (!validSourceField(body.source)) {
|
|
918
|
+
fail(res, 400, 'ERR_SOURCE', 'source 不合法。', origin)
|
|
919
|
+
return
|
|
920
|
+
}
|
|
921
|
+
try {
|
|
922
|
+
const record = await readSource(body.source)
|
|
923
|
+
if (!record || record.fingerprint !== null || record.level !== 0) {
|
|
924
|
+
fail(res, 409, 'ERR_SOURCE_NOT_FOUND', '没有可解除的禁止记录。', origin)
|
|
925
|
+
return
|
|
926
|
+
}
|
|
927
|
+
const answer = await askUser(`解除对应用「${body.source}」的禁止,是否允许?`)
|
|
928
|
+
if (answer.reason !== 'answered') {
|
|
929
|
+
const failure = dialogFailure(answer)
|
|
930
|
+
fail(res, failure.status, failure.code, failure.message, origin)
|
|
931
|
+
return
|
|
932
|
+
}
|
|
933
|
+
if (!answer.allowed) {
|
|
934
|
+
fail(res, 403, 'ERR_AUTH_DENIED', '用户取消了操作。', origin)
|
|
935
|
+
return
|
|
936
|
+
}
|
|
937
|
+
await removeSource(body.source)
|
|
938
|
+
sendJson(res, 200, { source: body.source }, origin)
|
|
939
|
+
} catch (error) {
|
|
940
|
+
fail(res, 500, 'ERR_INTERNAL', error && error.message ? String(error.message) : '解除禁止失败。', origin)
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
async function handleDelete(req, res, origin) {
|
|
945
|
+
const body = await readObject(req, res, origin)
|
|
946
|
+
if (body === undefined) return
|
|
947
|
+
if (!validSourceField(body.source)) {
|
|
948
|
+
fail(res, 400, 'ERR_SOURCE', 'source 不合法。', origin)
|
|
949
|
+
return
|
|
950
|
+
}
|
|
951
|
+
try {
|
|
952
|
+
await removeSource(body.source)
|
|
953
|
+
sendJson(res, 200, { source: body.source }, origin)
|
|
954
|
+
} catch (error) {
|
|
955
|
+
fail(res, 500, 'ERR_INTERNAL', error && error.message ? String(error.message) : '删除失败。', origin)
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
async function handleSubmit(req, res, origin) {
|
|
960
|
+
let body
|
|
961
|
+
try {
|
|
962
|
+
body = await readJson(req)
|
|
963
|
+
} catch {
|
|
964
|
+
fail(res, 400, 'ERR_REQUEST_JSON', '请求体不是合法的 JSON 对象。', origin)
|
|
965
|
+
return
|
|
966
|
+
}
|
|
967
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
968
|
+
fail(res, 400, 'ERR_REQUEST_JSON', '请求体必须是 JSON 对象。', origin)
|
|
969
|
+
return
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
const content = body.content
|
|
973
|
+
if (typeof content !== 'string' || content.trim() === '') {
|
|
974
|
+
fail(res, 400, 'ERR_CONTENT', 'content 必须是非空字符串。', origin)
|
|
975
|
+
return
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
const source = body.source === undefined ? 'external' : body.source
|
|
979
|
+
if (typeof source !== 'string' || !NAME_PATTERN.test(source)) {
|
|
980
|
+
fail(res, 400, 'ERR_SOURCE', 'source 必须是 1-64 位字母、数字、下划线或连字符。', origin)
|
|
981
|
+
return
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
const sessionName = body.session === undefined ? cfg.defaultSession : body.session
|
|
985
|
+
if (typeof sessionName !== 'string' || !NAME_PATTERN.test(sessionName)) {
|
|
986
|
+
fail(res, 400, 'ERR_SESSION', 'session 必须是 1-64 位字母、数字、下划线或连字符。', origin)
|
|
987
|
+
return
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
const trigger = body.trigger === undefined ? 'app' : body.trigger
|
|
991
|
+
if (trigger !== 'user' && trigger !== 'app') {
|
|
992
|
+
fail(res, 400, 'ERR_TRIGGER', 'trigger 只能是 user 或 app。', origin)
|
|
993
|
+
return
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
const fingerprint = body.fingerprint
|
|
997
|
+
if (typeof fingerprint !== 'string' || fingerprint.trim() === '') {
|
|
998
|
+
fail(res, 401, 'ERR_INPUT_FINGERPRINT', '缺少凭证,请先通过 POST /fingerprint 申请。', origin)
|
|
999
|
+
return
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
let gate
|
|
1003
|
+
try {
|
|
1004
|
+
const verified = await verifyCredential(source, fingerprint.trim())
|
|
1005
|
+
if (!verified.ok) {
|
|
1006
|
+
fail(res, 401, 'ERR_INPUT_FINGERPRINT', '来源与凭证不匹配。', origin)
|
|
1007
|
+
return
|
|
1008
|
+
}
|
|
1009
|
+
gate = await admitMessage(source, verified.record, trigger, content)
|
|
1010
|
+
} catch (error) {
|
|
1011
|
+
fail(res, 500, 'ERR_INTERNAL', error && error.message ? String(error.message) : '授权检查失败。', origin)
|
|
1012
|
+
return
|
|
1013
|
+
}
|
|
1014
|
+
if (!gate.ok) {
|
|
1015
|
+
fail(res, gate.status, gate.code, gate.message, origin)
|
|
1016
|
+
return
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
let timeoutMs = cfg.maxWaitMs
|
|
1020
|
+
if (body.timeout !== undefined) {
|
|
1021
|
+
const seconds = Number(body.timeout)
|
|
1022
|
+
if (!Number.isFinite(seconds) || seconds <= 0) {
|
|
1023
|
+
fail(res, 400, 'ERR_TIMEOUT', 'timeout 必须是正数秒。', origin)
|
|
1024
|
+
return
|
|
1025
|
+
}
|
|
1026
|
+
timeoutMs = Math.min(seconds * 1000, cfg.maxWaitMs)
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
let agent
|
|
1030
|
+
try {
|
|
1031
|
+
agent = await ensureAgent(sessionName)
|
|
1032
|
+
} catch (error) {
|
|
1033
|
+
const message = error && error.message ? String(error.message) : '会话无法创建或恢复。'
|
|
1034
|
+
const code = error instanceof RelayError ? error.code : 'ERR_SESSION_UNAVAILABLE'
|
|
1035
|
+
const status = error instanceof RelayError ? error.status : 500
|
|
1036
|
+
fail(res, status, code, message, origin)
|
|
1037
|
+
return
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
const id = buildId(sessionName, source)
|
|
1041
|
+
const task = {
|
|
1042
|
+
id,
|
|
1043
|
+
session: sessionName,
|
|
1044
|
+
source,
|
|
1045
|
+
state: 'pending',
|
|
1046
|
+
acceptedAt: Date.now(),
|
|
1047
|
+
waiters: new Set(),
|
|
1048
|
+
candidate: null,
|
|
1049
|
+
claimed: false,
|
|
1050
|
+
turn: null,
|
|
1051
|
+
timer: null,
|
|
1052
|
+
ttl: null,
|
|
1053
|
+
event: null,
|
|
1054
|
+
stream: null,
|
|
1055
|
+
streamTimer: null,
|
|
1056
|
+
}
|
|
1057
|
+
tasks.set(id, task)
|
|
1058
|
+
byMessage.set(id, task)
|
|
1059
|
+
|
|
1060
|
+
const message = {
|
|
1061
|
+
role: 'user',
|
|
1062
|
+
id,
|
|
1063
|
+
content: [{ type: 'text', text: serialize(content, source, trigger, gate.approved) }],
|
|
1064
|
+
source: { kind: 'user' },
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
try {
|
|
1068
|
+
agent.followup(message)
|
|
1069
|
+
} catch (error) {
|
|
1070
|
+
tasks.delete(id)
|
|
1071
|
+
byMessage.delete(id)
|
|
1072
|
+
fail(res, 500, 'ERR_DELIVERY', error && error.message ? String(error.message) : '消息投递失败。', origin)
|
|
1073
|
+
return
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
task.timer = later(() => {
|
|
1077
|
+
if (task.state !== 'pending' || task.claimed) return
|
|
1078
|
+
try {
|
|
1079
|
+
if (agent.inbox && typeof agent.inbox.remove === 'function') agent.inbox.remove(task.id)
|
|
1080
|
+
} catch {
|
|
1081
|
+
/* 撤不掉也要按作废处理 */
|
|
1082
|
+
}
|
|
1083
|
+
settle(task, 'expired', {
|
|
1084
|
+
id: task.id,
|
|
1085
|
+
session: task.session,
|
|
1086
|
+
source: task.source,
|
|
1087
|
+
code: 'ERR_QUEUE_EXPIRED',
|
|
1088
|
+
message: `排队超过 ${Math.round(cfg.queueLimitMs / 1000)} 秒仍未开始执行,已作废。`,
|
|
1089
|
+
})
|
|
1090
|
+
}, cfg.queueLimitMs)
|
|
1091
|
+
|
|
1092
|
+
if (body.stream === true) {
|
|
1093
|
+
openStream(res, task, origin, timeoutMs)
|
|
1094
|
+
return
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
if (body.wait !== true) {
|
|
1098
|
+
sendJson(res, 202, { id, status: 'pending' }, origin)
|
|
1099
|
+
return
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
await waitFor(task, timeoutMs)
|
|
1103
|
+
respondTask(res, task, origin)
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
async function handleResult(res, id, origin) {
|
|
1107
|
+
if (typeof id !== 'string' || id === '') {
|
|
1108
|
+
fail(res, 400, 'ERR_ID', 'id 不能为空。', origin)
|
|
1109
|
+
return
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
let task = tasks.get(id)
|
|
1113
|
+
if (!task) {
|
|
1114
|
+
task = await rebuild(id)
|
|
1115
|
+
if (!task) {
|
|
1116
|
+
fail(res, 404, 'ERR_RESULT_NOT_FOUND', '没有这个任务,或它从未被受理。', origin)
|
|
1117
|
+
return
|
|
1118
|
+
}
|
|
1119
|
+
tasks.set(id, task)
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
respondTask(res, task, origin)
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
function handleOptions(req, res, origin) {
|
|
1126
|
+
if (!origin) {
|
|
1127
|
+
fail(res, 403, 'ERR_ORIGIN', 'Origin not allowed.', null)
|
|
1128
|
+
return
|
|
1129
|
+
}
|
|
1130
|
+
res.statusCode = 204
|
|
1131
|
+
res.setHeader('Access-Control-Allow-Origin', origin)
|
|
1132
|
+
res.setHeader('Vary', 'Origin')
|
|
1133
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
|
|
1134
|
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
|
|
1135
|
+
res.setHeader('Access-Control-Max-Age', '600')
|
|
1136
|
+
res.end()
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
async function handle(req, res) {
|
|
1140
|
+
const origin = allowedOrigin(req)
|
|
1141
|
+
const url = new URL(req.url || '/', 'http://127.0.0.1')
|
|
1142
|
+
const path = url.pathname
|
|
1143
|
+
|
|
1144
|
+
if (path !== prefix && !path.startsWith(`${prefix}/`)) {
|
|
1145
|
+
fail(res, 404, 'ERR_NOT_FOUND', '没有这个路径。', origin)
|
|
1146
|
+
return
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
const rest = path.slice(prefix.length) || '/'
|
|
1150
|
+
|
|
1151
|
+
if (req.method === 'OPTIONS') {
|
|
1152
|
+
handleOptions(req, res, origin)
|
|
1153
|
+
return
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
if (rest === '/health' && req.method === 'GET') {
|
|
1157
|
+
sendJson(res, 200, { ok: true }, origin)
|
|
1158
|
+
return
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
if (rest === '/fingerprint' && req.method === 'POST') {
|
|
1162
|
+
await handleEnroll(req, res, origin)
|
|
1163
|
+
return
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
if (rest === '/fingerprint/reset' && req.method === 'POST') {
|
|
1167
|
+
await handleFingerprintReset(req, res, origin)
|
|
1168
|
+
return
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
if (rest === '/sources' && req.method === 'GET') {
|
|
1172
|
+
await handleSources(req, res, origin)
|
|
1173
|
+
return
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
if (rest === '/sources/level' && req.method === 'POST') {
|
|
1177
|
+
await handleLevel(req, res, origin)
|
|
1178
|
+
return
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
if (rest === '/sources/clear' && req.method === 'POST') {
|
|
1182
|
+
await handleClear(req, res, origin)
|
|
1183
|
+
return
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
if (rest === '/sources/delete' && req.method === 'POST') {
|
|
1187
|
+
await handleDelete(req, res, origin)
|
|
1188
|
+
return
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
if (rest === '/sessions' && req.method === 'GET') {
|
|
1192
|
+
const query = url.searchParams
|
|
1193
|
+
const givenSource = query.get('source')
|
|
1194
|
+
const givenFingerprint = query.get('fingerprint')
|
|
1195
|
+
if (typeof givenSource !== 'string' || typeof givenFingerprint !== 'string') {
|
|
1196
|
+
fail(res, 401, 'ERR_INPUT_FINGERPRINT', '会话列表需要 source 和 fingerprint。', origin)
|
|
1197
|
+
return
|
|
1198
|
+
}
|
|
1199
|
+
const verified = await verifyCredential(givenSource, givenFingerprint)
|
|
1200
|
+
if (!verified.ok || verified.record.level === 0) {
|
|
1201
|
+
fail(res, 401, 'ERR_INPUT_FINGERPRINT', '来源与凭证不匹配。', origin)
|
|
1202
|
+
return
|
|
1203
|
+
}
|
|
1204
|
+
const ids = new Set(knownSessions)
|
|
1205
|
+
try {
|
|
1206
|
+
await ensureWorkspace()
|
|
1207
|
+
for (const id of workspace.sessionIds) ids.add(id)
|
|
1208
|
+
} catch {
|
|
1209
|
+
/* 工作区不可用时退回本进程见过的集合 */
|
|
1210
|
+
}
|
|
1211
|
+
sendJson(res, 200, {
|
|
1212
|
+
sessions: Array.from(ids).sort().map((id) => ({ id })),
|
|
1213
|
+
}, origin)
|
|
1214
|
+
return
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
if (rest === '/submit' && req.method === 'POST') {
|
|
1218
|
+
await handleSubmit(req, res, origin)
|
|
1219
|
+
return
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
if (rest.startsWith('/result/') && req.method === 'GET') {
|
|
1223
|
+
await handleResult(res, decodeURIComponent(rest.slice('/result/'.length)), origin)
|
|
1224
|
+
return
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
fail(res, 404, 'ERR_NOT_FOUND', '没有这个路径。', origin)
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
function route(req, res) {
|
|
1231
|
+
handle(req, res).catch((error) => {
|
|
1232
|
+
fail(res, 500, 'ERR_INTERNAL', error && error.message ? String(error.message) : '内部错误。', allowedOrigin(req))
|
|
1233
|
+
})
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
// ════════════════════════════════════════
|
|
1237
|
+
// 装配
|
|
1238
|
+
// ════════════════════════════════════════
|
|
1239
|
+
|
|
1240
|
+
ctx.on('session/event', onSessionEvent)
|
|
1241
|
+
ctx.on('agent/inbox/claimed', onInboxClaimed)
|
|
1242
|
+
// global: true —— agent 作用域的事件不会自动冒泡到根上下文
|
|
1243
|
+
ctx.on('agent/assistant-stream', onAssistantStream, { global: true })
|
|
1244
|
+
ctx.on('agent/disposed', onAgentDisposed, { global: true })
|
|
1245
|
+
|
|
1246
|
+
ctx.effect(() => {
|
|
1247
|
+
const disposeRoute = ctx.webServer.register({
|
|
1248
|
+
kind: 'prefix',
|
|
1249
|
+
path: prefix,
|
|
1250
|
+
handler: route,
|
|
1251
|
+
})
|
|
1252
|
+
|
|
1253
|
+
return () => {
|
|
1254
|
+
disposeRoute()
|
|
1255
|
+
for (const timer of timers) clearTimeout(timer)
|
|
1256
|
+
timers.clear()
|
|
1257
|
+
tasks.clear()
|
|
1258
|
+
byMessage.clear()
|
|
1259
|
+
turnIndex.clear()
|
|
1260
|
+
agentCache.clear()
|
|
1261
|
+
attached.clear()
|
|
1262
|
+
knownSessions.clear()
|
|
1263
|
+
streamingByAgent.clear()
|
|
1264
|
+
workspace = null
|
|
1265
|
+
}
|
|
1266
|
+
})
|
|
1267
|
+
|
|
1268
|
+
ensureAgent(cfg.defaultSession).catch((error) => {
|
|
1269
|
+
console.error('[relay] 默认外部会话初始化失败:', error)
|
|
1270
|
+
})
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
/** 与 @deepseek-ai/dsh-home-paths 相同的优先级:配置 > $DSH_HOME > ~/.dsh。 */
|
|
1274
|
+
function resolveDshHome() {
|
|
1275
|
+
const configured = process.env.DSH_HOME
|
|
1276
|
+
if (typeof configured === 'string' && configured.trim() !== '') {
|
|
1277
|
+
return expandHome(configured.trim())
|
|
1278
|
+
}
|
|
1279
|
+
return join(homedir(), '.dsh')
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
function expandHome(value) {
|
|
1283
|
+
if (value === '~') return homedir()
|
|
1284
|
+
if (value.startsWith('~/') || value.startsWith('~\\')) return join(homedir(), value.slice(2))
|
|
1285
|
+
return value
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
function normalizeConfig(config) {
|
|
1289
|
+
const source = config && typeof config === 'object' ? config : {}
|
|
1290
|
+
|
|
1291
|
+
let pathPrefix = typeof source.pathPrefix === 'string' && source.pathPrefix.trim() !== ''
|
|
1292
|
+
? source.pathPrefix.trim().replace(/\/+$/u, '')
|
|
1293
|
+
: DEFAULTS.pathPrefix
|
|
1294
|
+
if (!pathPrefix.startsWith('/')) pathPrefix = `/${pathPrefix}`
|
|
1295
|
+
|
|
1296
|
+
const defaultSession = typeof source.defaultSession === 'string' && NAME_PATTERN.test(source.defaultSession)
|
|
1297
|
+
? source.defaultSession
|
|
1298
|
+
: DEFAULTS.defaultSession
|
|
1299
|
+
|
|
1300
|
+
const workspacePath = typeof source.workspacePath === 'string' && isAbsolute(source.workspacePath)
|
|
1301
|
+
? source.workspacePath
|
|
1302
|
+
: DEFAULTS.workspacePath
|
|
1303
|
+
|
|
1304
|
+
const workspaceTitle = typeof source.workspaceTitle === 'string' && source.workspaceTitle.trim() !== ''
|
|
1305
|
+
? source.workspaceTitle.trim()
|
|
1306
|
+
: DEFAULTS.workspaceTitle
|
|
1307
|
+
|
|
1308
|
+
return {
|
|
1309
|
+
pathPrefix,
|
|
1310
|
+
defaultSession,
|
|
1311
|
+
workspacePath,
|
|
1312
|
+
workspaceTitle,
|
|
1313
|
+
queueLimitMs: positive(source.queueLimitMs, DEFAULTS.queueLimitMs),
|
|
1314
|
+
maxWaitMs: positive(source.maxWaitMs, DEFAULTS.maxWaitMs),
|
|
1315
|
+
resultTtlMs: positive(source.resultTtlMs, DEFAULTS.resultTtlMs),
|
|
1316
|
+
authTimeoutMs: positive(source.authTimeoutMs, DEFAULTS.authTimeoutMs),
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
function positive(value, fallback) {
|
|
1321
|
+
const number = Number(value)
|
|
1322
|
+
return Number.isFinite(number) && number > 0 ? number : fallback
|
|
1323
|
+
}
|