@alexsun-top/opencode-chat-room 0.5.2 → 0.5.4

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 (46) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +28 -215
  3. package/README.zh-CN.md +27 -209
  4. package/docs/administrator-rooms.md +6 -22
  5. package/package.json +1 -4
  6. package/plugin.ts +1 -1
  7. package/server/admin-auth.ts +4 -2
  8. package/server/admin-routes.ts +2 -11
  9. package/server/admin-state.ts +15 -4
  10. package/server/assets/base.css +1 -1
  11. package/server/assets/chat/admin.js +30 -123
  12. package/server/assets/chat/announcements.js +17 -1
  13. package/server/assets/chat/attachments.js +4 -1
  14. package/server/assets/chat/editor.js +65 -15
  15. package/server/assets/chat/events.js +12 -7
  16. package/server/assets/chat/markdown.js +31 -11
  17. package/server/assets/chat/mentions.js +3 -1
  18. package/server/assets/chat/messages.js +55 -20
  19. package/server/assets/chat/questions.js +15 -4
  20. package/server/assets/chat/reminders.js +4 -3
  21. package/server/assets/chat/replies.js +2 -1
  22. package/server/assets/chat/room-watcher.js +45 -0
  23. package/server/assets/chat/rooms.js +62 -69
  24. package/server/assets/chat/state.js +8 -6
  25. package/server/assets/conversation.css +8 -5
  26. package/server/assets/responsive.css +5 -12
  27. package/server/chat-server.ts +26 -37
  28. package/server/chat.html +3 -10
  29. package/server/member-routes.ts +9 -11
  30. package/server/room-reminders.ts +15 -5
  31. package/server/wake.ts +11 -2
  32. package/skills/chatroom/SKILL.md +3 -7
  33. package/src/admin-client.ts +8 -45
  34. package/src/admin-credentials.ts +0 -19
  35. package/src/center-inbox.ts +0 -2
  36. package/src/mentions.ts +2 -1
  37. package/src/plugin-notifications.ts +4 -3
  38. package/src/resource-upload.ts +1 -1
  39. package/src/resources.ts +4 -1
  40. package/src/sqlite-state.ts +40 -0
  41. package/src/store.ts +4 -1
  42. package/src/v2-plugin.ts +1 -1
  43. package/server/admin-plan-routes.ts +0 -79
  44. package/server/admin-scheduler.ts +0 -42
  45. package/server/admin-task-routes.ts +0 -182
  46. package/src/supervision-inbox.ts +0 -62
package/server/chat.html CHANGED
@@ -113,17 +113,10 @@
113
113
  <dialog id="adminDialog" class="admin-dialog" aria-labelledby="adminHeading">
114
114
  <header class="admin-dialog-head"><h2 id="adminHeading" data-i18n="administration">Administration</h2><div class="admin-dialog-actions"><button id="btnRefreshAdmin" class="btn ghost small" type="button" data-i18n="refreshAdmin">Refresh</button><button id="btnCloseAdmin" class="reader-close" type="button" aria-label="Close" data-i18n-aria-label="close">×</button></div></header>
115
115
  <p id="adminStatus" class="hint" role="status" aria-live="polite"></p>
116
- <div class="admin-columns">
117
- <section><h3 data-i18n="designations">Designations</h3><p class="hint admin-scope-note" data-i18n="adminScopeNote">An administrator manages every room, including this one and rooms created later. The Agent room below is where the selected Agent is a member; it does not limit access.</p><label class="field"><span class="field-label" data-i18n="adminRoom">Administrator room</span><select id="adminRoomSelect" class="admin-select"></select></label>
118
- <label class="field"><span class="field-label" data-i18n="targetRoom">Agent membership room</span><select id="adminTargetRoom" class="admin-select"></select></label>
116
+ <div class="admin-guide"><p class="hint admin-scope-note" data-i18n="adminBindingGuide">Choose a room, then select a registered member. They must privately accept the invitation to finish setup.</p><label class="field"><span class="field-label" data-i18n="adminRoomLabel">Room to administer</span><select id="adminRoomSelect" class="admin-select"></select></label>
119
117
  <label class="field"><span class="field-label" data-i18n="targetAgent">Registered agent</span><select id="adminTargetAgent" class="admin-select"></select></label>
120
- <button id="btnDesignateAgent" class="btn primary small" type="button" data-i18n="designate">Designate and issue enrollment</button><div id="adminEnrollment" class="admin-enrollment" hidden></div>
118
+ <button id="btnDesignateAgent" class="btn primary small" type="button" data-i18n="adminDesignateAgent">Designate agent</button><div id="adminEnrollment" class="admin-enrollment" hidden></div>
121
119
  <button id="btnRevokeAdmin" class="btn ghost small danger-text" type="button" data-i18n="revokeDesignation">Revoke designation</button>
122
- </section>
123
- <section><h3 data-i18n="globalStatus">Global status</h3><div id="adminOverview" class="admin-overview"></div><h3 data-i18n="adminTasks">Tasks</h3>
124
- <form id="adminTaskForm"><label class="field"><span class="field-label" data-i18n="taskTargetRoom">Target room</span><select id="adminTaskRoom" class="admin-select"></select></label><label class="field"><span class="field-label" data-i18n="taskTargetAgent">Target agent</span><select id="adminTaskAgent" class="admin-select"></select></label><label class="field"><span class="field-label" data-i18n="taskText">Task</span><textarea id="adminTaskText" class="input" rows="2" maxlength="2000" required></textarea></label><button class="btn primary small" type="submit" data-i18n="dispatchTask">Dispatch task</button></form><ul id="adminTaskList" class="admin-list"></ul>
125
- <h3 data-i18n="timers">Timers</h3><form id="adminPlanForm" class="admin-plan-form"><input id="adminPlanName" class="input" maxlength="64" required data-i18n-placeholder="planName" placeholder="Timer name"><input id="adminPlanInterval" class="input" type="number" min="60" max="2592000" value="3600" required><textarea id="adminPlanText" class="input" rows="2" maxlength="2000" required></textarea><button class="btn primary small" type="submit" data-i18n="createTimer">Create timer</button></form><ul id="adminPlanList" class="admin-list"></ul>
126
- </section>
127
120
  </div>
128
121
  </dialog>
129
122
  <button id="roomDrawerBackdrop" class="room-drawer-backdrop" type="button" aria-label="Close room list" data-i18n-aria-label="closeRoomList" hidden></button>
