@dsh-mobile/mobile-remote 3.4.1 → 3.5.0-beta.2

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 (42) hide show
  1. package/README.md +1 -1
  2. package/docs/PRIVACY-POLICY.en.md +10 -2
  3. package/docs/PRIVACY-POLICY.md +10 -2
  4. package/docs/TERMS-OF-SERVICE.en.md +3 -2
  5. package/docs/TERMS-OF-SERVICE.md +3 -2
  6. package/lib/backup.js +30 -0
  7. package/lib/config.js +10 -0
  8. package/lib/host-plugins.js +290 -0
  9. package/lib/host-schedule.js +273 -0
  10. package/lib/host-team.js +89 -0
  11. package/lib/index.js +208 -3292
  12. package/lib/live-activity.js +351 -0
  13. package/lib/memory/context.js +17 -3
  14. package/lib/memory/decay.js +68 -4
  15. package/lib/memory/promises.js +116 -0
  16. package/lib/memory/routes.js +113 -1
  17. package/lib/memory/store.js +212 -13
  18. package/lib/memory/turn-hook.js +109 -0
  19. package/lib/phone-actions.js +17 -5
  20. package/lib/phone-announce.js +6 -5
  21. package/lib/phone-push.js +310 -0
  22. package/lib/protocol.js +16 -0
  23. package/lib/relay/connector.js +13 -1
  24. package/lib/routes/agents.js +405 -0
  25. package/lib/routes/app-state.js +179 -0
  26. package/lib/routes/backup.js +144 -0
  27. package/lib/routes/diagnostics.js +227 -0
  28. package/lib/routes/files.js +326 -0
  29. package/lib/routes/git.js +53 -0
  30. package/lib/routes/history.js +313 -0
  31. package/lib/routes/host-services.js +51 -0
  32. package/lib/routes/models.js +462 -0
  33. package/lib/routes/notifications.js +183 -0
  34. package/lib/routes/pairing.js +170 -0
  35. package/lib/routes/route-groups.js +20 -0
  36. package/lib/routes/send.js +341 -0
  37. package/lib/routes/sessions.js +462 -0
  38. package/lib/routes/toolbox.js +14 -0
  39. package/lib/routes/usage.js +211 -0
  40. package/lib/timeline.js +5 -1
  41. package/lib/toolbox.js +355 -0
  42. package/package.json +1 -1
