@twinsearth/dsh-fang 3.1.21 → 3.1.22

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 (113) hide show
  1. package/LICENSES/LICENSES/cordis-MIT.txt +39 -0
  2. package/client.js +197 -3
  3. package/defaults/defaults/umbrella-rules.yaml +113 -0
  4. package/package.json +2 -2
  5. package/sdk/sdk/README.md +65 -0
  6. package/sdk/sdk/examples/status-badge/README.md +16 -0
  7. package/sdk/sdk/examples/status-badge/client.js +60 -0
  8. package/sdk/sdk/examples/status-badge/cordis.patch.yml +7 -0
  9. package/sdk/sdk/examples/status-badge/index.js +12 -0
  10. package/sdk/sdk/examples/status-badge/package.json +24 -0
  11. package/sdk/sdk/templates/plugin/README.md +36 -0
  12. package/sdk/sdk/templates/plugin/client.js +35 -0
  13. package/sdk/sdk/templates/plugin/cordis.patch.yml +8 -0
  14. package/sdk/sdk/templates/plugin/icon.svg +5 -0
  15. package/sdk/sdk/templates/plugin/index.js +23 -0
  16. package/sdk/sdk/templates/plugin/locale/en.json +6 -0
  17. package/sdk/sdk/templates/plugin/package.json +36 -0
  18. package/src/kernel/types.mjs +1 -1
  19. package/src/src/compose.mjs +67 -0
  20. package/src/src/contract/client.js +86 -0
  21. package/src/src/contract/constants.js +79 -0
  22. package/src/src/contract/envelope.js +83 -0
  23. package/src/src/contract/index.js +19 -0
  24. package/src/src/contract/negotiate.js +106 -0
  25. package/src/src/contract/server.js +77 -0
  26. package/src/src/contract/transports.js +301 -0
  27. package/src/src/index.mjs +11 -0
  28. package/src/src/kernel/core.mjs +100 -0
  29. package/src/src/kernel/extensions.mjs +61 -0
  30. package/src/src/kernel/fsx.mjs +349 -0
  31. package/src/src/kernel/index.mjs +21 -0
  32. package/src/src/kernel/ledger.mjs +94 -0
  33. package/src/src/kernel/paths.mjs +182 -0
  34. package/src/src/kernel/role.mjs +68 -0
  35. package/src/src/kernel/rounds.mjs +172 -0
  36. package/src/src/kernel/schema.mjs +5 -0
  37. package/src/src/kernel/types.mjs +264 -0
  38. package/src/src/kernel/vendor/cosmokit.mjs +421 -0
  39. package/src/src/kernel/vendor/schemastery.mjs +638 -0
  40. package/src/src/lib/adapter-client.mjs +383 -0
  41. package/src/src/lib/adapter-protocol.mjs +243 -0
  42. package/src/src/lib/ai-secret-store.mjs +202 -0
  43. package/src/src/lib/boot-guard.mjs +182 -0
  44. package/src/src/lib/branch-store.mjs +84 -0
  45. package/src/src/lib/branch.mjs +74 -0
  46. package/src/src/lib/bridge-client.mjs +133 -0
  47. package/src/src/lib/broker-adapter.mjs +67 -0
  48. package/src/src/lib/broker.mjs +45 -0
  49. package/src/src/lib/business-producers.mjs +109 -0
  50. package/src/src/lib/command-cache.mjs +209 -0
  51. package/src/src/lib/compat.mjs +170 -0
  52. package/src/src/lib/composer-journal.mjs +128 -0
  53. package/src/src/lib/container/index.mjs +806 -0
  54. package/src/src/lib/decision-events.mjs +129 -0
  55. package/src/src/lib/decision-ingest-client.mjs +41 -0
  56. package/src/src/lib/decision-outbox.mjs +129 -0
  57. package/src/src/lib/default-essence.mjs +61 -0
  58. package/src/src/lib/desktop-launch.mjs +138 -0
  59. package/src/src/lib/essence.mjs +1211 -0
  60. package/src/src/lib/fork-client.mjs +410 -0
  61. package/src/src/lib/fork-config-lock.mjs +153 -0
  62. package/src/src/lib/fork-seed.mjs +304 -0
  63. package/src/src/lib/fork-supervision-settings.mjs +58 -0
  64. package/src/src/lib/fork-supervisor.mjs +122 -0
  65. package/src/src/lib/fs-guard.mjs +28 -0
  66. package/src/src/lib/http-auth.mjs +162 -0
  67. package/src/src/lib/idle-audit.mjs +178 -0
  68. package/src/src/lib/interaction-poke.mjs +61 -0
  69. package/src/src/lib/mirror-etag.mjs +92 -0
  70. package/src/src/lib/mirror-official-source.mjs +93 -0
  71. package/src/src/lib/mirror.mjs +478 -0
  72. package/src/src/lib/mother-link.mjs +156 -0
  73. package/src/src/lib/mutex.mjs +31 -0
  74. package/src/src/lib/permissions.mjs +115 -0
  75. package/src/src/lib/pnpm-store.mjs +189 -0
  76. package/src/src/lib/preferences.mjs +212 -0
  77. package/src/src/lib/producer-contract.mjs +162 -0
  78. package/src/src/lib/reflow.mjs +41 -0
  79. package/src/src/lib/remote.mjs +408 -0
  80. package/src/src/lib/restart-contract.mjs +650 -0
  81. package/src/src/lib/roots.mjs +30 -0
  82. package/src/src/lib/rule-registry.mjs +1101 -0
  83. package/src/src/lib/runtime-capture.mjs +307 -0
  84. package/src/src/lib/semaphore.mjs +34 -0
  85. package/src/src/lib/session-bundle.mjs +138 -0
  86. package/src/src/lib/session-format.mjs +658 -0
  87. package/src/src/lib/sse-parser.mjs +102 -0
  88. package/src/src/lib/ssrf-guard.mjs +170 -0
  89. package/src/src/lib/status-store.mjs +257 -0
  90. package/src/src/lib/task-handle.mjs +622 -0
  91. package/src/src/lib/ui-actions.mjs +55 -0
  92. package/src/src/lib/umbrella.mjs +1661 -0
  93. package/src/src/lib/upgrade-coordinator.mjs +107 -0
  94. package/src/src/lib/upgrade-status.mjs +43 -0
  95. package/src/src/plugins/adapter.mjs +1468 -0
  96. package/src/src/plugins/approver.mjs +1210 -0
  97. package/src/src/plugins/auditor.mjs +330 -0
  98. package/src/src/plugins/buffer-keeper.mjs +522 -0
  99. package/src/src/plugins/decision-center.mjs +2265 -0
  100. package/src/src/plugins/forker.mjs +1594 -0
  101. package/src/src/plugins/healer.mjs +664 -0
  102. package/src/src/plugins/hot-reloader.mjs +274 -0
  103. package/src/src/plugins/imports.mjs +247 -0
  104. package/src/src/plugins/orchestrator.mjs +3806 -0
  105. package/src/src/plugins/restart-guard.mjs +948 -0
  106. package/src/src/plugins/router.mjs +714 -0
  107. package/src/src/plugins/scorer.mjs +624 -0
  108. package/src/src/plugins/session-bridge.mjs +166 -0
  109. package/src/src/plugins/session-catalog.mjs +771 -0
  110. package/src/src/plugins/session-router.mjs +125 -0
  111. package/src/src/plugins/session-sync.mjs +171 -0
  112. package/src/src/plugins/umbrella.mjs +419 -0
  113. package/tools/recover-queue.mjs +133 -0
