@dsh-mobile/mobile-remote 3.3.1 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +9 -5
  2. package/docs/PRIVACY-POLICY.en.md +10 -3
  3. package/docs/PRIVACY-POLICY.md +10 -3
  4. package/docs/USER-GUIDE.zh-CN.md +1 -0
  5. package/lib/account-usage-query.js +60 -60
  6. package/lib/account-usage.js +10 -10
  7. package/lib/api-helpers.js +109 -109
  8. package/lib/assistant-prefs.js +82 -59
  9. package/lib/auto-config.js +65 -65
  10. package/lib/backup.js +117 -117
  11. package/lib/break-reminder.js +45 -45
  12. package/lib/client.js +93 -93
  13. package/lib/config.js +232 -218
  14. package/lib/git-read-bundled-provider.js +12 -12
  15. package/lib/git-read-service.js +5 -5
  16. package/lib/host-compat.js +84 -84
  17. package/lib/http-util.js +17 -17
  18. package/lib/index.js +1534 -1534
  19. package/lib/memory/context.js +44 -44
  20. package/lib/memory/decay.js +93 -93
  21. package/lib/memory/extract.js +77 -77
  22. package/lib/memory/routes.js +33 -33
  23. package/lib/memory/store.js +196 -196
  24. package/lib/notify-copy.js +93 -93
  25. package/lib/permission-guide.js +86 -86
  26. package/lib/persona-cards.js +73 -65
  27. package/lib/phone-action-args.js +175 -0
  28. package/lib/phone-actions.js +227 -0
  29. package/lib/phone-announce.js +58 -0
  30. package/lib/proactive-material.js +42 -42
  31. package/lib/proactive.js +121 -121
  32. package/lib/protected-paths.js +79 -79
  33. package/lib/protocol.js +61 -26
  34. package/lib/push.js +29 -29
  35. package/lib/rate-limit.js +16 -16
  36. package/lib/relay/connector.js +246 -102
  37. package/lib/relay/crypto.js +15 -15
  38. package/lib/relay/devices.js +36 -36
  39. package/lib/relay/fingerprint.js +34 -34
  40. package/lib/relay/identity.js +26 -26
  41. package/lib/relay/mux.js +60 -46
  42. package/lib/relay/noise.js +40 -40
  43. package/lib/relay/on-demand.js +33 -33
  44. package/lib/relay/p2p.js +239 -0
  45. package/lib/relay/pairing.js +24 -24
  46. package/lib/relay/phone.js +62 -40
  47. package/lib/relay/serve.js +21 -21
  48. package/lib/relay/signal.js +69 -0
  49. package/lib/relay/ws-server.js +32 -32
  50. package/lib/reminders.js +15 -15
  51. package/lib/rpc-adapter.js +43 -43
  52. package/lib/session-list.js +31 -31
  53. package/lib/session-rotation.js +95 -95
  54. package/lib/session-title-cache.js +35 -35
  55. package/lib/session-title-refresh.js +51 -51
  56. package/lib/timeline.js +140 -140
  57. package/lib/turn-outline.js +104 -104
  58. package/package.json +6 -13
@@ -1,31 +1,31 @@
1
- /**
2
- * 手机 API → 内核 RPC 的端点改名 / 载荷适配表,以及 RPC 失败到 HTTP 错误三元组的统一映射。
3
- * 从 lib/index.js 原样拆出(行为不变)。
4
- */
1
+
2
+
3
+
4
+
5
5
  import { randomUUID } from "node:crypto";
6
6
  import { redactPathText } from "./api-helpers.js";
7
7
 
