@marktrue/dsh-mobile-remote 3.2.4-alpha.2 → 3.2.4-alpha.20

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.
@@ -7,6 +7,7 @@ import { acquireLock, newOperationId, readTransaction, releaseLock, serverOperat
7
7
  transactionFile, updateLockPath, validOperationId, writeOwnedTransaction, convergeStaleTransaction, workRoot } from './plugin-update-transaction.js';
8
8
  import { checkForUpdate, prepareNpmArtifacts, runSelfUpdate, isTerminalPhase, resolvePluginUpdateSource, UPDATE_SOURCE_KIND } from './plugin-self-update.js';
9
9
  import { createOperationLog } from './plugin-update-log.js';
10
+ import { createUpdateCheckService } from './plugin-update-check.js';
10
11
 
11
12
  /// 客户端可达视图:只改写属于**本机回环主机源**的 artifact 路由,外部发布源保持原样(F1)。
12
13
  export function clientReleaseView(release, { clientOrigin = '', basePath = '/m', loopback = false } = {}) {
@@ -40,8 +41,12 @@ export function publicTransaction(tx, view = {}) {
40
41
  export function createPluginUpdateController(options) {
41
42
  const { home = homedir(), configValue, profileDir, packageName = '', npmPackageView, capabilities, localVersion, localContentSha256,
42
43
  status, log = () => {}, fetchImpl = fetch, auth = {}, basePath = '/m', workerOptions = {},
44
+ checkTimeoutMs = 12_000, checkSuccessTtlMs = 5 * 60 * 1000, checkFailureTtlMs = 30 * 1000,
45
+ asyncCheckTtlMs = 10 * 60 * 1000,
43
46
  schedule = fn => setImmediate(fn), runSelfUpdate: runner = runSelfUpdate, prepareNpmArtifacts: prepareRunner = prepareNpmArtifacts,
44
- persist = writeOwnedTransaction } = options;
47
+ runHostUpdate: hostRunner, persist = writeOwnedTransaction } = options;
48
+ // 只有调用方显式提供宿主更新执行器时才启用该通道(旧宿主/测试不提供即自动关闭)。
49
+ const runHostUpdate = typeof hostRunner === 'function' ? hostRunner : null;
45
50
  const currentFile = transactionFile(home), lockPath = updateLockPath(home);
46
51
  const preparedUpdates = new Map();
47
52
  const preparedTtlMs = 30 * 60 * 1000;
@@ -82,9 +87,19 @@ export function createPluginUpdateController(options) {
82
87
  } catch { /* cleanup is best-effort; never disrupt update checks */ }
83
88
  };
84
89
  cleanupPreparedUpdates();
90
+ const localContentNow = () => (typeof localContentSha256 === 'function' ? localContentSha256() : localContentSha256);
85
91
  const checking = () => checkForUpdate({ configValue, packageName, npmCwd: profileDir, npmPackageView,
86
- localVersion: typeof localVersion === 'function' ? localVersion() : localVersion, localContentSha256,
92
+ localVersion: typeof localVersion === 'function' ? localVersion() : localVersion, localContentSha256: localContentNow(),
87
93
  capabilities: capabilities(), fetchImpl, auth });
94
+ // issue #96:检查快照 + 有界异步任务(只读、内存、不持久化)。
95
+ const checkService = createUpdateCheckService({
96
+ checkFn: checking,
97
+ cacheKey: () => `${configValue}|${typeof localVersion === 'function' ? localVersion() : localVersion}|${localContentSha256 ?? ''}`,
98
+ checkTimeoutMs,
99
+ successTtlMs: checkSuccessTtlMs,
100
+ failureTtlMs: checkFailureTtlMs,
101
+ taskTtlMs: asyncCheckTtlMs,
102
+ });
88
103
  /// 手机视图:**只用于 HTTP 出口**,绝不写回内部事务(F1)。
89
104
  /// 内部 worker 必须继续用受信定位;当前 NPM 来源不会把 registry URL 投影给客户端。
90
105
  const clientView = clientOrigin => ({
@@ -107,7 +122,7 @@ export function createPluginUpdateController(options) {
107
122
  } };
108
123
  const old = readTransaction(currentFile);
109
124
  if (old && !isTerminalPhase(old.phase)) return { status: 409, body: { error: 'update-busy', transaction: publicTransaction(old) } };
110
- const checked = await checking(); Object.assign(status, checked);
125
+ const checked = await checkService.checkForSubmit(); Object.assign(status, checked);
111
126
  if (checked.state !== 'update-available') return { status: 200, body: { ok: true, action: 'none', check: checked } };
112
127
  const candidate = checked.candidate;
113
128
  if (!candidate?.carrier?.legacyMetadataMissing) {
@@ -160,22 +175,119 @@ export function createPluginUpdateController(options) {
160
175
  if (source.kind === UPDATE_SOURCE_KIND.OFF) return { status: 503, body: { error: 'update-source-off' } };
161
176
  if (source.kind === UPDATE_SOURCE_KIND.INVALID) return { status: 400, body: { error: 'update-source-invalid' } };
162
177
  if (!profileDir) return { status: 409, body: { error: 'profile-not-found' } };
178
+ // `canSelfUpdate` 现在由**通道**决定(宿主管理器或重启通道只要有一条可用即为真),
179
+ // 两条都不通才拒绝;原因码保留 `restart-unsupported` 以免旧 App 判断失效。
163
180
  if (!capabilities().canSelfUpdate) return { status: 409, body: { error: 'restart-unsupported' } };
164
181
  const view = clientView(clientOrigin);
165
182
  const old = readTransaction(currentFile);
166
183
  if (old && body.opId === old.opId) return { status: 200, body: { ok: true, action: 'accepted', opId: old.opId,
167
184
  transaction: publicTransaction(old, view), check: { ...status, release: clientReleaseView(status.release, view) } } };
168
185
  if (old && !isTerminalPhase(old.phase)) {
169
- const convergence = convergeStaleTransaction({ stateFile: currentFile, lockPath });
170
- if (!['converged','terminal'].includes(convergence.action)) return { status: 409, body: {
186
+ // issue #110 P3:收敛时带上当前运行内容哈希,避免把已生效的旧 restart-pending 一律 failed。
187
+ const convergence = convergeStaleTransaction({
188
+ stateFile: currentFile,
189
+ lockPath,
190
+ localContentSha256: localContentNow() ?? '',
191
+ });
192
+ if (!['converged','settled','terminal'].includes(convergence.action)) return { status: 409, body: {
171
193
  error: convergence.action === 'recovery-required' ? 'recovery-required' : 'update-busy', transaction: publicTransaction(old, view) } };
172
194
  }
173
- const checked = await checking(); Object.assign(status, checked);
195
+ let checked = await checkService.checkForSubmit(); Object.assign(status, checked);
196
+ // issue #96 review P2:检查本身不可用/超时时如实返回 503 check-unavailable,
197
+ // 不得被 targetVersion 比对误判成 candidate-changed,也不无意义重查。
198
+ if (checked.state === 'unavailable') {
199
+ return { status: 503, body: {
200
+ error: 'check-unavailable',
201
+ reason: checked.reason ?? 'update-check-unavailable',
202
+ check: checked,
203
+ } };
204
+ }
205
+ // 只有成功检查且 targetVersion 与候选确实不同,才强制重查一次;仍不同才 409。
206
+ if (typeof body.targetVersion === 'string') {
207
+ const snapshotTarget = () => checked.release?.plugin ?? checked.candidate?.plugin;
208
+ if (!snapshotTarget() || snapshotTarget()?.version !== body.targetVersion) {
209
+ checked = await checkService.check({ force: true });
210
+ Object.assign(status, checked);
211
+ if (checked.state === 'unavailable') {
212
+ return { status: 503, body: {
213
+ error: 'check-unavailable',
214
+ reason: checked.reason ?? 'update-check-unavailable',
215
+ check: checked,
216
+ } };
217
+ }
218
+ if (!snapshotTarget() || snapshotTarget()?.version !== body.targetVersion) {
219
+ return { status: 409, body: { error: 'candidate-changed', check: checked } };
220
+ }
221
+ }
222
+ }
174
223
  // **内部 release 原样保留**(持久化与 worker 都用它);只有响应体走手机视图。
175
224
  if (checked.state !== 'update-available') {
176
225
  return { status: 200, body: { ok: true, action: 'none', check: { ...checked, release: clientReleaseView(checked.release, view) } } };
177
226
  }
178
227
  const opId = body.opId ?? newOperationId();
228
+ // ── 通道分派:宿主原生管理器可用时走它(进程内更新,不重启) ──────────────
229
+ // 这条路径与下面的「重启通道」互斥:同一时刻只有一个事务、同一把锁。
230
+ if (typeof runHostUpdate === 'function' && capabilities().updateChannel === 'host-manager') {
231
+ const hostTarget = checked.release?.plugin ?? checked.candidate?.plugin;
232
+ if (!hostTarget?.version) return { status: 503, body: { error: 'update-candidate-incomplete' } };
233
+ if (typeof body.targetVersion === 'string' && body.targetVersion !== hostTarget.version) {
234
+ return { status: 409, body: { error: 'candidate-changed', check: checked } };
235
+ }
236
+ const lock = acquireLock(lockPath, { opId, stateFile: currentFile });
237
+ if (!lock.ok) return { status: 409, body: { error: lock.error, transaction: publicTransaction(readTransaction(currentFile), view) } };
238
+ const lease = lock.lease, stateFile = serverOperationPath(home, lease.generation);
239
+ const operationLog = createOperationLog({ home, generation: lease.generation,
240
+ redactPaths: [home, profileDir, workerOptions.pluginRoot, workerOptions.installedRoot] });
241
+ operationLog.setStage('host-manager', 'Host plugin manager update accepted');
242
+ let tx;
243
+ try {
244
+ tx = persist(stateFile, { ...workerOptions, opId, phase: 'staging', startedAt: new Date().toISOString(),
245
+ profileDir, release: checked.release ?? null, hostManager: true,
246
+ manifestUrl: checked.release?.manifestUrl ?? '',
247
+ targetVersion: hostTarget.version, targetContentSha256: hostTarget.contentSha256 ?? '',
248
+ targetAppVersion: checked.release?.app?.version ?? null,
249
+ currentFile, lockPath, lease, attempts: 0 }, { lockPath, lease, currentFile });
250
+ } catch {
251
+ releaseLock(lockPath, lease, { stateFile: currentFile });
252
+ operationLog.setStage('failed', 'Could not persist host manager admission state.');
253
+ operationLog.flush();
254
+ log('host manager update admission state write failed');
255
+ return { status: 500, body: { error: 'update-state-write-failed' } };
256
+ }
257
+ schedule(async () => {
258
+ try {
259
+ const run = await runHostUpdate({ opId, targetVersion: hostTarget.version,
260
+ installedVersion: typeof localVersion === 'function' ? localVersion() : localVersion,
261
+ onStep: step => { operationLog.setStage(step); workerOptions.onStep?.(step); },
262
+ log: message => { operationLog.appendStatus(message, 'worker'); } });
263
+ if (run.ok) {
264
+ operationLog.setStage('finished', 'Host plugin manager applied the update without a restart.');
265
+ finishOwnedTerminal(stateFile, { phase: 'settled', result: { ok: true, matched: 'host-manager' } },
266
+ { lockPath, lease, currentFile });
267
+ Object.assign(status, { state: 'up-to-date', reason: 'host-manager-applied', opId });
268
+ checkService.invalidate();
269
+ } else {
270
+ const reason = safeUpdateReason(run.reason);
271
+ operationLog.setStage('failed', `Host plugin manager update failed: ${reason}`);
272
+ // `restart-required` 表示包装好了但要重启才生效:这不回滚,如实报告。
273
+ finishOwnedTerminal(stateFile, { phase: run.reason === 'host-manager-restart-required' ? 'settled' : 'failed',
274
+ rolledBack: false, result: { ok: false, reason } }, { lockPath, lease, currentFile });
275
+ Object.assign(status, { state: run.reason === 'host-manager-restart-required' ? 'restarting' : 'update-failed', reason, opId });
276
+ }
277
+ operationLog.flush();
278
+ } catch (e) {
279
+ const reason = safeUpdateReason(e?.message);
280
+ try { finishOwnedTerminal(stateFile, { phase: 'failed', result: { ok: false, reason } }, { lockPath, lease, currentFile }); }
281
+ catch { /* lost lease: never overwrite a newer operation */ }
282
+ operationLog.setStage('failed', `Host manager worker failed: ${reason}`);
283
+ operationLog.flush();
284
+ Object.assign(status, { state: 'update-failed', reason, opId });
285
+ log('host manager update worker failed');
286
+ }
287
+ });
288
+ return { status: 200, body: { ok: true, action: 'accepted', opId, channel: 'host-manager',
289
+ transaction: publicTransaction(tx, view), check: { ...checked, release: clientReleaseView(checked.release, view) } } };
290
+ }
179
291
  let effectiveCheck = checked;
180
292
  let npmCandidate = checked.candidate ?? null;
181
293
  let preparedNpmArtifacts = null;
@@ -246,6 +358,7 @@ export function createPluginUpdateController(options) {
246
358
  if (run.ok) {
247
359
  operationLog.setStage('restart', 'Plugin install finished; waiting for host restart and health confirmation.');
248
360
  Object.assign(status, { state: 'restarting', reason: 'update-staged', opId });
361
+ checkService.invalidate();
249
362
  } else {
250
363
  const reason = safeUpdateReason(run.error);
251
364
  // 失败原因必须进日志:详情页要能直接看到,而不是只有一句“看安装输出”。
@@ -270,5 +383,14 @@ export function createPluginUpdateController(options) {
270
383
  return { status: 200, body: { ok: true, action: 'accepted', opId,
271
384
  transaction: publicTransaction(tx, view), check: { ...effectiveCheck, release: clientReleaseView(effectiveCheck.release, view) } } };
272
385
  }
273
- return { submit, check: checking, prepare };
386
+ return {
387
+ submit,
388
+ check: checking,
389
+ prepare,
390
+ checkSync: () => checkService.checkSync(),
391
+ checkForSubmit: () => checkService.checkForSubmit(),
392
+ startAsyncCheck: (options) => checkService.startAsync(options),
393
+ getAsyncCheck: (checkId) => checkService.getAsync(checkId),
394
+ invalidateCheck: () => checkService.invalidate(),
395
+ };
274
396
  }
@@ -105,8 +105,8 @@ export function clearTransaction(file) {
105
105
  }
106
106
 
107
107
  /** Converge only under the same OS arbitration as acquire/release/state writes. */
108
- export function convergeStaleTransaction({ stateFile, lockPath, expectedLease, now = () => Date.now(), staleMs = 600_000 } = {}) {
109
- const result = arbitrate(lockPath, { operation: "converge", stateFile, expectedLease, now: now(), staleMs });
108
+ export function convergeStaleTransaction({ stateFile, lockPath, expectedLease, localContentSha256 = "", now = () => Date.now(), staleMs = 600_000 } = {}) {
109
+ const result = arbitrate(lockPath, { operation: "converge", stateFile, expectedLease, localContentSha256, now: now(), staleMs });
110
110
  if (!result.ok) return { action: "blocked", error: result.error, transaction: readTransaction(stateFile) };
111
111
  return result;
112
112
  }
@@ -198,6 +198,42 @@ export function defaultIsPidAlive(pid) {
198
198
  if (!Number.isInteger(pid) || pid <= 0) return false;
199
199
  try { process.kill(pid, 0); return true; } catch(e) { return e.code === "EPERM"; }
200
200
  }
201
+
202
+ /** `/proc/<pid>/stat` 的 starttime(field 22);读不到返回 null。 */
203
+ export function processStartTime(pid) {
204
+ if (!Number.isInteger(pid) || pid <= 0) return null;
205
+ try {
206
+ const text = readFileSync(`/proc/${pid}/stat`, "utf8");
207
+ return text.slice(text.lastIndexOf(")") + 2).split(" ")[19] ?? null;
208
+ } catch {
209
+ return null;
210
+ }
211
+ }
212
+
213
+ /**
214
+ * issue #110 P1:按 `/proc/<pid>/stat` starttime 判断记录里的进程身份是否仍存活,
215
+ * 不能只用 kill(pid,0)(容器重建后 pid 会被复用)。
216
+ * - 记录带 start:必须与当前 starttime 完全一致;
217
+ * - 旧 holder 无 start:只能保守认为可能存活(不据此认领);
218
+ * - procfs 不可读:视为不存活。
219
+ */
220
+ export function processIdentityAlive(person) {
221
+ if (!person || !Number.isInteger(person.pid) || person.pid <= 0) return false;
222
+ const current = processStartTime(person.pid);
223
+ // 无 procfs(或 /proc/<pid> 读不到)时退回 kill(pid,0):宁可保守判活,不能误认领。
224
+ if (current === null) return defaultIsPidAlive(person.pid);
225
+ if (!person.start) return true;
226
+ return String(person.start) === String(current);
227
+ }
228
+
229
+ /** 锁 holder(worker/supervisor 任一)是否仍存活;用于启动认领判定。 */
230
+ export function lockHolderAlive(dir) {
231
+ const holder = readLock(dir);
232
+ if (!holder) return false;
233
+ if ([holder.worker, holder.supervisor].some(processIdentityAlive)) return true;
234
+ // 旧 holder 只写 pid(无 starttime):按 pid 保守判活,避免把活监督器当死。
235
+ return Number.isInteger(holder.pid) && processIdentityAlive({ pid: holder.pid, start: holder.start });
236
+ }
201
237
  export function lockHeld(dir) { return readLock(dir) !== null; }
202
238
  export function acquireLock(dir, { opId, pid = process.pid, now = Date.now(), lease, stateFile } = {}) {
203
239
  if (!validOperationId(opId)) return { ok: false, error: "invalid-operation-id" };
@@ -14,10 +14,23 @@ function identity(pid) {
14
14
  try { const text = readFileSync(`/proc/${pid}/stat`, 'utf8'); return { pid, start: text.slice(text.lastIndexOf(')') + 2).split(' ')[19] }; }
15
15
  catch { return { pid, start: null }; }
16
16
  }
17
+ function killAlive(pid) {
18
+ try { process.kill(pid, 0); return true; } catch(e) { return e.code === 'EPERM'; }
19
+ }
17
20
  function alive(person) {
18
21
  if (!person?.pid || !Number.isInteger(person.pid)) return false;
19
- try { process.kill(person.pid, 0); } catch(e) { return e.code === 'EPERM'; }
20
- return !person.start || identity(person.pid).start === person.start;
22
+ const current = identity(person.pid).start;
23
+ // 无 /proc 平台:回退 kill(pid,0) 保守判活,与 processIdentityAlive 口径一致。
24
+ if (current === null) return killAlive(person.pid);
25
+ if (!person.start) return true;
26
+ return String(person.start) === String(current);
27
+ }
28
+ function holderAlive(holder) {
29
+ if (!holder) return false;
30
+ const candidates = [holder.worker, holder.supervisor];
31
+ // 旧 holder 兼容:只有顶层 pid/starttime。
32
+ if (Number.isInteger(holder.pid)) candidates.push({ pid: holder.pid, start: holder.start });
33
+ return candidates.some(alive);
21
34
  }
22
35
  function owns(holder, lease) { return !!lease?.generation && holder?.generation === lease.generation && holder.opId === lease.opId; }
23
36
  function fence(holder, lease) { if (!owns(holder, lease)) throw new Error('lease-lost'); }
@@ -27,7 +40,7 @@ function execute(input) {
27
40
  const { lockPath, operation, lease, stateFile } = input;
28
41
  const holderFile = join(lockPath, 'holder.json');
29
42
  let holder = read(holderFile);
30
- const available = !holder || ![holder.worker, holder.supervisor].some(alive);
43
+ const available = !holderAlive(holder);
31
44
  if (operation === 'acquire') {
32
45
  if (holder && owns(holder, lease)) return { ok: true, lease, holder, reentrant: true };
33
46
  // Missing publication is not evidence of owner death. Legacy half-locks require manual repair.
@@ -154,10 +167,37 @@ function execute(input) {
154
167
  if (!tx) return { ok: true, action: 'none', transaction: null };
155
168
  if (terminal(tx.phase)) return { ok: true, action: 'terminal', transaction: tx };
156
169
  if (input.expectedLease && !owns(holder, input.expectedLease)) return { ok: true, action: 'superseded', transaction: tx };
157
- if (holder && [holder.worker, holder.supervisor].some(alive)) return { ok: true, action: 'active', transaction: tx };
158
- if (existsSync(lockPath) && !existsSync(holderFile)) return { ok: true, action: 'recent', transaction: tx };
170
+ if (holderAlive(holder)) return { ok: true, action: 'active', transaction: tx };
171
+ // holder.json 缺失:restart-pending 仍需按 stale 结算(不能因缺 holder 永久 recent);
172
+ // 其他阶段维持保守 recent。
173
+ if (existsSync(lockPath) && !existsSync(holderFile) && tx.phase !== 'restart-pending') {
174
+ return { ok: true, action: 'recent', transaction: tx };
175
+ }
176
+ // issue #110 P1-C:restart-pending + holder 全死 + stale:
177
+ // - 运行内容 == target → settled(保留 artifact/snapshot 元数据,不假称回滚成功);
178
+ // - 内容不匹配 → failed(confirmation-lost),不无限 pending。
179
+ if (tx.phase === 'restart-pending') {
180
+ const startedAt = Date.parse(tx.startedAt ?? tx.updatedAt ?? '');
181
+ // 缺时间戳视为 stale:restart-pending 不能因坏元数据永久 pending。
182
+ const stale = Number.isFinite(startedAt) ? input.now - startedAt >= input.staleMs : true;
183
+ if (!stale) return { ok: true, action: 'recent', transaction: tx };
184
+ const target = String(tx.targetContentSha256 ?? '').toLowerCase();
185
+ const local = String(input.localContentSha256 ?? '').toLowerCase();
186
+ const matched = target !== '' && local === target;
187
+ const next = {
188
+ ...tx,
189
+ phase: matched ? 'settled' : 'failed',
190
+ result: matched
191
+ ? { ok: true, matched: 'loaded-target-content-adopted' }
192
+ : { ok: false, reason: 'confirmation-lost' },
193
+ updatedAt: new Date(input.now).toISOString(),
194
+ };
195
+ atomic(stateFile, next);
196
+ if (holder) atomic(holderFile, null);
197
+ return { ok: true, action: matched ? 'settled' : 'converged', transaction: next };
198
+ }
159
199
  // Never relabel a possibly damaged install as an ordinary terminal failure.
160
- if (['installing','restart-pending','rolling-back'].includes(tx.phase)) return { ok: true, action: 'recovery-required', transaction: tx };
200
+ if (['installing','rolling-back'].includes(tx.phase)) return { ok: true, action: 'recovery-required', transaction: tx };
161
201
  if (input.now - Date.parse(tx.startedAt) < input.staleMs) return { ok: true, action: 'recent', transaction: tx };
162
202
  if (tx.lease && holder && !owns(holder, tx.lease)) return { ok: true, action: 'superseded', transaction: tx };
163
203
  const next = { ...tx, phase: 'failed', result: { ok: false, reason: 'holder-gone' } };
@@ -35,7 +35,7 @@ import {
35
35
  } from "./plugin-update-transaction.js";
36
36
  import { pluginContentDigest } from "./plugin-content-digest.js";
37
37
  import { verifyFrozenPackage } from "./runtime-dependency-snapshot.js";
38
- import { restartPlan } from "./plugin-self-update.js";
38
+ import { restartPlan, respawnCommandOf } from "./plugin-self-update.js";
39
39
  import { shellOptions } from "./tool-process.js";
40
40
 
41
41
  /** 等待宿主的默认超时:足够冷启动(含语料预热),又不至于让用户无限等。 */
@@ -138,14 +138,47 @@ export function portKillSnippet(port, fallbackPid = null) {
138
138
  * 默认重启器:**按当前实例**(端口占用者)终止,而不是事务里记的旧 PID;
139
139
  * 前台形态自行重新拉起。**返回结果不再被忽略**(F3)。
140
140
  */
141
- export function defaultRestart({ restartForm, port, pid = null, profile = "web", dshCommand = "dsh", log = () => {} }) {
142
- const plan = restartPlan({ form: restartForm, pid: null, profile, dshCommand });
141
+ /** 从 `/proc/<pid>/cmdline` 还原宿主原命令行(supervisor 的 argv 不是宿主 argv)。 */
142
+ export function respawnCommandFromProc(pid) {
143
+ if (!Number.isInteger(pid) || pid <= 0) return "";
144
+ try {
145
+ const parts = readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").filter((part) => part !== "");
146
+ return respawnCommandOf(parts);
147
+ } catch {
148
+ return "";
149
+ }
150
+ }
151
+
152
+ export function defaultRestart({
153
+ restartForm,
154
+ port,
155
+ pid = null,
156
+ hostPid = null,
157
+ profile = "web",
158
+ dshCommand = "dsh",
159
+ respawnCommand = "",
160
+ log = () => {},
161
+ spawnSyncImpl = spawnSync,
162
+ }) {
163
+ // issue #110 P2:supervisor 的 process.argv 是 `update-supervisor.js --state`,
164
+ // 不能拿它当宿主命令行;优先事务写入的 respawnCommand,其次 `/proc/<hostPid>/cmdline`。
165
+ let originalCommand = respawnCommand;
166
+ if (originalCommand === "" && Number.isInteger(hostPid)) originalCommand = respawnCommandFromProc(hostPid);
167
+ if (originalCommand === "") originalCommand = respawnCommandOf(process.argv);
168
+ const plan = restartPlan({ form: restartForm, pid: null, profile, dshCommand, respawnCommand: originalCommand });
143
169
  if (plan.mode === "unsupported") return { ok: false, error: "restart-unsupported" };
144
170
  const kill = portKillSnippet(port, pid);
171
+ // 保留原始 argv(如 --port 3082 / --no-open),不能落回 `dsh web --profile web`。
172
+ const respawn = plan.mode === "respawn"
173
+ ? (plan.commands?.[plan.commands.length - 1] ?? "")
174
+ : "";
175
+ if (plan.mode === "respawn" && (respawn === "" || originalCommand === "")) {
176
+ return { ok: false, error: "restart-command-missing" };
177
+ }
145
178
  const script = plan.mode === "respawn"
146
- ? `sleep 1; ${kill}; sleep 2; nohup ${dshCommand} web --profile ${profile} >/dev/null 2>&1 &`
179
+ ? `sleep 1; ${kill}; sleep 2; nohup ${respawn} >/dev/null 2>&1 &`
147
180
  : `sleep 1; ${kill}`;
148
- const r = spawnSync("bash", ["-lc", script], { encoding: "utf8" });
181
+ const r = spawnSyncImpl("bash", ["-lc", script], { encoding: "utf8" });
149
182
  if (r.error) return { ok: false, error: r.error.message };
150
183
  if (r.status !== 0) return { ok: false, error: `restart-script-exit-${r.status}: ${(r.stderr || "").trim()}` };
151
184
  log(`supervisor: 已安排重启(${plan.mode},目标=当前端口占用者)`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marktrue/dsh-mobile-remote",
3
- "version": "3.2.4-alpha.2",
3
+ "version": "3.2.4-alpha.20",
4
4
  "description": "DSH Mobile:把 DeepSeek Harness 变成随身控制台——手机远程发消息派活、看进度、收通知、审批决策、管理会话;配套 Flutter App(当前 Android 端,iOS 未开发)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -52,13 +52,13 @@
52
52
  "qrcode"
53
53
  ],
54
54
  "optionalDependencies": {
55
- "@marktrue/dsh-mobile-remote-app": "npm:@marktrue/dsh-mobile-remote@3.2.4-alpha.2-app"
55
+ "@marktrue/dsh-mobile-remote-app": "npm:@marktrue/dsh-mobile-remote@3.2.4-alpha.20-app"
56
56
  },
57
57
  "peerDependencies": {
58
- "@deepseek-ai/dsh-credentials": ">=0.1.0-rc.6 <0.3.0",
59
- "@deepseek-ai/dsh-llm": ">=0.1.0-rc.6 <0.3.0",
60
- "@deepseek-ai/dsh-sandbox-policy": ">=0.1.0-rc.6 <0.3.0",
61
- "@deepseek-ai/dsh-scope": ">=0.1.0-rc.6 <0.3.0",
58
+ "@deepseek-ai/dsh-credentials": ">=0.1.0-rc.6 <=0.2.2 || >=0.2.0-0 <0.2.0 || >=0.2.1-0 <0.2.1 || >=0.2.2-0 <0.2.2",
59
+ "@deepseek-ai/dsh-llm": ">=0.1.0-rc.6 <=0.2.2 || >=0.2.0-0 <0.2.0 || >=0.2.1-0 <0.2.1 || >=0.2.2-0 <0.2.2",
60
+ "@deepseek-ai/dsh-sandbox-policy": ">=0.1.0-rc.6 <=0.2.2 || >=0.2.0-0 <0.2.0 || >=0.2.1-0 <0.2.1 || >=0.2.2-0 <0.2.2",
61
+ "@deepseek-ai/dsh-scope": ">=0.1.0-rc.6 <=0.2.2 || >=0.2.0-0 <0.2.0 || >=0.2.1-0 <0.2.1 || >=0.2.2-0 <0.2.2",
62
62
  "@deepseek-ai/schemastery": ">=3.18.1",
63
63
  "dsh-codex-connect": ">=0.1.0-alpha.4.5"
64
64
  },
@@ -67,6 +67,9 @@
67
67
  "optional": true
68
68
  }
69
69
  },
70
+ "devDependencies": {
71
+ "semver": "^7.7.4"
72
+ },
70
73
  "publishConfig": {
71
74
  "registry": "https://registry.npmjs.org",
72
75
  "access": "public"