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
package/lib/index.js ADDED
@@ -0,0 +1,272 @@
1
+ /**
2
+ * dsh-remote-agent 插件入口:角色分发器。
3
+ *
4
+ * 一个包,两种角色,因为协议层、glob、产物判定这些地基是共用的:
5
+ *
6
+ * role: 'hub' 主电脑 —— 节点注册表 + remote_* 工具 + subagent provider
7
+ * role: 'worker' 副机 —— 拨入 hub、本地跑任务、按需外发产物
8
+ * role: 'both' 同机自测(一台机器同时当 hub 与 worker)
9
+ *
10
+ * **为什么这里刻意不写 `export const inject`**:
11
+ * 声明式 inject 是模块级的,一旦声明了 `['webServer','tools','systemPrompt']`,
12
+ * 那么在没有 webServer 的副机 profile 里整个插件都不会激活 —— worker 分支会被
13
+ * hub 的依赖一起拖死。所以 hub 侧改用作用域注入 `ctx.inject([...], cb)`:
14
+ * 缺服务时 hub 分支自然不激活,worker 分支照常跑。这也是 E3 契约要求的形态。
15
+ *
16
+ * worker 分支走动态 import:hub 进程不需要加载副机的任务引擎、进程管理、
17
+ * 文件遍历那一整套代码;副机进程也不需要在内存里挂着 hub 的注册表。
18
+ */
19
+ // schemastery 由 dsh 运行时提供。**必须顶层 import**,且必须在 package.json 里
20
+ // 声明为 peerDependency,否则 loader 判定该行没有 Config(实测报 `status: absent`)。
21
+ // 这与 dsh-better-sidebar 等已发布插件一致,是唯一被验证可用的形态。
22
+ import z from '@deepseek-ai/schemastery'
23
+ import { applyHub, newNodeToken, normalizeConfig, NODE_UPGRADE_PATH, HEALTH_PATH } from './hub/index.js'
24
+ import { registerSetupRoutes } from './setup-routes.js'
25
+
26
+ /** 角色取值。 */
27
+ export const ROLE = Object.freeze({ HUB: 'hub', WORKER: 'worker', BOTH: 'both' })
28
+
29
+ /**
30
+ * 解析本机角色。
31
+ *
32
+ * 为什么需要归一化 + 明确告警(t3 审计查出的真实风险):
33
+ * 原实现只做精确匹配,其余一律 `return ROLE.HUB`。于是 `role: 'Worker'`(大小写)、
34
+ * `'hub '`(尾空格)、`42`、`true` 全都**静默**变成 hub —— 而副机 profile 写错一个
35
+ * 字母的后果很严重:那台机器会以 **hub 身份**启动,注册 `/api/remote-agent/node`
36
+ * 直连端点与 healthz,而 hub 的 `nodeToken` 默认为空串 → **该端点不校验任何凭证**。
37
+ * 用户以为自己配的是"副机",实际开了个无鉴权的直连入口。
38
+ *
39
+ * 修法:先归一化(trim + 小写)以容忍常见笔误,再对**无法识别**的值返回 hub 但
40
+ * 附带 `invalid` 标记,由 apply() 记 warn —— 配置写错必须有反馈,不能静默。
41
+ *
42
+ * ── 2026-10-15 二次修订:未配置 ≠ hub ──────────────────────────────────────
43
+ *
44
+ * 原实现把 `''` / `undefined` 也当成 hub。这导致**首次安装的体验是错的**:
45
+ *
46
+ * · 副机装完 → `role` 走默认值 hub → 面板认为自己是主机 → 全 404,
47
+ * 而且**不会显示任何引导**(它以为自己配好了)
48
+ * · 用户必须去手工改 YAML 才能变成 worker —— 而改的时候还要同时改
49
+ * `inject`(hub 要 webServer/tools/systemPrompt,worker 不该要),
50
+ * 两个字段联动,极易配错
51
+ *
52
+ * 改成"**未配置就是未配置**":
53
+ * · `''` / `undefined` / `null` → `{ role: '', unconfigured: true }`
54
+ * · apply() 见到 unconfigured **什么都不注册**(不 hub、不 worker)
55
+ * · 面板两个端点都失败 → 显示引导 UI,让用户选
56
+ *
57
+ * 顺带这比原实现**更安全**:原实现下"配置写错"会静默变成 hub(注册一个
58
+ * nodeToken 为空、不校验凭证的直连端点);现在写错只是"未配置",不开任何入口。
59
+ *
60
+ * @returns {{role:string, invalid?:string, unconfigured?:true}}
61
+ * role 为 hub/worker/both,或 `''`(未配置);invalid 为原始非法值
62
+ */
63
+ export function resolveRoleDetail(config) {
64
+ const raw = config && typeof config === 'object' ? config.role : undefined
65
+ if (raw === undefined || raw === null || raw === '') return { role: '', unconfigured: true }
66
+ if (typeof raw === 'string') {
67
+ const norm = raw.trim().toLowerCase()
68
+ if (norm === ROLE.HUB || norm === ROLE.WORKER || norm === ROLE.BOTH) return { role: norm }
69
+ }
70
+ // 无法识别:**不再回退 hub**(那会静默开一个无鉴权入口)。
71
+ // 当成"未配置",由面板引导用户重新选。
72
+ return { role: '', invalid: raw, unconfigured: true }
73
+ }
74
+
75
+ /** 兼容旧签名:只返回角色字符串。 */
76
+ export function resolveRole(config) {
77
+ return resolveRoleDetail(config).role
78
+ }
79
+
80
+ function loggerOf(ctx) {
81
+ return (level, msg, extra) => {
82
+ try {
83
+ const l = ctx?.logger
84
+ if (l && typeof l[level] === 'function') l[level](`[remote-agent] ${msg}`, extra)
85
+ else if (l && typeof l.info === 'function') l.info(`[remote-agent] ${msg}`, extra)
86
+ else if (level === 'warn' || level === 'error') console.warn(`[remote-agent] ${msg}`, extra ?? '')
87
+ } catch {
88
+ /* 日志失败不影响主流程 */
89
+ }
90
+ }
91
+ }
92
+
93
+ /** 动态加载副机实现并调用 applyWorker。 */
94
+ async function applyWorkerBranch(ctx, config, log) {
95
+ let mod
96
+ try {
97
+ mod = await import('./node/index.js')
98
+ } catch (err) {
99
+ log('error', 'worker 分支加载失败:lib/node/index.js 不可用', {
100
+ error: String(err?.message ?? err),
101
+ })
102
+ return undefined
103
+ }
104
+ const fn = typeof mod?.applyWorker === 'function' ? mod.applyWorker : typeof mod?.apply === 'function' ? mod.apply : undefined
105
+ if (typeof fn !== 'function') {
106
+ log('error', 'worker 分支加载失败:lib/node/index.js 未导出 applyWorker')
107
+ return undefined
108
+ }
109
+ try {
110
+ return fn(ctx, config)
111
+ } catch (err) {
112
+ log('error', 'worker 分支挂载失败', { error: String(err?.message ?? err) })
113
+ return undefined
114
+ }
115
+ }
116
+
117
+ /**
118
+ * DSH 插件入口。
119
+ * @param {object} ctx Cordis 上下文
120
+ * @param {object} [config] 行配置(profiles/*.cordis.yml 里的 config)
121
+ */
122
+ export function apply(ctx, config = {}) {
123
+ const { role, invalid, unconfigured } = resolveRoleDetail(config)
124
+ const log = loggerOf(ctx)
125
+ // 配置写错必须有反馈。注意**不再回退 hub** —— 那会静默开一个
126
+ // nodeToken 为空、不校验凭证的直连端点(见 resolveRoleDetail 的说明)。
127
+ // 现在当成"未配置"处理:什么都不注册,面板显示引导让用户重选。
128
+ if (invalid !== undefined) {
129
+ log('warn', 'unrecognized role: treating as unconfigured (not falling back to hub)', {
130
+ got: invalid,
131
+ expected: [ROLE.HUB, ROLE.WORKER, ROLE.BOTH],
132
+ })
133
+ }
134
+ const handles = { role, hub: undefined, worker: undefined, unconfigured: unconfigured === true }
135
+
136
+ // ── 未配置:什么都不注册 ────────────────────────────────────────────────
137
+ //
138
+ // 为什么要有这个分支:首次安装时**插件无法知道这台机器是主机还是副机** ——
139
+ // 只有用户知道。而包内 `cordis.patch.yml` 必须有某个默认值,无论选哪个都会
140
+ // 让一半的装机场景是错的(原实现默认 hub:副机装完会以 hub 身份启动)。
141
+ //
142
+ // 所以默认值改成空,并在这里"什么都不做":
143
+ // · 不注册 hub 路由/工具(不开任何入口)
144
+ // · 不启动 worker 拨入
145
+ // · 面板两个端点都失败 → 显示引导 UI → 用户选 → 写入配置 → 重启
146
+ //
147
+ // 这也顺带修了一个安全问题:原实现下"role 写错"会静默变成 hub,
148
+ // 而 hub 的 nodeToken 默认为空 → 该直连端点不校验任何凭证。
149
+ //
150
+ // ⚠ 但**不能真的什么都不注册** —— 那样面板两个端点都失败,用户只看到
151
+ // 两个错误,拿不到引导。所以这里注册**一组最小引导路由**(只有 setup
152
+ // 相关的两三个),由它们承载引导 UI 的数据源。
153
+ //
154
+ // ── 2026-10-15 二次修订:引导路由**始终注册**(不只未配置时)──────────
155
+ //
156
+ // 原先只在 unconfigured 时注册,结果是:**已配置的机器无法通过面板改角色** ——
157
+ // 用户想从 hub 改成 worker(或反过来)只能去命令行或手改 YAML,而手改时
158
+ // 还要同时改 `inject`(两个字段联动,极易配错 —— 我们踩过)。
159
+ //
160
+ // 所以改成**无条件注册**:
161
+ // · `/setup/state` 在已配置时返回 `configured: true` + 当前值
162
+ // · `/setup/apply` 在已配置时**覆盖**(writePatchBlock 本就是 upsert)
163
+ // · 成本极低(两个路由,只用 webServer),收益是"任何状态下都能改角色"
164
+ //
165
+ // 注册时机:**先于** hub/worker 分支,这样即使后面某步抛错,改角色的
166
+ // 入口仍然可用(它是配置层面的逃生舱)。
167
+ handles.setup = registerSetupRoutes(ctx, config, log)
168
+
169
+ if (unconfigured === true) {
170
+ log('info', 'remote-agent is not configured yet: only setup routes are active')
171
+ return handles
172
+ }
173
+
174
+ if (role === ROLE.HUB || role === ROLE.BOTH) {
175
+ // ═══════════════════════════════════════════════════════════════════════
176
+ // 服务可见性:靠 loader 行上的**声明式 inject**(见 cordis.patch.yml)
177
+ // ═══════════════════════════════════════════════════════════════════════
178
+ //
179
+ // cordis 的防护:没有声明 inject 就直接读 `ctx.webServer` 会抛
180
+ // `cannot get property "webServer" without inject`(实测)。
181
+ //
182
+ // 而"运行时 ctx.inject(deps, cb)"这条路走不通(实测,2026-10-14):
183
+ // - inject 返回 thenable fiber,要 await 才算"加载完成"
184
+ // - 插件的 apply 是同步的,父 fiber 同步返回后框架清理未 settle 的子 fiber
185
+ // - 诊断:注册成功 13ms 后 `DISPOSED (fiber unloaded)`,路由被删且不再回来
186
+ // - `ctx.plugin({inject, apply})` 更糟:子插件的 apply 根本没被调用
187
+ //
188
+ // 所以 inject 声明在**行上**(cordis.patch.yml 的 `inject: [...]`):框架推迟
189
+ // 本行激活直到服务就绪,只 apply 一次、无子 fiber 抖动。这是唯一可用的形态。
190
+ //
191
+ // 副机(worker)不需要这些服务,必须在自己的 profile 里覆盖 `inject: []`,
192
+ // 否则该行永远 PENDING。见 profiles/worker.cordis.yml。
193
+ handles.hub = applyHub(ctx, config)
194
+ }
195
+
196
+ if (role === ROLE.WORKER || role === ROLE.BOTH) {
197
+ // 动态 import 是异步的;不 await —— apply 本身是同步契约。
198
+ // 失败已在 applyWorkerBranch 内部记日志,不让 host 因副机缺件而起不来。
199
+ void applyWorkerBranch(ctx, config, log).then((h) => {
200
+ handles.worker = h
201
+ })
202
+ }
203
+
204
+ return handles
205
+ }
206
+
207
+ export const Config = z.object({
208
+ role: z
209
+ // ⚠ 空字符串是**合法值**,表示"还没配置" —— 见 resolveRoleDetail 的说明。
210
+ // 不能用 `.default('hub')`:那会让副机装完以 hub 身份启动(注册一个
211
+ // nodeToken 为空、不校验凭证的直连端点),且面板不会显示引导。
212
+ .union([z.const('hub'), z.const('worker'), z.const('both'), z.const('')])
213
+ .default('')
214
+ .description(
215
+ '本机角色:hub=主机(派活方);worker=副机(干活方);both=同一台机器自测;'
216
+ + '留空=未配置(打开 Web 面板会显示引导,让你选)',
217
+ ),
218
+
219
+ // ── 副机(worker)专用 ────────────────────────────────────────
220
+ nodeId: z
221
+ .string()
222
+ .default('')
223
+ .description('副机唯一标识(留空则取主机名)。只能含字母数字 . _ -,以字母或数字开头。'),
224
+ transportMode: z
225
+ .union([z.const('direct'), z.const('relay')])
226
+ .default('relay')
227
+ .description('direct=副机主动连主机(主机地址需可达);relay=经中继 VPS 会合(双方都在 NAT 后时用)。'),
228
+ hubUrl: z
229
+ .string()
230
+ .default('')
231
+ .description('direct 模式:主机地址,形如 ws://主机IP:19387/api/remote-agent/node。'),
232
+ relayUrl: z
233
+ .string()
234
+ .default('')
235
+ .description('relay 模式:中继地址,形如 ws://中继IP:8890/relay。'),
236
+ roots: z.array(z.string())
237
+ .default([])
238
+ .description('副机允许任务操作的工作区根目录(绝对路径,必须真实存在)。留空退回保守默认。'),
239
+ stateDir: z.string()
240
+ .default('')
241
+ .description('副机任务状态落盘目录(留空用 ~/.dsh-remote-agent)。任务状态真身在这里。'),
242
+
243
+ // ── 主机(hub)专用 ──────────────────────────────────────────
244
+ relay: z.object({
245
+ url: z.string().default('').description('中继地址,留空表示不用中继。'),
246
+ token: z.string().default('').description('中继的 hub token(rt_ 开头那一半)。'),
247
+ })
248
+ .default({ url: '', token: '' })
249
+ .description('主机经中继接入时的地址与凭证。'),
250
+ nodeToken: z.string()
251
+ .default('')
252
+ .description('direct 模式下校验副机的共享口令。留空=不校验(仅限可信内网;公网暴露时必须填)。'),
253
+ uiPullRoot: z.string()
254
+ .default('')
255
+ .description('Web 面板拉取产物时唯一允许落地的目录(绝对路径)。留空则面板拉取按钮禁用。'),
256
+ uiEnabled: z.boolean()
257
+ .default(true)
258
+ .description('是否注册 Web 面板的控制路由。'),
259
+ })
260
+
261
+ // ⚠ 这里刻意**不写** `export default apply`。
262
+ //
263
+ // cordis loader 用 `unwrapExports()` 解析模块:
264
+ // exports = exports.default ?? exports
265
+ // 也就是说,只要模块有 default 导出,它就会**把整个命名空间替换成那个 default**。
266
+ // 我们的 default 是 `apply` 函数,于是 loader 拿到的是函数、而不是命名空间 ——
267
+ // 函数上没有 `Config`,判定链直接落到 `status: 'absent'`,插件页因此不出现配置表单。
268
+ // (对照:dsh-better-sidebar 等有 schema 的插件都没有 default 导出。)
269
+ //
270
+ // 保持只用具名导出(apply + Config + 若干常量),命名空间完整,Config 才能被读到。
271
+ // `apply` 已由上面的 `export function apply` 具名导出,这里不重复列出。
272
+ export { applyHub, newNodeToken, normalizeConfig, NODE_UPGRADE_PATH, HEALTH_PATH }
@@ -0,0 +1,231 @@
1
+ /**
2
+ * 副机侧的产物服务:清单构建 + 按需分块外发。
3
+ *
4
+ * 三条硬规则(来自用户锁定的契约):
5
+ * 1. manifest 先于字节 —— 任务结束只回清单,hub 显式 pull 才传输
6
+ * 2. 只有 role:final 过河 —— intermediate 永不出网
7
+ * 3. sha256 校验 —— 传输前后各算一次,不一致就报错,不静默接受
8
+ *
9
+ * 背压:分块前查写缓冲,超过高水位就等 drain。没有这个,一个 200MB 产物
10
+ * 会把 node 进程内存和中继的转发队列一起顶爆。
11
+ */
12
+ import { createHash } from 'node:crypto'
13
+ import fs from 'node:fs'
14
+ import path from 'node:path'
15
+ import {
16
+ ARTIFACT_CHUNK_BYTES,
17
+ ERROR_CODE,
18
+ RemoteAgentError,
19
+ } from '../protocol.js'
20
+ import { authorizePull, buildManifest, hashFile } from '../artifacts.js'
21
+ import { isDenied } from './exec.js'
22
+
23
+ /** 单次 pull 的默认上限:512 MiB。 */
24
+ const DEFAULT_MAX_PULL_BYTES = 512 * 1024 * 1024
25
+ /** 写缓冲高水位:超过就等,别把内存交给 socket。 */
26
+ const HIGH_WATER_BYTES = 2 * 1024 * 1024
27
+
28
+ export class ArtifactService {
29
+ constructor({ nodeId, caseInsensitive = true, maxPullBytes = DEFAULT_MAX_PULL_BYTES, onEvent }) {
30
+ this.nodeId = nodeId
31
+ this.caseInsensitive = caseInsensitive
32
+ this.maxPullBytes = maxPullBytes
33
+ this.onEvent = onEvent
34
+ /** 在跑的 pull:pullId → { aborted } */
35
+ this.active = new Map()
36
+ }
37
+
38
+ log(msg, extra) {
39
+ if (typeof this.onEvent === 'function') this.onEvent({ kind: 'artifact', msg, ...extra, at: Date.now() })
40
+ }
41
+
42
+ /** 构建清单(任务结束时调用一次)。 */
43
+ async build({ workspace, outputs, artifactRules, denyPaths = [], signal, hashFinal = true }) {
44
+ const manifest = await buildManifest({
45
+ workspace,
46
+ outputs,
47
+ artifactRules,
48
+ caseInsensitive: this.caseInsensitive,
49
+ denyPaths,
50
+ hashFinal,
51
+ signal,
52
+ includeOther: true,
53
+ })
54
+ this.log('manifest built', {
55
+ workspace: manifest.workspace,
56
+ counts: manifest.counts,
57
+ })
58
+ return manifest
59
+ }
60
+
61
+ /**
62
+ * 分块外发一个产物。
63
+ *
64
+ * @param {object} o
65
+ * @param {object} o.manifest 已构建的清单(授权依据)
66
+ * @param {string} o.pullId
67
+ * @param {string} o.relPath 清单内的相对路径
68
+ * @param {string} o.workspace 工作区绝对路径
69
+ * @param {number} [o.startOffset] 断点续传:从该字节偏移起流(0/缺省 = 从头)
70
+ * @param {(header:object, payload:Buffer)=>Promise<boolean>} o.emit 发送一帧(返回 false 表示连接断了)
71
+ * @param {() => Promise<void>} [o.drain] 背压等待
72
+ * @param {AbortSignal} [o.signal]
73
+ */
74
+ async pull(o) {
75
+ const { manifest, pullId, relPath, workspace, emit, drain, signal } = o
76
+
77
+ // startOffset:hub 侧半成品续传的起点。不带(旧 hub / 从头传)等价 0;
78
+ // 带了就必须是合法非负整数 —— 畸形值按协议违规处理,不静默归零。
79
+ let startOffset = 0
80
+ if (o.startOffset !== undefined && o.startOffset !== null) {
81
+ if (!Number.isInteger(o.startOffset) || o.startOffset < 0) {
82
+ throw new RemoteAgentError(`invalid startOffset: ${o.startOffset}`, ERROR_CODE.HASH_MISMATCH)
83
+ }
84
+ startOffset = o.startOffset
85
+ }
86
+
87
+ const auth = authorizePull(manifest, relPath, {
88
+ caseInsensitive: this.caseInsensitive,
89
+ maxBytes: this.maxPullBytes,
90
+ denyPaths: [],
91
+ })
92
+ if (!auth.ok) {
93
+ throw new RemoteAgentError(auth.message, auth.code)
94
+ }
95
+ const item = auth.item
96
+
97
+ const abs = path.join(workspace, ...item.path.split('/'))
98
+ // 二次校验:清单是快照,路径可能已被替换(符号链接/改名)
99
+ let real
100
+ try {
101
+ real = fs.realpathSync.native ? fs.realpathSync.native(abs) : fs.realpathSync(abs)
102
+ } catch {
103
+ throw new RemoteAgentError(`artifact vanished: ${item.path}`, ERROR_CODE.ARTIFACT_MISSING)
104
+ }
105
+ if (isDenied(real, [workspace], { caseInsensitive: this.caseInsensitive }) === false) {
106
+ throw new RemoteAgentError(`artifact escaped workspace: ${item.path}`, ERROR_CODE.ARTIFACT_DENIED)
107
+ }
108
+
109
+ const st = fs.statSync(real)
110
+ if (!st.isFile()) {
111
+ throw new RemoteAgentError(`not a regular file: ${item.path}`, ERROR_CODE.ARTIFACT_DENIED)
112
+ }
113
+ if (st.size > this.maxPullBytes) {
114
+ throw new RemoteAgentError(
115
+ `${st.size} bytes exceeds maxPullBytes=${this.maxPullBytes}`,
116
+ ERROR_CODE.ARTIFACT_TOO_LARGE,
117
+ )
118
+ }
119
+ // hub 认为的已收前缀比文件还大:副机上文件被截短/替换过,续传无意义
120
+ if (startOffset > st.size) {
121
+ throw new RemoteAgentError(
122
+ `resume startOffset ${startOffset} beyond file size ${st.size}: ${item.path}`,
123
+ ERROR_CODE.HASH_MISMATCH,
124
+ )
125
+ }
126
+
127
+ const token = { aborted: false }
128
+ this.active.set(pullId, token)
129
+ if (signal) {
130
+ if (signal.aborted) token.aborted = true
131
+ else signal.addEventListener('abort', () => {
132
+ token.aborted = true
133
+ }, { once: true })
134
+ }
135
+
136
+ // 传输前重新算 hash:清单生成与 pull 之间文件可能被改过。
137
+ // 报错优于"发一份和清单不符的字节过去"。
138
+ const preHash = await hashFile(real)
139
+ if (item.sha256 && preHash !== item.sha256) {
140
+ this.active.delete(pullId)
141
+ throw new RemoteAgentError(
142
+ `hash mismatch before transfer: manifest=${item.sha256} actual=${preHash}`,
143
+ ERROR_CODE.HASH_MISMATCH,
144
+ )
145
+ }
146
+
147
+ const digest = createHash('sha256')
148
+ // 从 startOffset 起流(startOffset === size 时没有 suffix 可发,直接走 done)
149
+ const stream = startOffset < st.size
150
+ ? fs.createReadStream(real, { start: startOffset, highWaterMark: ARTIFACT_CHUNK_BYTES })
151
+ : null
152
+ let offset = startOffset
153
+ let sent = 0
154
+
155
+ try {
156
+ if (stream) {
157
+ for await (const chunk of stream) {
158
+ if (token.aborted) break
159
+ digest.update(chunk)
160
+ if (drain) await drain()
161
+ const ok = await emit({
162
+ v: 1,
163
+ t: 'artifact/chunk',
164
+ pullId,
165
+ path: item.path,
166
+ offset,
167
+ total: st.size,
168
+ sha256: item.sha256,
169
+ nodeId: this.nodeId,
170
+ }, chunk)
171
+ if (!ok) break
172
+ offset += chunk.length
173
+ sent += chunk.length
174
+ }
175
+ }
176
+
177
+ if (token.aborted) {
178
+ this.log('pull aborted', { pullId, path: item.path, sent, startOffset })
179
+ return { ok: false, aborted: true, sent, path: item.path }
180
+ }
181
+
182
+ // done 帧统一为**全文累计**语义:
183
+ // bytes = startOffset + sent(全文总字节数,hub 侧 size 校验直接可比)
184
+ // sha256 = 全文哈希 —— 从头传时用流式 digest(能在传输中捕捉文件变动),
185
+ // 续传时前缀没过河、无法增量重算全文,用传输前算好的 preHash。
186
+ const actual = startOffset === 0 ? digest.digest('hex') : preHash
187
+ const verifyOk = !item.sha256 || actual === item.sha256
188
+ await emit({
189
+ v: 1,
190
+ t: 'artifact/done',
191
+ pullId,
192
+ path: item.path,
193
+ bytes: startOffset + sent,
194
+ sha256: actual,
195
+ expected: item.sha256 ?? null,
196
+ verified: verifyOk,
197
+ role: item.role,
198
+ kind: item.kind,
199
+ mtimeMs: item.mtimeMs,
200
+ nodeId: this.nodeId,
201
+ }, Buffer.alloc(0))
202
+
203
+ if (!verifyOk) {
204
+ this.log('hash mismatch after transfer', { pullId, path: item.path, expected: item.sha256, actual })
205
+ return { ok: false, hashMismatch: true, sent, path: item.path, sha256: actual }
206
+ }
207
+
208
+ this.log('pull complete', { pullId, path: item.path, bytes: startOffset + sent, startOffset })
209
+ return { ok: true, sent, path: item.path, sha256: actual, resumed: startOffset > 0 }
210
+ } finally {
211
+ this.active.delete(pullId)
212
+ stream?.destroy()
213
+ }
214
+ }
215
+
216
+ cancel(pullId) {
217
+ const t = this.active.get(pullId)
218
+ if (!t) return false
219
+ t.aborted = true
220
+ return true
221
+ }
222
+
223
+ cancelAll() {
224
+ for (const t of this.active.values()) t.aborted = true
225
+ this.active.clear()
226
+ }
227
+
228
+ static get highWaterBytes() {
229
+ return HIGH_WATER_BYTES
230
+ }
231
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * 纯 JS 行级 unified diff(提案 #21):零依赖(不 spawn git、不引 npm 包),
3
+ * 输出有界。副机在任务收尾时为 modify/add/delete 的文本文件生成 diff 块,
4
+ * 随 handoff 上报 —— 远程场景下用户没法随手 `git diff`,这个视图就是证据链。
5
+ *
6
+ * 算法与边界:
7
+ * - 公共前缀/后缀修剪后,中段用经典 DP LCS(每侧 ≤600 行,表 ≤602² × 2B)
8
+ * - 中段超限(巨型重写)不硬算:退化为"统计式"输出(@@ 头 + 近似增删行数
9
+ * + 明确标注未逐行展开)—— 宁可粗也不 O(n²) 爆内存
10
+ * - 输出 3 行上下文,相邻 hunk 间距 ≤6 行则合并;总输出超 maxBytes 截断
11
+ * - 输入按行数裁剪到 maxLines(超出部分不参与 diff,由 truncated 标注)
12
+ */
13
+
14
+ /** 每侧进入 LCS 的最大行数(前缀/后缀修剪后的中段)。 */
15
+ const MAX_LCS_LINES = 600
16
+ /** 单文件 diff 输出字节上限。 */
17
+ const MAX_DIFF_BYTES = 16 * 1024
18
+
19
+ /**
20
+ * 生成一个文件的 unified diff。
21
+ *
22
+ * @param {object} o
23
+ * @param {string} o.path 相对路径(diff 头里的 a/ b/ 用)
24
+ * @param {string} o.beforeText 前像文本(新增文件传 '')
25
+ * @param {string} o.afterText 后像文本(删除文件传 '')
26
+ * @param {number} [o.maxBytes] 输出字节上限
27
+ * @returns {{path: string, diff: string, truncated: boolean}|null}
28
+ * 无文本差异返回 null。
29
+ */
30
+ export function unifiedDiff({ path: filePath, beforeText, afterText, maxBytes = MAX_DIFF_BYTES }) {
31
+ const aLines = clipLines(String(beforeText ?? ''))
32
+ const bLines = clipLines(String(afterText ?? ''))
33
+ const truncatedInput = aLines.truncated || bLines.truncated
34
+
35
+ let out = `--- a/${filePath}\n+++ b/${filePath}\n`
36
+
37
+ // 1) 公共前缀/后缀修剪:绝大多数真实编辑只动文件的一小段
38
+ let start = 0
39
+ while (start < aLines.list.length && start < bLines.list.length && aLines.list[start] === bLines.list[start]) start += 1
40
+ let endA = aLines.list.length
41
+ let endB = bLines.list.length
42
+ while (endA > start && endB > start && aLines.list[endA - 1] === bLines.list[endB - 1]) { endA -= 1; endB -= 1 }
43
+
44
+ const midA = aLines.list.slice(start, endA)
45
+ const midB = bLines.list.slice(start, endB)
46
+ if (midA.length === 0 && midB.length === 0) return null // 无差异
47
+
48
+ // 2) 中段超限:统计式降级(近似按"整段替换"计数)
49
+ if (midA.length > MAX_LCS_LINES || midB.length > MAX_LCS_LINES) {
50
+ out += `@@ -${start + 1},${midA.length} +${start + 1},${midB.length} @@\n`
51
+ out += `# 内容过长未逐行展开(前像 ${midA.length} 行 / 后像 ${midB.length} 行,按替换近似 +${midB.length} -${midA.length})\n`
52
+ return { path: filePath, diff: out, truncated: true }
53
+ }
54
+
55
+ // 3) DP LCS(0/1 表 + 回溯)
56
+ const n = midA.length
57
+ const m = midB.length
58
+ const w = m + 1
59
+ const table = new Uint16Array((n + 1) * w)
60
+ for (let i = n - 1; i >= 0; i -= 1) {
61
+ for (let j = m - 1; j >= 0; j -= 1) {
62
+ table[i * w + j] = midA[i] === midB[j]
63
+ ? table[(i + 1) * w + (j + 1)] + 1
64
+ : Math.max(table[(i + 1) * w + j], table[i * w + (j + 1)])
65
+ }
66
+ }
67
+
68
+ /** 编辑脚本:{ t: ' '|'+'|'-', line },覆盖整份文件(含未变段,hunk 划分用) */
69
+ const script = []
70
+ for (let k = 0; k < start; k += 1) script.push({ t: ' ', line: aLines.list[k] })
71
+ let i = 0
72
+ let j = 0
73
+ while (i < n && j < m) {
74
+ if (midA[i] === midB[j]) { script.push({ t: ' ', line: midA[i] }); i += 1; j += 1 } else if (table[(i + 1) * w + j] >= table[i * w + (j + 1)]) { script.push({ t: '-', line: midA[i] }); i += 1 } else { script.push({ t: '+', line: midB[j] }); j += 1 }
75
+ }
76
+ while (i < n) { script.push({ t: '-', line: midA[i] }); i += 1 }
77
+ while (j < m) { script.push({ t: '+', line: midB[j] }); j += 1 }
78
+ for (let k = 0; k < aLines.list.length - endA; k += 1) script.push({ t: ' ', line: aLines.list[endA + k] })
79
+
80
+ // 4) hunk 划分:3 行上下文,间隔 ≤6 行合并(窗口 = 3 前缀 + 改动 + 4 截断)
81
+ const changedIdx = []
82
+ for (let k = 0; k < script.length; k += 1) if (script[k].t !== ' ') changedIdx.push(k)
83
+ if (changedIdx.length === 0) return null
84
+
85
+ const hunks = []
86
+ let from = Math.max(0, changedIdx[0] - 3)
87
+ let to = Math.min(script.length, changedIdx[0] + 4)
88
+ for (let k = 1; k < changedIdx.length; k += 1) {
89
+ if (changedIdx[k] - to <= 6) {
90
+ to = Math.min(script.length, changedIdx[k] + 4)
91
+ } else {
92
+ hunks.push([from, to])
93
+ from = Math.max(0, changedIdx[k] - 3)
94
+ to = Math.min(script.length, changedIdx[k] + 4)
95
+ }
96
+ }
97
+ hunks.push([from, to])
98
+
99
+ for (const [from0, to0] of hunks) {
100
+ const body = script.slice(from0, to0)
101
+ const aStart = body.findIndex((s) => s.t !== '+') // 前像行号从 1 计
102
+ const bStart = body.findIndex((s) => s.t !== '-') // 后像行号从 1 计
103
+ const aCount = body.filter((s) => s.t !== '+').length
104
+ const bCount = body.filter((s) => s.t !== '-').length
105
+ out += `@@ -${from0 + aStart + 1},${aCount} +${from0 + bStart + 1},${bCount} @@\n`
106
+ for (const s of body) out += s.t + s.line + '\n'
107
+ }
108
+
109
+ let truncated = truncatedInput
110
+ if (Buffer.byteLength(out, 'utf8') > maxBytes) {
111
+ out = `${out.slice(0, maxBytes)}\n# … 已截断(超过 ${maxBytes} 字节)\n`
112
+ truncated = true
113
+ }
114
+ return { path: filePath, diff: out, truncated }
115
+ }
116
+
117
+ /** 按行切分并裁剪到 1500 行(超出部分丢弃并标注)。 */
118
+ function clipLines(text, maxLines = 1500) {
119
+ const list = text.split(/\r?\n/)
120
+ // 结尾空行是 split 的尾巴("a\n" → ['a','']),不算内容行
121
+ if (list.length > 0 && list[list.length - 1] === '') list.pop()
122
+ if (list.length <= maxLines) return { list, truncated: false }
123
+ return { list: list.slice(0, maxLines), truncated: true }
124
+ }