@@ -0,0 +1,351 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+ import { readBody, sendError, sendJson } from "./http-util.js";
30
+
31
+ export const MIN_GAP_MS = 60_000;
32
+ export const KEEPALIVE_MS = 25 * 60_000;
33
+ export const STALE_AFTER_MS = 30 * 60_000;
34
+ export const END_DISMISS_AFTER_MS = 15 * 60_000;
35
+ export const P10_PER_HOUR = 12;
36
+ export const ALL_PER_HOUR = 60;
37
+ export const MAX_ACTIVITY_MS = 8 * 3600_000;
38
+ export const MAX_PAYLOAD_BYTES = 4096;
39
+ export const MAX_REGISTRATIONS = 4;
40
+ const HOUR = 3600_000;
41
+
42
+ const TOKEN_RE = /^[0-9a-f]{64,200}$/;
43
+ const ID_RE = /^[A-Za-z0-9-]{1,64}$/;
44
+ const STATES = ["idle", "thinking", "working", "needsYou", "error", "offline"];
45
+ const FRAMES = { idle: "idle", thinking: "thinking", working: "focus", needsYou: "worried", error: "error", offline: "sleepy" };
46
+ const DEFAULT_LABELS = {
47
+ idle: "Idle",
48
+ thinking: "Thinking",
49
+ working: "Working",
50
+ needsYou: "Needs you",
51
+ error: "Something failed",
52
+ offline: "Not connected",
53
+ needsYouCount: "{0} waiting for you",
54
+ };
55
+
56
+ const clean = (v, max) => (typeof v === "string" ? v.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, max) : "");
57
+
58
+
59
+ export function checkLabels(raw) {
60
+ const out = { ...DEFAULT_LABELS };
61
+ if (raw && typeof raw === "object") {
62
+ for (const k of Object.keys(DEFAULT_LABELS)) {
63
+ const v = clean(raw[k], 60);
64
+ if (v) out[k] = v;
65
+ }
66
+ }
67
+ return out;
68
+ }
69
+
70
+
71
+
72
+
73
+
74
+
75
+ export function contentState(summary, labels = DEFAULT_LABELS) {
76
+ const running = Math.max(0, Math.trunc(Number(summary?.running) || 0));
77
+ const needsYou = Math.max(0, Math.trunc(Number(summary?.needsYou) || 0));
78
+ const state =
79
+ summary?.connected === false ? "offline"
80
+ : needsYou > 0 ? "needsYou"
81
+ : summary?.failed ? "error"
82
+ : running > 0 ? (summary?.thinking ? "thinking" : "working")
83
+ : "idle";
84
+ const cs = { state, label: labels[state], frame: FRAMES[state], running, needsYou };
85
+ const task = clean(summary?.task, 80);
86
+ if (task) cs.task = task;
87
+ const session = clean(summary?.session, 120);
88
+ if (session) cs.session = session;
89
+ if (needsYou > 0) cs.needsYouText = labels.needsYouCount.replace("{0}", String(needsYou));
90
+ return cs;
91
+ }
92
+
93
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
94
+ export const isActive = (cs) => cs.running > 0 || cs.needsYou > 0;
95
+
96
+
97
+
98
+
99
+
100
+
101
+ export function decidePush(reg, next, now, { ending = false } = {}) {
102
+ if (now - reg.startedAt >= MAX_ACTIVITY_MS) return { send: false, expired: true };
103
+ const recent = reg.sent.filter((s) => now - s.at < HOUR);
104
+ const p10 = recent.filter((s) => s.priority === 10).length;
105
+ const roomAt = recent.length >= ALL_PER_HOUR ? recent[recent.length - ALL_PER_HOUR].at + HOUR : null;
106
+ const event = ending ? "end" : "update";
107
+ const changed = !same(next, reg.last);
108
+ if (!changed && !ending) {
109
+ const due = isActive(next) && reg.lastSentAt !== null && now - reg.lastSentAt >= KEEPALIVE_MS;
110
+ if (!due) return { send: false };
111
+ if (roomAt !== null) return { send: false, retryAt: roomAt };
112
+ return { send: true, priority: 5, event };
113
+ }
114
+ if (roomAt !== null) return { send: false, retryAt: roomAt };
115
+ const rose = next.needsYou > (reg.last?.needsYou ?? 0);
116
+ if ((rose || ending) && p10 < P10_PER_HOUR) {
117
+ return { send: true, priority: 10, event, alert: rose && !ending };
118
+ }
119
+ if (reg.lastSentAt !== null && now - reg.lastSentAt < MIN_GAP_MS) {
120
+ return { send: false, retryAt: reg.lastSentAt + MIN_GAP_MS };
121
+ }
122
+ return { send: true, priority: 5, event };
123
+ }
124
+
125
+
126
+ export function buildPayload(cs, { now, event = "update", alert = false, pcName = "" }) {
127
+ const nowSec = Math.floor(now / 1000);
128
+ const state = { ...cs };
129
+ const make = () => {
130
+ const aps = { timestamp: nowSec, event, "content-state": state, "stale-date": nowSec + STALE_AFTER_MS / 1000 };
131
+ if (event === "end") aps["dismissal-date"] = nowSec + END_DISMISS_AFTER_MS / 1000;
132
+ if (alert && cs.needsYouText) aps.alert = { title: clean(pcName, 60) || cs.label, body: cs.needsYouText };
133
+ return { aps };
134
+ };
135
+ let payload = make();
136
+ while (Buffer.byteLength(JSON.stringify(payload)) > MAX_PAYLOAD_BYTES && state.task) {
137
+ state.task = state.task.length > 8 ? state.task.slice(0, Math.floor(state.task.length / 2)) : undefined;
138
+ if (!state.task) delete state.task;
139
+ payload = make();
140
+ }
141
+ return payload;
142
+ }
143
+
144
+
145
+
146
+
147
+
148
+ export function createWorkerSender({ endpoint, fetchImpl = globalThis.fetch, timeoutMs = 10_000 } = {}) {
149
+ const base = typeof endpoint === "string" && /^https:\/\/[^/\s]+/.test(endpoint) ? endpoint.replace(/\/+$/, "") : null;
150
+ return async ({ token, environment, priority, payload }) => {
151
+ if (!base) return { skipped: "not-configured" };
152
+ const res = await fetchImpl(`${base}/api/push/live-activity`, {
153
+ method: "POST",
154
+ headers: { "content-type": "application/json", "user-agent": "dsh-mobile-remote" },
155
+ body: JSON.stringify({ token, environment, priority, payload }),
156
+ signal: AbortSignal.timeout(timeoutMs),
157
+ });
158
+ return { ok: res.status === 200, gone: res.status === 410, status: res.status };
159
+ };
160
+ }
161
+
162
+
163
+
164
+
165
+
166
+
167
+
168
+ export function createLiveActivity({ send, now = Date.now, logger = {}, setTimer = setTimeout, clearTimer = clearTimeout, keepAliveEvery = 5 * 60_000 } = {}) {
169
+
170
+ const regs = new Map();
171
+ let ticker = null;
172
+ const startTicker = () => {
173
+ if (ticker || !keepAliveEvery) return;
174
+ ticker = setInterval(() => {
175
+ if (regs.size === 0) {
176
+ clearInterval(ticker);
177
+ ticker = null;
178
+ return;
179
+ }
180
+ for (const [id, reg] of regs) if (!reg.timer) void push(id, reg);
181
+ }, keepAliveEvery);
182
+ ticker.unref?.();
183
+ };
184
+ let current = contentState({ running: 0, needsYou: 0 });
185
+ let lastSummary = { running: 0, needsYou: 0 };
186
+
187
+ const log = (msg) => logger.debug?.(`[live-activity] ${msg}`);
188
+
189
+ async function push(id, reg, ending = false) {
190
+ if (reg.timer) {
191
+ clearTimer(reg.timer);
192
+ reg.timer = null;
193
+ }
194
+ const t = now();
195
+ const next = contentState(lastSummary, reg.labels);
196
+ const d = decidePush(reg, next, t, { ending });
197
+ if (d.expired) {
198
+ regs.delete(id);
199
+ log(`expired ${id}`);
200
+ return;
201
+ }
202
+ if (!d.send) {
203
+ if (d.retryAt) reg.timer = setTimer(() => void push(id, reg, ending), Math.max(0, d.retryAt - t));
204
+ return;
205
+ }
206
+ reg.last = next;
207
+ reg.lastSentAt = t;
208
+ reg.sent = [...reg.sent.filter((s) => t - s.at < HOUR), { at: t, priority: d.priority }];
209
+ const payload = buildPayload(next, { now: t, event: d.event, alert: d.alert, pcName: reg.pcName });
210
+ try {
211
+ const out = await send({ token: reg.token, environment: reg.environment, priority: d.priority, payload });
212
+ if (out?.gone || d.event === "end") regs.delete(id);
213
+ log(`${id} ${d.event} p${d.priority}${out?.skipped ? ` (${out.skipped})` : ""}`);
214
+ } catch (e) {
215
+ log(`${id} send failed: ${e?.name ?? "error"}`);
216
+ }
217
+ }
218
+
219
+ return {
220
+
221
+ update(summary) {
222
+ lastSummary = summary ?? { running: 0, needsYou: 0 };
223
+ current = contentState(lastSummary);
224
+ for (const [id, reg] of regs) {
225
+ const next = contentState(lastSummary, reg.labels);
226
+
227
+ const ending = !isActive(next) && reg.last !== null && isActive(reg.last);
228
+ void push(id, reg, ending);
229
+ }
230
+ },
231
+
232
+
233
+ async handle(req, res, method) {
234
+ if (method !== "POST") return sendError(res, 405, "method-not-allowed"), true;
235
+ let body;
236
+ try {
237
+ body = JSON.parse(await readBody(req, 8 * 1024));
238
+ } catch {
239
+ return sendError(res, 400, "invalid-json"), true;
240
+ }
241
+ const id = body?.activityId;
242
+ if (typeof id !== "string" || !ID_RE.test(id)) return sendError(res, 400, "invalid-activity-id"), true;
243
+ if (body.token === null) {
244
+ const reg = regs.get(id);
245
+ if (reg?.timer) clearTimer(reg.timer);
246
+ regs.delete(id);
247
+ return sendJson(res, 200, { ok: true }), true;
248
+ }
249
+ if (typeof body.token !== "string" || !TOKEN_RE.test(body.token)) return sendError(res, 400, "invalid-token"), true;
250
+ const environment = body.environment === "sandbox" ? "sandbox" : "production";
251
+ const startedAt = Number.isFinite(body.startedAt) && body.startedAt <= now() ? body.startedAt : now();
252
+ if (!regs.has(id) && regs.size >= MAX_REGISTRATIONS) {
253
+
254
+ const [oldest] = regs.keys();
255
+ const old = regs.get(oldest);
256
+ if (old?.timer) clearTimer(old.timer);
257
+ regs.delete(oldest);
258
+ }
259
+ const prev = regs.get(id);
260
+ regs.set(id, {
261
+ token: body.token,
262
+ environment,
263
+ labels: checkLabels(body.labels),
264
+ pcName: clean(body.pcName, 60),
265
+ startedAt,
266
+
267
+ last: prev?.last ?? (body.contentState && typeof body.contentState === "object" ? contentState(body.contentState, checkLabels(body.labels)) : null),
268
+ lastSentAt: prev?.lastSentAt ?? null,
269
+ sent: prev?.sent ?? [],
270
+ timer: prev?.timer ?? null,
271
+ });
272
+ startTicker();
273
+ log(`registered ${id}`);
274
+ return sendJson(res, 200, { ok: true, budget: { p10PerHour: P10_PER_HOUR, perHour: ALL_PER_HOUR, minGapMs: MIN_GAP_MS } }), true;
275
+ },
276
+
277
+
278
+ get size() {
279
+ return regs.size;
280
+ },
281
+ get current() {
282
+ return current;
283
+ },
284
+
285
+
286
+ tick() {
287
+ for (const [id, reg] of regs) if (!reg.timer) void push(id, reg);
288
+ },
289
+
290
+ close() {
291
+ if (ticker) clearInterval(ticker);
292
+ ticker = null;
293
+ for (const reg of regs.values()) if (reg.timer) clearTimer(reg.timer);
294
+ regs.clear();
295
+ },
296
+ };
297
+ }
298
+
299
+ export { STATES as LIVE_ACTIVITY_STATES };
300
+
301
+
302
+
303
+
304
+
305
+
306
+
307
+
308
+
309
+
310
+
311
+
312
+
313
+ export function attachLiveActivity({ ctx, config, agentSessionId, sessionTitleOf, pending, send, every = 5_000 }) {
314
+ const service = createLiveActivity({ send: send ?? createWorkerSender({ endpoint: config?.liveActivityPush?.endpoint }), logger: ctx?.logger ?? {} });
315
+ const summary = () => {
316
+ let running = 0, task, session;
317
+ for (const a of ctx.get("agents")?.list?.() ?? []) {
318
+ if (!(a?.status === "running" || a?.status === "busy") || a?.session?.header?.origin === "subagent") continue;
319
+ running++;
320
+ if (!session) {
321
+ session = agentSessionId(a);
322
+ task = sessionTitleOf(a.session);
323
+ }
324
+ }
325
+
326
+ const needsYou = new Set(pending().map((e) => e?.rpcId)).size;
327
+ return { running, needsYou, task, session };
328
+ };
329
+ const refresh = () => {
330
+ if (service.size === 0) return;
331
+ try {
332
+ service.update(summary());
333
+ } catch {
334
+
335
+ }
336
+ };
337
+ const timer = every ? setInterval(refresh, every) : null;
338
+ timer?.unref?.();
339
+ return {
340
+ handle: (req, res, method) => service.handle(req, res, method),
341
+ refresh,
342
+ summary,
343
+ get size() {
344
+ return service.size;
345
+ },
346
+ close() {
347
+ if (timer) clearInterval(timer);
348
+ service.close();
349
+ },
350
+ };
351
+ }
@@ -23,6 +23,13 @@ export const MEMORY_CONTEXT_NAME = "mobile-remote:memory";
23
23
  const HEADER = "关于这位用户的长期记忆(来自你自己之前的记录,可能过时;与当前对话冲突时以当前对话为准):";
