dsh-remote-agent 0.0.0-stage → 0.4.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.
Files changed (70) hide show
  1. package/CHANGELOG.md +700 -0
  2. package/CONTRIBUTING.md +358 -0
  3. package/KNOWN-ISSUES.md +601 -0
  4. package/LICENSE +21 -0
  5. package/README.en.md +353 -0
  6. package/README.md +317 -2
  7. package/SECURITY.md +348 -0
  8. package/bin/dsh-remote-relay.js +257 -0
  9. package/bin/dsh-remote-setup.js +440 -0
  10. package/bin//345/217/214/345/207/273/350/277/220/350/241/214-/351/205/215/347/275/256/345/220/221/345/257/274.cmd +28 -0
  11. package/cordis.patch.yml +87 -0
  12. package/deploy/relay-vps/Caddyfile +24 -0
  13. package/deploy/relay-vps/README.md +132 -0
  14. package/deploy/relay-vps/dsh-remote-relay.service +47 -0
  15. package/deploy/relay-vps/nginx.conf +49 -0
  16. package/deploy/relay-vps/relay.env.example +20 -0
  17. package/docs/dispatch-automation-eval.md +140 -0
  18. package/docs/screenshots/panel-main.png +0 -0
  19. package/docs/screenshots/panel-task-detail.png +0 -0
  20. package/docs/verification-agent-e2e.md +425 -0
  21. package/docs/verification-repos-routing-real.md +521 -0
  22. package/docs/verification-resume-real.md +254 -0
  23. package/docs/worker-setup-pitfalls.md +266 -0
  24. package/lib/artifacts.js +451 -0
  25. package/lib/client.js +1752 -0
  26. package/lib/e2e.js +304 -0
  27. package/lib/glob.js +225 -0
  28. package/lib/hub/audit-log.js +161 -0
  29. package/lib/hub/hub-util.js +114 -0
  30. package/lib/hub/index.js +500 -0
  31. package/lib/hub/node-registry.js +943 -0
  32. package/lib/hub/pull-manager.js +781 -0
  33. package/lib/hub/registry-handshake.js +403 -0
  34. package/lib/hub/registry-ingest.js +346 -0
  35. package/lib/hub/relay-link.js +228 -0
  36. package/lib/hub/subagent-provider.js +424 -0
  37. package/lib/hub/templates.js +693 -0
  38. package/lib/hub/tools.js +1059 -0
  39. package/lib/hub/ui-routes.js +856 -0
  40. package/lib/hub/views.js +351 -0
  41. package/lib/identity.js +271 -0
  42. package/lib/index.js +272 -0
  43. package/lib/node/artifact-service.js +231 -0
  44. package/lib/node/diff.js +124 -0
  45. package/lib/node/exec.js +536 -0
  46. package/lib/node/hub-pin.js +71 -0
  47. package/lib/node/index.js +1022 -0
  48. package/lib/node/repos.js +134 -0
  49. package/lib/node/resource.js +63 -0
  50. package/lib/node/runner.js +792 -0
  51. package/lib/node/task-engine.js +712 -0
  52. package/lib/node/task-store.js +273 -0
  53. package/lib/node/transport.js +763 -0
  54. package/lib/pairing.js +186 -0
  55. package/lib/protocol.js +414 -0
  56. package/lib/relay-config.js +317 -0
  57. package/lib/relay.js +732 -0
  58. package/lib/setup-routes.js +313 -0
  59. package/lib/setup.js +522 -0
  60. package/lib/ws.js +466 -0
  61. package/package.json +103 -4
  62. package/profiles/README.md +573 -0
  63. package/profiles/hub.cordis.yml +84 -0
  64. package/profiles/worker.cordis.yml +60 -0
  65. package/scripts/check-doc-drift.mjs +785 -0
  66. package/scripts/check-packaging.mjs +130 -0
  67. package/scripts/diag-inject.mjs +243 -0
  68. package/scripts/e2e-live-check.mjs +181 -0
  69. package/scripts/relay-init.ps1 +286 -0
  70. package/scripts/relay-init.sh +199 -0