8
- // v3.1.2(适配 DSH 0.1.2-rc.1)——内核 RPC 契约变化:
9
- // ① 端点命名 namespace.method → namespace/method(session.models → session/modelCatalog、
10
- // session.history → session/control、goal.create → goals/create、subagent.* → subagents.*);
11
- // ② 载荷按新参数形态适配(单 request 包装 / 多参数平铺 / 零参数,见网关 typert 定义);
12
- // ③ 桌面 2.0.5 起 /api HTTP 通道被浏览器访问门禁+会话 Cookie 鉴权关闭(插件 fetch 必 403),
13
- // 统一改走进程内 ctx.typertGateway.invokeRpc(@Remote 网关,与宿主同域直通服务层)。
14
- // 旧宿主(无网关 / 接口未迁移)保留原 HTTP /api 降级路径(载荷保持旧契约不适配)。
15
- // v3.1.5(PR #11 P0):goal/subagent 的命名空间在内核注册表里是**复数**且参数是命名 wire 字段。
16
- // 网关按 `<namespace>/<method>` 严格查表并在 assertExactArguments 里逐字段比对
17
- // (@deepseek-ai/dsh-api-gateway/lib/index.js:738-762、1040-1051:endpoint 缺失报
18
- // gateway/invocation-unavailable、字段不符报 gateway/arguments-invalid),
19
- // 旧值 "subagent/list"、"subagent/interrupt"(单数命名空间 + 错方法名)与 goal/* 必然失败 →
20
- // 手机「子代理」「目标」面板恒报错。注册表事实(dsh-api-remotes/lib/client.js):
21
- // subagents/list(parentSessionId)、subagents/interruptByParent(childSessionId,parentSessionId,mode)、
22
- // goals/create(agentId,request{objective,maxGoalRounds?})、goals/{pause,resume,complete}(agentId,ref{id,revision})。
23
- // mode 在内核里是 z.literal("continuable"),故缺省即该唯一合法值。
24
- // T-02: DSH 0.2.1-rc.2 replaced interruptByParent(childSessionId, parentSessionId, mode) with
25
- // interruptByUser(childSessionId) (upgrade guide v0.2.1-rc.2/subagent-user-controls); hosts from
26
- // 0.2.2-rc.2 on have only the new one. "subagent.interrupt" now names the new endpoint and
27
- // "subagent.interruptByParent" the old one, which /subagents/interrupt tries only when the host
28
- // reports the new endpoint as missing (isEndpointUnavailable).
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
29
  const goalRefArgs = (p) => ({ agentId: p.sessionId, ref: p.ref });
