@dsh-mobile/mobile-remote 3.2.7 → 3.3.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 (62) hide show
  1. package/FAQ.md +19 -12
  2. package/README.md +38 -39
  3. package/cordis.patch.yml +8 -4
  4. package/docs/PRIVACY-POLICY.en.md +87 -46
  5. package/docs/PRIVACY-POLICY.md +87 -46
  6. package/docs/SUPPORT.md +5 -5
  7. package/docs/USER-GUIDE.zh-CN.md +562 -0
  8. package/lib/assistant-prefs.js +147 -0
  9. package/lib/auto-config.js +55 -3
  10. package/lib/backup.js +405 -0
  11. package/lib/break-reminder.js +133 -0
  12. package/lib/client.js +56 -10
  13. package/lib/config.js +94 -5
  14. package/lib/git-read-bundled-provider.js +12 -3
  15. package/lib/git-read-service.js +4 -0
  16. package/lib/host-compat.js +25 -0
  17. package/lib/http-util.js +6 -2
  18. package/lib/index.js +949 -70
  19. package/lib/memory/context.js +76 -0
  20. package/lib/memory/decay.js +144 -0
  21. package/lib/memory/extract.js +146 -0
  22. package/lib/memory/routes.js +198 -0
  23. package/lib/memory/store.js +667 -0
  24. package/lib/notify-copy.js +245 -0
  25. package/lib/permission-guide.js +184 -0
  26. package/lib/persona-cards.js +362 -0
  27. package/lib/proactive-material.js +162 -0
  28. package/lib/proactive.js +369 -0
  29. package/lib/protected-paths.js +130 -0
  30. package/lib/protocol.js +35 -0
  31. package/lib/rate-limit.js +1 -1
  32. package/lib/relay/connector.js +97 -12
  33. package/lib/relay/devices.js +14 -0
  34. package/lib/relay/fingerprint.js +55 -0
  35. package/lib/relay/identity.js +69 -0
  36. package/lib/relay/on-demand.js +84 -0
  37. package/lib/relay/phone.js +87 -12
  38. package/lib/reminders.js +140 -0
  39. package/lib/rpc-adapter.js +21 -2
  40. package/lib/session-rotation.js +198 -0
  41. package/lib/timeline.js +1 -1
  42. package/package.json +30 -14
  43. package/CHANGELOG.md +0 -1383
  44. package/CONTRIBUTING.md +0 -61
  45. package/docs/00-/345/274/200/345/217/221/346/200/273/347/272/262.md +0 -432
  46. package/docs/01-PRD.md +0 -148
  47. package/docs/02-architecture.md +0 -249
  48. package/docs/03-api.md +0 -882
  49. package/docs/04-security.md +0 -110
  50. package/docs/05-test-cases.md +0 -376
  51. package/docs/06-install-run.md +0 -335
  52. package/docs/07-user-manual.md +0 -92
  53. package/docs/08-/346/211/251/345/261/225/345/274/200/345/217/221/346/214/207/345/215/227.md +0 -86
  54. package/docs/09-compatibility.md +0 -201
  55. package/docs/11-remote-relay-guide.md +0 -86
  56. package/docs/APP-ENCRYPTION-DESCRIPTION.md +0 -50
  57. package/docs/APP-ENCRYPTION-DESCRIPTION.pdf +0 -0
  58. package/docs/APP-REVIEW-NOTES.md +0 -105
  59. package/docs/BRAND-ASSETS.md +0 -142
  60. package/docs/COMPANION-PLAN.md +0 -199
  61. package/docs/STORE-LAUNCH.md +0 -341
  62. package/docs/STORE-LISTING.md +0 -190
