@marktrue/dsh-mobile-remote 3.2.4-alpha.1 → 3.2.4-alpha.10

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.
@@ -288,7 +288,7 @@ export function isAllowedDownloadUrl(url) {
288
288
  * 该形态下如何更新;不能自更新时给出**与实际安装方式对应的那一条**降级指引(R11)。
289
289
  * `canSelfUpdate` 由调用方按宿主运行形态判定后传入。
290
290
  */
291
- export function planForShape(shape, { specifier = "", dirPath = "", canSelfUpdate = true, reason = "" } = {}) {
291
+ export function planForShape(shape, { specifier = "", dirPath = "", canSelfUpdate = true, reason = "", channel = "" } = {}) {
292
292
  const installCmd = "pnpm install";
293
293
  const base = (() => {
294
294
  switch (shape) {
@@ -330,7 +330,20 @@ export function planForShape(shape, { specifier = "", dirPath = "", canSelfUpdat
330
330
  };
331
331
  }
332
332
  })();
333
- return { ...base, shape, mode: canSelfUpdate ? "auto" : "guidance", reason };
333
+ // 通道优先:能走宿主原生管理器时,指引要描述**实际会发生什么**,而不是让用户去跑
334
+ // pnpm install(旧实现只按「能不能重启」决定 auto/guidance,容器里就永远给手工指引)。
335
+ if (channel === "host-manager") {
336
+ return {
337
+ summary: "由 DSH 插件管理器在进程内更新,无需重启宿主",
338
+ steps: ["确认目标版本", "宿主移除旧版本并安装新版本", "插件在进程内重新加载(连接不中断)"],
339
+ commands: [],
340
+ shape,
341
+ mode: "auto",
342
+ reason,
343
+ channel,
344
+ };
345
+ }
346
+ return { ...base, shape, mode: canSelfUpdate ? "auto" : "guidance", reason, channel };
334
347
  }
335
348
 
336
349
  /** 检查是否有新版(**不下载、不改动任何东西**)。 */
@@ -639,7 +652,7 @@ function writeJsonFile(file, doc) {
639
652
 
640
653
  // ── 重启 ──────────────────────────────────────────────────────────────────
641
654
 
642
- export function restartPlan({ form, pid = null, profile = "web", dshCommand = "dsh" } = {}) {
655
+ export function restartPlan({ form, pid = null, profile = "web", dshCommand = "dsh", respawnCommand = "" } = {}) {
643
656
  switch (form) {
644
657
  case "web-systemd":
645
658
  return {
@@ -648,11 +661,16 @@ export function restartPlan({ form, pid = null, profile = "web", dshCommand = "d
648
661
  commands: pid ? [`kill -TERM ${pid}`] : ["systemctl --user restart dsh-web.service"],
649
662
  };
650
663
  case "web-foreground":
651
- return {
652
- mode: "respawn",
653
- steps: ["终止当前宿主进程", "由分离脚本重新拉起 dsh web"],
654
- commands: pid ? [`kill -TERM ${pid}`, `${dshCommand} web --profile ${profile}`] : [`${dshCommand} web --profile ${profile}`],
655
- };
664
+ // 优先复用**本进程原样的命令行**(含 --port / --no-open 等参数):容器与自定义启动
665
+ // 方式下拼一个 `dsh web --profile x` 会丢掉这些参数,重启后端口就变了。
666
+ {
667
+ const respawn = respawnCommand !== "" ? respawnCommand : `${dshCommand} web --profile ${profile}`;
668
+ return {
669
+ mode: "respawn",
670
+ steps: ["终止当前宿主进程", "由分离脚本用原命令行重新拉起 dsh web"],
671
+ commands: pid ? [`kill -TERM ${pid}`, respawn] : [respawn],
672
+ };
673
+ }
656
674
  default:
657
675
  return {
658
676
  mode: "unsupported",
@@ -666,13 +684,96 @@ export function restartPlan({ form, pid = null, profile = "web", dshCommand = "d
666
684
  * 识别本机可自动重启的形态。
667
685
  * **默认读真实 `process.env`**——生产调用漏传 env 会让前台 web 永远探测不到(评审 R12)。
668
686
  */
669
- export function detectRestartForm({ env = process.env, platform = process.platform, hasSystemdUnit = () => false } = {}) {
687
+ export function detectRestartForm({ env = process.env, platform = process.platform, hasSystemdUnit = () => false, commandLine = null } = {}) {
670
688
  if (platform === "win32" || platform === "darwin") return "unsupported";
671
689
  if (hasSystemdUnit()) return "web-systemd";
690
+ // 显式标记:启动脚本/服务单元自己声明了这是可重启的前台 web。
672
691
  if (env?.DSH_PROFILE || env?.DSH_WEB_FOREGROUND === "1") return "web-foreground";
692
+ // 退一步看**实际命令行**:`dsh web ...` 本身就是前台 web 形态,与原命令行重启就能生效。
693
+ // 旧实现只看两个环境变量,于是容器/自定义启动(`dsh web --port 3082`,无 DSH_PROFILE)
694
+ // 被误判成 unsupported,整条自更新降级成「请到电脑上运行 pnpm install」。
695
+ // 命令行证据是**本进程自己的**,不依赖外部约定,因此可以作为该判定的依据。
696
+ if (Array.isArray(commandLine) && isDshWebCommandLine(commandLine)) return "web-foreground";
673
697
  return "unsupported";
674
698
  }
675
699
 
700
+ /**
701
+ * 判断命令行是否是前台 `dsh web` 调用。
702
+ *
703
+ * 只认「结尾是 dsh 入口 + `web` 子命令」的形状(兼容 `node <path>/dsh web ...`),
704
+ * 不猜其它形状——误判会让重启脚本执行错误的命令。
705
+ *
706
+ * @param {string[]} commandLine - 完整命令行(`process.argv` 形状)。
707
+ * @returns {boolean}
708
+ */
709
+ export function isDshWebCommandLine(commandLine) {
710
+ if (!Array.isArray(commandLine) || commandLine.length < 2) return false;
711
+ // 第一个参数是 node(或执行器),从第二个开始找 dsh 入口;允许前面有 `--flag`。
712
+ const rest = commandLine.slice(1);
713
+ const dshIndex = rest.findIndex((arg) => typeof arg === "string" && /(^|\/)dsh$/i.test(arg));
714
+ if (dshIndex === -1) return false;
715
+ // dsh 之后第一个**位置参数**必须是 `web`。
716
+ // 注意不能简单地「跳过所有 - 开头的参数再取第一个」:`--profile web` 的取值
717
+ // `web` 会被误当成子命令,而 `--profile web` 实际是「启动名为 web 的 profile」。
718
+ // 因此这里按 dsh 自己的 CLI 选项表跳过取值。
719
+ return firstDshPositional(rest.slice(dshIndex + 1)) === "web";
720
+ }
721
+
722
+ /** dsh 顶层会吃掉一个取值的选项(见 `dsh --help`)。 */
723
+ const DSH_VALUE_OPTIONS = new Set([
724
+ "--profile",
725
+ "--from-default-profile",
726
+ "--patch",
727
+ ]);
728
+
729
+ /**
730
+ * 取 dsh 参数里第一个位置参数,跳过选项及其取值。
731
+ *
732
+ * `--profile web` 与 `--patch a.yml` 的取值不算位置参数;`--flag=value` 形式不占额外参数。
733
+ *
734
+ * @param {string[]} args - dsh 之后的参数。
735
+ * @returns {string} 第一个位置参数,没有则空串。
736
+ */
737
+ export function firstDshPositional(args) {
738
+ for (let i = 0; i < args.length; i++) {
739
+ const arg = args[i];
740
+ if (typeof arg !== "string" || arg === "") continue;
741
+ if (arg.startsWith("-")) {
742
+ // 已带 `=` 的形式(`--profile=web`)不再吃下一个参数。
743
+ if (arg.includes("=")) continue;
744
+ if (DSH_VALUE_OPTIONS.has(arg)) i++;
745
+ continue;
746
+ }
747
+ return arg;
748
+ }
749
+ return "";
750
+ }
751
+
752
+ /**
753
+ * 用本进程原命令行重建一条可执行的 respawn 命令(用于前台 web 形态的重启)。
754
+ *
755
+ * 重新执行的必须是**同一入口、同一参数**;拿不到可靠命令行时返回空串,
756
+ * 由调用方退回 `dsh web --profile <name>` 的保守写法。
757
+ *
758
+ * @param {string[]} commandLine - `process.argv`。
759
+ * @returns {string} 可直接交给 shell 的命令行,或空串。
760
+ */
761
+ export function respawnCommandOf(commandLine) {
762
+ if (!isDshWebCommandLine(commandLine)) return "";
763
+ const parts = commandLine.map((arg) => String(arg));
764
+ // `process.argv[0]` 是 node 可执行文件;用 process.execPath 更稳(argv[0] 可能是别名)。
765
+ if (parts.length > 0) parts[0] = process.execPath;
766
+ return parts.map(shellQuote).join(" ");
767
+ }
768
+
769
+ /** 最小 shell 引用:只给含空白/特殊字符的参数加引号,避免破坏正常路径。 */
770
+ function shellQuote(value) {
771
+ const text = String(value);
772
+ if (text === "") return "''";
773
+ if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(text)) return text;
774
+ return `'${text.replace(/'/g, `'\\''`)}'`;
775
+ }
776
+
676
777
  export function buildRestartScript({ plan, pid = null, delayMs = 3000 } = {}) {
677
778
  const seconds = Math.max(0, Math.round(delayMs / 1000));
678
779
  if (plan?.mode === "supervised") {
@@ -41,7 +41,9 @@ export function createPluginUpdateController(options) {
41
41
  const { home = homedir(), configValue, profileDir, packageName = '', npmPackageView, capabilities, localVersion, localContentSha256,
42
42
  status, log = () => {}, fetchImpl = fetch, auth = {}, basePath = '/m', workerOptions = {},
43
43
  schedule = fn => setImmediate(fn), runSelfUpdate: runner = runSelfUpdate, prepareNpmArtifacts: prepareRunner = prepareNpmArtifacts,
44
- persist = writeOwnedTransaction } = options;
44
+ runHostUpdate: hostRunner, persist = writeOwnedTransaction } = options;
45
+ // 只有调用方显式提供宿主更新执行器时才启用该通道(旧宿主/测试不提供即自动关闭)。
46
+ const runHostUpdate = typeof hostRunner === 'function' ? hostRunner : null;
45
47
  const currentFile = transactionFile(home), lockPath = updateLockPath(home);
46
48
  const preparedUpdates = new Map();
47
49
  const preparedTtlMs = 30 * 60 * 1000;
@@ -160,6 +162,8 @@ export function createPluginUpdateController(options) {
160
162
  if (source.kind === UPDATE_SOURCE_KIND.OFF) return { status: 503, body: { error: 'update-source-off' } };
161
163
  if (source.kind === UPDATE_SOURCE_KIND.INVALID) return { status: 400, body: { error: 'update-source-invalid' } };
162
164
  if (!profileDir) return { status: 409, body: { error: 'profile-not-found' } };
165
+ // `canSelfUpdate` 现在由**通道**决定(宿主管理器或重启通道只要有一条可用即为真),
166
+ // 两条都不通才拒绝;原因码保留 `restart-unsupported` 以免旧 App 判断失效。
163
167
  if (!capabilities().canSelfUpdate) return { status: 409, body: { error: 'restart-unsupported' } };
164
168
  const view = clientView(clientOrigin);
165
169
  const old = readTransaction(currentFile);
@@ -176,6 +180,68 @@ export function createPluginUpdateController(options) {
176
180
  return { status: 200, body: { ok: true, action: 'none', check: { ...checked, release: clientReleaseView(checked.release, view) } } };
177
181
  }
178
182
  const opId = body.opId ?? newOperationId();
183
+ // ── 通道分派:宿主原生管理器可用时走它(进程内更新,不重启) ──────────────
184
+ // 这条路径与下面的「重启通道」互斥:同一时刻只有一个事务、同一把锁。
185
+ if (typeof runHostUpdate === 'function' && capabilities().updateChannel === 'host-manager') {
186
+ const hostTarget = checked.release?.plugin ?? checked.candidate?.plugin;
187
+ if (!hostTarget?.version) return { status: 503, body: { error: 'update-candidate-incomplete' } };
188
+ if (typeof body.targetVersion === 'string' && body.targetVersion !== hostTarget.version) {
189
+ return { status: 409, body: { error: 'candidate-changed', check: checked } };
190
+ }
191
+ const lock = acquireLock(lockPath, { opId, stateFile: currentFile });
192
+ if (!lock.ok) return { status: 409, body: { error: lock.error, transaction: publicTransaction(readTransaction(currentFile), view) } };
193
+ const lease = lock.lease, stateFile = serverOperationPath(home, lease.generation);
194
+ const operationLog = createOperationLog({ home, generation: lease.generation,
195
+ redactPaths: [home, profileDir, workerOptions.pluginRoot, workerOptions.installedRoot] });
196
+ operationLog.setStage('host-manager', 'Host plugin manager update accepted');
197
+ let tx;
198
+ try {
199
+ tx = persist(stateFile, { ...workerOptions, opId, phase: 'staging', startedAt: new Date().toISOString(),
200
+ profileDir, release: checked.release ?? null, hostManager: true,
201
+ manifestUrl: checked.release?.manifestUrl ?? '',
202
+ targetVersion: hostTarget.version, targetContentSha256: hostTarget.contentSha256 ?? '',
203
+ targetAppVersion: checked.release?.app?.version ?? null,
204
+ currentFile, lockPath, lease, attempts: 0 }, { lockPath, lease, currentFile });
205
+ } catch {
206
+ releaseLock(lockPath, lease, { stateFile: currentFile });
207
+ operationLog.setStage('failed', 'Could not persist host manager admission state.');
208
+ operationLog.flush();
209
+ log('host manager update admission state write failed');
210
+ return { status: 500, body: { error: 'update-state-write-failed' } };
211
+ }
212
+ schedule(async () => {
213
+ try {
214
+ const run = await runHostUpdate({ opId, targetVersion: hostTarget.version,
215
+ installedVersion: typeof localVersion === 'function' ? localVersion() : localVersion,
216
+ onStep: step => { operationLog.setStage(step); workerOptions.onStep?.(step); },
217
+ log: message => { operationLog.appendStatus(message, 'worker'); } });
218
+ if (run.ok) {
219
+ operationLog.setStage('finished', 'Host plugin manager applied the update without a restart.');
220
+ finishOwnedTerminal(stateFile, { phase: 'settled', result: { ok: true, matched: 'host-manager' } },
221
+ { lockPath, lease, currentFile });
222
+ Object.assign(status, { state: 'up-to-date', reason: 'host-manager-applied', opId });
223
+ } else {
224
+ const reason = safeUpdateReason(run.reason);
225
+ operationLog.setStage('failed', `Host plugin manager update failed: ${reason}`);
226
+ // `restart-required` 表示包装好了但要重启才生效:这不回滚,如实报告。
227
+ finishOwnedTerminal(stateFile, { phase: run.reason === 'host-manager-restart-required' ? 'settled' : 'failed',
228
+ rolledBack: false, result: { ok: false, reason } }, { lockPath, lease, currentFile });
229
+ Object.assign(status, { state: run.reason === 'host-manager-restart-required' ? 'restarting' : 'update-failed', reason, opId });
230
+ }
231
+ operationLog.flush();
232
+ } catch (e) {
233
+ const reason = safeUpdateReason(e?.message);
234
+ try { finishOwnedTerminal(stateFile, { phase: 'failed', result: { ok: false, reason } }, { lockPath, lease, currentFile }); }
235
+ catch { /* lost lease: never overwrite a newer operation */ }
236
+ operationLog.setStage('failed', `Host manager worker failed: ${reason}`);
237
+ operationLog.flush();
238
+ Object.assign(status, { state: 'update-failed', reason, opId });
239
+ log('host manager update worker failed');
240
+ }
241
+ });
242
+ return { status: 200, body: { ok: true, action: 'accepted', opId, channel: 'host-manager',
243
+ transaction: publicTransaction(tx, view), check: { ...checked, release: clientReleaseView(checked.release, view) } } };
244
+ }
179
245
  let effectiveCheck = checked;
180
246
  let npmCandidate = checked.candidate ?? null;
181
247
  let preparedNpmArtifacts = null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marktrue/dsh-mobile-remote",
3
- "version": "3.2.4-alpha.1",
3
+ "version": "3.2.4-alpha.10",
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.1-app"
55
+ "@marktrue/dsh-mobile-remote-app": "npm:@marktrue/dsh-mobile-remote@3.2.4-alpha.10-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"