@@ -161,7 +154,7 @@
161
154
  <label class="field"><span class="field-label" data-i18n="reminderTimezone">Timezone override (optional)</span><input id="reminderTimezone" class="input" autocomplete="off"></label>
162
155
  <p class="hint" data-i18n="reminderTimezoneHint">Leave blank to use the server timezone. Enter an IANA timezone to override it.</p>
163
156
  <label class="field"><span class="field-label" data-i18n="reminderText">Reminder text</span><textarea id="reminderText" class="input" rows="3" maxlength="1000" required></textarea></label>
164
- <p class="hint" data-i18n="reminderTemplateHint">Use {time}, {initiator}, and {room} in your message.</p>
157
+ <p id="reminderTemplateHint" class="hint" data-i18n="reminderTemplateHint">Use {{time}}, {{initiator}}, and {{room}} in your message.</p>
165
158
  <button class="btn primary small" type="submit" data-i18n="reminderCreate">Create reminder</button>
166
159
  </form>
167
160
  </section>
@@ -1,9 +1,10 @@
1
1
  import { memberActivity, type WorkState } from "../src/member-state";
2
- import { acknowledgeReadWithReceipts, readReceipts, readState, recordMessageReceipts, reportPresence, writeState, type ReceiptEvidence, type ReceiptIdentity } from "../src/store";
2
+ import { acknowledgeRead, acknowledgeReadWithReceipts, readReceipts, readState, recordMessageReceipts, reportPresence, type ReceiptEvidence, type ReceiptIdentity } from "../src/store";
3
3
  import { isReceiverOwnerID } from "../src/receiver-owner";
4
4
  import { clearPendingAdmission } from "../src/queue";
5
5
  import { touchActive } from "./wake";
6
6
  import { announcementRoutes } from "./announcement-routes";
7
+ import { jsonObject } from "./json-body";
7
8
 
8
9
  const json = (body: unknown, status = 200) => Response.json(body, { status });
9
10
  const states = new Set<WorkState>(["working", "idle", "waiting", "unknown"]);
@@ -17,7 +18,8 @@ export async function memberRoutes(req: Request, url: URL): Promise<Response | u
17
18
  const announcements = await announcementRoutes(req, url);
18
19
  if (announcements) return announcements;
19
20
  if (req.method === "POST" && url.pathname === "/read") {
20
- const body = (await req.json()) as Record<string, unknown>;
21
+ const body = await jsonObject<Record<string, unknown>>(req);
22
+ if (!body) return json({ error: "JSON object body is required" }, 400);
21
23
  const ts = body.ts;
22
24
  const roomId = String(body.roomId ?? "");
23
25
  const sessionID = String(body.sessionID ?? "");
@@ -48,15 +50,11 @@ export async function memberRoutes(req: Request, url: URL): Promise<Response | u
48
50
  touchActive(sessionID);
49
51
  return json({ ok: true, acceptedIDs: result.acceptedIDs });
50
52
  }
51
- const updated = await writeState((svc, reg) => {
52
- const entry = reg[roomId]?.[sessionID];
53
- if (!entry) return false;
54
- const actualTs = Math.min(ts, svc.getMessages(roomId).at(-1)?.createdAt ?? 0);
55
- if (actualTs > 0) entry.lastReadTs = Math.max(entry.lastReadTs ?? 0, actualTs);
56
- return { actualTs };
57
- });
58
- if (!updated) return json({ error: "registry entry not found" }, 404);
59
- clearPendingAdmission(sessionID, roomId, updated.actualTs);
53
+ // Read watermark is the hottest write path; update the registry row directly
54
+ // instead of rewriting every room and message.
55
+ const actualTs = await acknowledgeRead(roomId, sessionID, ts);
56
+ if (actualTs === null) return json({ error: "registry entry not found" }, 404);
57
+ clearPendingAdmission(sessionID, roomId, actualTs);
60
58
  touchActive(sessionID);
61
59
  return json({ ok: true });
62
60
  }
@@ -2,6 +2,7 @@ import { Cron } from "croner";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { databasePath } from "../src/store";
4
4
  import { initializeReminderSchema, withStateTransaction } from "../src/sqlite-state";
5
+ import type { Message } from "../src/room-service";
5
6
 
6
7
  type Schedule = { type: "once"; at: string; timezone?: string } | { type: "cron"; expression: string; timezone: string };
7
8
  type Row = { id: string; room_id: string; creator_session_id: string; initiator: string; text: string; schedule_type: string; at: string | null; expression: string | null; timezone: string | null; paused: number; next_run_at: number; created_at: number; last_error: string | null };
@@ -105,7 +106,8 @@ function template(text: string, at: number, initiator: string, room: string, tim
105
106
  const parts = Object.fromEntries(new Intl.DateTimeFormat("en-US", { timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23", timeZoneName: "longOffset" }).formatToParts(at).map(part => [part.type, part.value]));
106
107
  return `${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second} ${parts.timeZoneName} [${timezone}]`;
107
108
  })() : new Date(at).toISOString();
108
- const result = text.replace(/\{(time|initiator|room)\}/g, (_m, key: string) => key === "time" ? time : key === "initiator" ? initiator : room);
109
+ const result = text.replace(/\{\{(time|initiator|room)\}\}/g, (_m, key: string) =>
110
+ key === "time" ? time : key === "initiator" ? initiator : room);
109
111
  if (result.length > 2000) throw new Error("rendered reminder text exceeds 2000 characters");
110
112
  return result;
111
113
  }
@@ -171,11 +173,14 @@ export async function roomReminderRoutes(req: Request, url: URL): Promise<Respon
171
173
  return json(bodyOut, status);
172
174
  }
173
175
 
