@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,43 +1,48 @@
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
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
20
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
21
21
  import { join } from "node:path";
22
22
  import { readBody, sendError, sendJson } from "./http-util.js";
23
23
 
24
24
  export const PERSONA_SCHEMA = "dsh-mobile.persona/1";
25
- export const DEFAULT_PERSONA_ID = "workaholic";
25
+
26
+
27
+
28
+
29
+
30
+ export const NO_PERSONA_ID = "none";
26
31
  export const MAX_IMPORTED_CARDS = 20;
27
- /**
28
- * The card text that goes to the model, in UTF-8 bytes (T-31 fix: ~2k tokens). A-34: it is not the
29
- * system prompt: DSH renders prompt contexts into a user-role `<system-reminder>` message, and a DSH
30
- * config with `includeRuntimeContext: false` drops non-required contexts, this card among them.
31
- */
32
+
33
+
34
+
35
+
36
+
32
37
  export const MAX_PERSONA_PROMPT_BYTES = 8 * 1024;
33
- /** The only fields that reach the model. Unknown fields stay in the card, not in the prompt. */
38
+
34
39
  export const PERSONA_PROMPT_FIELDS = Object.freeze(["name", "summary", "identity", "speaking_style", "rhythm", "light_memory", "emotes", "forbidden_topics"]);
35
- /** Agent states the pet knows (T-27/T-29). Cards may add others; they are kept. */
40
+
36
41
  export const PERSONA_STATES = ["idle", "thinking", "working", "waiting", "done", "error"];
37
42
 
38
43
  const state = (expression, motion, bubbles) => ({ expression, motion, bubbles });
39
44
 