@@ -0,0 +1,424 @@
1
+ /**
2
+ * 主机侧 subagent provider(零外部依赖)。
3
+ *
4
+ * 定位:把"远程副机"接成 DSH 的一个**委派目标**。主 agent 用普通的
5
+ * subagent 工具派活,实际上任务跑在另一台电脑上;主 agent 拿到的是
6
+ * 一张交接卡,而不是副机的原始日志。
7
+ *
8
+ * 三条刻意的设计取舍:
9
+ *
10
+ * 1. `inheritsParentContext: false` —— 副机 agent 有独立的模型上下文,
11
+ * 不继承主机会话。这也意味着主机侧不需要(也不应该)把会话内容送出去。
12
+ *
13
+ * 2. `capabilities` 全 false —— provider 不实现 agentOptions / outputSchema /
14
+ * depthLimit / toolFilter / persona。声称支持却忽略参数,比明确不支持更糟:
15
+ * 上层会以为限制生效了。深度与并发由副机自己的 agent 循环负责。
16
+ *
17
+ * 3. **start() 不等待任务被接受** —— 只做同步可判定的拒绝(无在线节点、
18
+ * 多节点且未指定、节点不可达),然后立刻把 SubagentRun 交给持有者。
19
+ * 等 accept 是 result 的事:否则持有者在最长 ackTimeoutMs 内拿不到
20
+ * dispose 句柄,也就无法取消一条刚派出去的任务。
21
+ *
22
+ * 节点选择:request.label 里出现节点 id 或主机名就用它,否则要求恰好一个在线节点。
23
+ */
24
+ import { ERROR_CODE, TERMINAL_STATUS, TASK_MODE, TASK_STATUS, newTaskId, validateTaskStart } from '../protocol.js'
25
+ import { handoffSummaryText } from './tools.js'
26
+ // 投影共享层:副机上报的 handoff / progressTail / logTail 全部是不可信输入,
27
+ // 必须与工具路径、UI 路径用**同一份**白名单(见 views.js 的说明)。
28
+ import { handoffView, progressTailView } from './views.js'
29
+
30
+ /** goal 上限:控制帧上限 4 MiB,而 goal 会被塞进 task/start 帧。 */
31
+ const MAX_GOAL_CHARS = 64 * 1024
32
+ const GOAL_TRUNCATED_MARK = '\n\n[goal truncated: exceeded 65536 characters]'
33
+ /** 非文本块的 type 名也来自调用方,渲染前截断(否则 `[xxx… block omitted]` 无上界)。 */
34
+ const MAX_BLOCK_TYPE_CHARS = 64
35
+ /** 节点 id / 主机名的字符集,与 protocol.validateHello 的 nodeId 规则一致。 */
36
+ const NODE_TOKEN_CHAR = /[a-z0-9._-]/
37
+
38
+ /**
39
+ * 从 label 里认出节点名。label 形如 "build on DESKTOP-01" / "node:DESKTOP-01"。
40
+ *
41
+ * ── 为什么不能"第一个子串命中就返回"(修复前) ─────────────────────
42
+ * 旧实现按 `registry.nodes` 的插入顺序遍历,对每个节点做
43
+ * `text.includes(id)`,命中即返回。于是 **短 id 会劫持长 id 的 label**:
44
+ * 同时在线 `pc` 与 `pc-2` 时,label `"run on pc-2"` 会命中 `pc`
45
+ * ("pc-2" 里含 "pc"),任务被派到**错误的机器**上 —— 而且结果看起来
46
+ * 完全正常(有节点接单、任务跑完、回传交接卡),只是跑错了电脑。
47
+ * 谁先被插入取决于连接顺序,所以这是"有时对、有时错"的间歇性错误。
48
+ *
49
+ * 修法两条:
50
+ * ① **最长匹配优先** —— `pc-2`(4) 胜过 `pc`(2),把劫持消掉;
51
+ * ② **词边界** —— 匹配位置的相邻字符不能也是 id 字符,避免
52
+ * `pc` 命中 `apc` / `pcx` 这类"包含关系"。
53
+ * 等长冲突(两个不同 id 以同样长度命中)时返回 '' 让上层走"唯一在线节点"
54
+ * 规则或报"请在 label 里写明节点名"—— 宁可让调用方补一句,不可猜错机器。
55
+ */
56
+ export function nodeHintFromLabel(label, registry) {
57
+ // 句末标点不属于节点名,先剥掉:否则 "run on pc." 会被词边界判成不匹配。
58
+ const text = String(label ?? '').trim().toLowerCase().replace(/[.!?,;。!?,;]+$/, '')
59
+ if (text === '') return ''
60
+ const nodes = registry?.nodes
61
+ if (!nodes || typeof nodes.values !== 'function') return ''
62
+
63
+ let best = ''
64
+ let bestLen = 0
65
+ let ambiguous = false
66
+ for (const rec of nodes.values()) {
67
+ const id = typeof rec?.nodeId === 'string' ? rec.nodeId : ''
68
+ if (id === '') continue
69
+ const host = String(rec.hello?.hostname ?? '')
70
+ for (const token of [id, host]) {
71
+ if (token === '') continue
72
+ const needle = token.toLowerCase()
73
+ if (!containsNodeToken(text, needle)) continue
74
+ if (needle.length > bestLen) {
75
+ best = id
76
+ bestLen = needle.length
77
+ ambiguous = false
78
+ } else if (needle.length === bestLen && best !== '' && best !== id) {
79
+ // 两个不同节点等长命中:label 不足以定位,交给上层。
80
+ ambiguous = true
81
+ }
82
+ }
83
+ }
84
+ return ambiguous ? '' : best
85
+ }
86
+
87
+ /** needle 是否在 text 里以"完整节点名"的形态出现(两侧不能还是 id 字符)。 */
88
+ function containsNodeToken(text, needle) {
89
+ let from = 0
90
+ for (;;) {
91
+ const at = text.indexOf(needle, from)
92
+ if (at === -1) return false
93
+ const before = at === 0 ? '' : text[at - 1]
94
+ const after = text[at + needle.length] ?? ''
95
+ if (!NODE_TOKEN_CHAR.test(before) && !NODE_TOKEN_CHAR.test(after)) return true
96
+ from = at + 1
97
+ }
98
+ }
99
+
100
+ /** goal 收敛:截断而不是抛(一条超长 prompt 不该让整个派单失败)。 */
101
+ function clampGoal(text) {
102
+ if (text.length <= MAX_GOAL_CHARS) return text
103
+ return `${text.slice(0, MAX_GOAL_CHARS)}${GOAL_TRUNCATED_MARK}`
104
+ }
105
+
106
+ /**
107
+ * request.prompt(ContentBlock[])里的文本拼成 goal。非文本块如实标注,不静默丢弃。
108
+ *
109
+ * 两种输入形态都收:
110
+ * - `ContentBlock[]` —— 框架契约。
111
+ * - 裸 `string` —— 旧实现直接当成"不是数组 → 空 parts → goal 为 ''",
112
+ * 于是 `start()` 回落到用 **label 当 goal**:派出去的活变成了派单标题,
113
+ * 调用方看不到任何异常(静默数据丢失)。多认一种输入比丢掉内容安全。
114
+ */
115
+ export function promptToGoal(prompt) {
116
+ if (typeof prompt === 'string') return clampGoal(prompt.trim())
117
+ const blocks = Array.isArray(prompt) ? prompt : []
118
+ const parts = []
119
+ for (const b of blocks) {
120
+ if (!b || typeof b !== 'object') continue
121
+ if (b.type === 'text' && typeof b.text === 'string') {
122
+ parts.push(b.text)
123
+ continue
124
+ }
125
+ if (typeof b.type === 'string') parts.push(`[${b.type.slice(0, MAX_BLOCK_TYPE_CHARS)} block omitted]`)
126
+ }
127
+ return clampGoal(parts.join('\n\n').trim())
128
+ }
129
+
130
+ /**
131
+ * 任务状态 → SubagentStopReason。
132
+ *
133
+ * **显式全表**,不用 switch 的 default 兜底:default 会让"protocol.js 新增了
134
+ * 一个状态"这件事静默通过(新状态自动落进 error,看起来一切正常),而状态机
135
+ * 是冻结层里最该被钉住的东西。这里逐条列出 TASK_STATUS 全集,测试再遍历
136
+ * TASK_STATUS 断言每个键都在表里 —— 将来加状态就会红。
137
+ */
138
+ export const STOP_REASON_BY_STATUS = Object.freeze({
139
+ [TASK_STATUS.COMPLETED]: 'completed',
140
+ [TASK_STATUS.ABORTED]: 'aborted',
141
+ [TASK_STATUS.FAILED]: 'error',
142
+ [TASK_STATUS.INTERRUPTED]: 'error',
143
+ // 非终态:正常路径不会走到这里(result 等的是 awaitTerminal)。真到了说明
144
+ // "run 结束了但任务没有终态",那本身就是错误,如实报 error 而不是假装完成。
145
+ [TASK_STATUS.QUEUED]: 'error',
146
+ [TASK_STATUS.RUNNING]: 'error',
147
+ // 两阶段审批(提案 #2):PENDING_APPROVAL 非终态(到这儿同样是异常);
148
+ // REJECTED 终态 —— 任务从未跑过,按不变式归 error(没有"完成"语义)。
149
+ [TASK_STATUS.PENDING_APPROVAL]: 'error',
150
+ [TASK_STATUS.REJECTED]: 'error',
151
+ })
152
+
153
+ /** 未知状态(副机上报了本 hub 不认识的 status)→ error,不返回 undefined。 */
154
+ export function stopReasonOf(status) {
155
+ return STOP_REASON_BY_STATUS[status] ?? 'error'
156
+ }
157
+
158
+ /**
159
+ * 把副机上报的任务视图收敛成 fallbackText 能安全解引用的形状。
160
+ *
161
+ * 副机的 `progressTail` / `logTail` 是**不可信输入**(`node-registry.applyView`
162
+ * 把 task/sync 里的数组原样存下)。旧实现直接 `for (const p of progress)` 读
163
+ * `p.phase` —— 副机上报一个 `null` 元素就让这里抛 TypeError,异常被 provider
164
+ * 的兜底 catch 吞掉,于是一个**已完成**的任务被上报成
165
+ * "未完成:Cannot read properties of null"。这既是崩溃源,也让调用方完全
166
+ * 看不到真实结果。views.js 里已经为此写过一次(`progressTailView`),
167
+ * 这里改用同一份投影,不再各写一份。
168
+ */
169
+ function projectTaskForText(task) {
170
+ if (!task || typeof task !== 'object') return {}
171
+ return {
172
+ taskId: typeof task.taskId === 'string' ? task.taskId : null,
173
+ nodeId: typeof task.nodeId === 'string' ? task.nodeId : null,
174
+ status: typeof task.status === 'string' ? task.status : 'unknown',
175
+ // workspace 是**绝对路径**,会回显主机目录结构,与 handoffView 的取舍一致:不回传。
176
+ error: task.error && typeof task.error === 'object'
177
+ ? {
178
+ code: typeof task.error.code === 'string' ? task.error.code : '',
179
+ message: typeof task.error.message === 'string' ? task.error.message.slice(0, 500) : '',
180
+ }
181
+ : null,
182
+ progressTail: progressTailView(task.progressTail, { tail: 10 }),
183
+ logTail: Array.isArray(task.logTail)
184
+ ? task.logTail.slice(-15).map((l) => String(l).slice(0, 300))
185
+ : [],
186
+ }
187
+ }
188
+
189
+ /**
190
+ * @param {object} o
191
+ * @param {import('./node-registry.js').NodeRegistry} o.registry
192
+ * @param {import('./pull-manager.js').PullManager} o.pulls
193
+ * @param {(level:string,msg:string,extra?:object)=>void} [o.log]
194
+ * @param {object} [o.defaults]
195
+ * @returns {object} SubagentProvider
196
+ */
197
+ export function createRemoteAgentProvider({ registry, pulls, log, defaults = {} }) {
198
+ // 三个都做兜底:provider 是**可选服务**(hub 可能跑在没有 subagents 的组合里),
199
+ // 少传一个 log / pulls 不该让派单在 `log(...)` 处抛 TypeError —— 那是
200
+ // "装配期少一个依赖 → 运行期炸在第一个任务上",最难排查的一类失败。
201
+ const emit = typeof log === 'function' ? log : () => {}
202
+ const cancelPulls = (taskId) => {
203
+ try {
204
+ pulls?.cancelTask?.(taskId)
205
+ } catch {
206
+ /* 取消是尽力而为:pull 侧状态异常不该影响 result 落定 */
207
+ }
208
+ }
209
+ // 只接受**正的**有限数:`0` / 负数会被 validateTaskStart 夹到下限 1000ms,
210
+ // 于是一个配错成 `timeoutMs: -1` 的部署会让每条任务在 1 秒后被判超时 ——
211
+ // 比回落到 1 小时更糟(错得静默且看起来像"任务真的失败了")。
212
+ const defaultTimeoutMs =
213
+ Number.isFinite(defaults.timeoutMs) && defaults.timeoutMs > 0 ? defaults.timeoutMs : 60 * 60 * 1000
214
+ const ackTimeoutMs = registry?.limits?.ackTimeoutMs ?? 60_000
215
+
216
+ return {
217
+ name: 'remote-agent',
218
+ capabilities: {
219
+ agentOptions: false,
220
+ outputSchema: false,
221
+ depthLimit: false,
222
+ toolFilter: false,
223
+ persona: false,
224
+ },
225
+ inheritsParentContext: false,
226
+
227
+ async start(request) {
228
+ const label = typeof request?.label === 'string' ? request.label : ''
229
+ const goal = promptToGoal(request?.prompt)
230
+ const hint = nodeHintFromLabel(label, registry)
231
+
232
+ let nodeId
233
+ if (hint !== '') {
234
+ nodeId = hint
235
+ } else {
236
+ const online = registry.onlineNodes()
237
+ if (online.length === 0) throw new Error('remote-agent: 没有在线节点,先让副机接入')
238
+ if (online.length > 1) {
239
+ throw new Error(
240
+ `remote-agent: 有多个在线节点(${online.map((n) => n.nodeId).join(', ')}),请在 label 里写明节点名`,
241
+ )
242
+ }
243
+ nodeId = online[0].nodeId
244
+ }
245
+
246
+ const taskId = newTaskId()
247
+ const v = validateTaskStart({
248
+ taskId,
249
+ goal: goal === '' ? label || '(empty prompt)' : goal,
250
+ mode: TASK_MODE.AGENT,
251
+ constraints: { timeoutMs: defaultTimeoutMs },
252
+ origin: 'subagent',
253
+ })
254
+ if (!v.ok) throw new Error(`remote-agent: invalid task (${v.error})`)
255
+
256
+ // 同步可判定的失败在这里抛出:框架约定"start 拒绝 ⇒ 没有 run 需要释放"。
257
+ registry.createTask({ nodeId, spec: v.spec })
258
+ emit('info', 'subagent run dispatched', { taskId, nodeId, label })
259
+
260
+ let cancelled = false
261
+ // result 落定后 dispose() 不该再发 task/cancel:任务已经跑完,再发一条取消
262
+ // 只会让副机日志里多一条莫名其妙的 cancel,也可能打断同 id 的后续状态上报。
263
+ let settled = false
264
+ let resolveCancel
265
+ const cancelPromise = new Promise((r) => {
266
+ resolveCancel = r
267
+ })
268
+ const cancel = () => {
269
+ if (cancelled) return
270
+ cancelled = true
271
+ cancelPulls(taskId)
272
+ try {
273
+ registry.cancelTask(taskId)
274
+ } catch {
275
+ /* 节点已离线等:取消尽力而为 */
276
+ }
277
+ resolveCancel()
278
+ }
279
+
280
+ const result = (async () => {
281
+ const signal = request?.signal
282
+ const onAbort = () => cancel()
283
+ try {
284
+ if (signal) {
285
+ if (signal.aborted) cancel()
286
+ else signal.addEventListener('abort', onAbort, { once: true })
287
+ }
288
+
289
+ // 两条路竞争:任务真的跑到终态,或持有者放弃了这次运行。
290
+ //
291
+ // 为什么取消要单独成一条路:dispose() / signal abort 的语义是
292
+ // "持有者不再要这次运行",result 必须**及时**落定。若只等副机的终态帧,
293
+ // 一条刚派出去、副机还没回话的任务会把 result 挂到 ackTimeout 之后。
294
+ // 取消请求照发不误 —— 副机侧的任务该停还是要停。
295
+ const work = (async () => {
296
+ // 等 accept:节点拒绝工作区时会立刻回终态,所以两条路一起等。
297
+ await registry.awaitAccepted(taskId, { timeoutMs: ackTimeoutMs })
298
+ // 等终态。任务超时由副机自己执行并如实上报;这里的上界只是兜底,
299
+ // 防止节点中途彻底失联时把 subagent 永久挂住。
300
+ return registry.awaitTerminal(taskId, { timeoutMs: defaultTimeoutMs + ackTimeoutMs * 2 })
301
+ })()
302
+ work.catch(() => {}) // 竞争失败的那条不产生未处理 rejection
303
+
304
+ const raced = await Promise.race([
305
+ work.then(
306
+ (terminal) => ({ kind: 'terminal', terminal }),
307
+ (err) => ({ kind: 'error', err }),
308
+ ),
309
+ cancelPromise.then(() => ({ kind: 'cancelled' })),
310
+ ])
311
+
312
+ if (raced.kind === 'cancelled') {
313
+ const task = registry.getTask(taskId)
314
+ return {
315
+ output: [
316
+ {
317
+ type: 'text',
318
+ text: `远程任务 ${taskId} 已请求取消(节点 ${nodeId},最后一次状态 ${task?.status ?? 'unknown'})。`,
319
+ },
320
+ ],
321
+ structured: { taskId, nodeId, status: task?.status ?? 'unknown', cancelled: true },
322
+ stopReason: 'aborted',
323
+ diagnostic: 'run cancelled by the holder',
324
+ }
325
+ }
326
+
327
+ if (raced.kind === 'error') {
328
+ cancel()
329
+ const task = registry.getTask(taskId)
330
+ return {
331
+ output: [{ type: 'text', text: `远程任务 ${taskId} 未完成:${String(raced.err?.message ?? raced.err)}` }],
332
+ structured: { taskId, nodeId, status: task?.status ?? 'unknown' },
333
+ stopReason: String(raced.err?.code ?? '') === 'aborted' ? 'aborted' : 'error',
334
+ diagnostic: String(raced.err?.message ?? raced.err),
335
+ }
336
+ }
337
+
338
+ const terminal = raced.terminal
339
+ const handoff = terminal.handoff
340
+ // handoff 是**副机上报**的对象,字段集不受本文件控制:它会带
341
+ // workspace(绝对路径)、logs(可能含环境变量)、以及它版本的任何
342
+ // 新字段。工具路径(remote_handoff)早已改成走 handoffView,这里
343
+ // 曾经是 `structured: handoff` 裸直出 —— 而 provider 的返回值会进
344
+ // 主机会话日志,比 UI 那条路径更该加固(views.js 记的正是这个教训)。
345
+ const projected = handoffView(handoff)
346
+ // 文本渲染里有一行"工作区",而 handoffView **刻意**不含 workspace
347
+ // (绝对路径会回显主机目录结构)。这里给一个明确的占位,而不是让
348
+ // handoffSummaryText 打出 "undefined" —— 交付给人看的文本不该出现
349
+ // 未定义值,而且 "未回传" 本身就是正确信息。
350
+ const textSource = projected ? { ...projected, workspace: '(未回传)' } : null
351
+ const body = textSource
352
+ ? handoffSummaryText({ taskId, handoff: textSource })
353
+ : fallbackText(projectTaskForText(terminal))
354
+ return {
355
+ output: [{ type: 'text', text: body }],
356
+ structured: projected ?? { taskId, nodeId, status: terminal.status },
357
+ stopReason: stopReasonOf(terminal.status),
358
+ diagnostic:
359
+ terminal.status === TASK_STATUS.COMPLETED
360
+ ? undefined
361
+ : `${terminal.error?.code ?? terminal.status}: ${terminal.error?.message ?? 'remote task did not complete'}`,
362
+ }
363
+ } catch (err) {
364
+ // 兜底:任何意外都要落成一个 SubagentResult,绝不让 result 悬挂。
365
+ cancel()
366
+ const task = registry.getTask(taskId)
367
+ return {
368
+ output: [{ type: 'text', text: `远程任务 ${taskId} 未完成:${String(err?.message ?? err)}` }],
369
+ structured: { taskId, nodeId, status: task?.status ?? 'unknown' },
370
+ stopReason: String(err?.code ?? '') === 'aborted' ? 'aborted' : 'error',
371
+ diagnostic: String(err?.message ?? err),
372
+ }
373
+ } finally {
374
+ settled = true
375
+ if (signal) {
376
+ try {
377
+ signal.removeEventListener('abort', onAbort)
378
+ } catch {
379
+ /* signal 已失效 */
380
+ }
381
+ }
382
+ }
383
+ })()
384
+ // result 的拒绝已在内部全部转成 SubagentResult,这里再兜一层,
385
+ // 避免一个未处理的 rejection 打挂 host。
386
+ result.catch(() => {})
387
+
388
+ return {
389
+ id: taskId,
390
+ localAgent: undefined,
391
+ result,
392
+ async dispose() {
393
+ if (settled) return
394
+ cancel()
395
+ },
396
+ }
397
+ },
398
+ }
399
+ }
400
+
401
+ function fallbackText(task) {
402
+ const t = task && typeof task === 'object' ? task : {}
403
+ const lines = [
404
+ `# 远程任务 ${t.taskId ?? '(unknown)'}`,
405
+ '',
406
+ `- 节点:${t.nodeId ?? '(unknown)'}`,
407
+ `- 状态:${t.status ?? 'unknown'}`,
408
+ ]
409
+ if (t.error) lines.push(`- 错误:${t.error.code}: ${t.error.message}`)
410
+ const progress = Array.isArray(t.progressTail) ? t.progressTail : []
411
+ if (progress.length > 0) {
412
+ lines.push('', '进度尾巴:')
413
+ for (const p of progress.slice(-10)) lines.push(`- ${p.phase}${p.detail ? `: ${String(p.detail).slice(0, 200)}` : ''}`)
414
+ }
415
+ const logs = Array.isArray(t.logTail) ? t.logTail : []
416
+ if (logs.length > 0) {
417
+ lines.push('', '日志尾巴:')
418
+ for (const l of logs.slice(-15)) lines.push(`> ${String(l).slice(0, 300)}`)
419
+ }
420
+ if (!TERMINAL_STATUS.has(t.status)) lines.push('', '(任务尚未结束,副机仍在本地运行。)')
421
+ return lines.join('\n')
422
+ }
423
+
424
+ export { ERROR_CODE }