174
- export async function tickRoomReminders(now = Date.now()): Promise<void> {
176
+ export type ReminderWake = (roomId: string, roomName: string, text: string, message: Message) => void | Promise<void>;
177
+
178
+ export async function tickRoomReminders(now = Date.now(), wake?: ReminderWake): Promise<void> {
175
179
  await initializeReminderSchema(dbFile());
176
180
  const ids = await withStateTransaction(dbFile(), db => (db.query("SELECT id FROM room_reminders WHERE paused=0 AND next_run_at<=? ORDER BY next_run_at LIMIT 100").all(now) as Array<{ id: string }>).map(row => row.id));
177
181
  const failures: Array<{ id: string; error: string }> = [];
178
182
  for (const id of ids) {
183
+ let delivered: { roomName: string; message: Message } | undefined;
179
184
  const failure = await withStateTransaction(dbFile(), db => {
180
185
  const r = db.query("SELECT * FROM room_reminders WHERE id=? AND paused=0 AND next_run_at<=?").get(id, now) as Row | null;
181
186
  if (!r) return null;
@@ -188,7 +193,9 @@ export async function tickRoomReminders(now = Date.now()): Promise<void> {
188
193
  : (() => { throw new Error(`unsupported reminder schedule type: ${r.schedule_type}`); })();
189
194
  const tail = db.query("SELECT created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1").get(r.room_id) as { created_at: number } | null;
190
195
  const sentAt = Math.max(now, (tail?.created_at ?? 0) + 1), text = template(r.text, sentAt, r.initiator, room.name, r.timezone ?? undefined);
191
- db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question) VALUES(?,?, 'system',NULL,?,?,0)").run(randomUUID(), r.room_id, text, sentAt);
196
+ const message: Message = { id: `reminder:${randomUUID()}`, roomId: r.room_id, senderId: "system", text, createdAt: sentAt };
197
+ db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question) VALUES(?,?, 'system',NULL,?,?,0)").run(message.id, r.room_id, text, sentAt);
198
+ delivered = { roomName: room.name, message };
192
199
  if (upcoming === undefined) db.query("DELETE FROM room_reminders WHERE id=?").run(r.id);
193
200
  else db.query("UPDATE room_reminders SET next_run_at=?,last_error=NULL WHERE id=?").run(upcoming, r.id);
194
201
  })();
@@ -200,13 +207,16 @@ export async function tickRoomReminders(now = Date.now()): Promise<void> {
200
207
  }
201
208
  });
202
209
  if (failure) failures.push(failure);
210
+ else if (delivered && wake) {
211
+ try { await wake(delivered.message.roomId, delivered.roomName, delivered.message.text, delivered.message); } catch { /* Inbox polling remains the fallback. */ }
212
+ }
203
213
  }
204
214
  for (const failure of failures) console.error(`room reminder ${failure.id} paused after delivery error: ${failure.error}`);
205
215
  }
206
216
 
207
217
  let timer: ReturnType<typeof setInterval> | undefined;