24
24
 
25
25
 
26
+ const PROMISES_HEADER =
27
+ "你之前答应过要做的跟进事项(还没完成;用户在手机上标记完成后就不会再出现在这里):";
28
+
29
+
30
+ const MUTED_HEADER = "用户要求你不要主动提起这些内容(用户自己提到时可以正常回答):";
31
+
32
+
26
33
 
27
34
 
28
35
 
@@ -42,12 +49,19 @@ export function createMemoryContextProvider({
42
49
  try {
43
50
  const store = getStore();
44
51
  if (!store) return "";
45
- const body = store.contextFor(getMode(), {
52
+ const mode = getMode();
53
+ const body = store.contextFor(mode, {
46
54
  query: queryFor(context) ?? "",
47
55
  maxChars,
48
56
  });
49
- if (!body) return "";
50
- return `${HEADER}\n${body}`;
57
+ const parts = body ? [`${HEADER}\n${body}`] : [];
58
+
59
+
60
+ const promises = store.promisesContextFor?.(mode) ?? "";
61
+ if (promises) parts.push(`${PROMISES_HEADER}\n${promises}`);
62
+ const muted = store.mutedTermsFor?.() ?? [];
63
+ if (muted.length > 0) parts.push(`${MUTED_HEADER}${muted.map((t) => `「${t}」`).join("、")}`);
64
+ return parts.join("\n\n");
51
65
  } catch {
52
66
 
53
67
  return "";
@@ -105,7 +105,8 @@ export function nextDifficulty(difficulty) {
105
105
 
106
106
 
107
107
  export function retentionOfRow(row, now = new Date()) {
108
- if (row?.pinned) return 1;
108
+
109
+ if (row?.pinned && !isExpired(row, now)) return 1;
109
110
  const last = Number(row?.lastRecalledAt ?? row?.last_recalled_at ?? row?.createdAt ?? row?.created_at ?? 0);
110
111
  if (!Number.isFinite(last) || last <= 0) return 1;
111
112
  const days = (now.getTime() - last) / 86_400_000;
@@ -130,15 +131,78 @@ export function partitionInjectable(rows, { now = new Date(), limit = 20, thresh
130
131
 
131
132
 
132
133
 
133
- const isLive = (x) => Boolean(x.row.pinned) || x.retention >= threshold;
134
+
135
+ const pinned = (x) => isPinActive(x.row, now);
136
+ const isLive = (x) => {
137
+ if (isExpired(x.row, now)) return false;
138
+ if (pinned(x)) return true;
139
+ return x.retention >= threshold && x.weight >= EVIDENCE_THRESHOLD;
140
+ };
141
+ for (const x of scored) x.weight = evidenceWeightOf(x.row, now);
134
142
  const live = scored.filter(isLive);
135
143
  const frozen = scored.filter((x) => !isLive(x));
136
144
  live.sort((a, b) => {
137
- if (Boolean(a.row.pinned) !== Boolean(b.row.pinned)) return a.row.pinned ? -1 : 1;
138
- if (b.retention !== a.retention) return b.retention - a.retention;
145
+ if (pinned(a) !== pinned(b)) return pinned(a) ? -1 : 1;
146
+ const as = a.retention * a.weight;
147
+ const bs = b.retention * b.weight;
148
+ if (bs !== as) return bs - as;
139
149
  const au = Number(a.row.updatedAt ?? a.row.updated_at ?? 0);
140
150
  const bu = Number(b.row.updatedAt ?? b.row.updated_at ?? 0);
141
151
  return bu - au;
142
152
  });
143
153
  return { injectable: live.slice(0, limit), frozen };
144
154
  }
155
+
156
+
157
+
158
+
159
+
160
+
161
+
162
+
163
+
164
+
165
+ export const EVIDENCE_GRACE_DAYS = 14;
166
+
167
+
168
+ export const EVIDENCE_HALF_DAYS = 14;
169
+
170
+
171
+ export const EVIDENCE_THRESHOLD = 0.5;
172
+
173
+
174
+ export function isExpired(row, now = new Date()) {
175
+ const at = Number(row?.expiresAt ?? row?.expires_at ?? 0);
176
+ return Number.isFinite(at) && at > 0 && at <= now.getTime();
177
+ }
178
+
179
+
180
+ export function isPinActive(row, now = new Date()) {
181
+ return Boolean(row?.pinned) && !isExpired(row, now);
182
+ }
183
+
184
+
185
+
186
+
187
+
188
+ export function evidenceWeightOf(row, now = new Date()) {
189
+ if (isPinActive(row, now)) return 1;
190
+ if (row?.confirmed === true || row?.confirmed === 1) return 1;
191
+ const last = Number(row?.evidenceAt ?? row?.evidence_at ?? row?.updatedAt ?? row?.updated_at ?? row?.createdAt ?? 0);
192
+ if (!Number.isFinite(last) || last <= 0) return 1;
193
+ const days = (now.getTime() - last) / 86_400_000;
194
+ if (days <= EVIDENCE_GRACE_DAYS) return 1;
195
+ return 1 / (1 + (days - EVIDENCE_GRACE_DAYS) / EVIDENCE_HALF_DAYS);
196
+ }
197
+
198
+
199
+
200
+
201
+
202
+ export function evidenceStatusOf(row, now = new Date()) {
203
+ if (isExpired(row, now)) return "expired";
204
+ const w = evidenceWeightOf(row, now);
205
+ if (w < EVIDENCE_THRESHOLD) return "faded";
206
+ if (w < 1) return "fading";
207
+ return "active";
208
+ }
@@ -0,0 +1,116 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+ const MAX_TEXT = 200;
14
+ const MAX_PER_TURN = 2;
15
+
16
+
17
+ const COMMIT_ZH = /(?:我(?:会|将|稍后|回头|之后|再|来|明天|明早|今晚|今天|下午|晚点|下周|下个?星期|周[一二三四五六日天])|稍后我|回头我|晚点我)/;
18
+ const COMMIT_EN = /\b(?:I'll|I will|I'm going to|I am going to|I can (?:check|look|follow up)|I'll be back)\b/i;
19
+
20
+
21
+ const NOT_A_PROMISE = /(?:如果|要是|假如|是否|要不要|需要我|\bif\b|\bwould you\b|\bshould I\b|\bdo you want\b|\?|?)/i;
22
+
23
+ const WEEKDAYS_ZH = { 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6, 日: 0, 天: 0 };
24
+ const WEEKDAYS_EN = { monday: 1, tuesday: 2, wednesday: 3, thursday: 4, friday: 5, saturday: 6, sunday: 0 };
25
+
26
+ function at(base, dayOffset, hour, minute = 0) {
27
+ const d = new Date(base.getFullYear(), base.getMonth(), base.getDate() + dayOffset, hour, minute, 0, 0);
28
+ return d.getTime();
29
+ }
30
+
31
+
32
+ function hourOf(text, fallback) {
33
+ if (/(?:下午|afternoon)/i.test(text)) return 15;
34
+ if (/(?:上午|早上|早晨|morning)/i.test(text)) return 9;
35
+ if (/(?:中午|\bnoon\b|\blunch)/i.test(text)) return 12;
36
+ if (/(?:晚上|今晚|tonight|evening)/i.test(text)) return 20;
37
+ return fallback;
38
+ }
39
+
40
+
41
+ function daysUntil(base, weekday, nextWeek) {
42
+ let diff = (weekday - base.getDay() + 7) % 7;
43
+ if (diff === 0) diff = 7;
44
+ if (nextWeek && diff <= 7 - ((base.getDay() + 6) % 7) - 1) diff += 7;
45
+ return diff;
46
+ }
47
+
48
+
49
+
50
+
51
+
52
+
53
+ export function dueTimeOf(text, now = new Date()) {
54
+ const t = String(text ?? "");
55
+ let m;
56
+ if ((m = /(\d{1,3})\s*(?:个)?\s*(小时|hours?|hrs?)/i.exec(t)) && /(?:后|之后|以后|内|\bin\b|\bwithin\b)/i.test(t)) {
57
+ const h = Number(m[1]);
58
+ if (h >= 1 && h <= 72) return now.getTime() + h * 3_600_000;
59
+ }
60
+ if ((m = /(\d{1,2})\s*(天|days?)/i.exec(t)) && /(?:后|之后|以后|内|\bin\b|\bwithin\b)/i.test(t)) {
61
+ const d = Number(m[1]);
62
+ if (d >= 1 && d <= 30) return at(now, d, hourOf(t, 9));
63
+ }
64
+ if (/(?:后天|day after tomorrow)/i.test(t)) return at(now, 2, hourOf(t, 9));
65
+ if (/(?:明天|明早|明晚|tomorrow)/i.test(t)) return at(now, 1, /明早/.test(t) ? 9 : /明晚/.test(t) ? 20 : hourOf(t, 9));
66
+ if ((m = /(下个?)?(?:周|星期|礼拜)([一二三四五六日天])/.exec(t))) {
67
+ return at(now, daysUntil(now, WEEKDAYS_ZH[m[2]], Boolean(m[1])), hourOf(t, 9));
68
+ }
69
+ if ((m = /\b(next\s+)?(?:on\s+)?(monday|tuesday|wednesday|thursday|friday|saturday|sunday)\b/i.exec(t))) {
70
+ return at(now, daysUntil(now, WEEKDAYS_EN[m[2].toLowerCase()], Boolean(m[1])), hourOf(t, 9));
71
+ }
72
+ if (/(?:下周|下个星期|next week)/i.test(t)) return at(now, daysUntil(now, 1, false), 9);
73
+ if (/(?:今晚|今天晚上|tonight|this evening)/i.test(t)) {
74
+ const due = at(now, 0, 20);
75
+ return due > now.getTime() ? due : null;
76
+ }
77
+ if (/(?:今天下午|this afternoon)/i.test(t)) {
78
+ const due = at(now, 0, 15);
79
+ return due > now.getTime() ? due : null;
80
+ }
81
+ if (/(?:下班前|今天之内|今天内|end of (?:the )?day|\bEOD\b|later today)/i.test(t)) {
82
+ const due = at(now, 0, 18);
83
+ return due > now.getTime() ? due : now.getTime() + 2 * 3_600_000;
84
+ }
85
+ return null;
86
+ }
87
+
88
+
89
+ function sentences(text) {
90
+ return String(text ?? "")
91
+ .replace(/```[\s\S]*?```/g, " ")
92
+ .split(/(?<=[。!!;;])|(?<=[.??])\s+|\r?\n/)
93
+ .map((s) => s.replace(/^[\s>*\-•\d.)]+/, "").replace(/\s+/g, " ").trim())
94
+ .filter((s) => s.length >= 6);
95
+ }
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+ export function extractPromises(reply, { now = new Date() } = {}) {
104
+ const out = [];
105
+ for (const s of sentences(reply)) {
106
+ if (!(COMMIT_ZH.test(s) || COMMIT_EN.test(s))) continue;
107
+ if (NOT_A_PROMISE.test(s)) continue;
108
+ const dueAt = dueTimeOf(s, now);
109
+ if (dueAt == null || dueAt <= now.getTime()) continue;
110
+ const text = s.length > MAX_TEXT ? `${s.slice(0, MAX_TEXT - 1)}…` : s;
111
+ if (out.some((p) => p.text === text)) continue;
112
+ out.push({ text, dueAt });
113
+ if (out.length >= MAX_PER_TURN) break;
114
+ }
115
+ return out;
116
+ }