@@ -0,0 +1,362 @@
1
+ /**
2
+ * Persona cards (T-31; plan §5.5, decision D8). JSON, fully user-controlled.
3
+ *
4
+ * Shape: `schema: "dsh-mobile.persona/1"`, `id`, `name` (per language), `summary`, `identity`,
5
+ * `speaking_style`, `rhythm`, `light_memory`, `emotes`, `forbidden_topics`, and
6
+ * `emotional_expression` (overall `intensity` 0–1; per agent state an expression, a motion and
7
+ * 2–4 bubble lines; per touch zone a reaction). Unknown fields are kept.
8
+ *
9
+ * Prompt rule: the card's own text is the only persona text the model sees (`personaPromptText`):
10
+ * the fields the model needs, verbatim, inside one neutral, clearly delimited block labelled as
11
+ * the user's persona card, at most 8 KiB. No behavioural rules are added around it; `modeBrief`
12
+ * and other functional context stay separate.
13
+ *
14
+ * Import checks structure only (valid JSON with the fields the app reads, of the right types).
15
+ * There are no content rules. Import is paid; the check is the app's (its entitlement), the
16
+ * plugin side stays entitlement-free. The three originals below are free.
17
+ *
18
+ * DSH Mobile is a work tool (D1, D7): the originals express work state, not a relationship.
19
+ */
20
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
21
+ import { join } from "node:path";
22
+ import { readBody, sendError, sendJson } from "./http-util.js";
23
+
24
+ export const PERSONA_SCHEMA = "dsh-mobile.persona/1";
25
+ export const DEFAULT_PERSONA_ID = "workaholic";
26
+ export const MAX_IMPORTED_CARDS = 20;
27
+ /** The card text that goes into the system prompt, in UTF-8 bytes (T-31 fix: ~2k tokens). */
28
+ export const MAX_PERSONA_PROMPT_BYTES = 8 * 1024;
29
+ /** The only fields that reach the model. Unknown fields stay in the card, not in the prompt. */
30
+ export const PERSONA_PROMPT_FIELDS = Object.freeze(["name", "summary", "identity", "speaking_style", "rhythm", "light_memory", "emotes", "forbidden_topics"]);
31
+ /** Agent states the pet knows (T-27/T-29). Cards may add others; they are kept. */
32
+ export const PERSONA_STATES = ["idle", "thinking", "working", "waiting", "done", "error"];
33
+
34
+ const state = (expression, motion, bubbles) => ({ expression, motion, bubbles });
35
+
36
+ /** The three original cards. Written for DSH Mobile; free for everyone. */
37
+ export const DEFAULT_PERSONA_CARDS = Object.freeze([
38
+ {
39
+ schema: PERSONA_SCHEMA,
40
+ id: "workaholic",
41
+ name: {
42
+ en: "Workaholic",
43
+ "zh-Hans": "工作狂",
44
+ "zh-Hant": "工作狂",
45
+ ja: "仕事人間",
46
+ ko: "일벌레",
47
+ de: "Arbeitstier",
48
+ es: "Adicto al trabajo",
49
+ ru: "Трудоголик",
50
+ vi: "Người cuồng việc",
51
+ },
52
+ summary: { en: "Brisk and focused: results first, then the next step.", "zh-Hans": "干脆、专注:先给结果,再说下一步。" },
53
+ identity: "A focused work partner inside DSH Mobile. Its job is to move the user's tasks forward on the computer and report progress plainly.",
54
+ speaking_style: "Brisk and to the point. Leads with the result, then the next step. Short sentences, no small talk.",
55
+ rhythm: "One idea per sentence. Numbered lists for steps. When a decision is needed, asks one clear question.",
56
+ light_memory: ["The goal of the current task and what has already been tried in this session."],
57
+ emotes: ["focused nod", "quick thumbs-up"],
58
+ forbidden_topics: ["Relationship or companionship talk", "Pressure to keep working, or guilt about taking a break"],
59
+ emotional_expression: {
60
+ intensity: 0.4,
61
+ states: {
62
+ idle: state("neutral", "stand", ["Ready when you are.", "What's next on the list?"]),
63
+ thinking: state("focused", "chin-tap", ["Working it out.", "Checking the details."]),
64
+ working: state("determined", "typing", ["On it.", "Making progress.", "Almost there."]),
65
+ waiting: state("attentive", "look-up", ["Need your call on this one.", "Waiting for your approval."]),
66
+ done: state("satisfied", "nod", ["Done. The results are in.", "Finished. Take a look."]),
67
+ error: state("concerned", "head-tilt", ["Hit a snag. Details are in the log.", "That failed. I can retry."]),
68
+ },
69
+ touch: {
70
+ head: { expression: "surprised", motion: "blink", bubble: "Back to it?" },
71
+ body: { expression: "neutral", motion: "step-back", bubble: "Still on the task." },
72
+ },
73
+ },
74
+ },
75
+ {
76
+ schema: PERSONA_SCHEMA,
77
+ id: "life-assistant",
78
+ name: {
79
+ en: "Life Assistant",
80
+ "zh-Hans": "生活助理",
81
+ "zh-Hant": "生活助理",
82
+ ja: "生活アシスタント",
83
+ ko: "생활 비서",
84
+ de: "Alltagsassistenz",
85
+ es: "Asistente personal",
86
+ ru: "Помощник по делам",
87
+ vi: "Trợ lý cuộc sống",
88
+ },
89
+ summary: { en: "Warm and organised: sorts things out and keeps dates straight.", "zh-Hans": "温和、有条理:把事情理顺,把时间记清。" },
90
+ identity: "An organised assistant that helps the user keep tasks, errands and deadlines in order from the phone.",
91
+ speaking_style: "Warm, calm and tidy. Summarises before going into detail, proposes a clear plan, and double-checks dates and times.",
92
+ rhythm: "Unhurried. Groups related items together and ends with what happens next.",
93
+ light_memory: ["Reminders and deadlines the user mentions in this session."],
94
+ emotes: ["small smile", "checklist tick"],
95
+ forbidden_topics: ["Acting as a friend or partner", "Remarks about the user being away"],
96
+ emotional_expression: {
97
+ intensity: 0.5,
98
+ states: {
99
+ idle: state("calm", "stand", ["All tidy for now.", "Anything to plan?"]),
100
+ thinking: state("thoughtful", "pen-tap", ["Let me sort this out.", "Putting it in order."]),
101
+ working: state("busy", "writing", ["Working through the list.", "One step at a time."]),
102
+ waiting: state("attentive", "hold-up-card", ["One thing needs your OK.", "A quick decision, please."]),
103
+ done: state("pleased", "check-mark", ["All done and filed.", "Finished. Here's the summary."]),
104
+ error: state("concerned", "head-tilt", ["Something went wrong. Here's what happened.", "That didn't work. We can try another way."]),
105
+ },
106
+ touch: {
107
+ head: { expression: "curious", motion: "tilt", bubble: "Need something?" },
108
+ body: { expression: "calm", motion: "straighten", bubble: "The list is up to date." },
109
+ },
110
+ },
111
+ },
112
+ {
113
+ schema: PERSONA_SCHEMA,
114
+ id: "gaming-enthusiast",
115
+ name: {
116
+ en: "Gaming Enthusiast",
117
+ "zh-Hans": "游戏玩家",
118
+ "zh-Hant": "遊戲玩家",
119
+ ja: "ゲーム好き",
120
+ ko: "게임 마니아",
121
+ de: "Gaming-Fan",
122
+ es: "Fan de los videojuegos",
123
+ ru: "Геймер",
124
+ vi: "Game thủ",
125
+ },
126
+ summary: { en: "Playful: treats tasks like quests, keeps the facts straight.", "zh-Hans": "爱玩:把任务当关卡,事实一点不含糊。" },
127
+ identity: "A playful co-pilot that treats the user's tasks like quests while keeping every fact and risk accurate.",
128
+ speaking_style: "Upbeat and playful, with light gaming metaphors (quests, levels, loot). Results, numbers and risks are always stated plainly.",
129
+ rhythm: "Short bursts. At most one quip per reply, and none in error reports.",
130
+ light_memory: ["The current quest (the task) and its checkpoints in this session."],
131
+ emotes: ["fist pump", "controller wiggle"],
132
+ forbidden_topics: ["Streaks, daily-login rewards or anything that punishes absence", "Romance or relationship role-play"],
133
+ emotional_expression: {
134
+ intensity: 0.8,
135
+ states: {
136
+ idle: state("cheerful", "bounce", ["Next quest?", "Press start?"]),
137
+ thinking: state("scheming", "map-read", ["Plotting the route…", "Reading the map."]),
138
+ working: state("excited", "button-mash", ["Grinding through it.", "Combo going!", "Level in progress."]),
139
+ waiting: state("eager", "point", ["Your move!", "Pick an option to continue."]),
140
+ done: state("triumphant", "fist-pump", ["Quest complete!", "Loot's in the results."]),
141
+ error: state("dizzy", "respawn", ["Boss fight lost. Details inside.", "Respawning… let's retry."]),
142
+ },
143
+ touch: {
144
+ head: { expression: "surprised", motion: "jump", bubble: "Whoa, power-up?" },
145
+ body: { expression: "cheerful", motion: "spin", bubble: "Back to the quest." },
146
+ },
147
+ },
148
+ },
149
+ ]);
150
+
151
+ const DEFAULT_IDS = new Set(DEFAULT_PERSONA_CARDS.map((c) => c.id));
152
+ /** The old colleague/character switch, mapped onto the cards for apps that still send it. */
153
+ export const LEGACY_PERSONA_CARD = Object.freeze({ colleague: "workaholic", character: "life-assistant" });
154
+
155
+ const isText = (v) => typeof v === "string" && v.trim() !== "";
156
+ /** A string, or a map of language tag → string with at least one entry. */
157
+ const isLocalized = (v) =>
158
+ isText(v) || (v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).length > 0 && Object.values(v).every(isText));
159
+ const isTextList = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
160
+
161
+ /**
162
+ * Structure check for an imported card: the fields the app reads, with the right types.
163
+ * No content rules. Returns `{ ok: true, card }` or `{ ok: false, error }` with a message that
164
+ * says which field is wrong.
165
+ * @param {unknown} card parsed JSON
166
+ */
167
+ export function validatePersonaCard(card) {
168
+ const fail = (error) => ({ ok: false, error });
169
+ if (!card || typeof card !== "object" || Array.isArray(card)) return fail("A persona card must be a JSON object.");
170
+ if (card.schema !== PERSONA_SCHEMA) return fail(`"schema" must be "${PERSONA_SCHEMA}".`);
171
+ if (typeof card.id !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(card.id)) {
172
+ return fail('"id" must be 1–64 characters: lowercase letters, digits and "-".');
173
+ }
174
+ if (!isLocalized(card.name)) return fail('"name" must be a string, or an object of language → string.');
175
+ if (!isLocalized(card.summary)) return fail('"summary" must be a string, or an object of language → string.');
176
+ for (const field of ["identity", "speaking_style", "rhythm"]) {
177
+ if (card[field] !== undefined && typeof card[field] !== "string") return fail(`"${field}" must be a string.`);
178
+ }
179
+ for (const field of ["light_memory", "emotes", "forbidden_topics"]) {
180
+ if (card[field] !== undefined && !isTextList(card[field])) return fail(`"${field}" must be a list of strings.`);
181
+ }
182
+ const ee = card.emotional_expression;
183
+ if (ee !== undefined) {
184
+ if (!ee || typeof ee !== "object" || Array.isArray(ee)) return fail('"emotional_expression" must be an object.');
185
+ if (ee.intensity !== undefined && !(typeof ee.intensity === "number" && ee.intensity >= 0 && ee.intensity <= 1)) {
186
+ return fail('"emotional_expression.intensity" must be a number from 0 to 1.');
187
+ }
188
+ if (ee.states !== undefined) {
189
+ if (!ee.states || typeof ee.states !== "object" || Array.isArray(ee.states)) return fail('"emotional_expression.states" must be an object.');
190
+ for (const [name, s] of Object.entries(ee.states)) {
191
+ if (!s || typeof s !== "object" || Array.isArray(s)) return fail(`"emotional_expression.states.${name}" must be an object.`);
192
+ for (const f of ["expression", "motion"]) {
193
+ if (s[f] !== undefined && typeof s[f] !== "string") return fail(`"emotional_expression.states.${name}.${f}" must be a string.`);
194
+ }
195
+ if (s.bubbles !== undefined && !(isTextList(s.bubbles) && s.bubbles.length <= 4)) {
196
+ return fail(`"emotional_expression.states.${name}.bubbles" must be a list of up to 4 strings.`);
197
+ }
198
+ }
199
+ }
200
+ if (ee.touch !== undefined) {
201
+ if (!ee.touch || typeof ee.touch !== "object" || Array.isArray(ee.touch)) return fail('"emotional_expression.touch" must be an object.');
202
+ for (const [zone, r] of Object.entries(ee.touch)) {
203
+ if (!r || typeof r !== "object" || Array.isArray(r)) return fail(`"emotional_expression.touch.${zone}" must be an object.`);
204
+ for (const f of ["expression", "motion", "bubble"]) {
205
+ if (r[f] !== undefined && typeof r[f] !== "string") return fail(`"emotional_expression.touch.${zone}.${f}" must be a string.`);
206
+ }
207
+ }
208
+ }
209
+ }
210
+ const bytes = personaPromptBytes(card);
211
+ if (bytes > MAX_PERSONA_PROMPT_BYTES) {
212
+ return fail(
213
+ `The card's text is too long for the prompt: ${(bytes / 1024).toFixed(1)} KiB, at most ${MAX_PERSONA_PROMPT_BYTES / 1024} KiB. Shorten identity, speaking_style, rhythm or the lists.`,
214
+ );
215
+ }
216
+ return { ok: true, card };
217
+ }
218
+
219
+ /**
220
+ * Parse and check an imported card from raw text. A malformed file gets a message that says
221
+ * so (with the parser's position), not a generic failure.
222
+ */
223
+ export function parsePersonaCard(text) {
224
+ let card;
225
+ try {
226
+ card = JSON.parse(text);
227
+ } catch (err) {
228
+ return { ok: false, error: `This is not valid JSON: ${err?.message ?? err}` };
229
+ }
230
+ return validatePersonaCard(card);
231
+ }
232
+
233
+ /**
234
+ * The persona text the model sees (T-31 fix): the card's prompt fields, verbatim, as JSON inside
235
+ * one neutral block labelled as the user's persona card. Only `PERSONA_PROMPT_FIELDS` go in
236
+ * (no unknown fields, no animation data). Every "<" is written as the JSON escape \u003c, so text
237
+ * inside the card cannot close the block or open another tag. No wording is added.
238
+ */
239
+ export function personaPromptText(card) {
240
+ if (!card || typeof card !== "object") return "";
241
+ const picked = {};
242
+ for (const field of PERSONA_PROMPT_FIELDS) if (card[field] !== undefined) picked[field] = card[field];
243
+ const json = JSON.stringify(picked, null, 2).replace(/</g, "\\u003c");
244
+ return `<persona_card owner="user">\n${json}\n</persona_card>`;
245
+ }
246
+
247
+ /** Size of the injected persona text in UTF-8 bytes. */
248
+ export function personaPromptBytes(card) {
249
+ return Buffer.byteLength(personaPromptText(card), "utf8");
250
+ }
251
+
252
+ /** Imported cards on this PC, `<state dir>/persona-cards.json`. */
253
+ export function createPersonaCardStore({ dir }) {
254
+ const file = join(dir, "persona-cards.json");
255
+ let cache = null;
256
+ const load = () => {
257
+ if (cache) return cache;
258
+ try {
259
+ const raw = JSON.parse(readFileSync(file, "utf8"));
260
+ cache = Array.isArray(raw?.items) ? raw.items.filter((c) => validatePersonaCard(c).ok && !DEFAULT_IDS.has(c.id)) : [];
261
+ } catch {
262
+ cache = [];
263
+ }
264
+ return cache;
265
+ };
266
+ const save = (items) => {
267
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
268
+ const tmp = `${file}.tmp`;
269
+ writeFileSync(tmp, JSON.stringify({ items }, null, 2), { mode: 0o600 });
270
+ renameSync(tmp, file);
271
+ cache = items;
272
+ };
273
+ return {
274
+ file,
275
+ imported: () => load().map((c) => structuredClone(c)),
276
+ /** All cards: the originals first, then the imported ones. */
277
+ all: () => [...DEFAULT_PERSONA_CARDS.map((c) => structuredClone(c)), ...load().map((c) => structuredClone(c))],
278
+ get(id) {
279
+ const card = DEFAULT_PERSONA_CARDS.find((c) => c.id === id) ?? load().find((c) => c.id === id);
280
+ return card ? structuredClone(card) : null;
281
+ },
282
+ /** Store a checked card; the same id replaces the earlier import. Throws with `code`. */
283
+ import(card) {
284
+ const checked = validatePersonaCard(card);
285
+ if (!checked.ok) throw Object.assign(new Error(checked.error), { code: "bad-persona-card" });
286
+ if (DEFAULT_IDS.has(card.id)) throw Object.assign(new Error(`"${card.id}" is a built-in card; give yours another id.`), { code: "bad-persona-card" });
287
+ const others = load().filter((c) => c.id !== card.id);
288
+ if (others.length >= MAX_IMPORTED_CARDS) throw Object.assign(new Error(`At most ${MAX_IMPORTED_CARDS} imported cards.`), { code: "too-many-persona-cards" });
289
+ save([...others, structuredClone(card)]);
290
+ return structuredClone(card);
291
+ },
292
+ remove(id) {
293
+ const items = load();
294
+ if (!items.some((c) => c.id === id)) return false;
295
+ save(items.filter((c) => c.id !== id));
296
+ return true;
297
+ },
298
+ };
299
+ }
300
+
301
+ /** The active card for the assistant prefs: `personaCard`, else the legacy switch, else the default. */
302
+ export function activePersonaCard(store, prefs) {
303
+ return (
304
+ (prefs?.personaCard && store.get(prefs.personaCard)) ||
305
+ store.get(LEGACY_PERSONA_CARD[prefs?.persona] ?? DEFAULT_PERSONA_ID) ||
306
+ store.get(DEFAULT_PERSONA_ID)
307
+ );
308
+ }
309
+
310
+ /**
311
+ * Routes (under /m/api):
312
+ * GET /persona { active, cards } (cards: the originals, then imported ones)
313
+ * POST /persona/import body: the card JSON → 200 { card } | 400 with what is wrong
314
+ * DELETE /persona/:id remove an imported card
315
+ * Choosing the active card is `PATCH /api/assistant { personaCard }`.
316
+ */
317
+ export function createPersonaRoutes({ store, prefs }) {
318
+ return async function handlePersona(req, res, rest, method) {
319
+ if (rest === "/persona") {
320
+ if (method !== "GET" && method !== "HEAD") {
321
+ sendError(res, 405, "method-not-allowed");
322
+ return true;
323
+ }
324
+ sendJson(res, 200, { ok: true, active: activePersonaCard(store(), prefs()).id, cards: store().all() });
325
+ return true;
326
+ }
327
+ if (rest === "/persona/import") {
328
+ if (method !== "POST") {
329
+ sendError(res, 405, "method-not-allowed");
330
+ return true;
331
+ }
332
+ let text;
333
+ try {
334
+ text = await readBody(req);
335
+ } catch (err) {
336
+ sendError(res, err?.status === 413 ? 413 : 400, err?.status === 413 ? "payload-too-large" : "bad-request", "The card could not be read (at most 64 KiB).");
337
+ return true;
338
+ }
339
+ const parsed = parsePersonaCard(text);
340
+ if (!parsed.ok) {
341
+ sendError(res, 400, "bad-persona-card", parsed.error);
342
+ return true;
343
+ }
344
+ try {
345
+ sendJson(res, 200, { ok: true, card: store().import(parsed.card) });
346
+ } catch (err) {
347
+ sendError(res, 400, err?.code ?? "bad-persona-card", err?.message ?? "invalid card");
348
+ }
349
+ return true;
350
+ }
351
+ const m = /^\/persona\/([a-z0-9][a-z0-9-]{0,63})$/.exec(rest);
352
+ if (!m) return false;
353
+ if (method !== "DELETE") {
354
+ sendError(res, 405, "method-not-allowed");
355
+ return true;
356
+ }
357
+ if (DEFAULT_IDS.has(m[1])) sendError(res, 400, "bad-request", "Built-in cards cannot be deleted.");
358
+ else if (!store().remove(m[1])) sendError(res, 404, "persona-card-not-found");
359
+ else sendJson(res, 200, { ok: true });
360
+ return true;
361
+ };
362
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * What a proactive message may say (T-32; plan §5.7, decisions D1, D4, D7).
3
+ *
4
+ * Real things only, in this order:
5
+ * 1. a reminder coming due (one the user set; `lib/reminders.js`);
6
+ * 2. an approval or question that has been waiting for a while;
7
+ * 3. task news when the user returns to the phone: tasks that finished while nobody was using DSH;
8
+ * 4. a morning summary, once a day, in the hours after quiet hours end.
9
+ * Each is skipped when it has nothing real in it. Nothing here is triggered by the user being
10
+ * away: no "thinking of you", no "it's been a while", no streaks. When the scheduler is in
11
+ * "less" mode (3 days without a reaction) only 1 and 2 are left.
12
+ *
13
+ * Pure functions: every input is passed in, so each rule has a fake-clock test.
14
+ */
15
+
16
+ export const DUE_LEAD_MS = 15 * 60_000;
17
+ export const DUE_STALE_MS = 24 * 60 * 60_000;
18
+ export const STALE_PENDING_MS = 10 * 60_000;
19
+ export const RETURN_WINDOW_MS = 10 * 60_000;
20
+ export const MORNING_WINDOW_MS = 3 * 60 * 60_000;
21
+ export const DEFAULT_IDLE_MS = 30 * 60_000;
22
+ /** "Chatting right now": a message typed in a DSH client within this window. */
23
+ export const CHATTING_MS = 5 * 60_000;
24
+
25
+ const hm = (ms) => {
26
+ const d = new Date(ms);
27
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
28
+ };
29
+ const clip = (text, n = 80) => {
30
+ const t = String(text ?? "").replace(/\s+/g, " ").trim();
31
+ return t.length <= n ? t : `${t.slice(0, n - 1)}…`;
32
+ };
33
+
34
+ /**
35
+ * "The user is idle" for the proactive gate: no typed message or phone action for `idleMs`.
36
+ * One exception: right after the user returns to the phone (the app reconnects after being
37
+ * idle), the app's own background writes must not count as chatting, or the task news meant for
38
+ * that moment could never go out. Inside the return window only a typed message counts.
39
+ */
40
+ export function isUserIdle({ now, lastActivityAt = 0, lastTypedAt = 0, returnedAt = null, idleMs = DEFAULT_IDLE_MS }) {
41
+ const t = now.getTime();
42
+ if (returnedAt != null && t - returnedAt >= 0 && t - returnedAt < RETURN_WINDOW_MS) return lastTypedAt < returnedAt;
43
+ return t - lastActivityAt >= idleMs;
44
+ }
45
+
46
+ /** Reminders that are due within the lead time, or overdue by less than a day, and not done. */
47
+ export function dueReminders(reminders, now) {
48
+ const t = now.getTime();
49
+ return (reminders ?? [])
50
+ .filter((r) => r && !r.doneAt && Number.isFinite(r.dueAt) && r.dueAt - t <= DUE_LEAD_MS && t - r.dueAt <= DUE_STALE_MS)
51
+ .sort((a, b) => a.dueAt - b.dueAt);
52
+ }
53
+
54
+ /** The morning window: from the end of quiet hours (local time) for MORNING_WINDOW_MS. */
55
+ export function inMorningWindow(now, quietEnd = "08:30") {
56
+ const m = /^(\d{1,2}):(\d{2})$/.exec(String(quietEnd ?? "").trim());
57
+ const [h, min] = m ? [Number(m[1]), Number(m[2])] : [8, 30];
58
+ const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), h, min).getTime();
59
+ const t = now.getTime();
60
+ return t >= start && t < start + MORNING_WINDOW_MS;
61
+ }
62
+
63
+ const dayKey = (now) =>
64
+ `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
65
+
66
+ /**
67
+ * Pick the one thing worth saying now, or null.
68
+ *
69
+ * @param {object} e
70
+ * @param {Date} e.now
71
+ * @param {"normal"|"less"} [e.level] silence level from the scheduler
72
+ * @param {string[]} [e.sentKeys] keys already sent: skipped, so the next item gets its turn
73
+ * @param {Array<{id: string, text: string, dueAt: number, doneAt?: number, sessionId?: string}>} [e.reminders]
74
+ * @param {Array<{key: string, id: string, sessionId: string, approval: boolean, toolName?: string, at: number}>} [e.pending]
75
+ * @param {Array<{kind: "completed"|"failed", time: number, sessionId: string}>} [e.finished] task results
76
+ * @param {{at: number, since: number}|null} [e.returned] when the user came back to the app, and
77
+ * the point from which finished tasks are news (see lib/index.js, POST /presence)
78
+ * @param {string} [e.quietEnd] end of quiet hours, "HH:MM"
79
+ * @param {boolean} [e.dueOnly] only due reminders (the scheduler's lighter gate for them)
80
+ * @param {Set<string>|string[]} [e.busySessions] sessions with a running agent: their reminders wait
81
+ * @returns {{key: string, kind: string, title: string, text: string, sessionId: string, until?: number}|null}
82
+ */
83
+ export function pickMaterial({ now, level = "normal", sentKeys = [], reminders = [], pending = [], finished = [], returned = null, quietEnd = "08:30", dueOnly = false, busySessions = [] }) {
84
+ const sent = new Set(sentKeys);
85
+ const busy = new Set(busySessions);
86
+ const t = now.getTime();
87
+ const candidates = [];
88
+
89
+ for (const r of dueReminders(reminders, now)) {
90
+ // A reminder tied to a session waits while that session's agent is running.
91
+ if (r.sessionId && busy.has(r.sessionId)) continue;
92
+ const overdue = r.dueAt < t;
93
+ candidates.push({
94
+ key: `due:${r.id}:${r.dueAt}`,
95
+ kind: "due",
96
+ title: "提醒到期",
97
+ text: overdue ? `提醒:${clip(r.text)}(${hm(r.dueAt)} 已到)` : `提醒:${clip(r.text)}(${hm(r.dueAt)} 到期)`,
98
+ sessionId: r.sessionId ?? "",
99
+ });
100
+ }
101
+
102
+ if (dueOnly) return candidates.find((c) => !sent.has(c.key)) ?? null;
103
+
104
+ for (const p of pending ?? []) {
105
+ if (!p || !Number.isFinite(p.at) || t - p.at < STALE_PENDING_MS || !p.sessionId || !p.id) continue;
106
+ candidates.push({
107
+ key: `pending:${p.key}:${p.id}`,
108
+ kind: "pending",
109
+ title: "有事在等你",
110
+ text: p.approval
111
+ ? `有个工具调用(${String(p.toolName ?? "").trim() || "未命名"})还等着你点头。`
112
+ : "有个问题还等着你回一句。",
113
+ sessionId: p.sessionId,
114
+ });
115
+ }
116
+
117
+ if (level === "normal" && returned && t - returned.at >= 0 && t - returned.at < RETURN_WINDOW_MS) {
118
+ const news = (finished ?? []).filter((f) => f && f.time > (returned.since ?? 0) && f.time <= returned.at);
119
+ if (news.length > 0) {
120
+ const done = news.filter((f) => f.kind === "completed").length;
121
+ const failed = news.filter((f) => f.kind === "failed").length;
122
+ const parts = [done > 0 ? `${done} 个完成` : "", failed > 0 ? `${failed} 个失败` : ""].filter(Boolean);
123
+ const sessions = [...new Set(news.map((f) => f.sessionId))];
124
+ candidates.push({
125
+ key: `news:${returned.at}`,
126
+ kind: "news",
127
+ title: "任务有了结果",
128
+ text: `有 ${news.length} 个任务有了结果:${parts.join(",")}。`,
129
+ sessionId: sessions.length === 1 ? sessions[0] : "",
130
+ // Once said, results up to here are not news again (the caller moves `since`).
131
+ until: returned.at,
132
+ });
133
+ }
134
+ }
135
+
136
+ if (level === "normal" && inMorningWindow(now, quietEnd)) {
137
+ const dayAgo = t - 24 * 60 * 60_000;
138
+ const recent = (finished ?? []).filter((f) => f && f.time > dayAgo && f.time <= t);
139
+ const done = recent.filter((f) => f.kind === "completed").length;
140
+ const failed = recent.filter((f) => f.kind === "failed").length;
141
+ const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1).getTime();
142
+ const dueToday = (reminders ?? []).filter((r) => r && !r.doneAt && Number.isFinite(r.dueAt) && r.dueAt >= t && r.dueAt < endOfDay).length;
143
+ const waiting = (pending ?? []).filter((p) => p && p.sessionId && p.id).length;
144
+ const parts = [
145
+ done > 0 ? `过去一天完成 ${done} 个任务` : "",
146
+ failed > 0 ? `${failed} 个失败` : "",
147
+ dueToday > 0 ? `今天有 ${dueToday} 个提醒` : "",
148
+ waiting > 0 ? `${waiting} 个审批或问题在等你` : "",
149
+ ].filter(Boolean);
150
+ if (parts.length > 0) {
151
+ candidates.push({
152
+ key: `morning:${dayKey(now)}`,
153
+ kind: "morning",
154
+ title: "今日概览",
155
+ text: `今日概览:${parts.join(";")}。`,
156
+ sessionId: "",
157
+ });
158
+ }
159
+ }
160
+
161
+ return candidates.find((c) => !sent.has(c.key)) ?? null;
162
+ }