@dsh-mobile/mobile-remote 3.3.0 → 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.
- package/FAQ.md +2 -2
- package/LICENSE +0 -0
- package/README.md +13 -8
- package/docs/PRIVACY-POLICY.en.md +26 -18
- package/docs/PRIVACY-POLICY.md +26 -18
- package/docs/SUPPORT.md +1 -1
- package/docs/TERMS-OF-SERVICE.en.md +5 -3
- package/docs/TERMS-OF-SERVICE.md +5 -3
- package/docs/USER-GUIDE.zh-CN.md +7 -6
- package/lib/account-usage-query.js +60 -60
- package/lib/account-usage.js +10 -10
- package/lib/api-helpers.js +114 -110
- package/lib/assistant-prefs.js +119 -76
- package/lib/auto-config.js +65 -65
- package/lib/backup.js +159 -123
- package/lib/break-reminder.js +45 -45
- package/lib/client.js +336 -138
- package/lib/config.js +234 -218
- package/lib/git-read-bundled-provider.js +27 -7
- package/lib/git-read-service.js +5 -5
- package/lib/host-compat.js +84 -84
- package/lib/http-util.js +17 -17
- package/lib/index.js +1670 -1511
- package/lib/memory/context.js +45 -40
- package/lib/memory/decay.js +93 -93
- package/lib/memory/extract.js +77 -77
- package/lib/memory/routes.js +33 -33
- package/lib/memory/store.js +239 -192
- package/lib/notify-copy.js +93 -93
- package/lib/permission-guide.js +86 -86
- package/lib/persona-cards.js +73 -61
- package/lib/phone-action-args.js +175 -0
- package/lib/phone-actions.js +227 -0
- package/lib/phone-announce.js +58 -0
- package/lib/proactive-material.js +42 -42
- package/lib/proactive.js +122 -119
- package/lib/protected-paths.js +205 -45
- package/lib/protocol.js +62 -23
- package/lib/push.js +29 -29
- package/lib/rate-limit.js +16 -16
- package/lib/relay/connector.js +334 -81
- package/lib/relay/crypto.js +15 -15
- package/lib/relay/devices.js +64 -32
- package/lib/relay/fingerprint.js +34 -34
- package/lib/relay/identity.js +26 -26
- package/lib/relay/mux.js +60 -46
- package/lib/relay/noise.js +40 -40
- package/lib/relay/on-demand.js +36 -31
- package/lib/relay/p2p.js +239 -0
- package/lib/relay/pairing.js +54 -15
- package/lib/relay/phone.js +63 -39
- package/lib/relay/serve.js +21 -21
- package/lib/relay/signal.js +69 -0
- package/lib/relay/ws-server.js +245 -0
- package/lib/reminders.js +15 -15
- package/lib/rpc-adapter.js +43 -43
- package/lib/session-list.js +31 -31
- package/lib/session-rotation.js +95 -95
- package/lib/session-title-cache.js +35 -35
- package/lib/session-title-refresh.js +51 -51
- package/lib/timeline.js +140 -140
- package/lib/turn-outline.js +104 -104
- package/package.json +11 -18
package/lib/persona-cards.js
CHANGED
|
@@ -1,39 +1,48 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
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
|
-
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
export const NO_PERSONA_ID = "none";
|
|
26
31
|
export const MAX_IMPORTED_CARDS = 20;
|
|
27
|
-
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
28
37
|
export const MAX_PERSONA_PROMPT_BYTES = 8 * 1024;
|
|
29
|
-
|
|
38
|
+
|
|
30
39
|
export const PERSONA_PROMPT_FIELDS = Object.freeze(["name", "summary", "identity", "speaking_style", "rhythm", "light_memory", "emotes", "forbidden_topics"]);
|
|
31
|
-
|
|
40
|
+
|
|
32
41
|
export const PERSONA_STATES = ["idle", "thinking", "working", "waiting", "done", "error"];
|
|
33
42
|
|
|
34
43
|
const state = (expression, motion, bubbles) => ({ expression, motion, bubbles });
|
|
35
44
|
|
|
36
|
-
|
|
45
|
+
|
|
37
46
|
export const DEFAULT_PERSONA_CARDS = Object.freeze([
|
|
38
47
|
{
|
|
39
48
|
schema: PERSONA_SCHEMA,
|
|
@@ -149,21 +158,19 @@ export const DEFAULT_PERSONA_CARDS = Object.freeze([
|
|
|
149
158
|
]);
|
|
150
159
|
|
|
151
160
|
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
161
|
|
|
155
162
|
const isText = (v) => typeof v === "string" && v.trim() !== "";
|
|
156
|
-
|
|
163
|
+
|
|
157
164
|
const isLocalized = (v) =>
|
|
158
165
|
isText(v) || (v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).length > 0 && Object.values(v).every(isText));
|
|
159
166
|
const isTextList = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
|
|
160
167
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
|
|
167
174
|
export function validatePersonaCard(card) {
|
|
168
175
|
const fail = (error) => ({ ok: false, error });
|
|
169
176
|
if (!card || typeof card !== "object" || Array.isArray(card)) return fail("A persona card must be a JSON object.");
|
|
@@ -171,6 +178,7 @@ export function validatePersonaCard(card) {
|
|
|
171
178
|
if (typeof card.id !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(card.id)) {
|
|
172
179
|
return fail('"id" must be 1–64 characters: lowercase letters, digits and "-".');
|
|
173
180
|
}
|
|
181
|
+
if (card.id === NO_PERSONA_ID) return fail(`"id" cannot be "${NO_PERSONA_ID}": that word means "no persona card".`);
|
|
174
182
|
if (!isLocalized(card.name)) return fail('"name" must be a string, or an object of language → string.');
|
|
175
183
|
if (!isLocalized(card.summary)) return fail('"summary" must be a string, or an object of language → string.');
|
|
176
184
|
for (const field of ["identity", "speaking_style", "rhythm"]) {
|
|
@@ -216,10 +224,10 @@ export function validatePersonaCard(card) {
|
|
|
216
224
|
return { ok: true, card };
|
|
217
225
|
}
|
|
218
226
|
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
|
|
223
231
|
export function parsePersonaCard(text) {
|
|
224
232
|
let card;
|
|
225
233
|
try {
|
|
@@ -230,12 +238,12 @@ export function parsePersonaCard(text) {
|
|
|
230
238
|
return validatePersonaCard(card);
|
|
231
239
|
}
|
|
232
240
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
|
|
239
247
|
export function personaPromptText(card) {
|
|
240
248
|
if (!card || typeof card !== "object") return "";
|
|
241
249
|
const picked = {};
|
|
@@ -244,12 +252,12 @@ export function personaPromptText(card) {
|
|
|
244
252
|
return `<persona_card owner="user">\n${json}\n</persona_card>`;
|
|
245
253
|
}
|
|
246
254
|
|
|
247
|
-
|
|
255
|
+
|
|
248
256
|
export function personaPromptBytes(card) {
|
|
249
257
|
return Buffer.byteLength(personaPromptText(card), "utf8");
|
|
250
258
|
}
|
|
251
259
|
|
|
252
|
-
|
|
260
|
+
|
|
253
261
|
export function createPersonaCardStore({ dir }) {
|
|
254
262
|
const file = join(dir, "persona-cards.json");
|
|
255
263
|
let cache = null;
|
|
@@ -273,13 +281,13 @@ export function createPersonaCardStore({ dir }) {
|
|
|
273
281
|
return {
|
|
274
282
|
file,
|
|
275
283
|
imported: () => load().map((c) => structuredClone(c)),
|
|
276
|
-
|
|
284
|
+
|
|
277
285
|
all: () => [...DEFAULT_PERSONA_CARDS.map((c) => structuredClone(c)), ...load().map((c) => structuredClone(c))],
|
|
278
286
|
get(id) {
|
|
279
287
|
const card = DEFAULT_PERSONA_CARDS.find((c) => c.id === id) ?? load().find((c) => c.id === id);
|
|
280
288
|
return card ? structuredClone(card) : null;
|
|
281
289
|
},
|
|
282
|
-
|
|
290
|
+
|
|
283
291
|
import(card) {
|
|
284
292
|
const checked = validatePersonaCard(card);
|
|
285
293
|
if (!checked.ok) throw Object.assign(new Error(checked.error), { code: "bad-persona-card" });
|
|
@@ -298,22 +306,26 @@ export function createPersonaCardStore({ dir }) {
|
|
|
298
306
|
};
|
|
299
307
|
}
|
|
300
308
|
|
|
301
|
-
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
|
|
302
315
|
export function activePersonaCard(store, prefs) {
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
store.get(DEFAULT_PERSONA_ID)
|
|
307
|
-
);
|
|
316
|
+
const id = prefs?.personaCard;
|
|
317
|
+
if (typeof id !== "string" || id === "" || id === NO_PERSONA_ID) return null;
|
|
318
|
+
return store.get(id) ?? null;
|
|
308
319
|
}
|
|
309
320
|
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
|
|
317
329
|
export function createPersonaRoutes({ store, prefs }) {
|
|
318
330
|
return async function handlePersona(req, res, rest, method) {
|
|
319
331
|
if (rest === "/persona") {
|
|
@@ -321,7 +333,7 @@ export function createPersonaRoutes({ store, prefs }) {
|
|
|
321
333
|
sendError(res, 405, "method-not-allowed");
|
|
322
334
|
return true;
|
|
323
335
|
}
|
|
324
|
-
sendJson(res, 200, { ok: true, active: activePersonaCard(store(), prefs())
|
|
336
|
+
sendJson(res, 200, { ok: true, active: activePersonaCard(store(), prefs())?.id ?? null, cards: store().all() });
|
|
325
337
|
return true;
|
|
326
338
|
}
|
|
327
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
|
+
};
|