208
- export function startRoomReminderScheduler(): void {
218
+ export function startRoomReminderScheduler(wake?: ReminderWake): void {
209
219
  if (timer) return;
210
- timer = setInterval(() => { void tickRoomReminders().catch(() => {}); }, 1000);
220
+ timer = setInterval(() => { void tickRoomReminders(Date.now(), wake).catch(() => {}); }, 1000);
211
221
  timer.unref?.();
212
222
  }
package/server/wake.ts CHANGED
@@ -11,12 +11,21 @@ const activeSessions = new Map<string, number>();
11
11
  const WAKE_CLAIM_MS = 30_000;
12
12
  const WAKE_INACTIVE_MS = 2 * 60_000;
13
13
 
14
+ const MAX_TRACKED = 10_000;
15
+ function track(map: Map<string, number>, id: string, ttl: number): void {
16
+ map.set(id, Date.now());
17
+ if (map.size <= MAX_TRACKED) return;
18
+ const floor = Date.now() - ttl;
19
+ for (const [key, at] of map) if (at < floor) map.delete(key);
20
+ for (const key of map.keys()) { if (map.size <= MAX_TRACKED) break; map.delete(key); }
21
+ }
22
+
14
23
  export function claimWake(id: string): boolean {
15
24
  if (Date.now() - (wakeClaims.get(id) ?? 0) < WAKE_CLAIM_MS) return false;
16
- wakeClaims.set(id, Date.now());
25
+ track(wakeClaims, id, WAKE_CLAIM_MS);
17
26
  return true;
18
27
  }
19
- export function touchActive(id: string): void { if (id) activeSessions.set(id, Date.now()); }
28
+ export function touchActive(id: string): void { if (id) track(activeSessions, id, WAKE_INACTIVE_MS); }
20
29
 
21
30
  export async function wakeMentionedSessions(
22
31
  serveWakeUrl: string, roomId: string, roomName: string, text: string,
@@ -77,7 +77,7 @@ Names must be non-empty and no longer than 64 Unicode characters after trimming.
77
77
 
78
78
  Current room members can create, list, pause, resume, and delete reminders with `room` actions `reminder_create`, `reminder_list`, `reminder_update`, and `reminder_delete`. Create with `roomId`, `text`, and `schedule`: use `{ "type": "once", "at": "2026-11-11T09:00:00", "timezone": "Asia/Shanghai" }` or `{ "type": "cron", "expression": "0 9 * * 1-5", "timezone": "Asia/Shanghai" }`. Timezone is optional and defaults to the server's timezone. Updates use `reminderId` and one or more of `schedule`, `text`, and `paused`; deletion uses `reminderId`.
79
79
 
80
- Templates support `{time}`, `{initiator}`, and `{room}`. The server posts the rendered system message to the room. Missed recurring occurrences coalesce into one; a missed one-time reminder fires once after recovery. Reminders continue if their creator leaves. Ambiguous or nonexistent daylight-saving local times must be disambiguated with an explicit offset.
80
+ Templates support `{{time}}`, `{{initiator}}`, and `{{room}}`. The server posts the rendered system message to the room. Missed recurring occurrences coalesce into one; a missed one-time reminder fires once after recovery. Reminders continue if their creator leaves. Ambiguous or nonexistent daylight-saving local times must be disambiguated with an explicit offset.
81
81
 
82
82
  ## Share files and media
83
83
 
@@ -87,7 +87,7 @@ In central mode, upload a local file with the room tool:
87
87
  {"action":"upload_resource","roomId":"<room-id>","filePath":"<local-file-path>"}
88
88
  ```
89
89
 
90
- The plugin requests host file-read permissions and returns resource metadata and a `[[resource:<UUID>]]` marker. Include that marker in a normal `send` message, with a short description. Uploading does not send a message or join the room. Upload only when already authorized to participate in that room; do not join automatically to share a file.
90
+ The plugin requests host file-read permissions and returns resource metadata and a `[[resource:<UUID>]]` marker. Uploading alone is invisible: the attachment renders only when the exact marker appears in a sent message, so include it unchanged in a normal `send` message with a short description, outside backticks or code blocks. Do not paraphrase it, shorten the UUID, or mention it only as prose. Uploading does not send a message or join the room. Upload only when already authorized to participate in that room; do not join automatically to share a file.
91
91
 
92
92
  Respect permission denials and do not upload secrets or unrelated files. A local path is read on the machine running the plugin, not on the central server; remote URLs are not upload paths. The server sets the single-file size limit, defaulting to 500 MiB. Images, audio, and video may preview in the browser; other formats are offered as downloads. Resource markers refer to the room where the file was uploaded, not arbitrary filesystem paths or public links.
93
93
 
@@ -99,11 +99,7 @@ The separate `admin` tool supports operator-enrolled administrator rooms in cent
99
99
 
100
100
  When the user privately supplies an enrollment instruction, call `admin` with `action: "admin_claim"`, `roomId`, and `enrollmentKey` in that designated session. Never post the enrollment key in a room. The plugin stores the resulting capability privately; do not request, copy, or expose it. If enrollment fails, ask the operator to reset it.
101
101
 
102
- For a designated supervisor, `admin_overview` lists rooms, members, tasks, and plans. Use `admin_dispatch` with the administrator `roomId`, `targetRoomId`, `targetSessionID`, and `text` to assign work to an existing Agent without joining its room. Use `admin_history` for bounded target-room history and `admin_tasks` to inspect assignments. Room names or display names are not substitutes for target session IDs.
103
-
104
- Workers receiving an assignment can call `admin` with `action: "task_progress"`, `taskId`, `status`, and `progress`. Supported states are `pending`, `working`, `blocked`, `completed`, and `cancelled`. Report actual progress and blockers; a received steer is not evidence that work is complete. Do not join the administrator room to report progress.
105
-
106
- Use `admin_plan_create`, `admin_plans`, `admin_plan_update`, and `admin_plan_delete` for recurring supervision authorized by the user. Timers persist on the server and coalesce offline reminders; they do not guarantee execution while the host is unavailable. Check task reports and concrete evidence before declaring completion. Pause or delete a plan when its purpose ends.
102
+ For a designated supervisor, `admin_overview` lists rooms and members; `admin_history` reads bounded target-room history. To assign work, send a room message to the intended Agent. For scheduled work, create a room reminder containing the task and an @ mention.
107
103
 
108
104
  ## Testing and subagents
109
105
 
@@ -1,26 +1,20 @@
1
- import { loadAdminCapability, loadTaskToken, saveAdminCapability, type AdminIdentity } from "./admin-credentials";
1
+ import { loadAdminCapability, saveAdminCapability, type AdminIdentity } from "./admin-credentials";
2
2
  import type { CenterOpts } from "./center-client";
3
3
  import type { QueueTransport } from "./queue-transport";
4
4
  import { z } from "zod";
5
5
 
6
6
  export type AdminContext = { sessionID: string };
7
7
  export type AdminArgs = {
8
- action: "task_progress" | "admin_claim" | "admin_overview" | "admin_history" | "admin_dispatch" | "admin_tasks" |
9
- "admin_task_update" | "admin_plans" | "admin_plan_create" | "admin_plan_update" | "admin_plan_delete";
10
- roomId?: string; enrollmentKey?: string; targetRoomId?: string; targetSessionID?: string;
11
- text?: string; name?: string; intervalSeconds?: number; planId?: string; taskId?: string;
12
- status?: "pending" | "working" | "blocked" | "completed" | "cancelled";
13
- progress?: string; paused?: boolean; limit?: number;
8
+ action: "admin_claim" | "admin_overview" | "admin_history";
9
+ roomId?: string; enrollmentKey?: string; targetRoomId?: string;
10
+ limit?: number;
14
11
  };
15
12
  export const adminToolSchema = z.object({
16
- action: z.enum(["task_progress", "admin_claim", "admin_overview", "admin_history", "admin_dispatch", "admin_tasks", "admin_task_update", "admin_plans", "admin_plan_create", "admin_plan_update", "admin_plan_delete"]),
13
+ action: z.enum(["admin_claim", "admin_overview", "admin_history"]),
17
14
  roomId: z.string().optional(), enrollmentKey: z.string().optional(), targetRoomId: z.string().optional(),
18
- targetSessionID: z.string().optional(), text: z.string().max(2000).optional(), name: z.string().max(64).optional(),
19
- intervalSeconds: z.number().int().min(60).max(2_592_000).optional(), planId: z.string().optional(), taskId: z.string().optional(),
20
- status: z.enum(["pending", "working", "blocked", "completed", "cancelled"]).optional(), progress: z.string().max(2000).optional(), paused: z.boolean().optional(),
21
15
  limit: z.number().int().min(1).max(50).optional(),
22
16
  });
23
- export const adminToolDescription = "Administer an operator-enrolled room: overview, history, task dispatch, task progress, and plans. This tool never joins a room.";
17
+ export const adminToolDescription = "Administer an operator-designated room: overview and history. This tool never joins a room.";
24
18
  const safe = (value: string) => encodeURIComponent(value);
25
19
 
26
20
  async function send(opts: CenterOpts, path: string, method: string, body?: unknown,
@@ -51,20 +45,6 @@ export function protectedAdminRequest(opts: CenterOpts, path: string, method: "G
51
45
  export async function adminTool(args: AdminArgs, context: AdminContext, opts: CenterOpts,
52
46
  transport: QueueTransport): Promise<string> {
53
47
  if (!opts.center) return "error: admin actions require central mode";
54
- if (args.action === "task_progress") {
55
- if (!args.taskId || !args.status || args.progress === undefined || args.progress.length > 2000) return "error: taskId, status, and progress (up to 2000 characters) are required";
56
- if (transport.protocol === "v2" && !transport.receiverOwnerID) return "error: this runtime has no verified receiver owner identity";
57
- const deliveryToken = await loadTaskToken({ center: opts.center, taskId: args.taskId, sessionID: context.sessionID, ownerID: transport.receiverOwnerID ?? "" });
58
- if (!deliveryToken) return "error: no task progress token for this task and session";
59
- try {
60
- await send(opts, `/supervision/tasks/${safe(args.taskId)}/progress`, "POST",
61
- { taskToken: deliveryToken, status: args.status, progress: args.progress }, undefined, context.sessionID, transport.receiverOwnerID ?? "");
62
- return "task progress updated";
63
- } catch (error) {
64
- const message = error instanceof Error ? error.message : "task progress update failed";
65
- return `error: ${message.replaceAll(deliveryToken, "[redacted]")}`;
66
- }
67
- }
68
48
  const roomId = args.roomId?.trim();
69
49
  if (!roomId) return "error: roomId is required";
70
50
  const ownerID = transport.receiverOwnerID;
@@ -87,8 +67,8 @@ export async function adminTool(args: AdminArgs, context: AdminContext, opts: Ce
87
67
  }
88
68
  if (transport.protocol === "v2" && !ownerID) return "error: this runtime has no verified receiver owner identity";
89
69
  const identity: AdminIdentity = { center: opts.center, roomId, sessionID: context.sessionID, ownerID: ownerID ?? "" };
90
- const capability = await loadAdminCapability(identity);
91
- if (!capability) return "error: no admin binding for this session; ask the operator to enroll this agent";
70
+ // Designation is immediate; a claimed capability is only sent when one exists.
71
+ const capability = (await loadAdminCapability(identity)) ?? "";
92
72
  const root = `/admin/rooms/${safe(roomId)}`;
93
73
  const request = (route: string, method: string, body?: unknown) =>
94
74
  send(opts, `${root}${route}`, method, body, capability, context.sessionID, ownerID ?? "");
@@ -103,23 +83,6 @@ export async function adminTool(args: AdminArgs, context: AdminContext, opts: Ce
103
83
  query.set("limit", String(Math.min(50, Math.max(1, args.limit ?? 20))));
104
84
  result = await request(`/history?${query}`, "GET"); break;
105
85
  }
106
- case "admin_dispatch":
107
- if (!args.targetRoomId || !args.targetSessionID || !args.text?.trim()) return "error: targetRoomId, targetSessionID, and text are required";
108
- result = await request("/tasks", "POST", { targetRoomId: args.targetRoomId, targetSessionID: args.targetSessionID, text: args.text.trim() }); break;
109
- case "admin_tasks": result = await request("/tasks", "GET"); break;
110
- case "admin_task_update":
111
- if (!args.taskId || !args.status) return "error: taskId and status are required";
112
- result = await request(`/tasks/${safe(args.taskId)}`, "PATCH", { status: args.status, ...(args.progress === undefined ? {} : { progress: args.progress }) }); break;
113
- case "admin_plans": result = await request("/plans", "GET"); break;
114
- case "admin_plan_create":
115
- if (!args.name?.trim() || !args.text?.trim() || !args.intervalSeconds) return "error: name, intervalSeconds, and text are required";
116
- result = await request("/plans", "POST", { name: args.name.trim(), intervalSeconds: args.intervalSeconds, text: args.text.trim() }); break;
117
- case "admin_plan_update":
118
- if (!args.planId || args.paused === undefined) return "error: planId and paused are required";
119
- result = await request(`/plans/${safe(args.planId)}`, "PATCH", { paused: args.paused }); break;
120
- case "admin_plan_delete":
121
- if (!args.planId) return "error: planId is required";
122
- result = await request(`/plans/${safe(args.planId)}`, "DELETE"); break;
123
86
  default: return "error: unsupported admin action";
124
87
  }
125
88
  return JSON.stringify(result);
@@ -4,7 +4,6 @@ import path from "node:path";
4
4
  import { statePath } from "./store";
5
5
 
6
6
  export type AdminIdentity = { center: string; roomId: string; sessionID: string; ownerID: string };
7
- export type TaskIdentity = { center: string; taskId: string; sessionID: string; ownerID: string };
8
7
  const keyOf = (identity: AdminIdentity) => createHash("sha256").update(JSON.stringify([
9
8
  new URL(identity.center).origin, identity.roomId, identity.sessionID, identity.ownerID,
10
9
  ])).digest("hex");
@@ -12,13 +11,6 @@ const keyOf = (identity: AdminIdentity) => createHash("sha256").update(JSON.stri
12
11
  function credentialPath(identity: AdminIdentity): string {
13
12
  return path.join(path.dirname(statePath()), "admin-capabilities", `${keyOf(identity)}.json`);
14
13
  }
15
- function taskPath(identity: TaskIdentity): string {
16
- const key = createHash("sha256").update(JSON.stringify([
17
- new URL(identity.center).origin, identity.taskId, identity.sessionID, identity.ownerID,
18
- ])).digest("hex");
19
- return path.join(path.dirname(statePath()), "supervision-tokens", `${key}.json`);
20
- }
21
-
22
14
  async function persist(file: string, content: unknown): Promise<void> {
23
15
  const directory = path.dirname(file);
24
16
  await mkdir(directory, { recursive: true, mode: 0o700 });
@@ -45,14 +37,3 @@ export async function saveAdminCapability(identity: AdminIdentity, capability: s
45
37
  const file = credentialPath(identity);
46
38
  await persist(file, { origin: new URL(identity.center).origin, capability });
47
39
  }
48
-
49
- export async function loadTaskToken(identity: TaskIdentity): Promise<string | undefined> {
50
- try {
51
- const data = JSON.parse(await readFile(taskPath(identity), "utf8")) as { origin?: unknown; taskToken?: unknown };
52
- return data.origin === new URL(identity.center).origin && typeof data.taskToken === "string" ? data.taskToken : undefined;
53
- } catch { return undefined; }
54
- }
55
-
56
- export async function saveTaskToken(identity: TaskIdentity, taskToken: string): Promise<void> {
57
- await persist(taskPath(identity), { origin: new URL(identity.center).origin, taskToken });
58
- }
@@ -13,7 +13,6 @@ import { explicitlyAddresses } from "./mentions";
13
13
  import { claimBackgroundAttempt } from "./receiver-state";
14
14
  import { prepareReceiptCandidate, receiptDestination } from "./agent-receipts";
15
15
  import { serializeSessionPush } from "./session-delivery";
16
- import { checkSupervisionInbox } from "./supervision-inbox";
17
16
  export { serializeSessionPush } from "./session-delivery";
18
17
  import {
19
18
  sendAsyncNotification,
@@ -69,7 +68,6 @@ export async function checkCenterInbox(
69
68
  items = [...merged.values()].sort((a, b) => a.createdAt - b.createdAt);
70
69
  }
71
70
  await pushItemsToSession(opts, sessionID, items, transport, queued, qualified);
72
- await checkSupervisionInbox(opts, sessionID, transport);
73
71
  });
74
72
  } catch {
75
73
  // The next inbox poll retries failed delivery.
package/src/mentions.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { QueueItem } from "./queue";
2
2
 
3
3
  export function explicitlyMentions(item: QueueItem, recipient: string, sessionID?: string): boolean {
4
- if (!recipient.trim() || item.senderId === "system" || (sessionID !== undefined && item.senderSessionID === sessionID)) return false;
4
+ if (!recipient.trim() || (item.senderId === "system" && !item.id?.startsWith("reminder:")) || (sessionID !== undefined && item.senderSessionID === sessionID)) return false;
5
5
  const broadcast = /(?<![\p{L}\p{N}_.@])(?:<at>)?@(?:all|所有人)(?:<\/at>)?(?![\p{L}\p{N}_])/u.exec(item.text);
6
6
  if (broadcast && broadcast.index + broadcast[0].length <= 300) return true;
7
7
  const escaped = recipient.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -11,5 +11,6 @@ export function explicitlyMentions(item: QueueItem, recipient: string, sessionID
11
11
 
12
12
  export function explicitlyAddresses(item: QueueItem, recipient: string, sessionID?: string, roomKind?: "group" | "direct"): boolean {
13
13
  if (roomKind !== "direct") return explicitlyMentions(item, recipient, sessionID);
14
+ if (item.senderId === "system") return item.id?.startsWith("reminder:") ? explicitlyMentions(item, recipient, sessionID) : false;
14
15
  return item.senderId !== "system" && item.senderId !== sessionID && item.senderSessionID !== sessionID;
15
16
  }
@@ -96,10 +96,11 @@ export function createNotifier(deps: {
96
96
  const service = backgroundServiceKey(targetTransport);
97
97
  const cutoff = Math.max(entry.lastReadTs ?? 0, entry.lastQueuedTs ?? 0);
98
98
  prunePendingAdmission(sessionID, batch.roomId, cutoff, (items) => render(batch, entry.name, roomKind, items));
99
- const unread = batch.messages.filter((m) =>
99
+ const unreadAll = batch.messages.filter((m) =>
100
100
  m.createdAt > cutoff &&
101
101
  (m.senderSessionID !== undefined ? m.senderSessionID !== sessionID : m.senderId !== (roomKind === "direct" ? sessionID : entry.name)),
102
- ).slice(0, 20).map((item) => ({ ...item, roomKind }));
102
+ );
103
+ const unread = unreadAll.slice(-20).map((item) => ({ ...item, roomKind }));
103
104
  const existing = pendingAdmission(sessionID, batch.roomId);
104
105
  if (!unread.length && existing?.state !== "pending") return undefined;
105
106
  const maxTs = unread.reduce((max, m) => Math.max(max, m.createdAt), 0);
@@ -108,7 +109,7 @@ export function createNotifier(deps: {
108
109
  : unread;
109
110
  const eligibleItems = existing?.state === "pending" ? existing.items : delta.slice(-20);
110
111
  if (mentionOnly && !eligibleItems.some((message) => explicitlyAddresses(message, entry.name, sessionID, roomKind)) &&
111
- !delta.slice(-20).some((message) => explicitlyAddresses(message, entry.name, sessionID, roomKind))) return undefined;
112
+ !unreadAll.some((message) => explicitlyAddresses(message, entry.name, sessionID, roomKind))) return undefined;
112
113
  const base = entry.serverUrl ? new URL(entry.serverUrl) : undefined;
113
114
  const prefix = entry.protocol === "v2" ? (entry.apiPrefix || "/api").replace(/^\/+|\/+$/g, "") : "";
114
115
  const endpoint = entry.protocol === "v2" ? "prompt" : "prompt_async";
@@ -41,7 +41,7 @@ export async function uploadAgentResource(opts: UploadOptions, roomID: string, f
41
41
  });
42
42
  const data = await response.json().catch(() => ({})) as { resource?: Resource; error?: string };
43
43
  if (!response.ok || !data.resource) throw new Error(data.error ?? `upload failed (${response.status})`);
44
- return `${JSON.stringify(data.resource)}\n[[resource:${data.resource.id}]]`;
44
+ return `${JSON.stringify(data.resource)}\n[[resource:${data.resource.id}]]\nThe upload alone is invisible. To display this attachment, include the marker above unchanged in a send message, outside backticks or code blocks.`;
45
45
  }
46
46
 
47
47
  function inside(root: string, file: string): boolean {
package/src/resources.ts CHANGED
@@ -27,7 +27,10 @@ function mime(bytes: Uint8Array): string {
27
27
  if (String.fromCharCode(...bytes.slice(0, 4)) === "RIFF" && String.fromCharCode(...bytes.slice(8, 12)) === "WAVE") return "audio/wav";
28
28
  if (String.fromCharCode(...bytes.slice(0, 3)) === "ID3" || (bytes[0] === 0xff && (bytes[1]! & 0xe0) === 0xe0)) return "audio/mpeg";
29
29
  if (String.fromCharCode(...bytes.slice(0, 4)) === "OggS") return "audio/ogg";
30
- if (String.fromCharCode(...bytes.slice(4, 8)) === "ftyp") return "video/mp4";
30
+ if (String.fromCharCode(...bytes.slice(4, 8)) === "ftyp") {
31
+ const brand = String.fromCharCode(...bytes.slice(8, 12));
32
+ return brand === "avif" || brand === "avis" ? "image/avif" : "video/mp4";
33
+ }
31
34
  if (starts(0x1a, 0x45, 0xdf, 0xa3)) return "video/webm";
32
35
  return "application/octet-stream";
33
36
  }
@@ -360,6 +360,24 @@ export async function answerQuestion(file: string, roomID: string, questionID: s
360
360
  });
361
361
  }
362
362
 
363
+ export async function appendRoomMessage(file: string, roomID: string, sessionID: string, text: string, isQuestion: boolean): Promise<{ status: "ok"; message: Message } | { status: "missing" | "member" }> {
364
+ const db = await openStateDatabase(file);
365
+ return immediate(db, () => {
366
+ if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return { status: "missing" };
367
+ const member = db.query("SELECT g.name,r.kind FROM registry g JOIN rooms r ON r.id=g.room_id JOIN participants p ON p.room_id=g.room_id AND p.id=CASE WHEN r.kind='direct' THEN g.session_id ELSE g.name END WHERE g.room_id=? AND g.session_id=?").get(roomID, sessionID) as { name: string; kind: string } | null;
368
+ if (!member) return { status: "member" };
369
+ const tail = db.query("SELECT created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1").get(roomID) as { created_at: number } | null;
370
+ const message: Message = {
371
+ id: randomUUID(), roomId: roomID, senderId: member.kind === "direct" ? sessionID : member.name,
372
+ senderSessionID: sessionID, text, createdAt: Math.max(Date.now(), (tail?.created_at ?? 0) + 1),
373
+ ...(isQuestion ? { isQuestion: true } : {}),
374
+ };
375
+ db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question) VALUES(?,?,?,?,?,?,?)")
376
+ .run(message.id, roomID, message.senderId, sessionID, text, message.createdAt, isQuestion ? 1 : 0);
377
+ return { status: "ok", message };
378
+ });
379
+ }
380
+
363
381
  export async function sendReply(file: string, roomID: string, targetID: string, sessionID: string, text: string): Promise<{ status: "ok"; message: Message } | { status: "missing" | "member" | "target" | "question" }> {
364
382
  const db = await openStateDatabase(file);
365
383
  return immediate(db, () => {
@@ -450,6 +468,28 @@ export async function readMessageReceipts(file: string, roomID: string, messageI
450
468
  }).deferred();
451
469
  }
452
470
 
471
+ export async function acknowledgeQueued(file: string, roomID: string, sessionID: string, ts: number): Promise<number | null> {
472
+ const db = await openStateDatabase(file);
473
+ return immediate(db, () => {
474
+ if (!db.query("SELECT 1 FROM registry WHERE room_id=? AND session_id=?").get(roomID, sessionID)) return null;
475
+ const tail = db.query("SELECT created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1").get(roomID) as { created_at: number } | null;
476
+ const capped = Math.min(ts, tail?.created_at ?? 0);
477
+ db.query("UPDATE registry SET last_queued_ts=max(coalesce(last_queued_ts,0),?) WHERE room_id=? AND session_id=?").run(capped, roomID, sessionID);
478
+ return capped;
479
+ });
480
+ }
481
+
482
+ export async function acknowledgeRead(file: string, roomID: string, sessionID: string, ts: number): Promise<number | null> {
483
+ const db = await openStateDatabase(file);
484
+ return immediate(db, () => {
485
+ if (!db.query("SELECT 1 FROM registry WHERE room_id=? AND session_id=?").get(roomID, sessionID)) return null;
486
+ const tail = db.query("SELECT created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1").get(roomID) as { created_at: number } | null;
487
+ const actualTs = Math.min(ts, tail?.created_at ?? 0);
488
+ if (actualTs > 0) db.query("UPDATE registry SET last_read_ts=max(coalesce(last_read_ts,0),?) WHERE room_id=? AND session_id=?").run(actualTs, roomID, sessionID);
489
+ return actualTs;
490
+ });
491
+ }
492
+
453
493
  export async function writeMessageReceipts(file: string, roomID: string, sessionID: string, messageIDs: string[], evidence: ReceiptEvidence, identity: ReceiptIdentity, readAt: number, readThroughTs?: number): Promise<ReceiptWriteResult> {
454
494
  if (!messageIDs.length || messageIDs.length > 500 || messageIDs.some((id) => typeof id !== "string" || !id || id.length > 128) || !["displayed", "tool", "context"].includes(evidence)) return { status: "messageIDs", acceptedIDs: [] };
455
495
  const ids = [...new Set(messageIDs)];
package/src/store.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  import path from "node:path";
5
5
  import os from "node:os";
6
6
  import RoomService, { type Message, type Room } from "./room-service";
7
- import { answerQuestion as sqliteAnswerQuestion, sendReply as sqliteSendReply, readHistoryPage, readInboxPage as sqliteInboxPage, readMessageReceipts, readQuestionExcerpt as sqliteQuestionExcerpt, readQuestions as sqliteReadQuestions, readSqliteState, readUnreadPage, writeMessageReceipts, writePresenceState, writeSqliteState, type HistoryMessage } from "./sqlite-state";
7
+ import { acknowledgeQueued as sqliteAcknowledgeQueued, acknowledgeRead as sqliteAcknowledgeRead, answerQuestion as sqliteAnswerQuestion, appendRoomMessage as sqliteAppendRoomMessage, sendReply as sqliteSendReply, readHistoryPage, readInboxPage as sqliteInboxPage, readMessageReceipts, readQuestionExcerpt as sqliteQuestionExcerpt, readQuestions as sqliteReadQuestions, readSqliteState, readUnreadPage, writeMessageReceipts, writePresenceState, writeSqliteState, type HistoryMessage } from "./sqlite-state";
8
8
 
9
9
  export function statePath(): string {
10
10
  // JSON path remains the migration source; SQLite lives beside it.
@@ -35,8 +35,11 @@ export async function readHistory(roomID: string, beforeSeq?: number, limit = 10
35
35
  return readHistoryPage(databasePath(), roomID, beforeSeq, limit, exclude?.sessionID, exclude?.name);
36
36
  }
37
37
  export async function readQuestions(roomID: string): Promise<Message[]> { return sqliteReadQuestions(databasePath(), roomID); }
38
+ export function acknowledgeRead(roomID: string, sessionID: string, ts: number) { return sqliteAcknowledgeRead(databasePath(), roomID, sessionID, ts); }
39
+ export function acknowledgeQueued(roomID: string, sessionID: string, ts: number) { return sqliteAcknowledgeQueued(databasePath(), roomID, sessionID, ts); }
38
40
  export async function answerQuestion(roomID: string, questionID: string, sessionID: string, text: string) { return sqliteAnswerQuestion(databasePath(), roomID, questionID, sessionID, text); }
39
41
  export async function sendReply(roomID: string, targetID: string, sessionID: string, text: string) { return sqliteSendReply(databasePath(), roomID, targetID, sessionID, text); }
42
+ export function appendRoomMessage(roomID: string, sessionID: string, text: string, isQuestion: boolean) { return sqliteAppendRoomMessage(databasePath(), roomID, sessionID, text, isQuestion); }
40
43
  export async function readQuestionExcerpt(roomID: string, questionID: string) { return sqliteQuestionExcerpt(databasePath(), roomID, questionID); }
41
44
 
42
45
  export async function loadRooms(): Promise<Room[]> {
package/src/v2-plugin.ts CHANGED
@@ -80,7 +80,7 @@ export function createV2Setup(deps: {
80
80
  });
81
81
  toolRegistration = await context.tool.transform((editor) => editor.add({
82
82
  name: "room",
83
- description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements; manage reminders. Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup.",
83
+ description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements; manage reminders. Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media; upload_resource returns a [[resource:UUID]] marker, and the attachment renders only when that exact marker is included in a send message. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup.",
84
84
  options: { codemode: false },
85
85
  input: roomSchema(),
86
86
  execute: async (args, toolContext) => {
@@ -1,79 +0,0 @@
1
- import { hasAdminCapability, isOperator } from "./admin-auth";
2
- import type { Database } from "bun:sqlite";
3
- import { binding, exec, many, one, tx, validCurrent } from "./admin-state";
4
- import type { Binding } from "./admin-state";
5
-
6
- const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
7
- const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
8
- const auth = (request: Request, b: Binding) => isOperator(request) || hasAdminCapability(request, b);
9
- const planRows = (db: Database, id: string) => many(db,
10
- "SELECT id,admin_room_id AS adminRoomId,name,interval_seconds AS intervalSeconds,text,paused,next_run_at AS nextRunAt,created_at AS createdAt FROM admin_plans WHERE admin_room_id=? ORDER BY created_at DESC LIMIT 200", id);
11
-
12
- export async function adminPlanRoutes(request: Request, url: URL): Promise<Response | undefined> {
13
- const base = url.pathname.match(/^\/admin\/rooms\/([^/]+)\/plans$/);
14
- const child = url.pathname.match(/^\/admin\/rooms\/([^/]+)\/plans\/([^/]+)$/);
15
- if (!base && !child) return undefined;
16
- const roomID = decodeURIComponent((base ?? child)![1]!);
17
- if (base && request.method === "GET") return tx(db => {
18
- const b = binding(db, roomID);
19
- if (!b) return { error: "admin room not found", status: 404 };
20
- if (!auth(request, b)) return { error: "unauthorized", status: 401 };
21
- if (!isOperator(request) && !validCurrent(db, b)) return { error: "binding is no longer active", status: 409 };
22
- return { plans: planRows(db, roomID) };
23
- }).then(result => "status" in result ? json({ error: result.error }, result.status) : json(result));
24
- if (base && request.method === "POST") return createPlan(request, roomID);
25
- if (child && request.method === "PATCH") return updatePlan(request, roomID, decodeURIComponent(child[2]!));
26
- if (child && request.method === "DELETE") return deletePlan(request, roomID, decodeURIComponent(child[2]!));
27
- return json({ error: "method not allowed" }, 405);
28
- }
29
-
30
- async function createPlan(request: Request, roomID: string): Promise<Response> {
31
- const body: unknown = await request.json();
32
- if (!object(body) || typeof body.name !== "string" || !body.name.trim() || body.name.trim().length > 64 ||
33
- typeof body.text !== "string" || !body.text.trim() || body.text.trim().length > 2000 ||
34
- !Number.isInteger(body.intervalSeconds) || (body.intervalSeconds as number) < 60 || (body.intervalSeconds as number) > 2_592_000) return json({ error: "invalid plan" }, 400);
35
- const name = body.name.trim(), text = body.text.trim(), interval = body.intervalSeconds as number;
36
- const result = await tx(db => {
37
- const b = binding(db, roomID);
38
- if (!b) return { status: 404 as const };
39
- if (!auth(request, b)) return { status: 401 as const };
40
- if (!validCurrent(db, b)) return { status: 409 as const };
41
- const id = crypto.randomUUID(), now = Date.now();
42
- exec(db, "INSERT INTO admin_plans VALUES(?,?,?,?,?,0,?,?)", id, roomID, name, interval, text, now + interval * 1000, now);
43
- return { plan: { id, adminRoomId: roomID, name, intervalSeconds: interval, text, paused: false, nextRunAt: now + interval * 1000, createdAt: now } };
44
- });
45
- if ("status" in result) return json({ error: result.status === 401 ? "unauthorized" : result.status === 404 ? "admin room not found" : "binding is no longer active" }, result.status);
46
- return json(result, 201);
47
- }
48
-
49
- async function updatePlan(request: Request, roomID: string, planID: string): Promise<Response> {
50
- const body: unknown = await request.json();
51
- if (!object(body) || typeof body.paused !== "boolean") return json({ error: "paused must be boolean" }, 400);
52
- const result = await tx(db => {
53
- const b = binding(db, roomID);
54
- if (!b) return { status: 404 as const };
55
- if (!auth(request, b)) return { status: 401 as const };
56
- if (!validCurrent(db, b)) return { status: 409 as const };
57
- const plan = one<{ id: string; next_run_at: number; interval_seconds: number }>(db,
58
- "SELECT id,next_run_at,interval_seconds FROM admin_plans WHERE id=? AND admin_room_id=?", planID, roomID);
59
- if (!plan) return { status: 404 as const };
60
- const next = body.paused ? plan.next_run_at : Date.now() + plan.interval_seconds * 1000;
61
- exec(db, "UPDATE admin_plans SET paused=?,next_run_at=? WHERE id=?", body.paused ? 1 : 0, next, planID);
62
- if (body.paused) exec(db, "DELETE FROM admin_deliveries WHERE admin_room_id=? AND kind='supervision' AND task_id=? AND acknowledged=0", roomID, `plan:${planID}`);
63
- return { ok: true, nextRunAt: next };
64
- });
65
- if ("status" in result) return json({ error: result.status === 401 ? "unauthorized" : result.status === 404 ? "plan not found" : "binding is no longer active" }, result.status);
66
- return json(result);
67
- }
68
-
69
- async function deletePlan(request: Request, roomID: string, planID: string): Promise<Response> {
70
- const result = await tx(db => {
71
- const b = binding(db, roomID);
72
- if (!b) return 404;
73
- if (!auth(request, b)) return 401;
74
- if (!validCurrent(db, b)) return 409;
75
- exec(db, "DELETE FROM admin_deliveries WHERE admin_room_id=? AND kind='supervision' AND task_id=? AND acknowledged=0", roomID, `plan:${planID}`);
76
- return exec(db, "DELETE FROM admin_plans WHERE id=? AND admin_room_id=?", planID, roomID).changes ? 200 : 404;
77
- });
78
- return json(result === 200 ? { ok: true } : { error: result === 401 ? "unauthorized" : result === 409 ? "binding is no longer active" : "plan not found" }, result);
79
- }