@@ -0,0 +1,1594 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ // dsh-Fang 2.0 — fang-forker: the process layer for disposable fork dsh-Web instances.
4
+ //
5
+ // Hard boundary (CONTRACTS-V2.md §5.5 / §1):
6
+ // * mother-only: apply() starts with roleGate('forker'); in a fork nothing is registered.
7
+ // * The mother is immutable. `provision` only READS profileTemplate. With cleanTemplate
8
+ // (v2 default) the fork profile is cloned from a *forker-owned clean template* (written
9
+ // under the fork home), so a dirty mother profile can never leak into a fork; from the
10
+ // mother it takes one thing only — the node_modules source for the junction.
11
+ // Removal always goes through fsx.removeTree() (junction-safe: never enters the mother).
12
+ // * A fork shares nothing: its own DSH_HOME (env.DSH_HOME=homeDir), its own buffer dir,
13
+ // and in v2 a *deterministic* port from the pool (18000–18100) instead of --port 0.
14
+ // `allocatePorts=false` keeps the v1 `--port 0` behaviour.
15
+ // * This plugin owns process lifecycle only. Risk scoring / approval / routing / adapter
16
+ // handshakes do not live here (scorer / approver / router / adapter own those).
17
+ //
18
+ // Port pool (v2):
19
+ // * ports are probed with net.createServer().listen({port,host:'127.0.0.1'}) — a port is
20
+ // usable only if the bind test succeeds; a busy port is skipped (next candidate).
21
+ // * the occupancy table is persisted to <dataRoot>/ports.json as {port:{forkId,pid,at}}.
22
+ // On first port use, entries whose recorded child pid is dead (or that never got a pid)
23
+ // are reclaimed, so a crashed mother can never leak the deterministic pool forever.
24
+ // * spawn validates the child's printed URL port against the port it was told to bind:
25
+ // a mismatch is a hard failure (child stopped, {ok:false,error:'port-mismatch'}).
26
+ // * stop/reap/dispose release the port; pool exhaustion is {ok:false,error:'port-exhausted'}.
27
+ //
28
+ // Windows launch note (measured): the default launcher is a `.cmd`
29
+ // (<DSH_INSTALL>\resources\runtime\cli\bin\dsh.cmd). child_process.spawn('.cmd') throws
30
+ // EINVAL/ENOENT without a shell, so `.cmd`/`.bat` must be launched with
31
+ // `shell: true`; `.mjs`/`.js` entries are launched through node; `.exe` directly.
32
+ import { spawn as spawnProcess, spawnSync } from 'node:child_process'
33
+ import { randomBytes } from 'node:crypto'
34
+ import fs from 'node:fs'
35
+ import { createRequire } from 'node:module'
36
+ import net from 'node:net'
37
+ import path from 'node:path'
38
+ import {
39
+ AUDIT,
40
+ EXIT,
41
+ FORK_STATUS,
42
+ SERVICE,
43
+ bus,
44
+ copyTree,
45
+ ensureDir,
46
+ ensureModuleMirror,
47
+ exists,
48
+ iso,
49
+ listFiles,
50
+ mirrorModuleTree,
51
+ newId,
52
+ nowMs,
53
+ parseWebUrl,
54
+ readJson,
55
+ removeTree,
56
+ resolveFangLayout,
57
+ roleGate,
58
+ writeFileAtomic,
59
+ writeJsonAtomic,
60
+ z,
61
+ } from '../kernel/index.mjs'
62
+ import { computeBackoff, planRestart, reconcileOrphans, writeForkMeta, probeHttpAlive, SUPERVISION_DEFAULTS } from '../lib/fork-supervisor.mjs'
63
+ import { applyForkConfigLock, setProfileConfigReadonly } from '../lib/fork-config-lock.mjs'
64
+ import { DEFAULT_FORK_SEED, applyForkSeedToProfile } from '../lib/fork-seed.mjs'
65
+
66
+ export const name = 'fang-forker'
67
+ export const inject = []
68
+
69
+ /** In-process event topics (CONTRACTS.md §6). */
70
+ const EVENTS = {
71
+ started: 'fang/fork-started',
72
+ crashed: 'fang/fork-crashed',
73
+ reaped: 'fang/fork-reaped',
74
+ /** v2.7.3:自动重启失败 / 放弃重启(terminal=true 表示不会再有自动重试)。 */
75
+ restartFailed: 'fang/fork-restart-failed',
76
+ }
77
+
78
+ /** v2 deterministic port pool (CONTRACTS-V2.md §5.5). */
79
+ const DEFAULT_PORT_POOL = { start: 18000, end: 18100 }
80
+ /** Loopback interface a fork's `dsh web` binds; the pool is probed on the same host. */
81
+ const PORT_HOST = '127.0.0.1'
82
+ /** A bind probe that does not answer by then counts as "not usable" (fail-closed, try next). */
83
+ const PORT_PROBE_TIMEOUT_MS = 5000
84
+ /** Bundle list of the clean fork profile: base + web app + this bundle (Cordis patch). */
85
+ const CLEAN_TEMPLATE_BUNDLES = ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app']
86
+
87
+ // v3.1.0: DSH's first-run preview notice persists ui-settings-general.welcomeNoticeVersion.
88
+ // A clean profile that omits the row leaves the config form unavailable, so 「继续」 always
89
+ // reports "暂时无法保存确认状态". Seed the acknowledgement in every generated clean profile;
90
+ // the fork lock then appends its own disable rows.
91
+ const WELCOME_NOTICE_PATCH = [
92
+ '- id: ui-settings-general',
93
+ ' name: "@deepseek-ai/dsh-client-ui-settings-general"',
94
+ ' config:',
95
+ ' welcomeNoticeVersion: 2026-09-28.1',
96
+ '',
97
+ ].join('\n')
98
+
99
+ const DEFAULTS = {
100
+ cliPath: '',
101
+ profileTemplate: '',
102
+ startTimeoutMs: 60000,
103
+ maxForks: 8,
104
+ maxLogLines: 400,
105
+ dataRoot: '',
106
+ portPool: { ...DEFAULT_PORT_POOL },
107
+ allocatePorts: true,
108
+ cleanTemplate: true,
109
+ bundleName: '@twinsearth/dsh-fang',
110
+ forkProfileTag: 'web-base',
111
+ }
112
+
113
+ /** Files cloned from a (clean or mother) template profile: package.json + cordis*.yml only. */
114
+ const CLONED_RE = /^(package\.json|cordis.*\.ya?ml)$/i
115
+ const PROFILE_UNSAFE_RE = /[^a-zA-Z0-9_.-]/g
116
+ /** stdout/stderr scan window kept for `parseWebUrl` (the banner may be split over chunks). */
117
+ const SCAN_TEXT_LIMIT = 64 * 1024
118
+
119
+ export { parseWebUrl }
120
+
121
+ export const Config = z
122
+ .object({
123
+ cliPath: z.string().default('').description('dsh CLI 入口:.exe / .cmd / .mjs(空 = 由 spawn 入参给)'),
124
+ profileTemplate: z
125
+ .string()
126
+ .default('')
127
+ .description('母版 profile 目录:clone 源 / node_modules junction 源(cleanTemplate 时只用后者)'),
128
+ startTimeoutMs: z.natural().default(60000).description('等待 web URL 的启动超时(毫秒)'),
129
+ maxForks: z.natural().default(8).description('允许同时存活的分身上限'),
130
+ maxLogLines: z.natural().default(400).description('每个分身 stdout 滚动缓冲行数'),
131
+ dataRoot: z.string().default('').description('注册表/端口表落盘根目录(空 = 仅进程内存)'),
132
+ portPool: z
133
+ .object({
134
+ start: z.number().default(DEFAULT_PORT_POOL.start).description('端口池起始(含)'),
135
+ end: z.number().default(DEFAULT_PORT_POOL.end).description('端口池结束(含)'),
136
+ })
137
+ .default({})
138
+ .description('确定性端口池 18000–18100'),
139
+ allocatePorts: z
140
+ .boolean()
141
+ .default(true)
142
+ .description('true:预分配确定性端口(--port <port>);false:退回 v1 的 --port 0'),
143
+ cleanTemplate: z
144
+ .boolean()
145
+ .default(true)
146
+ .description('true:用内置干净模板(不继承母体脏 profile);false:沿用 profileTemplate'),
147
+ bundleName: z.string().default('@twinsearth/dsh-fang').description('干净模板 profile.bundles 的第三个 bundle'),
148
+ forkProfileTag: z.string().default('web-base').description('干净模板 profile 标签(模板目录/缺省 profile 名)'),
149
+ // v3.1.12:新机器/新用户的干净分身默认不带第三方插件;这里按“安装不激活 /
150
+ // 安装并激活”两组清单给每个新分身装默认插件(开关可关;失败不阻塞分身启动)。
151
+ forkSeed: z
152
+ .object({
153
+ enabled: z.boolean().default(true).description('派生新分身时安装默认第三方插件种子'),
154
+ install: z.array(z.string()).default([...DEFAULT_FORK_SEED.install]).description('只安装、不加入 profile bundles 的插件包名'),
155
+ activate: z.array(z.string()).default([...DEFAULT_FORK_SEED.activate]).description('安装并加入 profile bundles 的插件包名'),
156
+ })
157
+ .default({})
158
+ .description('派生分身的默认第三方插件种子'),
159
+ supervise: z.boolean().default(false)
160
+ .description('restart a crashed (already-ready) fork with exponential backoff; the patch layer enables it'),
161
+ maxRestarts: z.natural().default(SUPERVISION_DEFAULTS.maxRestarts)
162
+ .description('max automatic restarts per fork'),
163
+ backoffBaseMs: z.natural().default(SUPERVISION_DEFAULTS.baseMs)
164
+ .description('backoff base in milliseconds'),
165
+ backoffMaxMs: z.natural().default(SUPERVISION_DEFAULTS.maxMs)
166
+ .description('backoff cap in milliseconds'),
167
+ backoffJitter: z.number().min(0).max(0.9).default(SUPERVISION_DEFAULTS.jitter)
168
+ .description('backoff jitter ratio'),
169
+ healthPath: z.string().default(SUPERVISION_DEFAULTS.healthPath)
170
+ .description('HTTP liveness path (any response counts)')
171
+ })
172
+ .description('fang-forker 配置')
173
+
174
+ const msgOf = (e) => String(e && e.message ? e.message : e)
175
+
176
+ function safeProfile(value) {
177
+ const p = String(value ?? '').trim().replace(PROFILE_UNSAFE_RE, '_')
178
+ return p && p !== '.' && p !== '..' ? p : 'default'
179
+ }
180
+
181
+ /**
182
+ * Pure: is this cliPath a Windows shell launcher (.cmd/.bat)?
183
+ * Measured on Windows: spawn('...dsh.cmd', args) throws EINVAL/ENOENT unless shell:true.
184
+ */
185
+ export function isShellLauncher(cliPath) {
186
+ return /\.(cmd|bat)$/i.test(String(cliPath ?? '').trim())
187
+ }
188
+
189
+ /**
190
+ * Pure: argv appended to the CLI (CONTRACTS.md §5.1).
191
+ * v2: with allocatePorts the forker passes the pre-allocated `--port <n>`; the v1 fallback
192
+ * is still `--port 0` (OS picks a free port).
193
+ * v3.1.7: `patchPaths` are launcher layers (`--patch <path>`) handed to the child before
194
+ * its app args; the headless directory-picker overlay travels this way.
195
+ * @returns {string[]}
196
+ */
197
+ export function buildSpawnArgs({ profile = 'default', port = 0, noOpen = true, patchPaths = [] } = {}) {
198
+ const n = Math.floor(Number(port))
199
+ const p = Number.isInteger(n) && n >= 0 && n <= 65535 ? n : 0
200
+ const args = ['--profile', safeProfile(profile)]
201
+ for (const entry of Array.isArray(patchPaths) ? patchPaths : []) {
202
+ const patchPath = String(entry ?? '').trim()
203
+ if (patchPath) args.push('--patch', patchPath)
204
+ }
205
+ args.push('--port', String(p))
206
+ if (noOpen) args.push('--no-open')
207
+ return args
208
+ }
209
+
210
+ /**
211
+ * Pure: turn a cliPath into the exact `{command, args, shell}` triple to spawn.
212
+ * .cmd / .bat → shell launcher (shell:true)
213
+ * .mjs/.cjs/.js→ node + script prefix
214
+ * anything else (normally .exe) → direct spawn
215
+ * Never touches the filesystem, so it is safe to unit-test without launching anything.
216
+ * @returns {{command:string, args:string[], shell:boolean, windowsHide:boolean, nodeScript:boolean}}
217
+ */
218
+ export function buildLaunchSpec({ cliPath = '', profile = 'default', port = 0, patchPaths = [] } = {}) {
219
+ const entry = String(cliPath ?? '').trim()
220
+ const args = buildSpawnArgs({ profile, port, patchPaths })
221
+ if (isShellLauncher(entry)) {
222
+ // `shell: true` concatenates argv without escaping (DEP0190); a profile home or overlay
223
+ // path containing whitespace would otherwise split into two child arguments.
224
+ const quoted = args.map((arg) => (/[\s"]/u.test(arg) ? `"${String(arg).replace(/"/g, '\\"')}"` : arg))
225
+ return { command: entry, args: quoted, shell: true, windowsHide: true, nodeScript: false }
226
+ }
227
+ if (/\.(mjs|cjs|js)$/i.test(entry)) {
228
+ return { command: process.execPath, args: [entry, ...args], shell: false, windowsHide: true, nodeScript: true }
229
+ }
230
+ return { command: entry, args, shell: false, windowsHide: true, nodeScript: false }
231
+ }
232
+
233
+ /**
234
+ * v3.0.5/B5:派生进程环境变量白名单(不再全量继承母体 env —— 防止云密钥/适配器 token 泄漏给最低信任层)。
235
+ * 只放行启动 DSH 必需的运行时/代理变量;DSH_*、API key、token 等一律不继承(由 overrides 显式注入)。
236
+ * @param {Record<string, string|undefined>} [base]
237
+ * @param {Record<string, string|undefined>} [overrides]
238
+ * @returns {Record<string, string>}
239
+ */
240
+ export function buildForkChildEnv(base = process.env, overrides = {}) {
241
+ const KEYS = [
242
+ 'PATH', 'Path', 'PATHEXT', 'SystemRoot', 'SystemDrive', 'windir', 'ComSpec',
243
+ 'TEMP', 'TMP', 'TMPDIR', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA',
244
+ 'PROGRAMDATA', 'PROGRAMFILES', 'PROGRAMFILES(X86)', 'OS', 'NUMBER_OF_PROCESSORS',
245
+ 'PROCESSOR_ARCHITECTURE', 'USERNAME', 'USERDOMAIN', 'LANG', 'LC_ALL', 'TERM', 'SHELL',
246
+ 'HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'http_proxy', 'https_proxy', 'no_proxy',
247
+ ]
248
+ /** @type {Record<string,string>} */
249
+ const env = {}
250
+ for (const key of KEYS) {
251
+ if (typeof base?.[key] === 'string') env[key] = base[key]
252
+ }
253
+ for (const [key, value] of Object.entries(overrides ?? {})) {
254
+ if (typeof value === 'string') env[key] = value
255
+ else delete env[key]
256
+ }
257
+ return env
258
+ }
259
+
260
+ /**
261
+ * The launch overlay that pins the directory picker to the browser dialog in every
262
+ * fork/ESSENCE-RUNTIME web host.
263
+ *
264
+ * `dsh-host-directory-picker-auto` resolves `native` on win32/darwin whenever the
265
+ * bind is loopback and the launch is not SSH — it has no way to know the host was
266
+ * started headless through `dsh.cmd` (ELECTRON_RUN_AS_NODE, no Electron shell), so
267
+ * the native chooser has no window to open and "选择工作区" fails in the fork Web UI
268
+ * (v3.1.7 report). The documented composition switch is an overlay that disables
269
+ * the auto row and mounts the browse backend + its client surface directly; both
270
+ * package names exist as installation dependencies of the same DSH release.
271
+ */
272
+ export const HEADLESS_PICKER_OVERLAY = [
273
+ '# dsh-Fang v3.1.7: headless web host (dsh.cmd --no-open) has no native chooser window.',
274
+ '# Pin the directory-picker interaction to the browser dialog.',
275
+ '- id: directory-picker',
276
+ ' disabled: true',
277
+ '- insert:',
278
+ ' - id: directory-picker-browse',
279
+ " name: '@deepseek-ai/dsh-host-directory-picker-browse'",
280
+ ' - id: ui-directory-picker-browse',
281
+ " name: '@deepseek-ai/dsh-client-ui-directory-picker-browse'",
282
+ '',
283
+ ].join('\n')
284
+
285
+ /** File name of the headless launch overlay inside the fork/essence-runtime profile. */
286
+ export const HEADLESS_PICKER_OVERLAY_FILE = 'fang-headless.patch.yml'
287
+
288
+ /** Whether this DSH installation carries the browse-picker pair the overlay mounts. */
289
+ export function headlessPickerSupported({ cliPath = '' } = {}) {
290
+ const names = [
291
+ '@deepseek-ai/dsh-host-directory-picker-browse',
292
+ '@deepseek-ai/dsh-client-ui-directory-picker-browse',
293
+ ]
294
+ let require = null
295
+ try { require = createRequire(import.meta.url) } catch { require = null }
296
+ const anchors = []
297
+ // Desktop install: <root>/resources/app.asar/dsh/node_modules (asar-aware fs in the host).
298
+ try { anchors.push(path.join(path.dirname(process.execPath), 'resources', 'app.asar', 'dsh', 'node_modules')) } catch { /* ignore */ }
299
+ // Launcher-derived install root: .../resources/runtime/cli/bin/dsh.cmd → .../resources/app.asar/dsh/node_modules
300
+ const cli = String(cliPath ?? '').trim()
301
+ if (cli) {
302
+ const resources = path.resolve(path.dirname(cli), '..', '..', '..', '..', 'resources')
303
+ anchors.push(path.join(resources, 'app.asar', 'dsh', 'node_modules'))
304
+ }
305
+ for (const name of names) {
306
+ let found = false
307
+ if (require) {
308
+ try { require.resolve(name); found = true } catch { /* not resolvable here */ }
309
+ }
310
+ if (!found) {
311
+ for (const anchor of anchors) {
312
+ try {
313
+ if (fs.existsSync(path.join(anchor, ...name.split('/'), 'package.json'))) { found = true; break }
314
+ } catch { /* ignore */ }
315
+ }
316
+ }
317
+ if (!found) return false
318
+ }
319
+ return true
320
+ }
321
+
322
+ /**
323
+ * Write (or refresh) the headless-picker launch overlay in `profileDir`.
324
+ * `DSH_FANG_HEADLESS_PICKER_PATCH=0` opts out; an installation without the browse
325
+ * pair keeps the DSH default (native) so an unknown-version host is not patched blind.
326
+ * @param {string} profileDir The fork/essence-runtime profile directory.
327
+ * @param {{cliPath?: string, supported?: boolean}} [options] The launcher the fork will
328
+ * be started with; `supported` overrides the installation probe (tests).
329
+ * @returns {string|null} The overlay path to pass as `--patch`, or null.
330
+ */
331
+ export function writeHeadlessPickerOverlay(profileDir, { cliPath = '', supported } = {}) {
332
+ if (String(process.env.DSH_FANG_HEADLESS_PICKER_PATCH ?? '1') === '0') return null
333
+ if (!profileDir || !exists(profileDir)) return null
334
+ const available = typeof supported === 'boolean' ? supported : headlessPickerSupported({ cliPath })
335
+ if (!available) return null
336
+ const file = path.join(profileDir, HEADLESS_PICKER_OVERLAY_FILE)
337
+ try {
338
+ writeFileAtomic(file, HEADLESS_PICKER_OVERLAY)
339
+ return file
340
+ } catch {
341
+ return null
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Pure: why did a fork exit? (CONTRACTS.md §5.1)
347
+ * 0 = normal, 75 = the guard allowed a restart (supervisor contract), else crash.
348
+ * @returns {{kind:'normal'|'restart-request'|'crash', code:number|null, signal:string|null, restartRequested:boolean}}
349
+ */
350
+ export function classifyExit(code, signal = null) {
351
+ const n = code === null || code === undefined || Number.isNaN(Number(code)) ? null : Number(code)
352
+ if (n === EXIT.OK) return { kind: 'normal', code: n, signal, restartRequested: false }
353
+ if (n === EXIT.RESTART) return { kind: 'restart-request', code: n, signal, restartRequested: true }
354
+ return { kind: 'crash', code: n, signal, restartRequested: false }
355
+ }
356
+
357
+ /**
358
+ * Pure: normalise a configured port pool. Returns null for an unusable range, so the
359
+ * caller can fall back to the contract default instead of silently allocating nothing.
360
+ * @returns {{start:number, end:number}|null}
361
+ */
362
+ export function resolvePortPool(pool) {
363
+ const start = Math.floor(Number(pool?.start))
364
+ const end = Math.floor(Number(pool?.end))
365
+ if (!Number.isInteger(start) || !Number.isInteger(end)) return null
366
+ if (start < 1 || end > 65535 || start > end) return null
367
+ return { start, end }
368
+ }
369
+
370
+ /**
371
+ * Pure: the clean fork profile's package.json (CONTRACTS-V2.md §5.5).
372
+ * `dsh.profile.bundles` is the loader contract: base plugins, the web app, then this
373
+ * bundle — nothing inherited from the mother profile.
374
+ * @returns {{name:string, version:string, private:boolean, dsh:{profile:{bundles:string[]}}}}
375
+ */
376
+ export function buildTemplatePackageJson({ bundleName = DEFAULTS.bundleName, forkProfileTag = DEFAULTS.forkProfileTag } = {}) {
377
+ const tag = safeProfile(forkProfileTag)
378
+ const bundles = [...CLEAN_TEMPLATE_BUNDLES, String(bundleName ?? '').trim() || DEFAULTS.bundleName]
379
+ return {
380
+ name: `dsh-fang-fork-${tag}`,
381
+ version: '1.0.0',
382
+ private: true,
383
+ dsh: { profile: { bundles } },
384
+ }
385
+ }
386
+
387
+ /** Rolling stdout tail: line buffer capped at maxLines + a bounded text window for parseWebUrl. */
388
+ function createTextTail(maxLines) {
389
+ const limit = Math.max(0, Math.floor(Number(maxLines) || 0)) || DEFAULTS.maxLogLines
390
+ const lines = []
391
+ let partial = ''
392
+ let text = ''
393
+ const trim = () => {
394
+ if (lines.length > limit) lines.splice(0, lines.length - limit)
395
+ }
396
+ return {
397
+ lines,
398
+ get text() {
399
+ return text
400
+ },
401
+ push(chunk) {
402
+ const s = String(chunk ?? '')
403
+ text = (text + s).slice(-SCAN_TEXT_LIMIT)
404
+ partial += s
405
+ let idx
406
+ while ((idx = partial.indexOf('\n')) >= 0) {
407
+ lines.push(partial.slice(0, idx).replace(/\r$/, ''))
408
+ partial = partial.slice(idx + 1)
409
+ }
410
+ trim()
411
+ return s
412
+ },
413
+ feed(chunk) {
414
+ return this.push(chunk)
415
+ },
416
+ tail(n = 40) {
417
+ const count = Math.max(0, Math.floor(Number(n) || 0))
418
+ if (count === 0) return ''
419
+ const all = partial ? [...lines, partial.replace(/\r$/, '')] : lines
420
+ return all.slice(-count).join('\n')
421
+ },
422
+ }
423
+ }
424
+
425
+ /** Is this pid still alive? EPERM means "exists but not ours" — still alive. */
426
+ function isPidAlive(pid) {
427
+ const n = Number(pid)
428
+ if (!Number.isInteger(n) || n <= 0) return false
429
+ try {
430
+ process.kill(n, 0)
431
+ return true
432
+ } catch (e) {
433
+ return e && e.code === 'EPERM'
434
+ }
435
+ }
436
+
437
+ /**
438
+ * Bind-test one port on loopback: resolve true only when net can actually listen on it.
439
+ * Asynchronous by contract: never blocks the host event loop while probing a busy pool.
440
+ * @returns {Promise<boolean>}
441
+ */
442
+ function probePortFree(port, { host = PORT_HOST, timeoutMs = PORT_PROBE_TIMEOUT_MS } = {}) {
443
+ return new Promise((resolve) => {
444
+ const server = net.createServer()
445
+ let settled = false
446
+ let timer = null
447
+ const done = (free) => {
448
+ if (settled) return
449
+ settled = true
450
+ if (timer) clearTimeout(timer)
451
+ try {
452
+ server.close(() => {})
453
+ } catch {
454
+ /* already closed */
455
+ }
456
+ resolve(free)
457
+ }
458
+ timer = setTimeout(() => done(false), Math.max(1, Math.floor(timeoutMs) || PORT_PROBE_TIMEOUT_MS))
459
+ timer.unref?.()
460
+ server.once('error', () => done(false))
461
+ try {
462
+ server.listen({ port, host, exclusive: true }, () => done(true))
463
+ } catch {
464
+ done(false)
465
+ }
466
+ })
467
+ }
468
+
469
+ export function apply(ctx, config) {
470
+ // v2 deployment matrix: forker is a mother-only organ. Must be the FIRST statement —
471
+ // in a fork role nothing (service / timer / dir) may be created.
472
+ const gate = roleGate('forker', { cfgRole: config?.role, logger: ctx?.logger })
473
+ // v2 deployment matrix: this plugin is not deployed in this role — register nothing.
474
+ if (!gate.active) return
475
+
476
+ const rawConfig = { ...DEFAULTS, ...(config ?? {}) }
477
+ const portPool = resolvePortPool(rawConfig.portPool) ?? { ...DEFAULT_PORT_POOL }
478
+ const allocatePorts = rawConfig.allocatePorts !== false
479
+ const cleanTemplate = rawConfig.cleanTemplate !== false
480
+ const bundleName = String(rawConfig.bundleName ?? DEFAULTS.bundleName).trim() || DEFAULTS.bundleName
481
+ const forkProfileTag = safeProfile(rawConfig.forkProfileTag)
482
+ const cfg = { ...rawConfig, portPool, allocatePorts, cleanTemplate, bundleName, forkProfileTag }
483
+ // 运行时 supervise 开关:patch/config 的初值 + 可在不重启宿主的情况下切换(UI/API)。
484
+ let runtimeSupervise = cfg.supervise === true
485
+
486
+ const logger = ctx?.logger ?? { debug() {}, info() {}, warn() {}, error() {} }
487
+ const logWarn = (line) => {
488
+ try {
489
+ logger.warn?.(line)
490
+ } catch {
491
+ /* logger must never break the process layer */
492
+ }
493
+ }
494
+
495
+ /** Cross-plugin reads are always tolerant (auditor/approver may be disabled rows). */
496
+ const safeGet = (key) => {
497
+ try {
498
+ return ctx?.get?.(key)
499
+ } catch {
500
+ return undefined
501
+ }
502
+ }
503
+ const audit = (kind, data) => {
504
+ try {
505
+ const auditor = safeGet(SERVICE.auditor)
506
+ if (auditor && typeof auditor.append === 'function') return auditor.append(kind, data)
507
+ } catch {
508
+ /* auditing must never break fork lifecycle */
509
+ }
510
+ return null
511
+ }
512
+ const emit = (topic, payload) => {
513
+ try {
514
+ return bus.emit(topic, payload)
515
+ } catch {
516
+ return 0
517
+ }
518
+ }
519
+
520
+ /** 广播 Adapter token 刷新/生成;handler 异常隔离,绝不影响 spawn 流程。 */
521
+ const emitTokenRefresh = (forkId, token) => {
522
+ for (const handler of [...tokenRefreshHandlers]) {
523
+ try {
524
+ handler(forkId, token)
525
+ } catch {
526
+ /* 订阅者异常不得打断 spawn */
527
+ }
528
+ }
529
+ }
530
+
531
+ /** forkId -> fork record. Only the live child handle and log tail are in-memory-only. */
532
+ const records = new Map()
533
+ /** forkId -> disposer for an in-flight spawn promise (so plugin dispose cannot hang one). */
534
+ const pendingSpawns = new Set()
535
+ /** (forkId, token) 订阅者:每次 spawn 重新生成 Adapter token 时广播(首次派生与重启都会触发)。 */
536
+ const tokenRefreshHandlers = new Set()
537
+ /** port -> forkId reserved/assigned by THIS plugin instance (never release another instance's). */
538
+ const ownedPorts = new Map()
539
+ /** port -> {forkId,pid,at} persisted view of the pool (loaded lazily). */
540
+ const portTable = new Map()
541
+
542
+ let forksFile = ''
543
+ let portsFile = ''
544
+ let layout = null
545
+ if (cfg.dataRoot) {
546
+ try {
547
+ layout = resolveFangLayout({ dataRoot: cfg.dataRoot })
548
+ forksFile = layout.forksFile
549
+ portsFile = path.join(layout.dataDir, 'ports.json')
550
+ } catch (e) {
551
+ logWarn(`[fang-forker] layout resolve failed: ${msgOf(e)}`)
552
+ forksFile = ''
553
+ portsFile = ''
554
+ }
555
+ }
556
+ let registryLoaded = false
557
+ let portsLoaded = false
558
+ let disposed = false
559
+ const starting = () => [...records.values()].filter((r) => r.running || r.child || r.starting).length
560
+
561
+ /** v3.0.5/B4:持久化/列表用的 URL 一律去掉 ?token=(token 只在内存)。 */
562
+ const stripUrlToken = (url) => {
563
+ const raw = String(url ?? '')
564
+ if (!raw) return raw || null
565
+ try {
566
+ const parsed = new URL(raw)
567
+ if (!parsed.searchParams.has('token')) return raw
568
+ parsed.searchParams.delete('token')
569
+ return parsed.toString()
570
+ } catch {
571
+ return raw.replace(/([?&])token=[^&#]*&?/i, (_, sep) => (sep === '?' ? '?' : '')).replace(/[?&]$/, '')
572
+ }
573
+ }
574
+
575
+ const publicFork = (rec) => ({
576
+ forkId: rec.forkId,
577
+ taskTitle: rec.taskTitle ?? '',
578
+ status: rec.status ?? FORK_STATUS.STOPPED,
579
+ pid: rec.pid ?? null,
580
+ port: rec.port ?? null,
581
+ url: stripUrlToken(rec.url),
582
+ homeDir: rec.homeDir ?? '',
583
+ profile: rec.profile ?? '',
584
+ profileDir: rec.profileDir ?? '',
585
+ template: rec.template ?? '',
586
+ bufferDir: rec.bufferDir ?? '',
587
+ running: !!rec.running,
588
+ createdAt: rec.createdAt ?? null,
589
+ startedAt: rec.startedAt ?? null,
590
+ exitedAt: rec.exitedAt ?? null,
591
+ exit: rec.exit ?? null,
592
+ lastError: rec.lastError ?? null,
593
+ })
594
+
595
+ /** Load the persisted registry lazily, so `apply()` performs no I/O. */
596
+ const ensureRegistry = () => {
597
+ if (registryLoaded) return
598
+ registryLoaded = true
599
+ if (!forksFile) return
600
+ const saved = readJson(forksFile, null)
601
+ const rows = Array.isArray(saved) ? saved : Array.isArray(saved?.forks) ? saved.forks : []
602
+ for (const row of rows) {
603
+ const forkId = row && String(row.forkId ?? '').trim()
604
+ if (!forkId || records.has(forkId)) continue
605
+ records.set(forkId, { ...row, forkId, running: false, child: null, starting: false, restored: true, log: null })
606
+ }
607
+ }
608
+
609
+ const persist = () => {
610
+ if (!forksFile) return false
611
+ try {
612
+ writeJsonAtomic(forksFile, { at: iso(), forks: [...records.values()].map(publicFork) })
613
+ return true
614
+ } catch (e) {
615
+ logWarn(`[fang-forker] registry write failed: ${msgOf(e)}`)
616
+ return false
617
+ }
618
+ }
619
+
620
+ // ───────────────────────────── port pool ─────────────────────────────
621
+ const portsSnapshot = () => {
622
+ const out = {}
623
+ for (const port of [...portTable.keys()].sort((a, b) => a - b)) out[String(port)] = { ...portTable.get(port) }
624
+ return out
625
+ }
626
+
627
+ const persistPorts = () => {
628
+ if (!portsFile) return false
629
+ try {
630
+ writeJsonAtomic(portsFile, portsSnapshot())
631
+ return true
632
+ } catch (e) {
633
+ logWarn(`[fang-forker] ports write failed: ${msgOf(e)}`)
634
+ return false
635
+ }
636
+ }
637
+
638
+ /**
639
+ * Lazy load + startup reclaim. An entry is kept only when its recorded child pid is alive:
640
+ * a pid-less reservation belongs to a mother that died mid-spawn and must be reclaimed too.
641
+ */
642
+ const ensurePorts = () => {
643
+ if (portsLoaded) return
644
+ portsLoaded = true
645
+ if (!portsFile) return
646
+ const saved = readJson(portsFile, null)
647
+ const rows =
648
+ saved && typeof saved === 'object'
649
+ ? saved.ports && typeof saved.ports === 'object'
650
+ ? saved.ports
651
+ : saved
652
+ : {}
653
+ let changed = false
654
+ for (const [key, meta] of Object.entries(rows)) {
655
+ const port = Number(key)
656
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
657
+ changed = true
658
+ continue
659
+ }
660
+ const pid = meta ? Number(meta.pid) : null
661
+ if (!meta || !isPidAlive(pid)) {
662
+ changed = true
663
+ continue
664
+ }
665
+ portTable.set(port, { forkId: String(meta.forkId ?? ''), pid: Math.floor(pid), at: String(meta.at ?? '') })
666
+ }
667
+ if (changed) persistPorts()
668
+ }
669
+
670
+ /** Reserve a port for this instance (persisted with pid=null until the child exists). */
671
+ const reservePort = (port, forkId) => {
672
+ ensurePorts()
673
+ const n = Math.floor(Number(port))
674
+ if (!Number.isInteger(n) || n < 1 || n > 65535) return { ok: false, port: null, error: 'invalid-port' }
675
+ const existing = portTable.get(n)
676
+ if (existing && !ownedPorts.has(n) && existing.forkId !== String(forkId ?? '')) {
677
+ return { ok: false, port: n, error: 'port-in-use' }
678
+ }
679
+ portTable.set(n, { forkId: String(forkId ?? ''), pid: null, at: iso() })
680
+ ownedPorts.set(n, String(forkId ?? ''))
681
+ persistPorts()
682
+ return { ok: true, port: n }
683
+ }
684
+
685
+ /** Attach the real child pid to a reservation so a later startup can prove liveness. */
686
+ const bindPortToPid = (port, forkId, pid) => {
687
+ const n = Math.floor(Number(port))
688
+ if (ownedPorts.get(n) !== forkId) return false
689
+ portTable.set(n, { forkId, pid: Number(pid) || null, at: iso() })
690
+ persistPorts()
691
+ return true
692
+ }
693
+
694
+ /** Release a port owned by this instance (never another instance's / another fork's). */
695
+ const releaseOwnedPort = (port, forkId) => {
696
+ ensurePorts()
697
+ const n = Math.floor(Number(port))
698
+ if (!Number.isInteger(n) || n < 1) return { ok: true, port: null, released: false }
699
+ const owner = ownedPorts.get(n)
700
+ if (owner === undefined || (forkId && owner !== forkId)) {
701
+ return { ok: true, port: n, released: false, reason: 'not-owned' }
702
+ }
703
+ ownedPorts.delete(n)
704
+ const entry = portTable.get(n)
705
+ if (!entry) return { ok: true, port: n, released: false }
706
+ if (forkId && entry.forkId && entry.forkId !== forkId) {
707
+ return { ok: true, port: n, released: false, reason: 'not-owner' }
708
+ }
709
+ portTable.delete(n)
710
+ persistPorts()
711
+ return { ok: true, port: n, released: true }
712
+ }
713
+
714
+ /** Public release: removes any persisted entry for the port (operator/test escape hatch). */
715
+ const releasePort = (port) => {
716
+ ensurePorts()
717
+ const n = Math.floor(Number(port))
718
+ if (!Number.isInteger(n) || n < 1 || n > 65535) {
719
+ return { ok: false, port: null, released: false, error: 'invalid-port' }
720
+ }
721
+ ownedPorts.delete(n)
722
+ const held = portTable.delete(n)
723
+ if (held) persistPorts()
724
+ return { ok: true, port: n, released: held }
725
+ }
726
+
727
+ /**
728
+ * Allocate one deterministic port from the pool. A candidate is usable only when the
729
+ * loopback bind test succeeds; occupied candidates are skipped. Pool exhausted → error.
730
+ * @returns {Promise<{ok:boolean, port:number|null, reason:string, error?:string, pool?:object}>}
731
+ */
732
+ const allocatePort = async (opts = {}) => {
733
+ ensurePorts()
734
+ const forkId = String(opts.forkId ?? '').trim()
735
+ const { start, end } = portPool
736
+ for (let port = start; port <= end; port++) {
737
+ if (portTable.has(port)) continue
738
+ let free = false
739
+ try {
740
+ free = await probePortFree(port)
741
+ } catch {
742
+ free = false
743
+ }
744
+ if (!free) continue
745
+ portTable.set(port, { forkId, pid: null, at: iso() })
746
+ ownedPorts.set(port, forkId)
747
+ persistPorts()
748
+ return { ok: true, port, forkId, reason: '' }
749
+ }
750
+ return {
751
+ ok: false,
752
+ port: null,
753
+ forkId,
754
+ reason: 'port-exhausted',
755
+ error: 'port-exhausted',
756
+ pool: { ...portPool },
757
+ }
758
+ }
759
+
760
+ /** Windows: taskkill /PID <pid> /T /F kills the whole tree (electron children too). */
761
+ const killTree = (rec) => {
762
+ const pid = rec?.pid ?? rec?.child?.pid ?? null
763
+ if (process.platform === 'win32' && pid) {
764
+ try {
765
+ const res = spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true, timeout: 10000 })
766
+ if (res && res.status === 0) return true
767
+ } catch {
768
+ /* fall through to child.kill */
769
+ }
770
+ }
771
+ try {
772
+ if (rec?.child && typeof rec.child.kill === 'function') {
773
+ rec.child.kill('SIGTERM')
774
+ return true
775
+ }
776
+ } catch {
777
+ /* already gone */
778
+ }
779
+ return false
780
+ }
781
+
782
+ const isSafeToRemove = (homeDir) => {
783
+ const resolved = path.resolve(homeDir)
784
+ const root = path.parse(resolved).root
785
+ return resolved !== root && resolved.length > root.length + 1
786
+ }
787
+
788
+ // ───────────────────────────── clean template ─────────────────────────────
789
+ /**
790
+ * Write a clean fork profile template (CONTRACTS-V2.md §5.5):
791
+ * package.json { name, private, dsh.profile.bundles:[dsh-base,dsh-web-app,bundleName] }
792
+ * cordis.yml '[]'
793
+ * cordis.patch.yml '[]'
794
+ * node_modules junction → nodeModulesSource (absent source → warning, still ok)
795
+ * Idempotent: same content is rewritten, an existing junction is left untouched.
796
+ * @returns {{ok:boolean, dir:string, files:string[], warnings:string[], error?:string}}
797
+ */
798
+ const ensureTemplate = (opts = {}) => {
799
+ const rawDir = String(opts.templateDir ?? '').trim()
800
+ if (!rawDir) return { ok: false, dir: '', files: [], warnings: [], error: 'no-template-dir' }
801
+ const templateDir = path.resolve(rawDir)
802
+ const files = []
803
+ const warnings = []
804
+ try {
805
+ ensureDir(templateDir)
806
+ writeJsonAtomic(
807
+ path.join(templateDir, 'package.json'),
808
+ buildTemplatePackageJson({ bundleName: cfg.bundleName, forkProfileTag: cfg.forkProfileTag }),
809
+ )
810
+ files.push('package.json')
811
+ for (const name of ['cordis.yml', 'cordis.patch.yml']) {
812
+ writeFileAtomic(path.join(templateDir, name), name === 'cordis.patch.yml' ? WELCOME_NOTICE_PATCH : '[]\n')
813
+ files.push(name)
814
+ }
815
+ const srcRaw = String(opts.nodeModulesSource ?? '').trim()
816
+ const source = srcRaw ? path.resolve(srcRaw) : ''
817
+ const link = path.join(templateDir, 'node_modules')
818
+ if (source && exists(source)) {
819
+ try {
820
+ // v3.1.7: per-entry mirror instead of one whole-tree junction — see fsx.mirrorModuleTree.
821
+ const mirrored = mirrorModuleTree(source, link)
822
+ if (mirrored.ok !== true) warnings.push(`node-modules-mirror-failed: ${mirrored.error ?? 'unknown'}`)
823
+ else files.push('node_modules')
824
+ } catch (e) {
825
+ warnings.push(`node-modules-mirror-failed: ${msgOf(e)}`)
826
+ }
827
+ } else {
828
+ warnings.push('node-modules-source-missing')
829
+ }
830
+ return { ok: true, dir: templateDir, files, warnings }
831
+ } catch (e) {
832
+ return { ok: false, dir: templateDir, files, warnings, error: 'template-write-failed', message: msgOf(e) }
833
+ }
834
+ }
835
+
836
+ /** Clone exactly package.json + cordis*.yml from a template into the fork profile dir. */
837
+ const cloneProfileConfig = (fromDir, toDir) => {
838
+ const wanted = listFiles(fromDir).filter((rel) => !rel.includes('/') && CLONED_RE.test(rel))
839
+ copyTree(fromDir, toDir, { filter: (entryName) => CLONED_RE.test(entryName) })
840
+ return wanted.filter((rel) => exists(path.join(toDir, rel)))
841
+ }
842
+
843
+ // ───────────────────────────── provision ─────────────────────────────
844
+ /**
845
+ * Build homeDir/profiles/<profile>.
846
+ * cleanTemplate=true: the clone source is a forker-owned clean template
847
+ * (<homeDir>/templates/<forkProfileTag>); only package.json + cordis*.yml are cloned and
848
+ * the mother contributes the node_modules junction source only — a dirty mother profile
849
+ * can never leak in. cleanTemplate=false: v1 behaviour (clone from profileTemplate).
850
+ * @returns {{ok:boolean, forkId?:string, homeDir?:string, profileDir?:string, bufferDir?:string,
851
+ * profile?:string, template?:string, cloned?:string[], node_modules?:string|null,
852
+ * warnings?:string[], error?:string}}
853
+ */
854
+ const provision = (opts = {}) => {
855
+ ensureRegistry()
856
+ const homeRaw = String(opts.homeDir ?? '').trim()
857
+ if (!homeRaw) return { ok: false, error: 'no-home-dir' }
858
+ const templateRaw = String(opts.profileTemplate ?? cfg.profileTemplate ?? '').trim()
859
+ if (!templateRaw) return { ok: false, error: 'no-profile-template' }
860
+ const sourceTemplateDir = path.resolve(templateRaw)
861
+ if (!exists(sourceTemplateDir)) return { ok: false, error: 'profile-template-missing', profileTemplate: sourceTemplateDir }
862
+
863
+ const forkId = String(opts.forkId ?? '').trim() || newId('fork')
864
+ const existing = records.get(forkId)
865
+ if (existing && (existing.running || existing.starting)) return { ok: false, error: 'already-running', forkId }
866
+
867
+ const homeDir = path.resolve(homeRaw)
868
+ const profile = safeProfile(opts.profile ?? (cleanTemplate ? forkProfileTag : path.basename(sourceTemplateDir)))
869
+ const profileDir = path.join(homeDir, 'profiles', profile)
870
+ ensureDir(homeDir)
871
+ ensureDir(profileDir)
872
+
873
+ const warnings = []
874
+ // 显式 profileTemplate(例如原身 merged/profile)优先:此时不再用 clean template。
875
+ const useCleanTemplate = typeof opts.cleanTemplate === 'boolean' ? opts.cleanTemplate : cleanTemplate
876
+ const nodeModulesSource = String(opts.nodeModulesSource ?? '').trim() || path.join(sourceTemplateDir, 'node_modules')
877
+ let template = sourceTemplateDir
878
+ let cloned = []
879
+
880
+ if (useCleanTemplate) {
881
+ // Forker-owned clean template: never written into the mother profile directory.
882
+ const cleanDir = path.join(homeDir, 'templates', forkProfileTag)
883
+ const ensured = ensureTemplate({
884
+ templateDir: cleanDir,
885
+ nodeModulesSource: exists(nodeModulesSource) ? nodeModulesSource : '',
886
+ })
887
+ if (!ensured.ok) {
888
+ return {
889
+ ok: false,
890
+ error: ensured.error ?? 'clean-template-failed',
891
+ template: ensured.dir,
892
+ warnings: ensured.warnings,
893
+ }
894
+ }
895
+ template = ensured.dir
896
+ warnings.push(...ensured.warnings)
897
+ cloned = cloneProfileConfig(template, profileDir)
898
+ } else {
899
+ cloned = cloneProfileConfig(sourceTemplateDir, profileDir)
900
+ }
901
+ // 生产盘锁定:关闭插件安装 / 设置 UI(派生时写入 profile patch)。
902
+ // essence-runtime 是元宝的“配置态实例”,必须保留插件管理能力,不能套生产盘锁。
903
+ const configInstance = path.basename(String(profileDir)) === 'essence-runtime'
904
+ const configLock = configInstance ? { ok: true, skipped: true, runtime: true } : applyForkConfigLock(profileDir)
905
+ if (configLock.ok !== true) warnings.push('fork-config-lock-failed')
906
+ // 配置文件只读:防误写(DSH_FANG_FORK_PROFILE_RO=0 可关)。
907
+ const profileReadonly = setProfileConfigReadonly(profileDir, true)
908
+
909
+ // node_modules mirror in the fork profile (always to the mother's module tree).
910
+ // v3.1.7: one junction per top-level entry instead of a whole-tree junction. DSH's
911
+ // profile-scope resolver only supplies installation packages (`@deepseek-ai/*`) to an
912
+ // importer inside the profile tree or below a linked root; a whole-tree junction keeps
913
+ // the importer outside every scope, so lazy host imports fall back to plugin shims
914
+ // (w2m's shim emits `required: false` in a property schema → the provider rejects
915
+ // every request: "Invalid schema for function 'w2m_report'", v3.1.7 report).
916
+ let nodeModules = null
917
+ if (exists(nodeModulesSource)) {
918
+ try {
919
+ const mirrored = mirrorModuleTree(nodeModulesSource, path.join(profileDir, 'node_modules'))
920
+ if (mirrored.ok === true) nodeModules = nodeModulesSource
921
+ else warnings.push(`node-modules-mirror-failed: ${mirrored.error ?? 'unknown'}`)
922
+ } catch (e) {
923
+ warnings.push(`node-modules-mirror-failed: ${msgOf(e)}`)
924
+ }
925
+ } else if (!cleanTemplate) {
926
+ // Degraded but still usable: the fork simply has no node_modules link to the mother.
927
+ warnings.push('node-modules-missing')
928
+ }
929
+
930
+ const bufferDir = path.join(homeDir, 'fang', profile, 'buffer')
931
+ ensureDir(bufferDir)
932
+
933
+ const rec = existing ?? { forkId, createdAt: nowMs() }
934
+ Object.assign(rec, {
935
+ forkId,
936
+ taskTitle: String(opts.taskTitle ?? rec.taskTitle ?? ''),
937
+ homeDir,
938
+ profile,
939
+ profileDir,
940
+ bufferDir,
941
+ template,
942
+ nodeModules,
943
+ pid: rec.pid ?? null,
944
+ port: rec.port ?? null,
945
+ url: rec.url ?? null,
946
+ child: rec.child ?? null,
947
+ running: false,
948
+ starting: false,
949
+ status: FORK_STATUS.PROVISIONING,
950
+ exit: null,
951
+ lastError: null,
952
+ })
953
+ records.set(forkId, rec)
954
+ persist()
955
+ audit(AUDIT.FORK_CREATED, { forkId, homeDir, profile, taskTitle: rec.taskTitle, cloned, warnings, template })
956
+ return { ok: true, forkId, homeDir, profileDir, bufferDir, profile, template, cloned, node_modules: nodeModules, warnings, configLock, profileReadonly }
957
+ }
958
+
959
+ // ───────────────────────────── spawn ─────────────────────────────
960
+ /**
961
+ * Launch the fork and resolve once stdout printed the tokenized web URL.
962
+ * v2: with allocatePorts the child is told `--port <pool port>` and the printed URL port
963
+ * must match it; a mismatch stops the child ({ok:false,error:'port-mismatch'}).
964
+ * @returns {Promise<{ok:boolean, forkId?:string, pid?:number|null, port?:number, url?:string,
965
+ * token?:string, error?:string, expectedPort?:number}>}
966
+ */
967
+ const writeForkMetaOf = (rec) => {
968
+ if (!rec?.homeDir) return false
969
+ return writeForkMeta(rec.homeDir, {
970
+ forkId: rec.forkId, status: rec.status, pid: rec.pid ?? null, port: rec.port ?? null,
971
+ url: rec.url ?? null, profile: rec.profile ?? null,
972
+ crashCount: rec.crashCount ?? 0, restartCount: rec.restartCount ?? 0,
973
+ lastError: rec.lastError ?? null, startedAt: rec.startedAt ?? null,
974
+ exitedAt: rec.exitedAt ?? null, restartScheduledAt: rec.restartScheduledAt ?? null,
975
+ })
976
+ }
977
+
978
+ const spawn = async (opts = {}) => {
979
+ ensureRegistry()
980
+ ensurePorts()
981
+ const forkId = String(opts.forkId ?? '').trim() || newId('fork')
982
+ const homeDir = String(opts.homeDir ?? '').trim()
983
+ const profile = safeProfile(opts.profile ?? 'default')
984
+ const cliPath = String(opts.cliPath ?? cfg.cliPath ?? '').trim()
985
+ const timeoutMs = Math.max(1, Math.floor(Number(opts.timeoutMs ?? cfg.startTimeoutMs) || DEFAULTS.startTimeoutMs))
986
+ const maxLogLines = Math.max(1, Math.floor(Number(cfg.maxLogLines) || DEFAULTS.maxLogLines))
987
+
988
+ if (!homeDir) return { forkId, ok: false, error: 'no-home-dir' }
989
+ if (!cliPath) return { forkId, ok: false, error: 'no-cli-path' }
990
+ const previous = records.get(forkId)
991
+ if (previous && (previous.running || previous.child || previous.starting)) {
992
+ return { forkId, ok: false, error: 'already-running', pid: previous.pid ?? null }
993
+ }
994
+ const maxForks = Math.max(1, Math.floor(Number(cfg.maxForks) || DEFAULTS.maxForks))
995
+ if (starting() >= maxForks) return { forkId, ok: false, error: 'max-forks', limit: maxForks }
996
+
997
+ const collector = createTextTail(maxLogLines)
998
+ const rec = previous ?? { forkId, createdAt: nowMs(), taskTitle: '' }
999
+ Object.assign(rec, {
1000
+ forkId,
1001
+ homeDir,
1002
+ profile,
1003
+ profileDir: rec.profileDir ?? path.join(path.resolve(homeDir), 'profiles', profile),
1004
+ pid: null,
1005
+ port: null,
1006
+ url: null,
1007
+ child: null,
1008
+ running: false,
1009
+ starting: true,
1010
+ status: FORK_STATUS.PROVISIONING,
1011
+ exit: null,
1012
+ lastError: null,
1013
+ intentionalStop: false,
1014
+ startedAt: nowMs(),
1015
+ ready: false,
1016
+ cliPath,
1017
+ crashCount: rec.crashCount ?? 0,
1018
+ restartCount: rec.restartCount ?? 0,
1019
+ restartScheduledAt: null,
1020
+ /**
1021
+ * v3 Adapter Bearer token:**每次 spawn 重新生成**,只存在于母体内存 + 分身环境变量。
1022
+ * 不写 fang-meta.json、不进 forks.json(publicFork 不含)、不写 URL —— 母体重启后
1023
+ * 旧 token 自然失效,孤儿分身不会被接管(PROTOCOL-V3 §3)。
1024
+ */
1025
+ adapterToken: randomBytes(24).toString('hex'),
1026
+ log: collector,
1027
+ })
1028
+ records.set(forkId, rec)
1029
+ // v3.0.9 生产盘:每次打开/重启都从来源模板重放配置(原身 merged 或 clean template),
1030
+ // 分身自己的改动不保存;sessions/storages/buffer 与 node_modules junction 保持不动。
1031
+ const templateDirForRec = String(rec.template ?? '').trim()
1032
+ if (templateDirForRec && exists(templateDirForRec) && exists(rec.profileDir)) {
1033
+ try {
1034
+ // 重放前先解锁,否则复制会因只读失败。
1035
+ setProfileConfigReadonly(rec.profileDir, false)
1036
+ cloneProfileConfig(templateDirForRec, rec.profileDir)
1037
+ const settingsSrc = path.join(templateDirForRec, 'settings')
1038
+ if (exists(settingsSrc)) {
1039
+ const settingsDst = path.join(rec.profileDir, 'settings')
1040
+ if (exists(settingsDst)) removeTree(settingsDst)
1041
+ copyTree(settingsSrc, settingsDst)
1042
+ }
1043
+ rec.configSync = { at: nowMs(), from: templateDirForRec }
1044
+ } catch (e) {
1045
+ rec.configSync = { at: nowMs(), ok: false, error: msgOf(e) }
1046
+ }
1047
+ }
1048
+ try { rec.configLock = applyForkConfigLock(rec.profileDir) } catch { rec.configLock = { ok: false } }
1049
+ try { rec.profileReadonly = setProfileConfigReadonly(rec.profileDir, true) } catch { rec.profileReadonly = { ok: false } }
1050
+ // v3.1.7: repair a whole-tree `node_modules` junction left by any previous release into
1051
+ // the per-entry mirror. This is what makes the fork host resolve the installation's
1052
+ // `@deepseek-ai/*` packages for profile plugins again; without it every agent request in
1053
+ // the fork is rejected by the provider (w2m offline shim → invalid tool schema).
1054
+ try {
1055
+ const repaired = ensureModuleMirror(path.join(rec.profileDir, 'node_modules'))
1056
+ rec.nodeModulesMirror = {
1057
+ changed: repaired.changed === true,
1058
+ ok: repaired.ok !== false,
1059
+ source: repaired.source ?? null,
1060
+ links: Array.isArray(repaired.links) ? repaired.links.length : 0,
1061
+ error: repaired.error ?? null,
1062
+ }
1063
+ } catch (e) {
1064
+ rec.nodeModulesMirror = { ok: false, changed: false, error: msgOf(e) }
1065
+ }
1066
+ // v3.1.12:默认第三方插件种子。install=只安装;activate=安装并激活(写入 bundles)。
1067
+ // 种子安装在独立 seed home(dsh 自带 pnpm),模块以 hardlink 合并进分身 node_modules;
1068
+ // 同一指纹只装一次。失败不阻塞分身启动,但结果保留在 rec.forkSeed 供 UI 诊断。
1069
+ rec.forkSeed = null
1070
+ if (cfg.forkSeed?.enabled !== false && !String(profile).startsWith('essence-') && process.env.DSH_FANG_FORK_SEED !== '0') {
1071
+ const seedRoot = path.join(path.dirname(path.resolve(homeDir)), '.plugin-seed')
1072
+ try { setProfileConfigReadonly(rec.profileDir, false) } catch { /* ignore */ }
1073
+ try {
1074
+ rec.forkSeed = await applyForkSeedToProfile({
1075
+ seed: cfg.forkSeed ?? DEFAULT_FORK_SEED,
1076
+ profileDir: rec.profileDir,
1077
+ seedRoot,
1078
+ cliPath,
1079
+ logger: ctx?.logger,
1080
+ })
1081
+ } catch (e) {
1082
+ rec.forkSeed = { ok: false, error: 'fork-seed-threw', detail: msgOf(e) }
1083
+ } finally {
1084
+ try { setProfileConfigReadonly(rec.profileDir, true) } catch { /* ignore */ }
1085
+ }
1086
+ if (rec.forkSeed?.ok === false) {
1087
+ audit(AUDIT.FORK_CREATED, { forkId, forkSeedError: rec.forkSeed.error, forkSeedDetail: String(rec.forkSeed.detail ?? '').slice(0, 600) })
1088
+ }
1089
+ }
1090
+ writeForkMetaOf(rec)
1091
+ // 广播新 token:首次派生 = 生成,重启 = 刷新;订阅者拿到的是「当前 token」,
1092
+ // 不是「进程就绪」信号(进程就绪以 fang/fork-started 为准)。
1093
+ emitTokenRefresh(forkId, rec.adapterToken)
1094
+
1095
+ // Port: explicit spawn option > deterministic pool allocation > v1 --port 0.
1096
+ const requested = Math.floor(Number(opts.port))
1097
+ let expectedPort = 0
1098
+ if (Number.isInteger(requested) && requested > 0 && requested <= 65535) {
1099
+ const reserved = reservePort(requested, forkId)
1100
+ if (!reserved.ok) {
1101
+ rec.starting = false
1102
+ rec.status = FORK_STATUS.STOPPED
1103
+ rec.lastError = reserved.error ?? 'port-in-use'
1104
+ persist()
1105
+ return { forkId, ok: false, error: rec.lastError }
1106
+ }
1107
+ expectedPort = reserved.port
1108
+ } else if (allocatePorts) {
1109
+ const alloc = await allocatePort({ forkId })
1110
+ if (!alloc.ok) {
1111
+ rec.starting = false
1112
+ rec.status = FORK_STATUS.STOPPED
1113
+ rec.lastError = alloc.error ?? 'port-exhausted'
1114
+ persist()
1115
+ return { forkId, ok: false, error: rec.lastError, reason: alloc.reason, pool: { ...portPool } }
1116
+ }
1117
+ expectedPort = alloc.port
1118
+ }
1119
+ if (expectedPort > 0) rec.port = expectedPort
1120
+ if (disposed) {
1121
+ rec.starting = false
1122
+ if (expectedPort > 0) releaseOwnedPort(expectedPort, forkId)
1123
+ return { forkId, ok: false, error: 'disposed' }
1124
+ }
1125
+
1126
+ return new Promise((resolve) => {
1127
+ let done = false
1128
+ let timer = null
1129
+ let cleanup = null
1130
+
1131
+ const releaseReserved = () => {
1132
+ if (expectedPort > 0) releaseOwnedPort(expectedPort, forkId)
1133
+ }
1134
+
1135
+ const finish = (result) => {
1136
+ if (done) return false
1137
+ done = true
1138
+ rec.starting = false
1139
+ if (timer) {
1140
+ clearTimeout(timer)
1141
+ timer = null
1142
+ }
1143
+ if (cleanup) pendingSpawns.delete(cleanup)
1144
+ resolve({ forkId, ...result })
1145
+ return true
1146
+ }
1147
+
1148
+ cleanup = () => {
1149
+ if (done) return
1150
+ rec.intentionalStop = true
1151
+ killTree(rec)
1152
+ rec.running = false
1153
+ rec.child = null
1154
+ rec.starting = false
1155
+ releaseReserved()
1156
+ finish({ ok: false, error: 'disposed' })
1157
+ }
1158
+ pendingSpawns.add(cleanup)
1159
+
1160
+ // v3.1.7: the headless web host (`dsh.cmd --no-open`, ELECTRON_RUN_AS_NODE) has no
1161
+ // window for the native directory chooser; pin the browse interaction through a
1162
+ // launcher overlay so "select workspace" works inside every fork Web UI.
1163
+ const patchPaths = []
1164
+ const headlessOverlay = writeHeadlessPickerOverlay(rec.profileDir, { cliPath })
1165
+ if (headlessOverlay) patchPaths.push(headlessOverlay)
1166
+ const spec = buildLaunchSpec({ cliPath, profile, port: expectedPort, patchPaths })
1167
+ const env = buildForkChildEnv(process.env, {
1168
+ DSH_HOME: homeDir,
1169
+ // Fork identity is injected by the forker (a fork must never be able to call itself mother).
1170
+ DSH_FANG_ROLE: 'fork',
1171
+ DSH_FANG_TASK_ID: forkId,
1172
+ ...(opts.env ?? {}),
1173
+ // v3:Adapter Bearer token(PROTOCOL-V3 §3)。放在 opts.env 之后,母体生成的 token 优先。
1174
+ DSH_ADAPTER_TOKEN: rec.adapterToken,
1175
+ })
1176
+ let child = null
1177
+ try {
1178
+ child = spawnProcess(spec.command, spec.args, {
1179
+ env,
1180
+ ...(exists(homeDir) ? { cwd: homeDir } : {}),
1181
+ windowsHide: spec.windowsHide,
1182
+ shell: spec.shell,
1183
+ stdio: ['ignore', 'pipe', 'pipe'],
1184
+ })
1185
+ } catch (e) {
1186
+ rec.status = FORK_STATUS.CRASHED
1187
+ rec.lastError = 'spawn-error'
1188
+ rec.exit = { kind: 'crash', code: null, message: msgOf(e) }
1189
+ releaseReserved()
1190
+ persist()
1191
+ return finish({ ok: false, error: 'spawn-error', message: msgOf(e), spec })
1192
+ }
1193
+
1194
+ rec.child = child
1195
+ rec.pid = child.pid ?? null
1196
+ if (expectedPort > 0 && rec.pid) bindPortToPid(expectedPort, forkId, rec.pid)
1197
+ // Note: on a failed launch (ENOENT/EINVAL) `child.pid` is undefined and the
1198
+ // `error` event arrives on the next tick — never resolve early here, or that
1199
+ // event would have no listener and surface as an uncaughtException.
1200
+
1201
+ const onData = (chunk) => {
1202
+ collector.push(chunk)
1203
+ if (rec.url) return
1204
+ const found = parseWebUrl(collector.text)
1205
+ if (!found) return
1206
+ // v2: the deterministic port is only trusted when the child really bound it.
1207
+ if (expectedPort > 0 && found.port !== expectedPort) {
1208
+ const pid = rec.pid
1209
+ rec.lastError = 'port-mismatch'
1210
+ const stopped = stopRecord(rec)
1211
+ persist()
1212
+ finish({
1213
+ ok: false,
1214
+ error: 'port-mismatch',
1215
+ expectedPort,
1216
+ pid,
1217
+ port: found.port,
1218
+ url: found.url,
1219
+ killed: stopped.killed,
1220
+ })
1221
+ return
1222
+ }
1223
+ rec.url = found.url
1224
+ rec.port = found.port
1225
+ rec.token = found.token ?? null
1226
+ rec.status = FORK_STATUS.RUNNING
1227
+ rec.running = true
1228
+ rec.starting = false
1229
+ rec.ready = true
1230
+ rec.startedAt = nowMs()
1231
+ writeForkMetaOf(rec)
1232
+ if (expectedPort > 0 && rec.pid) bindPortToPid(expectedPort, forkId, rec.pid)
1233
+ persist()
1234
+ emit(EVENTS.started, { forkId, pid: rec.pid, port: rec.port })
1235
+ audit(AUDIT.FORK_STARTED, { forkId, pid: rec.pid, port: rec.port, url: rec.url, profile })
1236
+ finish({
1237
+ ok: true,
1238
+ pid: rec.pid,
1239
+ port: rec.port,
1240
+ url: rec.url,
1241
+ token: rec.token,
1242
+ ...(expectedPort > 0 ? { allocatedPort: expectedPort } : {}),
1243
+ ...(rec.forkSeed ? { forkSeed: rec.forkSeed } : {}),
1244
+ })
1245
+ }
1246
+ // The tokenized banner is normally on stdout; scanning stderr too costs nothing.
1247
+ try {
1248
+ child.stdout?.on('data', onData)
1249
+ child.stderr?.on('data', onData)
1250
+ } catch {
1251
+ /* pipes unavailable: the timeout path below still settles the promise */
1252
+ }
1253
+
1254
+ child.once('error', (e) => {
1255
+ rec.running = false
1256
+ rec.child = null
1257
+ rec.starting = false
1258
+ rec.status = FORK_STATUS.CRASHED
1259
+ rec.lastError = msgOf(e)
1260
+ rec.exit = { kind: 'crash', code: null, message: msgOf(e) }
1261
+ releaseReserved()
1262
+ persist()
1263
+ finish({ ok: false, error: 'spawn-error', message: msgOf(e), log: collector.tail(20) })
1264
+ })
1265
+
1266
+ child.once('exit', (code, signal) => {
1267
+ const exitInfo = classifyExit(code, signal)
1268
+ rec.exit = exitInfo
1269
+ rec.exitedAt = nowMs()
1270
+ rec.running = false
1271
+ rec.child = null
1272
+ rec.starting = false
1273
+ if (rec.intentionalStop) rec.status = FORK_STATUS.STOPPED
1274
+ else {
1275
+ rec.status = FORK_STATUS.CRASHED
1276
+ emit(EVENTS.crashed, { forkId, code: exitInfo.code, kind: exitInfo.kind })
1277
+ audit(AUDIT.FORK_CRASHED, { forkId, code: exitInfo.code, kind: exitInfo.kind, signal })
1278
+ }
1279
+ // A dead child never keeps a deterministic port: release it on every exit path.
1280
+ releaseReserved()
1281
+ if (!rec.intentionalStop) rec.crashCount = (rec.crashCount ?? 0) + 1
1282
+ // A reap may already have deleted the record + home; never resurrect it from the exit handler.
1283
+ if (records.get(forkId) === rec) {
1284
+ writeForkMetaOf(rec)
1285
+ persist()
1286
+ }
1287
+ if (!rec.intentionalStop && runtimeSupervise && !disposed) {
1288
+ const plan = planRestart(exitInfo, rec, {
1289
+ maxRestarts: cfg.maxRestarts, baseMs: cfg.backoffBaseMs,
1290
+ maxMs: cfg.backoffMaxMs, jitter: cfg.backoffJitter,
1291
+ })
1292
+ if (plan.action === 'restart' && rec.cliPath && records.get(forkId) === rec) {
1293
+ rec.restartCount = (rec.restartCount ?? 0) + 1
1294
+ rec.restartScheduledAt = nowMs() + plan.delayMs
1295
+ rec.status = FORK_STATUS.PROVISIONING
1296
+ rec.lastError = `crash-restart-in-${plan.delayMs}ms`
1297
+ writeForkMetaOf(rec)
1298
+ rec.restartTimer = setTimeout(() => { rec.restartTimer = null; void restartFork(rec) }, plan.delayMs)
1299
+ audit(AUDIT.FORK_CRASHED, { forkId, restartInMs: plan.delayMs, attempt: plan.attempt, cause: plan.reason })
1300
+ } else if (plan.action === 'give-up') {
1301
+ rec.lastError = `restart-given-up:${plan.reason}`
1302
+ writeForkMetaOf(rec)
1303
+ audit(AUDIT.FORK_CRASHED, { forkId, restartGivenUp: plan.reason })
1304
+ // 放弃重启 = 终态:不会再有自动重试,订阅者据此 fail-fast。
1305
+ emit(EVENTS.restartFailed, { forkId, error: rec.lastError, terminal: true })
1306
+ }
1307
+ }
1308
+ finish({ ok: false, error: 'exited', code: exitInfo.code, signal, kind: exitInfo.kind, log: collector.tail(20) })
1309
+ })
1310
+
1311
+ timer = setTimeout(() => {
1312
+ rec.lastError = 'timeout'
1313
+ const stopped = stopRecord(rec)
1314
+ persist()
1315
+ finish({
1316
+ ok: false,
1317
+ error: 'timeout',
1318
+ pid: rec.pid,
1319
+ timeoutMs,
1320
+ killed: stopped.killed,
1321
+ log: collector.tail(40),
1322
+ })
1323
+ }, timeoutMs)
1324
+ })
1325
+ }
1326
+
1327
+ // ───────────────────────────── stop / reap ─────────────────────────────
1328
+ /** Shared stop primitive: kill the tree, mark stopped, release the port. Idempotent. */
1329
+ const stopRecord = (rec) => {
1330
+ rec.intentionalStop = true
1331
+ if (rec.restartTimer) { clearTimeout(rec.restartTimer); rec.restartTimer = null }
1332
+ rec.restartScheduledAt = null
1333
+ rec.ready = false
1334
+ // token 随进程死亡作废:绝不留给下一次 spawn 复用(restartFork 会重新生成)。
1335
+ rec.adapterToken = null
1336
+ const wasRunning = !!rec.running || !!rec.child || !!rec.starting
1337
+ const pid = rec.pid ?? rec.child?.pid ?? null
1338
+ if (wasRunning) {
1339
+ killTree(rec)
1340
+ rec.running = false
1341
+ rec.child = null
1342
+ rec.starting = false
1343
+ rec.status = FORK_STATUS.STOPPED
1344
+ rec.exitedAt = nowMs()
1345
+ } else if (rec.status !== FORK_STATUS.REAPED) {
1346
+ rec.status = FORK_STATUS.STOPPED
1347
+ }
1348
+ if (rec.port) releaseOwnedPort(rec.port, rec.forkId)
1349
+ return { ok: true, forkId: rec.forkId, pid, killed: wasRunning }
1350
+ }
1351
+
1352
+ /** Kill the process tree. Idempotent: an already-dead fork returns ok with killed:false. */
1353
+ const stop = (forkId) => {
1354
+ ensureRegistry()
1355
+ ensurePorts()
1356
+ const id = String(forkId ?? '').trim()
1357
+ const rec = records.get(id)
1358
+ if (!rec) return { ok: false, error: 'not-found', forkId: id }
1359
+ const res = stopRecord(rec)
1360
+ persist()
1361
+ return res
1362
+ }
1363
+
1364
+ /** stop + removeTree(homeDir) + registry delete. removeTree is junction-safe. */
1365
+ const reap = (forkId) => {
1366
+ ensureRegistry()
1367
+ ensurePorts()
1368
+ const id = String(forkId ?? '').trim()
1369
+ const rec = records.get(id)
1370
+ if (!rec) return { ok: false, error: 'not-found', forkId: id }
1371
+ stop(id)
1372
+ rec.status = FORK_STATUS.REAPED
1373
+ writeForkMetaOf(rec)
1374
+ const homeDir = rec.homeDir ? path.resolve(rec.homeDir) : ''
1375
+ let removed = false
1376
+ if (homeDir && isSafeToRemove(homeDir)) removed = exists(homeDir) ? removeTree(homeDir) : false
1377
+ records.delete(id)
1378
+ persist()
1379
+ emit(EVENTS.reaped, { forkId: id })
1380
+ audit(AUDIT.FORK_REAPED, { forkId: id, homeDir, removed })
1381
+ return { ok: true, forkId: id, removed, homeDir }
1382
+ }
1383
+
1384
+ // ───────────────────────────── introspection ─────────────────────────────
1385
+ const status = (forkId) => {
1386
+ ensureRegistry()
1387
+ const id = String(forkId ?? '').trim()
1388
+ const rec = records.get(id)
1389
+ if (!rec) return { forkId: id, running: false, pid: null, error: 'not-found' }
1390
+ return publicFork(rec)
1391
+ }
1392
+
1393
+ const list = () => {
1394
+ ensureRegistry()
1395
+ return [...records.values()]
1396
+ .map(publicFork)
1397
+ .sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0) || String(a.forkId).localeCompare(String(b.forkId)))
1398
+ }
1399
+
1400
+ const logs = (forkId, tailLines = 40) => {
1401
+ ensureRegistry()
1402
+ const rec = records.get(String(forkId ?? '').trim())
1403
+ if (!rec || !rec.log) return ''
1404
+ return rec.log.tail(tailLines)
1405
+ }
1406
+
1407
+ /**
1408
+ * v3 Adapter Bearer token(内存 only)。母体用它给 Remote/AdapterClient 加
1409
+ * `Authorization: Bearer`;**不要**把它塞进 status()/publicFork()(那会随
1410
+ * `/fang/api/status` 暴露给浏览器,也会落 forks.json)。
1411
+ * @returns {string} fork 不存在或已停止时为空串
1412
+ */
1413
+ const adapterToken = (forkId) => {
1414
+ ensureRegistry()
1415
+ const rec = records.get(String(forkId ?? '').trim())
1416
+ return typeof rec?.adapterToken === 'string' ? rec.adapterToken : ''
1417
+ }
1418
+
1419
+ /**
1420
+ * v3.0.5/B4:只在内存中返回带 token 的 Web URL,用于“打开分身”。
1421
+ * 该值绝不落盘、不进入 publicFork/list/status。
1422
+ */
1423
+ const openUrl = (forkId) => {
1424
+ ensureRegistry()
1425
+ const rec = records.get(String(forkId ?? '').trim())
1426
+ if (!rec || !rec.running || !rec.url) return { ok: false, error: 'not-running' }
1427
+ return { ok: true, forkId: rec.forkId, url: rec.url, port: rec.port ?? null }
1428
+ }
1429
+
1430
+ /** Re-spawn a crashed-but-ready fork after the backoff timer fires. */
1431
+ const restartFork = async (rec) => {
1432
+ if (disposed || rec.intentionalStop || records.get(rec.forkId) !== rec) return
1433
+ if (!rec.cliPath) {
1434
+ rec.lastError = 'restart-no-cli'
1435
+ writeForkMetaOf(rec)
1436
+ emit(EVENTS.restartFailed, { forkId: rec.forkId, error: 'restart-no-cli', terminal: true })
1437
+ return
1438
+ }
1439
+ rec.ready = false
1440
+ const out = await spawn({
1441
+ forkId: rec.forkId, homeDir: rec.homeDir, profile: rec.profile,
1442
+ cliPath: rec.cliPath, taskTitle: rec.taskTitle ?? '',
1443
+ })
1444
+ if (!out.ok && !disposed && records.get(rec.forkId) === rec) {
1445
+ rec.lastError = `restart-failed:${out.error}`
1446
+ writeForkMetaOf(rec)
1447
+ // 自动重启尝试失败:Forker 可能还会按 supervise 计划再试,因此 terminal=false。
1448
+ emit(EVENTS.restartFailed, {
1449
+ forkId: rec.forkId,
1450
+ error: String(out.error ?? 'restart-failed'),
1451
+ terminal: false,
1452
+ })
1453
+ }
1454
+ }
1455
+
1456
+ /** HTTP liveness for a fork (any response counts); process state is reported separately. */
1457
+ const health = async (forkId) => {
1458
+ ensureRegistry()
1459
+ ensurePorts()
1460
+ const id = String(forkId ?? '').trim()
1461
+ const rec = records.get(id)
1462
+ if (!rec) return { ok: false, error: 'not-found', forkId: id }
1463
+ const alive = !!rec.running && !!rec.child && rec.child.exitCode === null
1464
+ const http = alive && rec.port ? await probeHttpAlive(rec.port, { path: cfg.healthPath }) : false
1465
+ return { ok: true, forkId: id, status: rec.status, running: alive, pid: rec.pid ?? null, port: rec.port ?? null, http, url: rec.url ?? null }
1466
+ }
1467
+
1468
+ /** Reconcile persisted records after a mother restart; never kills a live foreign pid. */
1469
+ const recover = async () => {
1470
+ ensureRegistry()
1471
+ ensurePorts()
1472
+ const actions = reconcileOrphans(
1473
+ [...records.values()].map((rec) => ({ forkId: rec.forkId, status: rec.status, pid: rec.pid })),
1474
+ isPidAlive,
1475
+ )
1476
+ for (const action of actions) {
1477
+ if (action.action !== 'mark-crashed') continue
1478
+ const rec = records.get(action.forkId)
1479
+ if (!rec) continue
1480
+ rec.pid = null
1481
+ rec.running = false
1482
+ rec.child = null
1483
+ rec.ready = false
1484
+ rec.status = FORK_STATUS.CRASHED
1485
+ rec.lastError = `orphaned:${action.reason}`
1486
+ if (rec.port) releaseOwnedPort(rec.port, rec.forkId)
1487
+ writeForkMetaOf(rec)
1488
+ }
1489
+ persist()
1490
+ return { ok: true, actions, forks: actions.filter((a) => a.action === 'mark-crashed').length }
1491
+ }
1492
+
1493
+ /** 真实进程存活判断(用于归档确认 stop 真的生效,而不是只看 rec.running 状态)。 */
1494
+ const alive = (forkId) => {
1495
+ ensureRegistry()
1496
+ const rec = records.get(String(forkId ?? '').trim())
1497
+ if (!rec) return false
1498
+ const pid = rec.pid ?? rec.child?.pid ?? null
1499
+ return isPidAlive(pid)
1500
+ }
1501
+
1502
+ const service = {
1503
+ role: gate.role,
1504
+ provision,
1505
+ spawn,
1506
+ stop,
1507
+ reap,
1508
+ alive,
1509
+ health,
1510
+ recover,
1511
+ status,
1512
+ list,
1513
+ logs,
1514
+ adapterToken,
1515
+ getToken: adapterToken,
1516
+ openUrl,
1517
+ onTokenRefresh(handler) {
1518
+ if (typeof handler !== 'function') return () => {}
1519
+ tokenRefreshHandlers.add(handler)
1520
+ return () => tokenRefreshHandlers.delete(handler)
1521
+ },
1522
+ allocatePort,
1523
+ releasePort,
1524
+ ensureTemplate,
1525
+ portPool: () => ({ ...portPool }),
1526
+ ports: () => {
1527
+ ensurePorts()
1528
+ return portsSnapshot()
1529
+ },
1530
+ get config() {
1531
+ return { ...cfg }
1532
+ },
1533
+ /** 运行时看护状态;enabled 可在不重启宿主的情况下切换。 */
1534
+ getSupervision() {
1535
+ return {
1536
+ enabled: runtimeSupervise,
1537
+ configured: cfg.supervise === true,
1538
+ maxRestarts: cfg.maxRestarts,
1539
+ backoffBaseMs: cfg.backoffBaseMs,
1540
+ backoffMaxMs: cfg.backoffMaxMs,
1541
+ backoffJitter: cfg.backoffJitter,
1542
+ healthPath: cfg.healthPath,
1543
+ }
1544
+ },
1545
+ setSupervise(enabled) {
1546
+ runtimeSupervise = enabled === true
1547
+ try { audit(AUDIT.FORK_SUPERVISION, { enabled: runtimeSupervise }) } catch { /* audit optional */ }
1548
+ return { ok: true, enabled: runtimeSupervise }
1549
+ },
1550
+ }
1551
+
1552
+ ctx.effect(() => ctx.provide(SERVICE.forker, service))
1553
+ // Plugin unload must never leave orphan children (or leaked pool ports) behind.
1554
+ ctx.effect(() => () => {
1555
+ disposed = true
1556
+ for (const pending of [...pendingSpawns]) {
1557
+ try {
1558
+ pending()
1559
+ } catch {
1560
+ /* ignore */
1561
+ }
1562
+ }
1563
+ for (const rec of records.values()) {
1564
+ if (rec.restartTimer) { clearTimeout(rec.restartTimer); rec.restartTimer = null }
1565
+ if (rec.running || rec.child || rec.starting) {
1566
+ rec.intentionalStop = true
1567
+ killTree(rec)
1568
+ rec.running = false
1569
+ rec.child = null
1570
+ rec.starting = false
1571
+ }
1572
+ }
1573
+ for (const [port, forkId] of [...ownedPorts]) {
1574
+ try {
1575
+ releaseOwnedPort(port, forkId)
1576
+ } catch {
1577
+ /* best effort on unload */
1578
+ }
1579
+ }
1580
+ persist()
1581
+ })
1582
+ return service
1583
+ }
1584
+
1585
+ export const _internals = {
1586
+ createTextTail,
1587
+ safeProfile,
1588
+ isPidAlive,
1589
+ probePortFree,
1590
+ DEFAULTS,
1591
+ EVENTS,
1592
+ DEFAULT_PORT_POOL,
1593
+ CLEAN_TEMPLATE_BUNDLES,
1594
+ }