@duke-dsh-plugins/dsh-remote-control 1.1.5 → 1.1.7

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.
package/README.md CHANGED
@@ -75,7 +75,7 @@ scripts/verify-pairing.mjs /remote-pairing 命令逻辑自检(mock ctx;devD
75
75
 
76
76
  ```bash
77
77
  # DSH 插件市场(推荐):在「设置 → 插件市场」添加索引 URL 后搜「DSH Pocket」安装
78
- # https://unpkg.com/@duke-dsh-plugins/dsh-remote-control-market@latest/index.json
78
+ # https://unpkg.com/@duke-dsh-plugins/dsh-remote-control@latest/market/index.json
79
79
  #
80
80
  # 或直接用插件管理器:会解析 peerDependencies 并做兼容性 gate
81
81
  plugin_manager install @duke-dsh-plugins/dsh-remote-control
@@ -24,8 +24,9 @@
24
24
  // 生成缩略图,按 §5.10 的 assistant.image / image.fetch 通道发给手机。
25
25
  import { randomUUID, createHash } from "node:crypto";
26
26
  import { readFileSync } from "node:fs";
27
- import { readFile } from "node:fs/promises";
28
- import { hostname } from "node:os";
27
+ import { mkdir, readFile } from "node:fs/promises";
28
+ import { homedir, hostname } from "node:os";
29
+ import { join } from "node:path";
29
30
  import { createRequire } from "node:module";
30
31
  import { msg, sanitizeEnvelope } from "./protocol.mjs";
31
32
  import { ASSISTANT_THROTTLE_PER_SEC } from "./config.mjs";
@@ -51,6 +52,23 @@ import {
51
52
  */
52
53
  const DELIVERED_MAX_BYTES = 20 * 1024 * 1024;
53
54
 
55
+ /**
56
+ * 单会话待发流式文本的字符上限(正文 + 思考合计)。
57
+ *
58
+ * 流式缓冲按「保序队列」实现:同一 125ms 窗口内的块都受这个上限约束,
59
+ * 超了从**最旧**的内容开始丢(保留顺序,不丢新内容),
60
+ * 避免长时间运行 / 异常事件流把内存吃满。
61
+ */
62
+ const STREAM_BUFFER_MAX_CHARS = 65_536;
63
+
64
+ /**
65
+ * 单会话待发流式**块**数的上限。
66
+ *
67
+ * 块只在「类型切换」时新增,125ms 窗口内正常也就几条;但异常事件流
68
+ * (重连回放 / 高频交替)不该让块数无界增长——超了从最旧的块开始丢。
69
+ */
70
+ const STREAM_BUFFER_MAX_BLOCKS = 256;
71
+
54
72
  /**
55
73
  * 单会话待执行消息的条数上限(契约 §5.2 session.queue)。
56
74
  *
@@ -783,6 +801,34 @@ export function hostErrorOf(e, fallbackCode) {
783
801
  return { code, message: errText(e) };
784
802
  }
785
803
 
804
+ /**
805
+ * 契约 §5.1 session.create:**默认工作目录**。
806
+ *
807
+ * 手机端不传 cwd(或传空串)时,不再让宿主回退到 DSH 后端的 process.cwd(),
808
+ * 而是解析为 Host 用户主目录下的 `.dsh/remote`(用 node:path.join 拼,
809
+ * Windows / POSIX 都对)。
810
+ * @param {string} [home] 用户主目录(默认 os.homedir())
811
+ * @returns {string} 绝对路径
812
+ */
813
+ export function defaultSessionCwd(home = homedir()) {
814
+ return join(home, ".dsh", "remote");
815
+ }
816
+
817
+ /**
818
+ * 契约 §5.1 session.create:解析手机端传来的 cwd。
819
+ *
820
+ * 缺省 / undefined / 空串 / trim 后空串 → 默认目录(`~/.dsh/remote`);
821
+ * 其余按既有行为 trim 后返回;显式 cwd 不自动创建目录。
822
+ * @param {unknown} raw payload.cwd
823
+ * @param {string} [home] 用户主目录(默认 os.homedir())
824
+ * @returns {{cwd:string, isDefault:boolean}}
825
+ */
826
+ export function resolveSessionCwd(raw, home = homedir()) {
827
+ const explicit = typeof raw === "string" ? raw : "";
828
+ if (explicit.trim() !== "") return { cwd: explicit.trim(), isDefault: false };
829
+ return { cwd: defaultSessionCwd(home), isDefault: true };
830
+ }
831
+
786
832
  /** result / error 信封(契约 §5)。 */
787
833
  function resultOf(m, value) {
788
834
  return msg("result", { id: m.id, ok: true, value });
@@ -802,10 +848,19 @@ export class HostBridge {
802
848
  #cfg;
803
849
  #log;
804
850
  #pluginVersion;
851
+ // v1.1.4:session.create 的默认工作目录基准(用户主目录)+ 建目录实现
852
+ // —— 二者都可注入,生产用 homedir() / fs.mkdir,测试用临时目录(不写真实 home)。
853
+ #homeDir;
854
+ #mkdir;
805
855
  #disposed = false; // dispose() 后禁止一切出站与拦截
806
- #deltaBuf = new Map(); // sessionId -> { text, timer }(正文增量)
807
- #reasoningBuf = new Map(); // sessionId -> { text, timer }(思考增量,v1.0.7 与正文分流)
856
+ // v1.1.x:每个 session 一个**统一保序**的流式缓冲(正文 + 思考共用一条队列)
857
+ // sessionId -> { blocks: [{kind:"text"|"reasoning", text}], timer }
858
+ // 同一 125ms 窗口内只合并**相邻同类**块;不同类各占一块 → 冲刷时严格按
859
+ // 原始 chunk 顺序发 assistant.delta / assistant.reasoningDelta(跨类型也保序)。
860
+ #streamBuf = new Map();
808
861
  #modelSelections = new Map(); // sessionId -> {provider, model, reasoningEffort?}(v1.0.8 内存态)
862
+ // v1.1.7:有效权限的直播兜底;权威查询仍优先走 permissions 持久投影。
863
+ #permissionSelections = new Map(); // sessionId -> string(含派生态 custom)
809
864
  #pending = new Map(); // askId -> { resolve, kind, sessionId, timer, abortHandler, signal }
810
865
  #titles = new Map(); // sessionId -> title(turn.end 推送文案用)
811
866
  #pushToken = ""; // 手机 push.register 上报的 token(内存态)
@@ -836,6 +891,8 @@ export class HostBridge {
836
891
  * push: { notify:(req:object)=>Promise<{ok:boolean,reason?:string}>, configured:boolean, unavailableReason?:()=>string },
837
892
  * config: any,
838
893
  * log: (level:"info"|"warn"|"error", message:string, extra?:object)=>void,
894
+ * homeDir?: string, // v1.1.4:默认 cwd 的基准目录(默认 os.homedir())
895
+ * mkdir?: (p:string)=>Promise<unknown>, // v1.1.4:建默认目录(默认 fs.mkdir recursive)
839
896
  * }} deps
840
897
  */
841
898
  constructor(deps) {
@@ -844,6 +901,12 @@ export class HostBridge {
844
901
  this.#push = deps.push;
845
902
  this.#cfg = deps.config;
846
903
  this.#log = deps.log;
904
+ this.#homeDir =
905
+ typeof deps.homeDir === "string" && deps.homeDir !== "" ? deps.homeDir : homedir();
906
+ this.#mkdir =
907
+ typeof deps.mkdir === "function"
908
+ ? deps.mkdir
909
+ : (p) => mkdir(p, { recursive: true });
847
910
  this.#pluginVersion = pluginVersion();
848
911
  this.#hostName = hostname();
849
912
  this.#dshVersion = dshVersion();
@@ -868,10 +931,13 @@ export class HostBridge {
868
931
  this.#on("api-session/removed", (sessionId) => {
869
932
  const key = String(sessionId);
870
933
  this.#titles.delete(key);
934
+ this.#permissionSelections.delete(key);
871
935
  // 会话没了,它的待执行列表与交付物历史条目也没有意义了(避免内存泄漏)
872
936
  this.#queues.delete(key);
873
937
  this.#deliveredEntries.delete(key);
874
938
  this.#runningSessions.delete(key);
939
+ // 待发的流式增量也没意义了(定时器一并清掉,别在会话没了之后还出站)
940
+ this.#dropStream(key);
875
941
  this.#sendEvent("session.removed", { sessionId: key });
876
942
  });
877
943
  this.#on("api-session/status", (sessionId, running) => {
@@ -890,20 +956,27 @@ export class HostBridge {
890
956
 
891
957
  // agent/assistant-stream:文本增量与**思考增量分流**,按 sessionId 合并节流(≤8 条/秒)
892
958
  // v1.0.7:chunk.type==='reasoning-delta' → assistant.reasoningDelta(§5.2)
959
+ // v1.1.x:两者进**同一条保序队列**——原先两个独立缓冲 + 固定「先正文后思考」
960
+ // 的冲刷顺序会把 reasoning→text 的 wire 顺序倒过来(手机端按到达顺序渲染,
961
+ // 与冷启动历史「思考在前」不一致,用户看到正文跑到思考前面)。
893
962
  this.#on("agent/assistant-stream", (payload) => {
894
963
  try {
895
964
  const frame = payload?.frame;
896
- if (!frame || frame.type !== "chunk") return;
897
- const chunk = frame.chunk;
898
- if (!chunk || typeof chunk.text !== "string" || chunk.text === "") return;
899
- if (chunk.type !== "text-delta" && chunk.type !== "reasoning-delta") return;
965
+ if (!frame) return;
900
966
  const sessionId = payload?.agent?.session?.id;
901
967
  if (!sessionId) return;
902
- if (chunk.type === "reasoning-delta") {
903
- this.#queueReasoning(String(sessionId), chunk.text);
968
+ // 一条 assistant 流结束时立即冲刷,后续 tool.call/result、图片等持久事件
969
+ // 不得越过尚未上屏的正文/思考。
970
+ if (frame.type === "end") {
971
+ this.#flushStream(String(sessionId));
904
972
  return;
905
973
  }
906
- this.#queueDelta(String(sessionId), chunk.text);
974
+ if (frame.type !== "chunk") return;
975
+ const chunk = frame.chunk;
976
+ if (!chunk || typeof chunk.text !== "string" || chunk.text === "") return;
977
+ if (chunk.type !== "text-delta" && chunk.type !== "reasoning-delta") return;
978
+ // 正文与思考进**同一条保序队列**(v1.1.x):跨类型的先后关系必须保住
979
+ this.#queueStream(String(sessionId), chunk.type === "reasoning-delta" ? "reasoning" : "text", chunk.text);
907
980
  } catch (e) {
908
981
  this.#log("warn", "assistant-stream bridge error", { error: errText(e) });
909
982
  }
@@ -915,8 +988,8 @@ export class HostBridge {
915
988
  const sessionId = payload?.agent?.session?.id;
916
989
  if (!sessionId) return;
917
990
  if (payload.status === "idle") {
918
- this.#flushDelta(String(sessionId));
919
- this.#flushReasoning(String(sessionId));
991
+ // 先统一冲刷全部待发块(正文 + 思考,**保持原始顺序**),再发 turn.end
992
+ this.#flushStream(String(sessionId));
920
993
  this.#sendEvent("turn.end", { sessionId: String(sessionId), status: "idle" });
921
994
  this.#maybeNotifyTurnEnd(String(sessionId));
922
995
  }
@@ -931,8 +1004,8 @@ export class HostBridge {
931
1004
  if (!sessionId) return;
932
1005
  const err = payload.error;
933
1006
  const message = err && typeof err.message === "string" ? err.message : String(err);
934
- this.#flushDelta(String(sessionId));
935
- this.#flushReasoning(String(sessionId));
1007
+ // 与 idle 同口径:先统一冲刷(保序),再发 turn.end
1008
+ this.#flushStream(String(sessionId));
936
1009
  this.#sendEvent("turn.end", { sessionId: String(sessionId), status: "error", error: message });
937
1010
  this.#maybeNotifyTurnEnd(String(sessionId), message);
938
1011
  } catch (e) {
@@ -954,12 +1027,18 @@ export class HostBridge {
954
1027
  const type = event?.type;
955
1028
  if (type === "tool/call") {
956
1029
  const mapped = mapToolCallEvent(sessionId, event);
957
- if (mapped !== null) this.#sendEvent("tool.call", mapped);
1030
+ if (mapped !== null) {
1031
+ this.#flushStream(sessionId);
1032
+ this.#sendEvent("tool.call", mapped);
1033
+ }
958
1034
  return;
959
1035
  }
960
1036
  if (type === "tool/result") {
961
1037
  const mapped = mapToolResultEvent(sessionId, event);
962
- if (mapped !== null) this.#sendEvent("tool.result", mapped);
1038
+ if (mapped !== null) {
1039
+ this.#flushStream(sessionId);
1040
+ this.#sendEvent("tool.result", mapped);
1041
+ }
963
1042
  return;
964
1043
  }
965
1044
  if (type === "model/selection") {
@@ -970,14 +1049,24 @@ export class HostBridge {
970
1049
  this.#sendEvent("session.modelChanged", { sessionId, model: selection });
971
1050
  return;
972
1051
  }
1052
+ if (type === "permission/preset" || type === "sandbox/mode" || type === "approval/policy") {
1053
+ // v1.1.7:桌面端当前权限由这三类 knob 事件共同折叠,不是单看 preset。
1054
+ // current(session) 与桌面端 permissions.currentValue 投影共用同一 derive;
1055
+ // 因而直接改 sandbox/approval 导致的 custom 也能同步到手机。
1056
+ this.#emitPermissionChanged(session, event);
1057
+ return;
1058
+ }
973
1059
  if (type === "assistant/message") {
974
- // v1.0.9(§5.10):助手消息里的图片 → 广播 assistant.image(带内联缩略图)
1060
+ // v1.0.9(§5.10):助手消息里的图片 → 广播 assistant.image(带内联缩略图)。
1061
+ // 即便本条没有图片,也先把之前的流式文本/思考冲出去,保持时间线顺序。
1062
+ this.#flushStream(sessionId);
975
1063
  this.#emitAssistantImages(sessionId, event);
976
1064
  return;
977
1065
  }
978
1066
  if (type === "deliverables/presented") {
979
1067
  // present 工具投递的文件:宿主记的是**路径**,不是图片附件块 →
980
1068
  // 不桥接的话手机端永远看不到这些图(用户反馈:桌面有、手机没有)。
1069
+ this.#flushStream(sessionId);
981
1070
  void this.#emitDeliveredImages(sessionId, event);
982
1071
  return;
983
1072
  }
@@ -1009,6 +1098,35 @@ export class HostBridge {
1009
1098
  return () => this.dispose();
1010
1099
  }
1011
1100
 
1101
+ /**
1102
+ * 权限 knob 变化 → session.permissionChanged(v1.1.7)。
1103
+ * 新宿主用 permissionPresets.current(session) 取有效值;旧宿主没有 current 时,
1104
+ * 只在明确的 permission/preset 事件上回退其 preset,不对 sandbox/approval 臆造值。
1105
+ */
1106
+ #emitPermissionChanged(session, event) {
1107
+ const sessionId = String(session?.id ?? "");
1108
+ if (sessionId === "") return;
1109
+ const svc = this.#service("permissionPresets");
1110
+ let permission = null;
1111
+ if (svc && typeof svc.current === "function") {
1112
+ try {
1113
+ const current = svc.current(session);
1114
+ if (typeof current === "string" && current !== "") permission = current;
1115
+ } catch (e) {
1116
+ this.#log("warn", "permission current failed; change event skipped", {
1117
+ sessionId,
1118
+ error: errText(e),
1119
+ });
1120
+ }
1121
+ } else if (event?.type === "permission/preset") {
1122
+ const preset = event?.data?.preset;
1123
+ if (typeof preset === "string" && preset !== "") permission = preset;
1124
+ }
1125
+ if (permission === null) return;
1126
+ this.#permissionSelections.set(sessionId, permission);
1127
+ this.#sendEvent("session.permissionChanged", { sessionId, permission });
1128
+ }
1129
+
1012
1130
  /** 广播归档全集(契约 §5.2 session.archives)。没有注册表 → 不发。 */
1013
1131
  #broadcastArchives() {
1014
1132
  const ids = this.#archivedSessionIds();
@@ -1212,14 +1330,10 @@ export class HostBridge {
1212
1330
  /** 释放全部资源(定时器/待答项/监听)。 */
1213
1331
  dispose() {
1214
1332
  this.#disposed = true;
1215
- for (const b of this.#deltaBuf.values()) {
1216
- if (b.timer !== null) clearTimeout(b.timer);
1217
- }
1218
- this.#deltaBuf.clear();
1219
- for (const b of this.#reasoningBuf.values()) {
1333
+ for (const b of this.#streamBuf.values()) {
1220
1334
  if (b.timer !== null) clearTimeout(b.timer);
1221
1335
  }
1222
- this.#reasoningBuf.clear();
1336
+ this.#streamBuf.clear();
1223
1337
  for (const entry of this.#pending.values()) {
1224
1338
  if (entry.timer !== null) clearTimeout(entry.timer);
1225
1339
  if (entry.signal && entry.abortHandler) {
@@ -1606,58 +1720,101 @@ export class HostBridge {
1606
1720
  }
1607
1721
  }
1608
1722
 
1609
- // ---- assistant.delta 节流 -------------------------------------------------
1723
+ // ---- assistant 流式增量:统一保序缓冲(正文 + 思考,v1.1.x)---------------
1610
1724
 
1611
- #queueDelta(sessionId, text) {
1612
- let b = this.#deltaBuf.get(sessionId);
1725
+ /**
1726
+ * 入队一个流式增量块。
1727
+ *
1728
+ * 规则:
1729
+ * - 正文(text)与思考(reasoning)进**同一条队列**,块按到达顺序排;
1730
+ * - 同一窗口内**只合并相邻同类**块(尾块同类就并进去);
1731
+ * - 不同类**不跨块合并**——否则 reasoning 与 text 会糊成一条,
1732
+ * 冲刷时无法还原原始先后顺序。
1733
+ *
1734
+ * @param {string} sessionId
1735
+ * @param {"text"|"reasoning"} kind
1736
+ * @param {string} text
1737
+ */
1738
+ #queueStream(sessionId, kind, text) {
1739
+ if (this.#disposed) return; // dispose() 后不再产生任何出站
1740
+ let b = this.#streamBuf.get(sessionId);
1613
1741
  if (b === undefined) {
1614
- b = { text: "", timer: null };
1615
- this.#deltaBuf.set(sessionId, b);
1742
+ b = { blocks: [], timer: null };
1743
+ this.#streamBuf.set(sessionId, b);
1616
1744
  }
1617
- b.text += text;
1618
- if (b.text.length > 65_536) b.text = b.text.slice(-65_536); // 内存上限
1745
+ const last = b.blocks[b.blocks.length - 1];
1746
+ if (last !== undefined && last.kind === kind) {
1747
+ last.text += text;
1748
+ } else {
1749
+ b.blocks.push({ kind, text });
1750
+ }
1751
+ this.#trimStreamBuffer(b);
1619
1752
  if (b.timer === null) {
1620
- b.timer = setTimeout(() => this.#flushDelta(sessionId), Math.ceil(1000 / ASSISTANT_THROTTLE_PER_SEC));
1753
+ b.timer = setTimeout(() => this.#flushStream(sessionId), Math.ceil(1000 / ASSISTANT_THROTTLE_PER_SEC));
1621
1754
  }
1622
1755
  }
1623
1756
 
1624
- #flushDelta(sessionId) {
1625
- const b = this.#deltaBuf.get(sessionId);
1757
+ /**
1758
+ * 内存上限:单会话待发文本(正文 + 思考合计)不超过 STREAM_BUFFER_MAX_CHARS。
1759
+ *
1760
+ * 超了从**最旧**的内容开始丢(保序:只丢头,不动类型顺序,也不丢新内容)。
1761
+ * 块数另有 STREAM_BUFFER_MAX_BLOCKS 上限(类型频繁切换时的兜底)。
1762
+ * @param {{blocks:{kind:string,text:string}[]}} b
1763
+ */
1764
+ #trimStreamBuffer(b) {
1765
+ let total = 0;
1766
+ for (const blk of b.blocks) total += blk.text.length;
1767
+ let excess = total - STREAM_BUFFER_MAX_CHARS;
1768
+ while (excess > 0 && b.blocks.length > 0) {
1769
+ const first = b.blocks[0];
1770
+ if (first.text.length <= excess) {
1771
+ excess -= first.text.length;
1772
+ b.blocks.shift();
1773
+ } else {
1774
+ first.text = first.text.slice(excess);
1775
+ excess = 0;
1776
+ }
1777
+ }
1778
+ while (b.blocks.length > STREAM_BUFFER_MAX_BLOCKS) b.blocks.shift();
1779
+ }
1780
+
1781
+ /**
1782
+ * 冲刷一个会话的全部待发块:**严格按原始 chunk 顺序**逐块发
1783
+ * (assistant.delta / assistant.reasoningDelta),跨类型也保序。
1784
+ * @param {string} sessionId
1785
+ */
1786
+ #flushStream(sessionId) {
1787
+ const b = this.#streamBuf.get(sessionId);
1626
1788
  if (b === undefined) return;
1627
1789
  if (b.timer !== null) {
1628
1790
  clearTimeout(b.timer);
1629
1791
  b.timer = null;
1630
1792
  }
1631
- const text = b.text;
1632
- b.text = "";
1633
- if (text !== "") this.#sendEvent("assistant.delta", { sessionId, text });
1634
- }
1635
-
1636
- // ---- assistant.reasoningDelta 节流(v1.0.7,与正文同口径 ≤8 条/秒)--------
1637
-
1638
- #queueReasoning(sessionId, text) {
1639
- let b = this.#reasoningBuf.get(sessionId);
1640
- if (b === undefined) {
1641
- b = { text: "", timer: null };
1642
- this.#reasoningBuf.set(sessionId, b);
1643
- }
1644
- b.text += text;
1645
- if (b.text.length > 65_536) b.text = b.text.slice(-65_536); // 内存上限
1646
- if (b.timer === null) {
1647
- b.timer = setTimeout(() => this.#flushReasoning(sessionId), Math.ceil(1000 / ASSISTANT_THROTTLE_PER_SEC));
1793
+ const blocks = b.blocks;
1794
+ b.blocks = [];
1795
+ // 空了就别占着 map(会话很多时避免无界增长)
1796
+ if (this.#streamBuf.get(sessionId) === b) this.#streamBuf.delete(sessionId);
1797
+ if (this.#disposed) return; // dispose() 后不再产生任何出站
1798
+ for (const blk of blocks) {
1799
+ if (blk.text === "") continue;
1800
+ if (blk.kind === "reasoning") {
1801
+ this.#sendEvent("assistant.reasoningDelta", { sessionId, text: blk.text });
1802
+ } else {
1803
+ this.#sendEvent("assistant.delta", { sessionId, text: blk.text });
1804
+ }
1648
1805
  }
1649
1806
  }
1650
1807
 
1651
- #flushReasoning(sessionId) {
1652
- const b = this.#reasoningBuf.get(sessionId);
1808
+ /** 丢弃某会话的待发块(会话没了)——清定时器 + 清队列。 */
1809
+ #dropStream(sessionId) {
1810
+ const b = this.#streamBuf.get(sessionId);
1653
1811
  if (b === undefined) return;
1654
1812
  if (b.timer !== null) {
1655
1813
  clearTimeout(b.timer);
1656
1814
  b.timer = null;
1657
1815
  }
1658
- const text = b.text;
1659
- b.text = "";
1660
- if (text !== "") this.#sendEvent("assistant.reasoningDelta", { sessionId, text });
1816
+ b.blocks = [];
1817
+ this.#streamBuf.delete(sessionId);
1661
1818
  }
1662
1819
 
1663
1820
  // ---- 业务请求分发(§5.1)---------------------------------------------------
@@ -1691,6 +1848,10 @@ export class HostBridge {
1691
1848
  return await this.#rSessionSelectModel(m);
1692
1849
  case "session.model":
1693
1850
  return await this.#rSessionModel(m);
1851
+ case "session.selectPermission":
1852
+ return await this.#rSessionSelectPermission(m);
1853
+ case "session.permission":
1854
+ return await this.#rSessionPermission(m);
1694
1855
  case "session.queue":
1695
1856
  return this.#rSessionQueue(m);
1696
1857
  case "session.archive":
@@ -2073,19 +2234,43 @@ export class HostBridge {
2073
2234
  try {
2074
2235
  const sc = this.#sc();
2075
2236
  const req = {};
2076
- if (typeof p.cwd === "string" && p.cwd !== "") {
2077
- // v1.1.4:cwd 若命中某个**已注册工作区**的目录,改传 `workspaceId`
2078
- // 让会话自动归到该工作区下面(与 PC 端「在工作区里新建」一致——
2079
- // PC 走 createInWorkspace → createNamed({workspaceId}))。
2080
- // 旧实现只传 cwd,宿主不会 attach 到任何工作区 → PC 上显示「未分组」。
2081
- // 未命中(普通目录)保持传 cwd,与 PC 在任意目录新建一样 = 未分组。
2082
- // resolveByPath 不创建工作区、不改写注册表;路径不存在会 reject → 兜底回 cwd。
2083
- const ws = await this.#resolveWorkspaceByCwd(p.cwd);
2084
- if (ws !== null) {
2085
- req.workspaceId = ws;
2086
- } else {
2087
- req.cwd = p.cwd;
2237
+ // v1.1.4:cwd 缺省 / undefined / 空串 / trim 后空串时,**不再**交给宿主
2238
+ // 回退到 DSH 后端的 process.cwd()——解析为 Host 用户主目录下的
2239
+ // `~/.dsh/remote`,并**先确保目录存在**(失败直接回错,不静默回退)。
2240
+ // 显式非空 cwd 保持原行为(不自动建目录)。
2241
+ const { cwd, isDefault } = resolveSessionCwd(p.cwd, this.#homeDir);
2242
+ if (isDefault) {
2243
+ if (p.cwd !== undefined && p.cwd !== null && typeof p.cwd !== "string") {
2244
+ this.#log("warn", "session.create got a non-string cwd; using the default directory", {
2245
+ type: typeof p.cwd,
2246
+ });
2088
2247
  }
2248
+ try {
2249
+ await this.#mkdir(cwd);
2250
+ } catch (e) {
2251
+ this.#log("error", "failed to create the default session directory", {
2252
+ error: errText(e),
2253
+ });
2254
+ this.#reply(
2255
+ m,
2256
+ errorOf(m, "session-create-failed", "cannot create session directory: " + errText(e)),
2257
+ );
2258
+ return;
2259
+ }
2260
+ }
2261
+ // v1.1.4:cwd 若命中某个**已注册工作区**的目录,改传 `workspaceId`
2262
+ // 让会话自动归到该工作区下面(与 PC 端「在工作区里新建」一致——
2263
+ // PC 走 createInWorkspace → createNamed({workspaceId}))。
2264
+ // 旧实现只传 cwd,宿主不会 attach 到任何工作区 → PC 上显示「未分组」。
2265
+ // 未命中(普通目录)保持传 cwd,与 PC 在任意目录新建一样 = 未分组。
2266
+ // resolveByPath 不创建工作区、不改写注册表;路径不存在会 reject → 兜底回 cwd。
2267
+ // 默认目录(~/.dsh/remote)同样走这条反查:已注册 → 传 workspaceId,
2268
+ // 未注册 → 传该 cwd(**不自动注册工作区**)。
2269
+ const ws = await this.#resolveWorkspaceByCwd(cwd);
2270
+ if (ws !== null) {
2271
+ req.workspaceId = ws;
2272
+ } else {
2273
+ req.cwd = cwd;
2089
2274
  }
2090
2275
  if (agentPreset !== "") req.agentPreset = agentPreset;
2091
2276
  let value;
@@ -2325,6 +2510,146 @@ export class HostBridge {
2325
2510
  this.#reply(m, resultOf(m, { model: this.#modelSelections.get(sessionId) ?? null }));
2326
2511
  }
2327
2512
 
2513
+ /** 契约 §5.1/§5.8(v1.1.7)session.selectPermission:切换已存在会话的权限。
2514
+ * Host 不做根会话/subagent 的额外限制(App 自行限制入口);未知 preset、Auto 准入
2515
+ * 与 resolveAgent 的宿主拒绝均按原错误码/原文回传,绝不在本机假成功。 */
2516
+ async #rSessionSelectPermission(m) {
2517
+ const p = m.payload ?? {};
2518
+ const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
2519
+ const permission = typeof p.permission === "string" ? p.permission.trim() : "";
2520
+ if (sessionId === "" || permission === "") {
2521
+ this.#reply(m, errorOf(m, "bad-params", "sessionId and permission required"));
2522
+ return;
2523
+ }
2524
+ const svc = this.#service("permissionPresets");
2525
+ if (!svc || typeof svc.set !== "function") {
2526
+ this.#reply(m, errorOf(m, "service-unavailable", "permissionPresets.set unavailable"));
2527
+ return;
2528
+ }
2529
+ let sc = null;
2530
+ try {
2531
+ sc = this.#sc();
2532
+ } catch (e) {
2533
+ this.#reply(m, errorOf(m, "service-unavailable", errText(e)));
2534
+ return;
2535
+ }
2536
+ if (typeof sc.resolveAgent !== "function") {
2537
+ this.#reply(m, errorOf(m, "service-unavailable", "sessionController.resolveAgent unavailable"));
2538
+ return;
2539
+ }
2540
+ let session = null;
2541
+ try {
2542
+ const agentRes = await sc.resolveAgent(sessionId);
2543
+ // 与创建时一致:兼容直接 Agent、{agent} 与旧版 {error};拒绝不得改写。
2544
+ if (agentRes?.error) throw agentRes.error;
2545
+ session = agentRes?.agent?.session ?? agentRes?.session ?? null;
2546
+ if (!session) {
2547
+ this.#reply(m, errorOf(m, "session-not-found", `session "${sessionId}" has no live agent`));
2548
+ return;
2549
+ }
2550
+ } catch (e) {
2551
+ const err = hostErrorOf(e, "session-select-permission-failed");
2552
+ this.#log("warn", "resolveAgent for selectPermission failed", { sessionId, code: err.code });
2553
+ this.#reply(m, errorOf(m, err.code, err.message));
2554
+ return;
2555
+ }
2556
+ try {
2557
+ await svc.set(session, permission);
2558
+ } catch (e) {
2559
+ const err = hostErrorOf(e, "session-select-permission-failed");
2560
+ this.#log("warn", "selectPermission failed", { sessionId, code: err.code });
2561
+ this.#reply(m, errorOf(m, err.code, err.message));
2562
+ return;
2563
+ }
2564
+ // set() 已成功即不能把它伪装成失败。新宿主回读有效值(与桌面端同 derive),
2565
+ // 旧宿主没有 current() 时回显刚被 set 接受的 preset。
2566
+ let selected = permission;
2567
+ if (typeof svc.current === "function") {
2568
+ try {
2569
+ const current = svc.current(session);
2570
+ if (typeof current === "string" && current !== "") selected = current;
2571
+ } catch (e) {
2572
+ this.#log("warn", "permission current readback failed; returning accepted preset", {
2573
+ sessionId,
2574
+ error: errText(e),
2575
+ });
2576
+ }
2577
+ }
2578
+ this.#permissionSelections.set(sessionId, selected);
2579
+ this.#reply(m, resultOf(m, { permission: selected }));
2580
+ }
2581
+
2582
+ /** 契约 §5.1/§5.8(v1.1.7)session.permission:查询有效权限。
2583
+ * 权威来源是 permissions 持久投影 values.permissions.currentValue(桌面端同源),
2584
+ * 因而根会话与 subagent 都可冷读,且不要求激活 live Agent。投影不可用时依次退回
2585
+ * permissionPresets.current(liveSession) 与直播内存态;全部不可用回 null,不臆造。 */
2586
+ async #rSessionPermission(m) {
2587
+ const p = m.payload ?? {};
2588
+ const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
2589
+ if (sessionId === "") {
2590
+ this.#reply(m, errorOf(m, "bad-params", "sessionId required"));
2591
+ return;
2592
+ }
2593
+ try {
2594
+ const sc = this.#sc();
2595
+ if (typeof sc.projections === "function") {
2596
+ const projections = await sc.projections({ sessionId }, this.#signal(10_000));
2597
+ const view = projections?.values?.permissions;
2598
+ if (view !== undefined && view !== null) {
2599
+ const permission =
2600
+ typeof view.currentValue === "string" && view.currentValue !== "" ? view.currentValue : null;
2601
+ if (permission !== null) this.#permissionSelections.set(sessionId, permission);
2602
+ this.#reply(m, resultOf(m, { permission }));
2603
+ return;
2604
+ }
2605
+ }
2606
+ } catch (e) {
2607
+ this.#log("warn", "permissions projection unavailable; falling back to live tracking", {
2608
+ sessionId,
2609
+ error: errText(e),
2610
+ });
2611
+ }
2612
+
2613
+ // 旧宿主没有 permissions 投影时,live Session 的 current() 仍是有效值权威来源。
2614
+ // 但 subagent 查询绝不能为了兜底而激活 Agent:先用 inspect 冷读身份,命中即只回内存态。
2615
+ try {
2616
+ const svc = this.#service("permissionPresets");
2617
+ const sc = this.#sc();
2618
+ let coldSubagent = false;
2619
+ if (typeof sc.inspect === "function") {
2620
+ try {
2621
+ const inspected = await sc.inspect(sessionId, this.#signal(10_000));
2622
+ const meta = inspected?.meta;
2623
+ coldSubagent = meta?.origin === "subagent" ||
2624
+ (typeof meta?.parentSessionId === "string" && meta.parentSessionId !== "");
2625
+ } catch (e) {
2626
+ this.#log("warn", "permission subagent identity inspect unavailable", {
2627
+ sessionId,
2628
+ error: errText(e),
2629
+ });
2630
+ }
2631
+ }
2632
+ if (!coldSubagent && svc && typeof svc.current === "function" && typeof sc.resolveAgent === "function") {
2633
+ const agentRes = await sc.resolveAgent(sessionId);
2634
+ const session = agentRes?.agent?.session ?? agentRes?.session ?? null;
2635
+ if (session) {
2636
+ const current = svc.current(session);
2637
+ if (typeof current === "string" && current !== "") {
2638
+ this.#permissionSelections.set(sessionId, current);
2639
+ this.#reply(m, resultOf(m, { permission: current }));
2640
+ return;
2641
+ }
2642
+ }
2643
+ }
2644
+ } catch (e) {
2645
+ this.#log("warn", "live permission read unavailable; falling back to tracked value", {
2646
+ sessionId,
2647
+ error: errText(e),
2648
+ });
2649
+ }
2650
+ this.#reply(m, resultOf(m, { permission: this.#permissionSelections.get(sessionId) ?? null }));
2651
+ }
2652
+
2328
2653
  /** 模式目录(宿主 Agent preset 目录)。服务缺失/抛错 → 空目录。 */
2329
2654
  async #loadAgentPresets() {
2330
2655
  const svc = this.#service("agentPresets");
package/market/index.json CHANGED
@@ -69,9 +69,29 @@
69
69
  "sortKeys": {}
70
70
  },
71
71
  "versions": [
72
+ {
73
+ "version": "1.1.7",
74
+ "publishTimestamp": 1793320998,
75
+ "source": {
76
+ "type": "npm"
77
+ },
78
+ "engines": {
79
+ "dsh": "^0.1.5-rc.3 || ^0.2.0-rc.1 || ^0.2.1-rc.0"
80
+ }
81
+ },
82
+ {
83
+ "version": "1.1.6",
84
+ "publishTimestamp": 1793202911,
85
+ "source": {
86
+ "type": "npm"
87
+ },
88
+ "engines": {
89
+ "dsh": "^0.1.5-rc.3 || ^0.2.0-rc.1 || ^0.2.1-rc.0"
90
+ }
91
+ },
72
92
  {
73
93
  "version": "1.1.5",
74
- "publishTimestamp": 1793149102,
94
+ "publishTimestamp": 1793149134,
75
95
  "source": {
76
96
  "type": "npm"
77
97
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duke-dsh-plugins/dsh-remote-control",
3
- "version": "1.1.5",
3
+ "version": "1.1.7",
4
4
  "description": "Remote-control bridge for DeepSeek Harness: pairs a HarmonyOS phone app with the desktop Host over an end-to-end-encrypted public relay (WebSocket). Lets the phone list/create/switch sessions, send prompts, watch streamed replies, cancel turns, and answer approval and ask-user-question requests from anywhere; pushes Huawei Push Kit notifications (gracefully disabled when AGC is unconfigured) for approvals, questions, and turn completion. The pairing QR lives in the DSH settings panel (\"DSH Pocket\"). Fail-open by design: any relay timeout or fault hands the request back to the desktop answerer.",
5
5
  "type": "module",
6
6
  "main": "index.js",