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

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.
@@ -0,0 +1,206 @@
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
+
32
+ export const SCHEDULES_FEATURE = "schedules";
33
+
34
+ const ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
35
+ const TITLE_MAX = 120;
36
+ const PROMPT_MAX = 32 * 1024;
37
+ const HISTORY_LIMIT = 20;
38
+ const PROMPT_VIEW_MAX = 16 * 1024;
39
+
40
+ const str = (v) => (typeof v === "string" ? v : undefined);
41
+ const clamp = (s, max) => (typeof s === "string" && s.length > max ? `${s.slice(0, max)}…` : s);
42
+
43
+
44
+ export function scheduleView(entry) {
45
+ if (!entry || typeof entry !== "object" || typeof entry.id !== "string") return null;
46
+ const target = entry.target && typeof entry.target === "object"
47
+ ? { kind: str(entry.target.kind) ?? "unknown", ...(str(entry.target.sessionId) ? { sessionId: entry.target.sessionId } : {}) }
48
+ : null;
49
+ const last = entry.lastDelivery && typeof entry.lastDelivery === "object"
50
+ ? { deliveredAt: str(entry.lastDelivery.deliveredAt) ?? null, targetSessionId: str(entry.lastDelivery.targetSessionId) ?? null }
51
+ : null;
52
+ const timing = { kind: str(entry.kind) ?? "unknown" };
53
+ for (const key of ["afterSeconds", "everySeconds"]) if (Number.isFinite(entry[key])) timing[key] = entry[key];
54
+ for (const key of ["time", "timeZone", "expression", "rrule"]) if (str(entry[key])) timing[key] = entry[key];
55
+ if (Array.isArray(entry.weekdays)) timing.weekdays = entry.weekdays.filter((d) => Number.isInteger(d));
56
+ return {
57
+ id: entry.id,
58
+ title: str(entry.title) ?? "",
59
+ prompt: clamp(str(entry.prompt) ?? "", PROMPT_VIEW_MAX),
60
+ status: ["active", "paused", "ended"].includes(entry.status) ? entry.status : "unknown",
61
+ timing,
62
+
63
+ nextAt: str(entry.scheduledAt) ?? null,
64
+ createdAt: str(entry.createdAt) ?? null,
65
+ updatedAt: str(entry.updatedAt) ?? null,
66
+ running: entry.executionActive === true,
67
+ target,
68
+ lastDelivery: last,
69
+ };
70
+ }
71
+
72
+ const receiptView = (r) => ({
73
+ scheduledAt: str(r?.scheduledAt) ?? null,
74
+ deliveredAt: str(r?.deliveredAt) ?? null,
75
+ targetSessionId: str(r?.targetSessionId) ?? null,
76
+ });
77
+
78
+
79
+ export function schedulePatchOf(body) {
80
+ if (!body || typeof body !== "object" || Array.isArray(body)) return { error: "body must be an object" };
81
+ const patch = {};
82
+ if (body.title !== undefined) {
83
+ if (typeof body.title !== "string" || !body.title.trim()) return { error: "title must be a non-empty string" };
84
+ if (body.title.trim().length > TITLE_MAX) return { error: `title is at most ${TITLE_MAX} characters` };
85
+ patch.title = body.title.trim();
86
+ }
87
+ if (body.prompt !== undefined) {
88
+ if (typeof body.prompt !== "string" || !body.prompt.trim()) return { error: "prompt must be a non-empty string" };
89
+ if (body.prompt.length > PROMPT_MAX) return { error: "prompt is too long" };
90
+ patch.prompt = body.prompt;
91
+ }
92
+ if (body.active !== undefined) {
93
+ if (typeof body.active !== "boolean") return { error: "active must be true or false" };
94
+ patch.active = body.active;
95
+ }
96
+ if (Object.keys(patch).length === 0) return { error: "nothing to change" };
97
+ const expected = body.expectedUpdatedAt;
98
+ if (expected !== undefined && expected !== null && typeof expected !== "string") return { error: "expectedUpdatedAt must be a string or null" };
99
+ return { patch, expectedUpdatedAt: expected };
100
+ }
101
+
102
+
103
+ function answerMiss(res, result) {
104
+ if (result?.code === "schedule_not_found") { sendError(res, 404, "schedule-not-found"); return true; }
105
+ if (result?.code === "schedule_conflict") { sendError(res, 409, "schedule-conflict", "the task changed on the computer; reload it"); return true; }
106
+ if (result?.code === "schedule_execution_pending") { sendError(res, 409, "schedule-execution-pending", "this task is already being delivered"); return true; }
107
+ return false;
108
+ }
109
+ function answerThrown(res, err) {
110
+ const code = typeof err?.code === "string" ? err.code : undefined;
111
+
112
+ const inputCode = code && code !== "schedule/input-invalid" ? code : err?.details?.code;
113
+ if (inputCode && /^[a-z_]+$/.test(inputCode)) return sendError(res, 400, "schedule-invalid", `${inputCode}: ${String(err?.message ?? "")}`.slice(0, 300));
114
+ return sendError(res, 500, "schedule-failed", String(err?.message ?? err).slice(0, 300));
115
+ }
116
+
117
+
118
+
119
+
120
+ export function createScheduleRoutes({ service, logger }) {
121
+ const svc = () => {
122
+ try {
123
+ const s = service();
124
+ return s && typeof s.catalog === "function" && typeof s.edit === "function" ? s : undefined;
125
+ } catch {
126
+ return undefined;
127
+ }
128
+ };
129
+ const readJsonBody = async (req, res) => {
130
+ try {
131
+ return JSON.parse(await readBody(req)) ?? {};
132
+ } catch (err) {
133
+ sendError(res, err?.status === 413 ? 413 : 400, err?.status === 413 ? "payload-too-large" : "bad-request");
134
+ return undefined;
135
+ }
136
+ };
137
+
138
+ return async function handleSchedules(req, res, rest, method, url) {
139
+ if (rest !== "/schedules" && !rest.startsWith("/schedules/")) return false;
140
+ const s = svc();
141
+ if (!s) {
142
+ sendError(res, 503, "schedule-unavailable", "this computer's DSH does not offer scheduled tasks");
143
+ return true;
144
+ }
145
+ try {
146
+ if (rest === "/schedules") {
147
+ if (method !== "GET" && method !== "HEAD") { sendError(res, 405, "method-not-allowed"); return true; }
148
+ const entries = await s.catalog();
149
+ const items = (Array.isArray(entries) ? entries : []).map(scheduleView).filter(Boolean);
150
+ sendJson(res, 200, { ok: true, items, total: items.length });
151
+ return true;
152
+ }
153
+ const m = /^\/schedules\/([^/]+)(\/run)?$/.exec(rest);
154
+ if (!m) { sendError(res, 404, "not-found"); return true; }
155
+ let id;
156
+ try { id = decodeURIComponent(m[1]); } catch { id = ""; }
157
+ if (!ID_RE.test(id)) { sendError(res, 400, "bad-schedule-id"); return true; }
158
+ if (m[2]) {
159
+ if (method !== "POST") { sendError(res, 405, "method-not-allowed"); return true; }
160
+ const result = await s.run({ id });
161
+ if (answerMiss(res, result)) return true;
162
+ sendJson(res, 200, { ok: true, item: scheduleView(result) });
163
+ return true;
164
+ }
165
+ if (method === "GET" || method === "HEAD") {
166
+ const result = await s.view({ id });
167
+ if (answerMiss(res, result)) return true;
168
+ let history = [];
169
+ if (typeof s.history === "function") {
170
+ try {
171
+ const page = await s.history({ id, limit: HISTORY_LIMIT });
172
+ if (Array.isArray(page?.records)) history = page.records.map(receiptView);
173
+ } catch (err) {
174
+ logger?.debug?.(`mobile-remote: schedule history ${id}: ${err?.message ?? err}`);
175
+ }
176
+ }
177
+ sendJson(res, 200, { ok: true, item: scheduleView(result), history });
178
+ return true;
179
+ }
180
+ if (method === "PATCH") {
181
+ const body = await readJsonBody(req, res);
182
+ if (body === undefined) return true;
183
+ const parsed = schedulePatchOf(body);
184
+ if (parsed.error) { sendError(res, 400, "bad-request", parsed.error); return true; }
185
+ const result = await s.edit({ id, action: "update", patch: parsed.patch, ...(parsed.expectedUpdatedAt !== undefined ? { expectedUpdatedAt: parsed.expectedUpdatedAt } : {}) });
186
+ if (answerMiss(res, result)) return true;
187
+ sendJson(res, 200, { ok: true, item: scheduleView(result) });
188
+ return true;
189
+ }
190
+ if (method === "DELETE") {
191
+
192
+ if (url?.searchParams?.get("confirm") !== "1") { sendError(res, 400, "confirmation-required", "deleting a task needs confirm=1"); return true; }
193
+ const expected = url.searchParams.get("expectedUpdatedAt");
194
+ const result = await s.edit({ id, action: "delete", ...(expected ? { expectedUpdatedAt: expected } : {}) });
195
+ if (answerMiss(res, result)) return true;
196
+ sendJson(res, 200, { ok: true, deleted: result?.deleted === true, id });
197
+ return true;
198
+ }
199
+ sendError(res, 405, "method-not-allowed");
200
+ return true;
201
+ } catch (err) {
202
+ answerThrown(res, err);
203
+ return true;
204
+ }
205
+ };
206
+ }
@@ -0,0 +1,89 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+ import { sendError, sendJson } from "./http-util.js";
22
+
23
+
24
+ export const AGENT_TEAM_FEATURE = "agent-team";
25
+
26
+ const MAX_TASKS = 256;
27
+ const TEXT_MAX = 4000;
28
+
29
+ const str = (v) => (typeof v === "string" ? v : undefined);
30
+ const clamp = (s, max) => (typeof s === "string" && s.length > max ? `${s.slice(0, max)}…` : s);
31
+
32
+
33
+ export function teamTaskView(t) {
34
+ if (!t || typeof t !== "object" || typeof t.id !== "string") return null;
35
+ return {
36
+ id: t.id,
37
+ subject: clamp(str(t.subject) ?? "", 500),
38
+ description: clamp(str(t.description) ?? "", TEXT_MAX),
39
+ status: ["pending", "in_progress", "completed"].includes(t.status) ? t.status : "unknown",
40
+ ready: t.ready === true,
41
+ blockedBy: Array.isArray(t.blockedBy) ? t.blockedBy.filter((x) => typeof x === "string").slice(0, 64) : [],
42
+ ownerId: str(t.ownerId) ?? null,
43
+ ownerName: str(t.ownerName) ?? null,
44
+ writeScopes: Array.isArray(t.writeScopes) ? t.writeScopes.filter((x) => typeof x === "string").slice(0, 32) : [],
45
+ warnings: Array.isArray(t.writeScopeWarnings) ? t.writeScopeWarnings.filter((x) => typeof x === "string").slice(0, 16) : [],
46
+ };
47
+ }
48
+
49
+
50
+
51
+
52
+
53
+ export function createTeamRoutes({ service, agents, logger }) {
54
+ const get = (fn) => {
55
+ try { return fn(); } catch { return undefined; }
56
+ };
57
+ return async function handleTeam(req, res, rest, method, url) {
58
+ if (rest !== "/team/tasks") return false;
59
+ if (method !== "GET" && method !== "HEAD") { sendError(res, 405, "method-not-allowed"); return true; }
60
+ const svc = get(service);
61
+ if (!svc || typeof svc.listTasks !== "function") {
62
+ sendError(res, 503, "team-unavailable", "this computer's DSH does not offer agent teams");
63
+ return true;
64
+ }
65
+ const sessionId = url?.searchParams?.get("sessionId") ?? "";
66
+ if (!sessionId) { sendError(res, 400, "bad-request", "missing sessionId"); return true; }
67
+ const agent = get(() => agents()?.get?.(sessionId));
68
+ if (!agent) {
69
+ sendJson(res, 200, { ok: true, sessionId, enabled: null, tasks: null });
70
+ return true;
71
+ }
72
+ let enabled = null;
73
+ try {
74
+ if (typeof svc.isEnabled === "function") enabled = svc.isEnabled(agent) === true;
75
+ } catch (err) {
76
+ logger?.debug?.(`mobile-remote: team isEnabled ${sessionId}: ${err?.message ?? err}`);
77
+ }
78
+ try {
79
+ const list = await svc.listTasks(agent);
80
+ const tasks = (Array.isArray(list) ? list : []).slice(0, MAX_TASKS).map(teamTaskView).filter(Boolean);
81
+ sendJson(res, 200, { ok: true, sessionId, enabled, tasks });
82
+ } catch (err) {
83
+
84
+ logger?.debug?.(`mobile-remote: team listTasks ${sessionId}: ${err?.message ?? err}`);
85
+ sendJson(res, 200, { ok: true, sessionId, enabled, tasks: null });
86
+ }
87
+ return true;
88
+ };
89
+ }