40
- /** The three original cards. Written for DSH Mobile; free for everyone. */
45
+
41
46
  export const DEFAULT_PERSONA_CARDS = Object.freeze([
42
47
  {
43
48
  schema: PERSONA_SCHEMA,
@@ -153,21 +158,19 @@ export const DEFAULT_PERSONA_CARDS = Object.freeze([
153
158
  ]);
154
159
 
155
160
  const DEFAULT_IDS = new Set(DEFAULT_PERSONA_CARDS.map((c) => c.id));
156
- /** The old colleague/character switch, mapped onto the cards for apps that still send it. */
157
- export const LEGACY_PERSONA_CARD = Object.freeze({ colleague: "workaholic", character: "life-assistant" });
158
161
 
159
162
  const isText = (v) => typeof v === "string" && v.trim() !== "";
160
- /** A string, or a map of language tag → string with at least one entry. */
163
+
161
164
  const isLocalized = (v) =>
162
165
  isText(v) || (v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).length > 0 && Object.values(v).every(isText));
163
166
  const isTextList = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
164
167
 
165
- /**
166
- * Structure check for an imported card: the fields the app reads, with the right types.
167
- * No content rules. Returns `{ ok: true, card }` or `{ ok: false, error }` with a message that
168
- * says which field is wrong.
169
- * @param {unknown} card parsed JSON
170
- */
168
+
169
+
170
+
171
+
172
+
173
+
171
174
  export function validatePersonaCard(card) {
172
175
  const fail = (error) => ({ ok: false, error });
173
176
  if (!card || typeof card !== "object" || Array.isArray(card)) return fail("A persona card must be a JSON object.");
@@ -175,6 +178,7 @@ export function validatePersonaCard(card) {
175
178
  if (typeof card.id !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(card.id)) {
176
179
  return fail('"id" must be 1–64 characters: lowercase letters, digits and "-".');
177
180
  }
181
+ if (card.id === NO_PERSONA_ID) return fail(`"id" cannot be "${NO_PERSONA_ID}": that word means "no persona card".`);
178
182
  if (!isLocalized(card.name)) return fail('"name" must be a string, or an object of language → string.');
179
183
  if (!isLocalized(card.summary)) return fail('"summary" must be a string, or an object of language → string.');
180
184
  for (const field of ["identity", "speaking_style", "rhythm"]) {
@@ -220,10 +224,10 @@ export function validatePersonaCard(card) {
220
224
  return { ok: true, card };
221
225
  }
222
226
 
223
- /**
224
- * Parse and check an imported card from raw text. A malformed file gets a message that says
225
- * so (with the parser's position), not a generic failure.
226
- */
227
+
228
+
229
+
230
+
227
231
  export function parsePersonaCard(text) {
228
232
  let card;
229
233
  try {
@@ -234,12 +238,12 @@ export function parsePersonaCard(text) {
234
238
  return validatePersonaCard(card);
235
239
  }
236
240
 
237
- /**
238
- * The persona text the model sees (T-31 fix): the card's prompt fields, verbatim, as JSON inside
239
- * one neutral block labelled as the user's persona card. Only `PERSONA_PROMPT_FIELDS` go in
240
- * (no unknown fields, no animation data). Every "<" is written as the JSON escape \u003c, so text
241
- * inside the card cannot close the block or open another tag. No wording is added.
242
- */
241
+
242
+
243
+
244
+
245
+
246
+
243
247
  export function personaPromptText(card) {
244
248
  if (!card || typeof card !== "object") return "";
245
249
  const picked = {};
@@ -248,12 +252,12 @@ export function personaPromptText(card) {
248
252
  return `<persona_card owner="user">\n${json}\n</persona_card>`;
249
253
  }
250
254
 
251
- /** Size of the injected persona text in UTF-8 bytes. */
255
+
252
256
  export function personaPromptBytes(card) {
253
257
  return Buffer.byteLength(personaPromptText(card), "utf8");
254
258
  }
255
259
 
256
- /** Imported cards on this PC, `<state dir>/persona-cards.json`. */
260
+
257
261
  export function createPersonaCardStore({ dir }) {
258
262
  const file = join(dir, "persona-cards.json");
259
263
  let cache = null;
@@ -277,13 +281,13 @@ export function createPersonaCardStore({ dir }) {
277
281
  return {
278
282
  file,
279
283
  imported: () => load().map((c) => structuredClone(c)),
280
- /** All cards: the originals first, then the imported ones. */
284
+
281
285
  all: () => [...DEFAULT_PERSONA_CARDS.map((c) => structuredClone(c)), ...load().map((c) => structuredClone(c))],
282
286
  get(id) {
283
287
  const card = DEFAULT_PERSONA_CARDS.find((c) => c.id === id) ?? load().find((c) => c.id === id);
284
288
  return card ? structuredClone(card) : null;
285
289
  },
286
- /** Store a checked card; the same id replaces the earlier import. Throws with `code`. */
290
+
287
291
  import(card) {
288
292
  const checked = validatePersonaCard(card);
289
293
  if (!checked.ok) throw Object.assign(new Error(checked.error), { code: "bad-persona-card" });
@@ -302,22 +306,26 @@ export function createPersonaCardStore({ dir }) {
302
306
  };
303
307
  }
304
308
 
305
- /** The active card for the assistant prefs: `personaCard`, else the legacy switch, else the default. */
309
+
310
+
311
+
312
+
313
+
314
+
306
315
  export function activePersonaCard(store, prefs) {
307
- return (
308
- (prefs?.personaCard && store.get(prefs.personaCard)) ||
309
- store.get(LEGACY_PERSONA_CARD[prefs?.persona] ?? DEFAULT_PERSONA_ID) ||
310
- store.get(DEFAULT_PERSONA_ID)
311
- );
316
+ const id = prefs?.personaCard;
317
+ if (typeof id !== "string" || id === "" || id === NO_PERSONA_ID) return null;
318
+ return store.get(id) ?? null;
312
319
  }
313
320
 
314
- /**
315
- * Routes (under /m/api):
316
- * GET /persona { active, cards } (cards: the originals, then imported ones)
317
- * POST /persona/import body: the card JSON → 200 { card } | 400 with what is wrong
318
- * DELETE /persona/:id remove an imported card
319
- * Choosing the active card is `PATCH /api/assistant { personaCard }`.
320
- */
321
+
322
+
323
+
324
+
325
+
326
+
327
+
328
+
321
329
  export function createPersonaRoutes({ store, prefs }) {
322
330
  return async function handlePersona(req, res, rest, method) {
323
331
  if (rest === "/persona") {
@@ -325,7 +333,7 @@ export function createPersonaRoutes({ store, prefs }) {
325
333
  sendError(res, 405, "method-not-allowed");
326
334
  return true;
327
335
  }
328
- sendJson(res, 200, { ok: true, active: activePersonaCard(store(), prefs()).id, cards: store().all() });
336
+ sendJson(res, 200, { ok: true, active: activePersonaCard(store(), prefs())?.id ?? null, cards: store().all() });
329
337
  return true;
330
338
  }
331
339
  if (rest === "/persona/import") {
@@ -0,0 +1,175 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+ export const ACTIONS = Object.freeze(["add_reminder", "add_event", "set_alarm", "set_timer", "open_link"]);
13
+ export const TOOL_NAMES = Object.freeze(Object.fromEntries(ACTIONS.map((a) => [a, `phone_${a}`])));
14
+
15
+ export const MAX_TITLE = 200;
16
+ export const MAX_NOTES = 1000;
17
+ export const MAX_URL = 2048;
18
+ export const MAX_TIMER_SECONDS = 24 * 3600;
19
+ export const MAX_EVENT_MS = 7 * 24 * 3600 * 1000;
20
+ const DAYS = Object.freeze(["mon", "tue", "wed", "thu", "fri", "sat", "sun"]);
21
+
22
+ const ISO_WITH_OFFSET = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})$/;
23
+
24
+ const CONTROL = /[\u0000-\u001f\u007f]/;
25
+
26
+
27
+ export const parseIsoWithOffset = (value) => {
28
+ if (typeof value !== "string" || value.length > 40) return undefined;
29
+ const m = ISO_WITH_OFFSET.exec(value);
30
+ if (!m) return undefined;
31
+ const [, y, mo, d, h, mi, s = "0", off] = m.map((x, i) => (i === 0 || i === 7 ? x : x === undefined ? x : Number(x)));
32
+ if (mo < 1 || mo > 12 || h > 23 || mi > 59 || s > 59 || y < 2000 || y > 2100) return undefined;
33
+ const daysInMonth = new Date(Date.UTC(y, mo, 0)).getUTCDate();
34
+ if (d < 1 || d > daysInMonth) return undefined;
35
+ if (off !== "Z") {
36
+ const oh = Number(off.slice(1, 3));
37
+ const om = Number(off.slice(4, 6));
38
+ if (oh > 14 || om > 59) return undefined;
39
+ }
40
+ const t = Date.parse(value);
41
+ return Number.isFinite(t) ? t : undefined;
42
+ };
43
+
44
+ const text = (value, name, { max = MAX_TITLE, required = false } = {}) => {
45
+ if (value === undefined && !required) return { ok: true, value: undefined };
46
+ if (typeof value !== "string") return { ok: false, error: `${name} must be a string` };
47
+ const v = value.trim();
48
+ if (required && v === "") return { ok: false, error: `${name} must not be empty` };
49
+ if (v.length > max) return { ok: false, error: `${name} is longer than ${max} characters` };
50
+ const allowedWhitespace = name === "notes" ? v.replace(/[\n\t]/g, "") : v;
51
+ if (CONTROL.test(allowedWhitespace)) return { ok: false, error: `${name} contains control characters` };
52
+ return { ok: true, value: v === "" ? undefined : v };
53
+ };
54
+
55
+
56
+ export const validateLink = (value) => {
57
+ if (typeof value !== "string") return { ok: false, error: "url must be a string" };
58
+ if (value.length > MAX_URL) return { ok: false, error: `url is longer than ${MAX_URL} characters` };
59
+ if (value !== value.trim() || /[\s\u0000-\u001f\u007f]/.test(value)) return { ok: false, error: "url must not contain spaces or control characters" };
60
+ let u;
61
+ try { u = new URL(value); } catch { return { ok: false, error: "url is not a valid URL" }; }
62
+ if (u.protocol !== "http:" && u.protocol !== "https:") return { ok: false, error: "only http and https links are allowed" };
63
+ if (u.username !== "" || u.password !== "") return { ok: false, error: "links with a user name or password are not allowed" };
64
+ if (u.hostname === "") return { ok: false, error: "url has no host" };
65
+ return { ok: true, value };
66
+ };
67
+
68
+ const exact = (args, allowed) => {
69
+ if (args === null || typeof args !== "object" || Array.isArray(args)) return "arguments must be an object";
70
+ const extra = Object.keys(args).filter((k) => !allowed.includes(k));
71
+ return extra.length > 0 ? `unknown argument: ${extra[0].slice(0, 40)}` : undefined;
72
+ };
73
+ const collect = (parts) => {
74
+ const out = {};
75
+ for (const [key, r] of Object.entries(parts)) {
76
+ if (!r.ok) return r;
77
+ if (r.value !== undefined) out[key] = r.value;
78
+ }
79
+ return { ok: true, value: out };
80
+ };
81
+ const time = (value, name, required = true) => {
82
+ if (value === undefined && !required) return { ok: true, value: undefined };
83
+ return parseIsoWithOffset(value) === undefined
84
+ ? { ok: false, error: `${name} must be an ISO-8601 time with an offset, like 2026-11-24T09:00:00+08:00` }
85
+ : { ok: true, value };
86
+ };
87
+
88
+ const VALIDATORS = {
89
+ add_reminder: (a) => exact(a, ["title", "at"]) ? { ok: false, error: exact(a, ["title", "at"]) }
90
+ : collect({ title: text(a.title, "title", { required: true }), at: time(a.at, "at") }),
91
+ add_event: (a) => {
92
+ const bad = exact(a, ["title", "start", "end", "location", "notes"]);
93
+ if (bad) return { ok: false, error: bad };
94
+ const r = collect({
95
+ title: text(a.title, "title", { required: true }),
96
+ start: time(a.start, "start"),
97
+ end: time(a.end, "end", false),
98
+ location: text(a.location, "location"),
99
+ notes: text(a.notes, "notes", { max: MAX_NOTES }),
100
+ });
101
+ if (!r.ok || r.value.end === undefined) return r;
102
+ const span = parseIsoWithOffset(r.value.end) - parseIsoWithOffset(r.value.start);
103
+ if (span <= 0) return { ok: false, error: "end must be after start" };
104
+ if (span > MAX_EVENT_MS) return { ok: false, error: "an event can last at most 7 days" };
105
+ return r;
106
+ },
107
+ set_alarm: (a) => {
108
+ const bad = exact(a, ["time", "label", "days"]);
109
+ if (bad) return { ok: false, error: bad };
110
+ if (typeof a.time !== "string" || !/^([01]\d|2[0-3]):[0-5]\d$/.test(a.time)) return { ok: false, error: "time must be HH:MM (24-hour)" };
111
+ const label = text(a.label, "label");
112
+ if (!label.ok) return label;
113
+ let days;
114
+ if (a.days !== undefined) {
115
+ if (!Array.isArray(a.days) || a.days.length === 0 || a.days.length > 7 || a.days.some((d) => !DAYS.includes(d)) || new Set(a.days).size !== a.days.length) {
116
+ return { ok: false, error: "days must be a list of distinct mon, tue, wed, thu, fri, sat, sun" };
117
+ }
118
+ days = DAYS.filter((d) => a.days.includes(d));
119
+ }
120
+ return { ok: true, value: { time: a.time, ...(label.value === undefined ? {} : { label: label.value }), ...(days ? { days } : {}) } };
121
+ },
122
+ set_timer: (a) => {
123
+ const bad = exact(a, ["seconds", "label"]);
124
+ if (bad) return { ok: false, error: bad };
125
+ if (!Number.isInteger(a.seconds) || a.seconds < 1 || a.seconds > MAX_TIMER_SECONDS) return { ok: false, error: `seconds must be a whole number from 1 to ${MAX_TIMER_SECONDS}` };
126
+ return collect({ seconds: { ok: true, value: a.seconds }, label: text(a.label, "label") });
127
+ },
128
+ open_link: (a) => {
129
+ const bad = exact(a, ["url"]);
130
+ if (bad) return { ok: false, error: bad };
131
+ return collect({ url: validateLink(a.url) });
132
+ },
133
+ };
134
+
135
+
136
+ export const validatePhoneAction = (action, args) => {
137
+ const v = VALIDATORS[action];
138
+ return v ? v(args) : { ok: false, error: "unknown action" };
139
+ };
140
+
141
+ const str = (description, max) => ({ type: "string", description, maxLength: max });
142
+ const ISO = "ISO-8601 date and time WITH a UTC offset, e.g. 2026-11-24T09:00:00+08:00";
143
+
144
+
145
+ export const TOOL_SPECS = Object.freeze({
146
+ add_reminder: {
147
+ description: "Add a reminder on the user's phone. The phone asks the user to confirm first.",
148
+ parameters: { type: "object", additionalProperties: false, required: ["title", "at"], properties: { title: str("What to be reminded of", MAX_TITLE), at: str(ISO, 40) } },
149
+ },
150
+ add_event: {
151
+ description: "Add a calendar event on the user's phone. The phone asks the user to confirm first.",
152
+ parameters: {
153
+ type: "object", additionalProperties: false, required: ["title", "start"],
154
+ properties: { title: str("Event title", MAX_TITLE), start: str(ISO, 40), end: str(`${ISO}; after start, at most 7 days later`, 40), location: str("Where", MAX_TITLE), notes: str("Notes", MAX_NOTES) },
155
+ },
156
+ },
157
+ set_alarm: {
158
+ description: "Set an alarm on the user's phone. The phone asks the user to confirm first.",
159
+ parameters: {
160
+ type: "object", additionalProperties: false, required: ["time"],
161
+ properties: { time: str("Local time HH:MM, 24-hour", 5), label: str("Alarm label", MAX_TITLE), days: { type: "array", description: "Repeat on these days; omit for once", items: { type: "string", enum: [...DAYS] } } },
162
+ },
163
+ },
164
+ set_timer: {
165
+ description: "Start a countdown timer on the user's phone. The phone asks the user to confirm first.",
166
+ parameters: {
167
+ type: "object", additionalProperties: false, required: ["seconds"],
168
+ properties: { seconds: { type: "integer", description: `1 to ${MAX_TIMER_SECONDS}`, minimum: 1, maximum: MAX_TIMER_SECONDS }, label: str("Timer label", MAX_TITLE) },
169
+ },
170
+ },
171
+ open_link: {
172
+ description: "Open a web link (http or https only) on the user's phone. The phone shows the full address and asks the user to confirm first.",
173
+ parameters: { type: "object", additionalProperties: false, required: ["url"], properties: { url: str("http(s) URL without a user name or password", MAX_URL) } },
174
+ },
175
+ });
@@ -0,0 +1,227 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+ import { randomUUID } from "node:crypto";
18
+ import { hostname } from "node:os";
19
+ import { ACTIONS, TOOL_NAMES, TOOL_SPECS, validatePhoneAction } from "./phone-action-args.js";
20
+ import { PHONE_ACTIONS_FEATURE } from "./protocol.js";
21
+ import { createCapableTracker, GRACE_MS } from "./phone-announce.js";
22
+ import { readBody, sendError, sendJson } from "./http-util.js";
23
+
24
+ export const FEATURE = PHONE_ACTIONS_FEATURE;
25
+
26
+ export const ASK_MS = 30_000;
27
+
28
+ export const PENDING_MS = 35_000;
29
+ const TOMBSTONE_MS = 10 * 60_000;
30
+ const MAX_TOMBSTONES = 256;
31
+ const MAX_PENDING = 16;
32
+ export const STATUSES = Object.freeze(["done", "cancelled", "timeout", "denied-permission", "unsupported", "error"]);
33
+ const DETAIL_MAX = 200;
34
+
35
+ const OUTPUT_SCHEMA = {
36
+ type: "object",
37
+ properties: { status: { type: "string", enum: [...STATUSES] }, detail: { type: "string" } },
38
+ required: ["status"],
39
+ additionalProperties: false,
40
+ };
41
+
42
+ const cleanDetail = (v) => (typeof v === "string" ? v.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, DETAIL_MAX) : "");
43
+ const sessionIdOf = (agent) => agent?.session?.id ?? String(agent?.id ?? "").replace(/^session:/, "");
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+ export const createPhoneActions = ({ ctx, broadcast, phoneConnected, pcName, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout, graceMs = GRACE_MS }) => {
53
+ const pending = new Map();
54
+ const settled = new Map();
55
+ const turns = new Map();
56
+ const name = pcName || hostname();
57
+ let supported = false;
58
+ let native = false;
59
+ let toolDisposers = null;
60
+ let turnSeq = 0;
61
+
62
+ const settle = (id, result, { byPhone = false } = {}) => {
63
+ const entry = pending.get(id);
64
+ if (!entry) return false;
65
+ pending.delete(id);
66
+ clearTimer(entry.timer);
67
+ entry.offAbort?.();
68
+ if (byPhone) {
69
+ settled.set(id, now());
70
+ if (settled.size > MAX_TOMBSTONES) settled.delete(settled.keys().next().value);
71
+ }
72
+
73
+ broadcast({ type: "phone-action-resolved", id, status: result.status });
74
+ ctx.logger?.debug?.(`mobile-remote: phone-action ${entry.action} ${id} → ${result.status}`);
75
+ entry.resolve(result);
76
+ return true;
77
+ };
78
+
79
+ const request = (action, args, exec) => {
80
+ if (!phoneConnected()) throw new Error("phone not connected: the DSH Mobile app is not connected to this computer right now, so this action cannot be done. Tell the user.");
81
+ if (pending.size >= MAX_PENDING) throw new Error("too many phone actions are waiting for the user");
82
+ const id = randomUUID();
83
+ const sessionId = sessionIdOf(exec?.agent);
84
+ const turnId = turns.get(sessionId);
85
+ const at = now();
86
+ return new Promise((resolve) => {
87
+ const entry = { resolve, action, timer: null, offAbort: null };
88
+ entry.timer = setTimer(() => settle(id, { status: "timeout", detail: "the phone did not answer in time" }), PENDING_MS);
89
+ entry.timer.unref?.();
90
+ const signal = exec?.signal;
91
+ if (signal) {
92
+ const onAbort = () => settle(id, { status: "cancelled", detail: "the agent stopped this call" });
93
+ if (signal.aborted) queueMicrotask(onAbort);
94
+ else {
95
+ signal.addEventListener("abort", onAbort, { once: true });
96
+ entry.offAbort = () => signal.removeEventListener("abort", onAbort);
97
+ }
98
+ }
99
+ pending.set(id, entry);
100
+ broadcast({
101
+ type: "phone-action-request", id, pcName: name, action, args,
102
+ expiresAt: at + ASK_MS,
103
+ ...(sessionId ? { sessionId } : {}),
104
+ ...(turnId ? { turnId } : {}),
105
+ });
106
+ });
107
+ };
108
+
109
+ const toolFor = (action) => ({
110
+ name: TOOL_NAMES[action],
111
+ description: TOOL_SPECS[action].description,
112
+ parameters: TOOL_SPECS[action].parameters,
113
+ output: {
114
+ schema: OUTPUT_SCHEMA,
115
+ render: (_args, value) => [{ type: "text", text: `${TOOL_NAMES[action]}: ${value.status}${value.detail ? ` (${value.detail})` : ""}` }],
116
+ },
117
+ async execute(args, exec) {
118
+ const v = validatePhoneAction(action, args);
119
+ if (!v.ok) throw new Error(`invalid arguments: ${v.error}`);
120
+ const result = await request(action, v.value, exec);
121
+ return result.detail ? { status: result.status, detail: result.detail } : { status: result.status };
122
+ },
123
+ });
124
+
125
+ const hostTools = () => {
126
+ let tools;
127
+
128
+
129
+ try { tools = ctx.get?.("tools"); } catch { tools = undefined; }
130
+ if (typeof tools?.register !== "function") { try { tools = ctx.tools; } catch { tools = undefined; } }
131
+ return typeof tools?.register === "function" ? tools : undefined;
132
+ };
133
+
134
+ const addTools = (tools, options) => {
135
+ const disposers = [];
136
+ try {
137
+ for (const action of ACTIONS) disposers.push(tools.register(toolFor(action), options));
138
+ } catch (err) {
139
+ for (const d of disposers) try { d?.(); } catch { }
140
+ ctx.logger?.warn?.(`mobile-remote: phone tools not registered (${err?.message ?? err})`);
141
+ return null;
142
+ }
143
+ return disposers;
144
+ };
145
+ const removeTools = () => {
146
+ for (const d of toolDisposers ?? []) try { d?.(); } catch { }
147
+ toolDisposers = null;
148
+ };
149
+
150
+
151
+ const capable = createCapableTracker({
152
+ graceMs, setTimer, clearTimer,
153
+ onActive: () => { if (supported && !native && toolDisposers === null) toolDisposers = addTools(hostTools(), undefined); },
154
+ onIdle: () => { if (!native) removeTools(); },
155
+ });
156
+
157
+
158
+
159
+
160
+
161
+
162
+
163
+
164
+
165
+ const register = () => {
166
+ if (supported) return true;
167
+ const tools = hostTools();
168
+ if (!tools) return false;
169
+ native = typeof tools.resolve === "function";
170
+ if (native) {
171
+ toolDisposers = addTools(tools, { when: () => capable.active() });
172
+ if (toolDisposers === null) return false;
173
+ } else if (capable.active()) toolDisposers = addTools(tools, undefined);
174
+ supported = true;
175
+
176
+ let offTurns;
177
+ try {
178
+ offTurns = ctx.on?.("session/event", (session, event) => {
179
+ if (event?.type === "turn/start") turns.set(session.id, `t${++turnSeq}-${now().toString(36)}`);
180
+ else if (event?.type === "turn/end") turns.delete(session.id);
181
+ });
182
+ } catch { }
183
+ ctx.effect?.(() => () => {
184
+ try { offTurns?.(); } catch { }
185
+ turns.clear();
186
+ capable.dispose();
187
+ removeTools();
188
+ supported = false;
189
+ for (const id of [...pending.keys()]) settle(id, { status: "cancelled", detail: "plugin stopped" });
190
+ });
191
+ return true;
192
+ };
193
+
194
+
195
+ const handle = async (req, res, method) => {
196
+ if (method !== "POST") return sendError(res, 405, "method-not-allowed"), true;
197
+ let body;
198
+ try { body = JSON.parse(await readBody(req, 8 * 1024)) ?? {}; } catch (err) {
199
+ return sendError(res, err?.status === 413 ? 413 : 400, err?.status === 413 ? "payload-too-large" : "bad-request"), true;
200
+ }
201
+ const id = typeof body.id === "string" ? body.id : "";
202
+ if (id === "" || id.length > 80 || !STATUSES.includes(body.status) || (body.detail !== undefined && typeof body.detail !== "string")) {
203
+ return sendError(res, 400, "bad-request", "id and a known status are required"), true;
204
+ }
205
+
206
+ for (const [k, at] of settled) if (now() - at > TOMBSTONE_MS) settled.delete(k);
207
+ if (settled.has(id)) return sendError(res, 409, "already-answered"), true;
208
+ const detail = cleanDetail(body.detail);
209
+ if (!settle(id, detail === "" ? { status: body.status } : { status: body.status, detail }, { byPhone: true })) {
210
+ return sendError(res, 404, "unknown-or-expired"), true;
211
+ }
212
+ sendJson(res, 200, { ok: true });
213
+ return true;
214
+ };
215
+
216
+ return {
217
+ register,
218
+ handle,
219
+
220
+ attach: (res, req) => capable.attach(res, req),
221
+
222
+ toolsOffered: () => capable.active(),
223
+
224
+ features: () => (supported ? [FEATURE] : []),
225
+ pendingCount: () => pending.size,
226
+ };
227
+ };
@@ -0,0 +1,58 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+ export const ANNOUNCE_HEADER = "x-dsh-phone-actions";
13
+ export const GRACE_MS = 60_000;
14
+
15
+
16
+ export const isAnnounced = (req) => {
17
+ const header = req?.headers?.[ANNOUNCE_HEADER];
18
+ if ((Array.isArray(header) ? header[0] : header) === "1") return true;
19
+ try { return new URL(String(req?.url ?? ""), "http://x").searchParams.get(ANNOUNCE_HEADER) === "1"; } catch { return false; }
20
+ };
21
+
22
+
23
+
24
+
25
+
26
+
27
+ export const createCapableTracker = ({ onActive, onIdle, graceMs = GRACE_MS, setTimer = setTimeout, clearTimer = clearTimeout } = {}) => {
28
+ const streams = new Set();
29
+ let timer = null;
30
+ let disposed = false;
31
+ const active = () => streams.size > 0 || timer !== null;
32
+ const detach = (res) => {
33
+ if (!streams.delete(res) || streams.size > 0 || disposed) return;
34
+ timer = setTimer(() => { timer = null; if (!disposed) onIdle?.(); }, graceMs);
35
+ timer.unref?.();
36
+ };
37
+ return {
38
+ active,
39
+ count: () => streams.size,
40
+
41
+ attach(res, req) {
42
+ if (disposed || streams.has(res) || !isAnnounced(req)) return false;
43
+ const wasActive = active();
44
+ if (timer !== null) { clearTimer(timer); timer = null; }
45
+ streams.add(res);
46
+ res.on("close", () => detach(res));
47
+ res.on("error", () => detach(res));
48
+ if (!wasActive) onActive?.();
49
+ return true;
50
+ },
51
+ dispose() {
52
+ disposed = true;
53
+ if (timer !== null) clearTimer(timer);
54
+ timer = null;
55
+ streams.clear();
56
+ },
57
+ };
58
+ };