30
30
  export const RPC_ENDPOINT_RENAMES = {
31
31
  "session.models": "session/modelCatalog",
@@ -58,11 +58,11 @@ export const RPC_PAYLOAD_ADAPTER = {
58
58
  "goal.resume": goalRefArgs,
59
59
  "goal.complete": goalRefArgs,
60
60
  };
61
- /**
62
- * Gateway error codes that mean "this host has no such endpoint" (as opposed to a failed call):
63
- * an unknown endpoint, a withdrawn definition, or a service without the method. Only these may
64
- * trigger a fallback to an older endpoint; any other failure is the real answer.
65
- */
61
+
62
+
63
+
64
+
65
+
66
66
  const ENDPOINT_UNAVAILABLE_CODES = new Set([
67
67
  "gateway/invocation-unavailable",
68
68
  "gateway/definition-unavailable",
@@ -70,21 +70,21 @@ const ENDPOINT_UNAVAILABLE_CODES = new Set([
70
70
  ]);
71
71
  export const isEndpointUnavailable = (err) => ENDPOINT_UNAVAILABLE_CODES.has(err?.code);
72
72
 
73
- // 流式端点:只取首帧(如 session/control 基线流),unary invoke 会被网关拒绝
73
+
74
74
  export const RPC_STREAM_METHODS = new Set(["session.control"]);
75
- /** v3.1.2:session/control(baseline)中取某会话的投影值(modelSelection/imageLimits 等)。 */
75
+
76
76
  export const projectionOf = (control, sessionId) =>
77
77
  control?.type === "baseline" ? control.value?.projections?.[sessionId]?.values : undefined;
78
78
 
79
- // Phase 1(S3):apiRpc 失败统一映射——传输层 502、超时/中止 504、内核错误透传 status(默认 400),
80
- // 错误码兜底 fallbackCode。返回 [status, code, message] 元组,展开进 error():
81
- // error(res, ...rpcError(err, "xxx-failed")) → { error: code, detail: message }
82
- // v2.8.2 修复:调用展开 f(...obj) 走迭代器协议,要求 obj 为 iterable——普通对象字面量与
83
- // Object.create(null) 均非 iterable,会抛 "Spread syntax requires ...iterable[Symbol.iterator]":
84
- // 2.8.1 起全部 11 处 API 错误路径因此退化为 HTTP 500 { error: "internal" },真实 status/code/detail
85
- // 全部丢失(该 TypeError 上抛到 handleApi 外层 catch)。数组是唯一同时满足展开与三元组表达的形态。
86
- // code 仅接受非空 string:内核自定义错误码是文档字符串(queue-item-not-found 等),
87
- // DOMException.code 等数字码不在契约内 → 落 fallbackCode(行为收窄,见 docs 契约)。
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
88
  export const rpcError = (err, fallbackCode) => {
89
89
  const rawCode = typeof err?.code === "string" && err.code !== "" ? err.code : fallbackCode;
90
90
  const code = rawCode === "session/not-found" ? "session-not-found" : rawCode;
@@ -95,8 +95,8 @@ export const rpcError = (err, fallbackCode) => {
95
95
  : err?.name === "TimeoutError" || err?.name === "AbortError"
96
96
  ? 504
97
97
  : err?.status ?? 400;
98
- // v3.1.5 S7:内核错误原文只进日志;回客户端的 detail 一律脱敏(宿主 message 常带
99
- // 会话/工作区/设置文件绝对路径)。这里覆盖全部 rpcError 调用点。
98
+
99
+
100
100
  let message;
101
101
  try {
102
102
  message = redactPathText(err?.message ?? String(err));
@@ -1,27 +1,27 @@
1
- /**
2
- * 会话列表排序键与「消息时间表」剪枝计划(纯函数)。
3
- * 从 lib/index.js 原样拆出(行为不变)。
4
- */
1
+
2
+
3
+
4
+
5
5
  import { isVisibleConversationMessage } from "./timeline.js";
6
6
 
7
- /**
8
- * 会话列表排序键(ADR 0013):`lastMessageAt` → `lastActivity` → `createdAt`。
9
- * 后两级只为旧内核/旧插件降级保留,新版正常路径恒有 `lastMessageAt`。
10
- */
7
+
8
+
9
+
10
+
11
11
  export const sessionListSortKey = (row) => {
12
12
  if (typeof row?.lastMessageAt === "number") return row.lastMessageAt;
13
13
  if (typeof row?.lastActivity === "number") return row.lastActivity;
14
14
  return typeof row?.createdAt === "number" ? row.createdAt : 0;
15
15
  };
16
16
 
17
- /** 会话列表排序:时间倒序;**等值时以 id 为次级键**,保证顺序稳定不抖动(US29)。 */
17
+
18
18
  export const compareSessionsForList = (a, b) => {
19
19
  const diff = sessionListSortKey(b) - sessionListSortKey(a);
20
20
  if (diff !== 0) return diff;
21
21
  return String(a?.id ?? "").localeCompare(String(b?.id ?? ""));
22
22
  };
23
23
 
24
- /** 取会话日志里最新一条**可见对话消息**的时间(回填用);无消息返回 null。 */
24
+
25
25
  export const latestMessageTimeOf = (events) => {
26
26
  let latest = null;
27
27
  for (const event of events ?? []) {
@@ -33,25 +33,25 @@ export const latestMessageTimeOf = (events) => {
33
33
  return latest;
34
34
  };
35
35
 
36
- /** 完整语料观测的新鲜度上限:超过它说明最近没人拉过列表,语料可能落后于新建会话。 */
36
+
37
37
  export const CORPUS_FRESH_MS = 30 * 60 * 1000;
38
38
 
39
- /**
40
- * 规划 `messageTimeMap` 的存在性剪枝(**纯函数**,供契约自检直接断言)。
41
- *
42
- * 为什么按存在性、而不按消息时间的新旧:该表的值是「最近一条消息**发生**的时间」,
43
- * 不是记录的时效。一个 10 天没说话但**依然存在**的会话若被删掉排序键,就会掉回
44
- * `lastActivity` 排序而莫名上浮,并触发反复回填。所以只在**会话确实消失**时清理。
45
- *
46
- * 三条安全约束:
47
- * 1. 从未观测过完整语料(`corpusObservedAt === 0`)→ 不剪枝(回退分支只有活动会话,
48
- * 拿它当"全量"会误删休眠会话);
49
- * 2. 观测过旧(超过 [CORPUS_FRESH_MS])→ 不剪枝,且清空待确认集合(否则陈旧判断会被
50
- * 当成"第一次确认",下一轮直接误删);
51
- * 3. 连续两次观测都缺失才删([misses] 是上一次的待删集合),躲开"新建会话尚未落盘"竞态。
52
- *
53
- * @returns `{ remove, misses }`:本轮应删除的 id,以及下一轮的待确认集合。
54
- */
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
55
  export const planMessageTimePrune = ({
56
56
  messageTimeIds,
57
57
  corpusIds,
@@ -63,15 +63,15 @@ export const planMessageTimePrune = ({
63
63
  const corpus = corpusIds instanceof Set ? corpusIds : new Set(corpusIds ?? []);
64
64
  const fresh = corpusObservedAt > 0 && corpus.size > 0 && now - corpusObservedAt <= freshMs;
65
65
  if (!fresh) {
66
- // 无观测/观测过旧:不剪枝;丢弃待确认集合,避免陈旧判断变成"已确认"
66
+
67
67
  return { remove: [], misses: new Set() };
68
68
  }
69
69
  const nextMisses = new Set();
70
70
  const remove = [];
71
71
  for (const id of messageTimeIds ?? []) {
72
- if (corpus.has(id)) continue; // 会话仍存在:保留排序键(哪怕是很久以前的)
73
- if (misses.has(id)) remove.push(id); // 连续两次缺失 → 确认消失
74
- else nextMisses.add(id); // 第一次缺失 → 待下轮确认
72
+ if (corpus.has(id)) continue;
73
+ if (misses.has(id)) remove.push(id);
74
+ else nextMisses.add(id);
75
75
  }
76
76
  return { remove, misses: nextMisses };
77
77
  };
@@ -1,52 +1,52 @@
1
- /**
2
- * 会话按天轮换 + 新会话恢复指引(P1-17)。
3
- *
4
- * 借鉴的是 `dsh-bili-whale` 的「会话一天一换」:一天的上下文太长之后,模型会开始
5
- * 把上午的调试细节当成当前任务的约束,用户也要翻很久才找得到今天说的话。
6
- *
7
- * **但不自动切。** 自动新建会话会在用户正要接着说「刚才那个 bug」时把上下文断掉,
8
- * 那种体验比长会话糟糕得多。所以这里只做两件事:
9
- * 1. 判断「这个会话是不是跨天了、该建议开新的」——`rotationAdvice()`;
10
- * 2. 开新会话时给出「上次聊到…」的指引——`resumeBrief()`。
11
- * 切换由用户在界面上按下,插件不替他决定。
12
- *
13
- * 与记忆库的分工:记忆库存的是**长期事实**(他偏好短句、项目用 npm),
14
- * 这里的摘要只覆盖**这一条会话最近聊了什么**,用完即弃,不写库。
15
- * 两者的寿命不同,混在一起会让"三天前随口一句"变成"长期偏好"。
16
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
17
  import { localDayKey } from "./proactive.js";
18
18
  import { blocksToText } from "./timeline.js";
19
19
 
20
- /**
21
- * 本地日历日的键(`YYYY-MM-DD`)。
22
- *
23
- * 直接用 `proactive.js` 的 `localDayKey()`,不另写一份:两处"今天"的定义必须
24
- * 完全一致,否则主动消息的每日上限与这里的跨天判断会在零点附近出现分歧
25
- * (一个认为已经是新的一天,另一个还认为昨天)。
26
- */
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
27
  export function dayKey(at) {
28
28
  const d = at instanceof Date ? at : new Date(at);
29
29
  if (Number.isNaN(d.getTime())) return "";
30
30
  return localDayKey(d);
31
31
  }
32
32
 
33
- /**
34
- * 判断一条会话是否该建议轮换。纯函数,不读盘不读库。
35
- *
36
- * 只在**真跨天**时建议,同一天内不管聊了多久都不建议——同一天的长会话是用户
37
- * 自己聊出来的,中途劝他换一个只会打断他。唯一额外的触发条件是「跨天且这一轮
38
- * 已经结束」,因为用户正在等回复时劝他换会话最没有意义。
39
- *
40
- * @param {object} e
41
- * @param {number} e.lastMessageAt 该会话最近一条消息的时间戳(毫秒)
42
- * @param {Date} [e.now]
43
- * @param {boolean} [e.busy] 该会话是否正在跑(跑着就不劝)
44
- * @returns {{shouldRotate: boolean, reason: string, idleDays: number}}
45
- */
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
46
  export function rotationAdvice({ lastMessageAt, now = new Date(), busy = false } = {}) {
47
47
  const last = Number(lastMessageAt);
48
- // 没有时间戳(新会话、或旧版 App 没上报)时不建议:宁可少劝一次,
49
- // 也不要在一条刚建的会话上弹「要不要开新会话」。
48
+
49
+
50
50
  if (!Number.isFinite(last) || last <= 0) {
51
51
  return { shouldRotate: false, reason: "unknown-last-message", idleDays: 0 };
52
52
  }
@@ -61,13 +61,13 @@ export function rotationAdvice({ lastMessageAt, now = new Date(), busy = false }
61
61
  return { shouldRotate: false, reason: "same-day", idleDays: 0 };
62
62
  }
63
63
 
64
- // 用日历日之差而不是 24 小时差:晚上 11 点聊到凌晨 1 点只隔两小时,
65
- // 但用户确实跨了一天,新会话对他是「今天」的开始。
64
+
65
+
66
66
  const idleDays = Math.max(1, calendarDaysBetween(lastDay, today));
67
67
  return { shouldRotate: true, reason: "crossed-day", idleDays };
68
68
  }
69
69
 
70
- /** 两个 `YYYY-MM-DD` 之间隔了几个日历日。用 UTC 构造避免夏令时造成 23/25 小时。 */
70
+
71
71
  function calendarDaysBetween(fromKey, toKey) {
72
72
  const [fy, fm, fd] = fromKey.split("-").map(Number);
73
73
  const [ty, tm, td] = toKey.split("-").map(Number);
@@ -76,30 +76,30 @@ function calendarDaysBetween(fromKey, toKey) {
76
76
  return Math.round((b - a) / 86_400_000);
77
77
  }
78
78
 
79
- /** 单条摘要文本的上限。够说清「在做什么」,又不会把整段对话搬进新会话。 */
79
+
80
80
  export const MAX_LINE_CHARS = 120;
81
81
 
82
- /** 最多带几条最近的用户发言。3 条足够让用户认出「哦对,昨天在弄那个」。 */
82
+
83
83
  export const MAX_LINES = 3;
84
84
 
85
- /**
86
- * 从会话事件里挑出「上次聊到」的几条。
87
- *
88
- * **形状很关键**:`sessions.get(id).events` 给的是**原始内核事件**,文本在
89
- * `data.message.content` 的 blocks 里;而 `/api/history` 下发的是 `summarizeEvent()`
90
- * 之后的**摘要事件**,文本在 `data.text`。两者都能到这里(活动会话给原始、
91
- * 休眠会话经 `loadDormantSession` 也可能给原始),所以都要认。
92
- * 只认其一的话,真实会话会静默提取不到任何片段——空摘要看起来像"昨天没聊什么"。
93
- *
94
- * 只取**真人发言**:`message.source.kind === "user"`。系统注入(plugin /
95
- * agent-instructions / tool)不算「聊到」——它们是内核塞进去的指令,
96
- * 当成用户说的话会让摘要前言不搭后语。旧内核没有 `source` 时按真人处理。
97
- *
98
- * @param {object[]} events 会话事件(原始或已摘要的形状都接受)
99
- * @param {object} [opts]
100
- * @param {number} [opts.limit]
101
- * @returns {string[]} 由旧到新的几条用户发言(已截断、已去重)
102
- */
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
103
  export function recentUserLines(events, { limit = MAX_LINES } = {}) {
104
104
  if (!Array.isArray(events)) return [];
105
105
  const lines = [];
@@ -107,13 +107,13 @@ export function recentUserLines(events, { limit = MAX_LINES } = {}) {
107
107
  if (ev?.type !== "user/message") continue;
108
108
  const data = ev.data;
109
109
  if (!data || typeof data !== "object") continue;
110
- // 原始事件的来源标记在 `data.message.source`,摘要事件在 `data.source`。
110
+
111
111
  const kind = data.message?.source?.kind ?? data.source?.kind;
112
112
  if (typeof kind === "string" && kind !== "" && kind !== "user") continue;
113
113
 
114
114
  const text = oneLine(textOf(data));
115
115
  if (!text) continue;
116
- // 同一条重复出现(重试、回放)时只留一次。
116
+
117
117
  if (lines.includes(text)) continue;
118
118
  lines.push(text);
119
119
  if (lines.length > limit) lines.shift();
@@ -121,12 +121,12 @@ export function recentUserLines(events, { limit = MAX_LINES } = {}) {
121
121
  return lines;
122
122
  }
123
123
 
124
- /**
125
- * 从一条 user/message 的 `data` 里取出文本。两种形状:
126
- * - 原始:`data.message.content` 是 blocks 数组 → 用 `blocksToText`
127
- * - 摘要:`data.text` 已是字符串
128
- * 其它情况返回空串(宁可少一条,也不要 `[object Object]` 进摘要)。
129
- */
124
+
125
+
126
+
127
+
128
+
129
+
130
130
  function textOf(data) {
131
131
  if (typeof data.text === "string") return data.text;
132
132
  const content = data.message?.content;
@@ -134,7 +134,7 @@ function textOf(data) {
134
134
  return "";
135
135
  }
136
136
 
137
- /** 压成一行、去空白、截断。摘要里出现换行会让「上次聊到」变成一大段。 */
137
+
138
138
  function oneLine(raw) {
139
139
  if (typeof raw !== "string") return "";
140
140
  const flat = raw.replace(/\s+/g, " ").trim();
@@ -142,19 +142,19 @@ function oneLine(raw) {
142
142
  return flat.length > MAX_LINE_CHARS ? `${flat.slice(0, MAX_LINE_CHARS)}…` : flat;
143
143
  }
144
144
 
145
- /**
146
- * 生成新会话开头的「上次聊到…」。
147
- *
148
- * 返回的是一段**给模型看**的文本,插在新会话的第一条消息前面。它的措辞要满足两点:
149
- * - 明确这是**以前**的上下文,不是用户这次的要求;
150
- * - 明确可能与当前冲突、以当前为准——否则模型会拿昨天的结论硬套今天的事。
151
- *
152
- * @param {object} e
153
- * @param {string[]} [e.lines] `recentUserLines()` 的结果
154
- * @param {number} [e.idleDays] 隔了几天
155
- * @param {string} [e.sessionTitle] 旧会话标题(有就用,帮用户确认是哪条)
156
- * @returns {string} 没有可用内容时返回空串
157
- */
145
+
146
+
147
+
148
+
149
+
150
+
151
+
152
+
153
+
154
+
155
+
156
+
157
+
158
158
  export function resumeBrief({ lines = [], idleDays = 1, sessionTitle = "" } = {}) {
159
159
  const usable = (Array.isArray(lines) ? lines : []).filter(
160
160
  (l) => typeof l === "string" && l.trim() !== "",
@@ -175,24 +175,24 @@ export function resumeBrief({ lines = [], idleDays = 1, sessionTitle = "" } = {}
175
175
  ].join("\n");
176
176
  }
177
177
 
178
- /**
179
- * 一次算完「该不该劝换」+「换了之后带什么」。
180
- *
181
- * @param {object} e
182
- * @param {object[]} e.events
183
- * @param {number} e.lastMessageAt
184
- * @param {Date} [e.now]
185
- * @param {boolean} [e.busy]
186
- * @param {string} [e.sessionTitle]
187
- */
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+
187
+
188
188
  export function buildRotation({ events, lastMessageAt, now = new Date(), busy = false, sessionTitle = "" }) {
189
189
  const advice = rotationAdvice({ lastMessageAt, now, busy });
190
190
  const lines = recentUserLines(events);
191
191
  return {
192
192
  ...advice,
193
193
  lines,
194
- // 建议轮换但没有可带的片段时,resumeBrief 返回空串——那就单纯开个新会话,
195
- // 不要塞一段「上次聊到:(空)」进去。
194
+
195
+
196
196
  brief: advice.shouldRotate ? resumeBrief({ lines, idleDays: advice.idleDays, sessionTitle }) : "",
197
197
  };
198
198
  }
@@ -1,36 +1,36 @@
1
- // issue #20 第 2 步(实现要点 1):**revision 失效的持久化标题缓存**。
2
- //
3
- // 背景(见 issue #20 的 note 702 / 793):
4
- // - `/sessions` 在响应前同步折叠**全部休眠会话**的标题,而折叠要完整读取每个会话日志
5
- // (追加式多帧 zstd)——隔离实测冷缓存 68.2 s、生产 600 s 未返回。
6
- // - 内核 `sessionQuery.observeSession(id)` 返回的 lease 带 `revision`(来自**不读日志**的
7
- // `persistence.stat()`)。revision 未变即意味着日志没变 → **可以零日志读取地复用标题**。
8
- // - 但 `stat()` 本身也不便宜(实测 61.9 ms/会话 → 全量 354 个 21.9 s),所以本缓存
9
- // **必须同时有界**:条目数有界、每次请求的发散量有界(由调用方的时间预算控制)。
10
- //
11
- // 本模块只负责"存与取",不做调度——预算与 single-flight 由调用方掌握。
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
12
 
13
13
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
14
14
  import { dirname } from "node:path";
15
15
 
16
- /** 默认条目上限:约 1000 个会话足够覆盖常见语料,且文件体积可控(~100 KB 量级)。 */
16
+
17
17
  export const DEFAULT_MAX_ENTRIES = 1000;
18
18
 
19
- /**
20
- * @param {object} options
21
- * @param {string} options.file 落盘路径(`~/.dsh/mobile-remote/session-titles.json`)
22
- * @param {number} [options.maxEntries] 条目上限(超出按最久未更新淘汰)
23
- * @param {() => number} [options.now] 时间源(测试可注入)
24
- */
19
+
20
+
21
+
22
+
23
+
24
+
25
25
  export const createTitleCache = ({ file, maxEntries = DEFAULT_MAX_ENTRIES, now = Date.now }) => {
26
- /** sessionId -> { title: string|null, revision: string, at: number } */
26
+
27
27
  const entries = new Map();
28
28
  let dirty = false;
29
29
 
30
- /**
31
- * 读盘并替换当前内存快照。只接受 version 1;缺失/损坏/未知格式一律降级为空缓存,
32
- * 缓存坏了不该让列表挂掉,也不能把不可信字段当成已确认的标题事实。
33
- */
30
+
31
+
32
+
33
+
34
34
  const load = () => {
35
35
  entries.clear();
36
36
  dirty = false;
@@ -44,7 +44,7 @@ export const createTitleCache = ({ file, maxEntries = DEFAULT_MAX_ENTRIES, now =
44
44
  if (id === "") continue;
45
45
  if (!value || typeof value !== "object" || Array.isArray(value)) continue;
46
46
  if (typeof value.revision !== "string" || value.revision === "") continue;
47
- // 只有显式 null 才代表“确实没有标题”;缺失或其它类型必须回源,不能伪造命中。
47
+
48
48
  if (value.title !== null && typeof value.title !== "string") continue;
49
49
  const title = value.title === "" ? null : value.title;
50
50
  entries.set(id, { title, revision: value.revision, at: typeof value.at === "number" ? value.at : 0 });
@@ -55,24 +55,24 @@ export const createTitleCache = ({ file, maxEntries = DEFAULT_MAX_ENTRIES, now =
55
55
  }
56
56
  };
57
57
 
58
- /**
59
- * 取缓存标题。
60
- * @returns `{ hit: true, title }` 表示 **revision 相同、可零日志读取地复用**;
61
- * `{ hit: false }` 表示需要回源折叠。
62
- */
58
+
59
+
60
+
61
+
62
+
63
63
  const get = (id, revision) => {
64
64
  if (typeof id !== "string" || id === "" || typeof revision !== "string" || revision === "") {
65
65
  return { hit: false };
66
66
  }
67
67
  const entry = entries.get(id);
68
68
  if (!entry || entry.revision !== revision) return { hit: false };
69
- // 命中也要刷新时间戳:淘汰按"最久未更新",命中说明这个会话仍活跃。
69
+
70
70
  entry.at = now();
71
71
  dirty = true;
72
72
  return { hit: true, title: entry.title };
73
73
  };
74
74
 
75
- /** 写入(title 允许为 null——"确实没有标题"同样是可缓存的事实)。 */
75
+
76
76
  const set = (id, revision, title) => {
77
77
  if (typeof id !== "string" || id === "" || typeof revision !== "string" || revision === "") return;
78
78
  entries.set(id, {
@@ -84,7 +84,7 @@ export const createTitleCache = ({ file, maxEntries = DEFAULT_MAX_ENTRIES, now =
84
84
  prune();
85
85
  };
86
86
 
87
- /** 按 `at` 淘汰到上限以内。 */
87
+
88
88
  const prune = () => {
89
89
  if (entries.size <= maxEntries) return;
90
90
  const sorted = [...entries.entries()].sort((a, b) => a[1].at - b[1].at);
@@ -95,7 +95,7 @@ export const createTitleCache = ({ file, maxEntries = DEFAULT_MAX_ENTRIES, now =
95
95
  }
96
96
  };
97
97
 
98
- /** 原子落盘(临时文件 + rename)。没有变更时是空操作。 */
98
+
99
99
  const flush = () => {
100
100
  if (!dirty) return false;
101
101
  try {
@@ -106,7 +106,7 @@ export const createTitleCache = ({ file, maxEntries = DEFAULT_MAX_ENTRIES, now =
106
106
  dirty = false;
107
107
  return true;
108
108
  } catch {
109
- // 落盘失败不该影响本次响应:内存缓存仍然有效。
109
+
110
110
  return false;
111
111
  }
112
112
  };
@@ -117,7 +117,7 @@ export const createTitleCache = ({ file, maxEntries = DEFAULT_MAX_ENTRIES, now =
117
117
  set,
118
118
  flush,
119
119
  size: () => entries.size,
120
- /** 仅测试用:直接观察某条目。 */
120
+
121
121
  peek: (id) => entries.get(id),
122
122
  };
123
123
  };