@alexsun-top/opencode-chat-room 0.5.1 → 0.5.3

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 (49) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +28 -207
  3. package/README.zh-CN.md +27 -201
  4. package/docs/administrator-rooms.md +6 -22
  5. package/package.json +4 -5
  6. package/plugin.ts +19 -4
  7. package/server/admin-routes.ts +2 -11
  8. package/server/admin-state.ts +15 -4
  9. package/server/assets/base.css +10 -0
  10. package/server/assets/chat/admin.js +67 -128
  11. package/server/assets/chat/attachments.js +1 -1
  12. package/server/assets/chat/editor.js +248 -0
  13. package/server/assets/chat/events.js +13 -11
  14. package/server/assets/chat/index.js +4 -0
  15. package/server/assets/chat/mentions.js +38 -28
  16. package/server/assets/chat/message-window.js +18 -0
  17. package/server/assets/chat/messages.js +49 -57
  18. package/server/assets/chat/questions.js +115 -43
  19. package/server/assets/chat/receipts.js +0 -1
  20. package/server/assets/chat/reminders.js +102 -0
  21. package/server/assets/chat/replies.js +150 -0
  22. package/server/assets/chat/room-watcher.js +37 -0
  23. package/server/assets/chat/rooms.js +59 -70
  24. package/server/assets/chat/state.js +29 -9
  25. package/server/assets/conversation.css +33 -9
  26. package/server/assets/responsive.css +15 -16
  27. package/server/chat-server.ts +21 -2
  28. package/server/chat.html +23 -13
  29. package/server/inbox.ts +5 -1
  30. package/server/room-reminders.ts +222 -0
  31. package/server/wake.ts +6 -3
  32. package/skills/chatroom/SKILL.md +11 -7
  33. package/src/admin-client.ts +6 -43
  34. package/src/admin-credentials.ts +0 -19
  35. package/src/agent-receipts.ts +13 -18
  36. package/src/mentions.ts +2 -1
  37. package/src/plugin-notifications.ts +4 -0
  38. package/src/queue.ts +7 -2
  39. package/src/reminder-client.ts +50 -0
  40. package/src/resource-read.ts +118 -0
  41. package/src/resource-upload.ts +1 -1
  42. package/src/resources.ts +1 -1
  43. package/src/sqlite-state.ts +43 -3
  44. package/src/store.ts +22 -8
  45. package/src/supervision-inbox.ts +6 -18
  46. package/src/v2-plugin.ts +11 -5
  47. package/server/admin-plan-routes.ts +0 -79
  48. package/server/admin-scheduler.ts +0 -42
  49. package/server/admin-task-routes.ts +0 -182
@@ -1,23 +1,18 @@
1
1
  import { request, type CenterOpts } from "./center-client";
2
2
  import { sendAsyncNotification, sendQueue, type QueueTransport } from "./queue-transport";
3
- import { loadAdminCapability, saveTaskToken } from "./admin-credentials";
3
+ import { loadAdminCapability } from "./admin-credentials";
4
4
  import { protectedAdminRequest } from "./admin-client";
5
5
 
6
- type Delivery = { id: string; admissionID?: string; adminRoomId?: string; kind: "task" | "supervision"; text: string; taskId?: string; taskToken?: string; targetRoomId?: string };
6
+ type Delivery = { id: string; admissionID?: string; adminRoomId?: string; kind: "supervision"; text: string };
7
7
  type Inbox = { deliveries?: Delivery[]; supervisionRoomIds?: string[] };
8
8
 
9
- function promptText(item: Delivery, taskToken?: string): string {
10
- const text = taskToken ? item.text.replaceAll(taskToken, "[redacted]") : item.text;
11
- if (item.kind === "task") {
12
- const source = item.targetRoomId ? ` Target room: ${item.targetRoomId}.` : "";
13
- return `<supervision>Task from admin room ${item.adminRoomId}.${source} Task ID: ${item.taskId}. Report progress using admin(action="task_progress", taskId="${item.taskId}", status="working", progress="...").\nTask: ${text}</supervision>`;
14
- }
15
- return `<supervision>Reminder from admin room ${item.adminRoomId}. Use admin(action="admin_overview", roomId="${item.adminRoomId}") to review it.\n${text}</supervision>`;
9
+ function promptText(item: Delivery): string {
10
+ return `<supervision>Reminder from admin room ${item.adminRoomId}. Use admin(action="admin_overview", roomId="${item.adminRoomId}") to review it.\n${item.text}</supervision>`;
16
11
  }
17
12
 
18
13
  async function push(opts: CenterOpts, sessionID: string, ownerID: string, transport: QueueTransport,
19
14
  item: Delivery, capability?: string): Promise<void> {
20
- const text = promptText(item, capability ?? item.taskToken);
15
+ const raw = promptText(item), text = capability ? raw.replaceAll(capability, "[redacted]") : raw;
21
16
  const admissionID = item.admissionID ?? item.id;
22
17
  const result = transport.protocol === "v1" ? await sendAsyncNotification(transport, sessionID, text)
23
18
  : await sendQueue(transport, sessionID, text, admissionID, "steer");
@@ -37,13 +32,6 @@ export async function checkSupervisionInbox(opts: CenterOpts, sessionID: string,
37
32
  } catch { return; }
38
33
  if (!inbox || typeof inbox !== "object") return;
39
34
 
40
- for (const item of (Array.isArray(inbox.deliveries) ? inbox.deliveries : []).slice(0, 50)) {
41
- if (item?.kind !== "task" || !item.id || !item.taskId || !item.taskToken || typeof item.text !== "string") continue;
42
- try { await saveTaskToken({ center: opts.center, taskId: item.taskId, sessionID, ownerID }, item.taskToken); }
43
- catch { continue; }
44
- try { await push(opts, sessionID, ownerID, transport, item); } catch { /* Retry the durable item next sweep. */ }
45
- }
46
-
47
35
  const hintedRooms = Array.isArray(inbox.supervisionRoomIds)
48
36
  ? [...new Set(inbox.supervisionRoomIds.filter((room): room is string => typeof room === "string" && !!room))].slice(0, 50)
49
37
  : [];
@@ -57,6 +45,6 @@ export async function checkSupervisionInbox(opts: CenterOpts, sessionID: string,
57
45
  if (item?.kind !== "supervision" || item.adminRoomId !== roomId || !item.id || typeof item.text !== "string") continue;
58
46
  try { await push(opts, sessionID, ownerID, transport, item, capability); } catch { /* Retry with the same server-issued ID next sweep. */ }
59
47
  }
60
- } catch { /* A room's protected feed does not block other admin rooms or task delivery. */ }
48
+ } catch { /* A room's protected feed does not block other admin rooms. */ }
61
49
  }
62
50
  }
package/src/v2-plugin.ts CHANGED
@@ -20,7 +20,7 @@ export type V2Runtime = {
20
20
  export function createV2Setup(deps: {
21
21
  runtime(directory: string, transport: QueueTransport): V2Runtime;
22
22
  run<T>(runtime: V2Runtime, callback: () => T): T;
23
- execute(args: z.infer<ReturnType<typeof roomSchema>>, sessionID: string, permissionContext: { directory: string; worktree?: string; ask(input: { permission: string; patterns: string[]; always: string[]; metadata: Record<string, unknown> }): Promise<void> }): Promise<string>;
23
+ execute(args: z.infer<ReturnType<typeof roomSchema>>, sessionID: string, permissionContext: { directory: string; worktree?: string; signal?: AbortSignal; ask(input: { permission: string; patterns: string[]; always: string[]; metadata: Record<string, unknown> }): Promise<void> }): Promise<string>;
24
24
  admin?: (args: z.infer<typeof adminToolSchema>, sessionID: string, transport: QueueTransport, center: CenterOptions) => Promise<string>;
25
25
  observe(runtime: V2Runtime, sessionID: string): Promise<void>;
26
26
  poll(sessions: ReadonlySet<string>, transport: QueueTransport, center: CenterOptions): Promise<void>;
@@ -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; upload files and media",
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) => {
@@ -90,6 +90,7 @@ export function createV2Setup(deps: {
90
90
  const permissionContext = {
91
91
  directory: context.location.directory,
92
92
  worktree: context.location.directory,
93
+ signal: toolContext.signal,
93
94
  ask: (input: { permission: string; patterns: string[]; always: string[]; metadata: Record<string, unknown> }) => context.permission.assert({
94
95
  sessionID: toolContext.sessionID,
95
96
  agent: toolContext.agent,
@@ -100,7 +101,8 @@ export function createV2Setup(deps: {
100
101
  source: { type: "tool", messageID: toolContext.messageID, id: toolContext.id },
101
102
  }),
102
103
  };
103
- return { content: [{ type: "text", text: await deps.execute(args, toolContext.sessionID, permissionContext) }] };
104
+ const result = await deps.execute(args, toolContext.sessionID, permissionContext);
105
+ return { content: [{ type: "text", text: result }] };
104
106
  });
105
107
  },
106
108
  }));
@@ -148,16 +150,20 @@ export function createV2Setup(deps: {
148
150
  };
149
151
  }
150
152
 
151
- function roomSchema() {
153
+ export function roomSchema() {
152
154
  return z.object({
153
- action: z.enum(["create", "join", "leave", "list", "send", "poll", "members", "upload_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete"]),
155
+ action: z.enum(["create", "join", "leave", "list", "send", "poll", "members", "upload_resource", "read_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete"]),
154
156
  name: z.string().max(64).optional().describe("For join: your own participant display name, NOT the room name (required). For create: the new room name."),
155
157
  roomId: z.string().optional(),
158
+ resourceId: z.string().optional(),
156
159
  filePath: z.string().optional().describe("Local regular file to upload; central mode only; requires host read permission."),
157
160
  text: z.string().max(2000).optional(),
158
161
  isQuestion: z.boolean().optional(),
159
162
  announcementName: z.string().optional().describe("Name of a room announcement; distinct from participant or room name."),
160
163
  content: z.string().optional().describe("Announcement content, at most 5000 Unicode characters."),
164
+ reminderId: z.string().optional(),
165
+ schedule: z.discriminatedUnion("type", [z.object({ type: z.literal("once"), at: z.string(), timezone: z.string().refine((value) => { try { new Intl.DateTimeFormat("en", { timeZone: value }); return true; } catch { return false; } }, "timezone must be an IANA timezone").optional() }), z.object({ type: z.literal("cron"), expression: z.string().regex(/^\S+\s+\S+\s+\S+\s+\S+\s+\S+$/), timezone: z.string().refine((value) => { try { new Intl.DateTimeFormat("en", { timeZone: value }); return true; } catch { return false; } }, "timezone must be an IANA timezone").optional() })]).optional(),
166
+ paused: z.boolean().optional(),
161
167
  }).superRefine((args, ctx) => {
162
168
  if (args.action === "join" && !args.name?.trim()) {
163
169
  ctx.addIssue({ code: "custom", path: ["name"], message: "name is required to join a room" });
@@ -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
- }
@@ -1,42 +0,0 @@
1
- import { binding, exec, many, tx, validCurrent } from "./admin-state";
2
- import { randomUUID } from "node:crypto";
3
-
4
- type PlanRow = { id: string; admin_room_id: string; interval_seconds: number; next_run_at: number; text: string };
5
- type OpenTask = { text: string; status: string; progress: string };
6
- type Reminder = { id: string; acknowledged: number };
7
-
8
- export async function tickAdminScheduler(now = Date.now()): Promise<void> {
9
- await tx((db) => {
10
- const due = many<PlanRow>(db, "SELECT * FROM admin_plans WHERE paused=0 AND next_run_at<=? ORDER BY next_run_at LIMIT 100", now);
11
- for (const plan of due) {
12
- const b = binding(db, plan.admin_room_id);
13
- if (!b || !validCurrent(db, b)) {
14
- exec(db, "UPDATE admin_plans SET next_run_at=? WHERE id=?", now + plan.interval_seconds * 1000, plan.id);
15
- continue;
16
- }
17
- const tasks = many<OpenTask>(db, "SELECT text,status,progress FROM admin_tasks WHERE admin_room_id=? AND status IN ('pending','working','blocked') ORDER BY created_at DESC LIMIT 20", b.room_id);
18
- const summary = tasks.length ? `\nOpen tasks:\n${tasks.map(t => `- ${t.status}: ${t.text}${t.progress ? ` (${t.progress})` : ""}`).join("\n")}` : "\nNo open tasks.";
19
- const text = `${plan.text}${summary}`.slice(0, 5000);
20
- const taskID = `plan:${plan.id}`;
21
- const existing = db.query("SELECT id,acknowledged FROM admin_deliveries WHERE admin_room_id=? AND kind='supervision' AND task_id=?").get(b.room_id, taskID) as Reminder | null;
22
- if (existing && !existing.acknowledged) {
23
- exec(db, "UPDATE admin_deliveries SET text=?,created_at=?,generation=?,recipient_room_id=?,session_id=?,owner_id=?,membership_id=? WHERE id=?", text, now, b.generation, b.target_room_id, b.session_id, b.receiver_owner_id, b.membership_id, existing.id);
24
- } else if (existing) {
25
- const id = randomUUID();
26
- exec(db, "UPDATE admin_deliveries SET id=?,admission_id=?,text=?,created_at=?,generation=?,recipient_room_id=?,session_id=?,owner_id=?,membership_id=?,acknowledged=0 WHERE id=?", id, `msg_${id}`, text, now, b.generation, b.target_room_id, b.session_id, b.receiver_owner_id, b.membership_id, existing.id);
27
- } else {
28
- const id = randomUUID();
29
- exec(db, "INSERT INTO admin_deliveries(id,admin_room_id,generation,recipient_room_id,session_id,owner_id,membership_id,kind,text,task_id,admission_id,created_at) VALUES(?,?,?,?,?,?,?,'supervision',?,?,?,?)", id,b.room_id,b.generation,b.target_room_id,b.session_id,b.receiver_owner_id,b.membership_id,text,taskID,`msg_${id}`,now);
30
- }
31
- exec(db, "UPDATE admin_plans SET next_run_at=? WHERE id=?", now + plan.interval_seconds * 1000, plan.id);
32
- }
33
- });
34
- }
35
-
36
- let timer: ReturnType<typeof setInterval> | undefined;
37
- export function startAdminScheduler(): void {
38
- if (timer || !process.env.CHAT_ROOM_ADMIN_TOKEN || !process.env.CHAT_ROOM_SERVER_TOKEN || process.env.CHAT_ROOM_ADMIN_TOKEN === process.env.CHAT_ROOM_SERVER_TOKEN) return;
39
- timer = setInterval(() => { void tickAdminScheduler().catch(() => {}); }, 5000);
40
- timer.unref?.();
41
- }
42
- export function stopAdminScheduler(): void { if (timer) clearInterval(timer); timer = undefined; }
@@ -1,182 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import type { Database } from "bun:sqlite";
3
- import { hasAdminCapability, isOperator } from "./admin-auth";
4
- import { binding, digest, exec, isAgentMember, many, matchesHash, newSecret, one, queue, tx, validCurrent } from "./admin-state";
5
- import type { Binding } from "./admin-state";
6
-
7
- const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
8
- const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
9
- const statuses = ["pending", "working", "blocked", "completed", "cancelled"] as const;
10
- type TaskStatus = typeof statuses[number];
11
- const auth = (request: Request, b: Binding) => isOperator(request) || hasAdminCapability(request, b);
12
- type TaskRow = { id: string; admin_room_id: string; admin_generation: number; target_room_id: string; target_session_id: string; target_owner_id: string; target_membership_id: string; text: string; status: string; progress: string; delivery_token_hash: string; created_at: number; updated_at: number };
13
- type DeliveryRow = { id: string; admissionID: string; adminRoomId: string; generation: number; recipientRoomId: string; membershipID: string; kind: string; text: string; taskId: string | null; taskToken: string | null; createdAt: number };
14
- type TaskView = { id: string; adminRoomId: string; generation: number; targetRoomId: string; targetSessionID: string; text: string; status: string; progress: string; createdAt: number; updatedAt: number };
15
- type AckDelivery = { id: string; admin_room_id: string; generation: number; recipient_room_id: string; session_id: string; owner_id: string; membership_id: string; kind: string };
16
- const revokeTaskDelivery = (db: Database, roomID: string, taskID: string) => {
17
- exec(db, "DELETE FROM admin_deliveries WHERE admin_room_id=? AND kind='task' AND task_id=? AND acknowledged=0", roomID, taskID);
18
- // A delivered prompt cannot be recalled; revoke its token so it cannot report progress.
19
- exec(db, "UPDATE admin_deliveries SET task_token=NULL WHERE admin_room_id=? AND kind='task' AND task_id=?", roomID, taskID);
20
- };
21
-
22
- export async function adminTaskRoutes(request: Request, url: URL): Promise<Response | undefined> {
23
- const base = url.pathname.match(/^\/admin\/rooms\/([^/]+)\/tasks$/);
24
- const update = url.pathname.match(/^\/admin\/rooms\/([^/]+)\/tasks\/([^/]+)$/);
25
- if (base && request.method === "GET") return tx(db => {
26
- const b = binding(db, decodeURIComponent(base[1]!));
27
- if (!b) return { error: "admin room not found", status: 404 };
28
- if (!auth(request, b)) return { error: "unauthorized", status: 401 };
29
- if (!isOperator(request) && !validCurrent(db, b)) return { error: "binding is no longer active", status: 409 };
30
- return { tasks: many<TaskView>(db, "SELECT id,admin_room_id AS adminRoomId,admin_generation AS generation,target_room_id AS targetRoomId,target_session_id AS targetSessionID,text,status,progress,created_at AS createdAt,updated_at AS updatedAt FROM admin_tasks WHERE admin_room_id=? ORDER BY created_at DESC LIMIT 200", b.room_id) };
31
- }).then(result => "status" in result ? json({ error: result.error }, result.status) : json(result));
32
- if (base && request.method === "POST") return createTask(request, decodeURIComponent(base[1]!));
33
- if (update && request.method === "PATCH") return updateTask(request, decodeURIComponent(update[1]!), decodeURIComponent(update[2]!));
34
- if (url.pathname === "/supervision/inbox" && request.method === "GET") return inbox(request, url);
35
- if (url.pathname === "/supervision/ack" && request.method === "POST") return acknowledge(request);
36
- const progress = url.pathname.match(/^\/supervision\/tasks\/([^/]+)\/progress$/);
37
- if (progress && request.method === "POST") return reportProgress(request, decodeURIComponent(progress[1]!));
38
- return undefined;
39
- }
40
-
41
- async function createTask(request: Request, roomID: string): Promise<Response> {
42
- const body: unknown = await request.json();
43
- if (!object(body) || typeof body.targetRoomId !== "string" || !body.targetRoomId || typeof body.targetSessionID !== "string" || !body.targetSessionID || typeof body.text !== "string" || !body.text.trim() || body.text.trim().length > 2000) return json({ error: "invalid task" }, 400);
44
- const targetRoomID = body.targetRoomId, targetSessionID = body.targetSessionID, text = body.text.trim();
45
- const result = await tx(db => {
46
- const b = binding(db, roomID);
47
- if (!b) return { status: 404 as const };
48
- if (!auth(request, b)) return { status: 401 as const };
49
- if (!validCurrent(db, b)) return { status: 409 as const };
50
- const recipient = one<{ receiver_owner_id: string | null; membership_id: string }>(db, "SELECT receiver_owner_id,membership_id FROM registry WHERE room_id=? AND session_id=?", targetRoomID, targetSessionID);
51
- if (!recipient || !isAgentMember(db, targetRoomID, targetSessionID, recipient.receiver_owner_id ?? "", recipient.membership_id)) return { status: 409 as const };
52
- const id = randomUUID(), now = Date.now(), taskToken = newSecret();
53
- exec(db, "INSERT INTO admin_tasks(id,admin_room_id,admin_generation,target_room_id,target_session_id,target_owner_id,target_membership_id,text,status,progress,delivery_token_hash,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,'pending','',?,?,?)",
54
- id, roomID, b.generation, targetRoomID, targetSessionID, recipient.receiver_owner_id ?? "", recipient.membership_id, text, digest(taskToken), now, now);
55
- queue(db, b, "task", text, id, taskToken, { roomID: targetRoomID, sessionID: targetSessionID, ownerID: recipient.receiver_owner_id ?? "", membershipID: recipient.membership_id });
56
- return { task: { id, adminRoomId: roomID, generation: b.generation, targetRoomId: targetRoomID, targetSessionID, text, status: "pending", progress: "", createdAt: now, updatedAt: now } };
57
- });
58
- if ("status" in result) return json({ error: result.status === 404 ? "admin room not found" : result.status === 401 ? "unauthorized" : "active agent target not found" }, result.status);
59
- return json(result, 201);
60
- }
61
-
62
- async function updateTask(request: Request, roomID: string, taskID: string): Promise<Response> {
63
- const body: unknown = await request.json();
64
- if (!object(body) || (body.status !== undefined && !statuses.includes(body.status as typeof statuses[number])) ||
65
- (body.progress !== undefined && (typeof body.progress !== "string" || body.progress.length > 2000))) return json({ error: "invalid task update" }, 400);
66
- const update = body as { status?: TaskStatus; progress?: string };
67
- const result = await tx(db => {
68
- const b = binding(db, roomID);
69
- if (!b) return { status: 404 as const };
70
- if (!auth(request, b)) return { status: 401 as const };
71
- if (!validCurrent(db, b)) return { status: 409 as const };
72
- const task = one<TaskRow>(db, "SELECT * FROM admin_tasks WHERE id=? AND admin_room_id=?", taskID, roomID);
73
- if (!task || task.admin_generation !== b.generation) return { status: 404 as const };
74
- const status = update.status ?? task.status;
75
- if (task.status === "completed" || task.status === "cancelled") return { status: 409 as const };
76
- const progress = update.progress === undefined ? task.progress : update.progress.trim();
77
- const updatedAt = Date.now();
78
- const terminal = status === "completed" || status === "cancelled";
79
- exec(db, "UPDATE admin_tasks SET status=?,progress=?,delivery_token_hash=?,updated_at=? WHERE id=? AND admin_generation=?", status, progress, terminal ? "" : task.delivery_token_hash, updatedAt, taskID, b.generation);
80
- if (terminal) revokeTaskDelivery(db, roomID, taskID);
81
- return { task: { id: taskID, adminRoomId: roomID, generation: b.generation, targetRoomId: task.target_room_id,
82
- targetSessionID: task.target_session_id, text: task.text, status, progress, createdAt: task.created_at, updatedAt } };
83
- });
84
- if ("status" in result) return json({ error: result.status === 401 ? "unauthorized" : result.status === 404 ? "task not found" : "binding is no longer active" }, result.status);
85
- return json(result);
86
- }
87
-
88
- async function reportProgress(request: Request, taskID: string): Promise<Response> {
89
- const body: unknown = await request.json();
90
- const sessionID = request.headers.get("x-chat-agent-session") ?? "";
91
- const ownerID = request.headers.get("x-chat-agent-owner") ?? "";
92
- if (!object(body) || typeof body.taskToken !== "string" || typeof body.status !== "string" ||
93
- !statuses.includes(body.status as TaskStatus) || typeof body.progress !== "string" || body.progress.length > 2000) return json({ error: "invalid task progress" }, 400);
94
- const update = body as { taskToken: string; status: TaskStatus; progress: string };
95
- const result = await tx(db => {
96
- const task = one<TaskRow>(db, "SELECT * FROM admin_tasks WHERE id=?", taskID);
97
- if (!task) return false;
98
- const b = binding(db, task.admin_room_id);
99
- if (!b || task.admin_generation !== b.generation || task.status === "completed" || task.status === "cancelled" || !validCurrent(db, b) ||
100
- sessionID !== task.target_session_id || ownerID !== task.target_owner_id ||
101
- !isAgentMember(db, task.target_room_id, task.target_session_id, task.target_owner_id, task.target_membership_id) ||
102
- !task.delivery_token_hash || !matchesHash(update.taskToken, task.delivery_token_hash)) return null;
103
- const terminal = update.status === "completed" || update.status === "cancelled";
104
- exec(db, "UPDATE admin_tasks SET status=?,progress=?,delivery_token_hash=?,updated_at=? WHERE id=? AND admin_generation=?",
105
- update.status, update.progress.trim(), terminal ? "" : task.delivery_token_hash, Date.now(), taskID, b.generation);
106
- if (terminal) revokeTaskDelivery(db, b.room_id, taskID);
107
- return true;
108
- });
109
- if (result === null) return json({ error: "task progress credential rejected" }, 401);
110
- return result ? json({ ok: true }) : json({ error: "task not found" }, 404);
111
- }
112
-
113
- async function inbox(request: Request, url: URL): Promise<Response> {
114
- const sessionID = url.searchParams.get("sessionID") ?? "";
115
- const ownerID = url.searchParams.get("receiverOwnerID") ?? "";
116
- const adminRoomID = url.searchParams.get("adminRoomId");
117
- if (!sessionID || sessionID.length > 128 || ownerID.length > 128) return json({ error: "invalid agent identity" }, 400);
118
- return adminRoomID ? protectedInbox(request, sessionID, ownerID, adminRoomID) : taskInbox(sessionID, ownerID);
119
- }
120
-
121
- function pruneStale(db: Database, sessionID: string, ownerID: string): void {
122
- db.query(`DELETE FROM admin_deliveries AS d WHERE d.acknowledged=0 AND d.session_id=? AND d.owner_id=? AND (
123
- NOT EXISTS(SELECT 1 FROM admin_rooms a WHERE a.room_id=d.admin_room_id AND a.generation=d.generation AND EXISTS(
124
- SELECT 1 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
125
- WHERE g.room_id=a.target_room_id AND g.session_id=a.session_id AND g.membership_id=a.membership_id AND coalesce(g.receiver_owner_id,'')=a.receiver_owner_id AND (g.protocol IN ('v1','v2') OR coalesce(g.host,'')!='')))
126
- OR NOT EXISTS(SELECT 1 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
127
- WHERE g.room_id=d.recipient_room_id AND g.session_id=d.session_id AND g.membership_id=d.membership_id AND coalesce(g.receiver_owner_id,'')=d.owner_id AND (g.protocol IN ('v1','v2') OR coalesce(g.host,'')!='')))`)
128
- .run(sessionID, ownerID);
129
- }
130
-
131
- async function taskInbox(sessionID: string, ownerID: string): Promise<Response> {
132
- const result = await tx(db => {
133
- pruneStale(db, sessionID, ownerID);
134
- const deliveries = many<DeliveryRow>(db, `SELECT d.id,d.admission_id AS admissionID,d.admin_room_id AS adminRoomId,d.generation,
135
- d.recipient_room_id AS recipientRoomId,d.membership_id AS membershipID,d.kind,d.text,d.task_id AS taskId,d.task_token AS taskToken,d.created_at AS createdAt
136
- FROM admin_deliveries d JOIN admin_tasks t ON t.id=d.task_id AND t.admin_room_id=d.admin_room_id AND t.admin_generation=d.generation
137
- AND t.target_room_id=d.recipient_room_id AND t.target_session_id=d.session_id AND t.target_owner_id=d.owner_id AND t.target_membership_id=d.membership_id
138
- WHERE d.session_id=? AND d.owner_id=? AND d.kind='task' AND d.acknowledged=0 ORDER BY d.created_at LIMIT 100`, sessionID, ownerID)
139
- .map(({ taskToken, recipientRoomId, membershipID, ...delivery }) => ({ ...delivery, targetRoomId: recipientRoomId, ...(taskToken ? { taskToken } : {}) }));
140
- const supervisionRoomIds = many<{ admin_room_id: string }>(db, `SELECT DISTINCT d.admin_room_id FROM admin_deliveries d JOIN admin_rooms a ON a.room_id=d.admin_room_id
141
- WHERE d.session_id=a.session_id AND d.owner_id=a.receiver_owner_id AND d.membership_id=a.membership_id AND d.recipient_room_id=a.target_room_id
142
- AND d.generation=a.generation AND d.session_id=? AND d.owner_id=? AND d.kind='supervision' AND d.acknowledged=0 ORDER BY d.admin_room_id LIMIT 100`, sessionID, ownerID).map(row => row.admin_room_id);
143
- return { deliveries, supervisionRoomIds };
144
- });
145
- return json(result);
146
- }
147
-
148
- async function protectedInbox(request: Request, sessionID: string, ownerID: string, roomID: string): Promise<Response> {
149
- const result = await tx(db => {
150
- const b = binding(db, roomID);
151
- if (!b) return { status: 404 as const };
152
- const operator = isOperator(request);
153
- if (!operator && (sessionID !== b.session_id || ownerID !== b.receiver_owner_id || !hasAdminCapability(request, b))) return { status: 401 as const };
154
- if (!validCurrent(db, b)) return { status: 409 as const };
155
- pruneStale(db, b.session_id, b.receiver_owner_id);
156
- return { deliveries: many<DeliveryRow>(db, `SELECT id,admission_id AS admissionID,admin_room_id AS adminRoomId,generation,
157
- recipient_room_id AS recipientRoomId,membership_id AS membershipID,kind,text,task_id AS taskId,task_token AS taskToken,created_at AS createdAt
158
- FROM admin_deliveries WHERE admin_room_id=? AND generation=? AND recipient_room_id=? AND session_id=? AND owner_id=? AND membership_id=? AND kind='supervision' AND acknowledged=0 ORDER BY created_at LIMIT 100`,
159
- roomID, b.generation, b.target_room_id, b.session_id, b.receiver_owner_id, b.membership_id).map(({ taskToken, membershipID, recipientRoomId, ...delivery }) => delivery) };
160
- });
161
- 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);
162
- return json(result);
163
- }
164
-
165
- async function acknowledge(request: Request): Promise<Response> {
166
- const body: unknown = await request.json();
167
- if (!object(body) || typeof body.id !== "string" || typeof body.sessionID !== "string" || typeof body.receiverOwnerID !== "string") return json({ error: "invalid acknowledgement" }, 400);
168
- const ack = body as { id: string; sessionID: string; receiverOwnerID: string };
169
- const ok = await tx(db => {
170
- const delivery = one<AckDelivery>(db, "SELECT * FROM admin_deliveries WHERE id=? AND acknowledged=0", ack.id);
171
- if (!delivery || delivery.session_id !== ack.sessionID || delivery.owner_id !== ack.receiverOwnerID) return false;
172
- const b = binding(db, delivery.admin_room_id);
173
- if (!b || b.generation !== delivery.generation || !validCurrent(db, b) ||
174
- !isAgentMember(db, delivery.recipient_room_id, delivery.session_id, delivery.owner_id, delivery.membership_id)) return false;
175
- if (delivery.kind === "supervision" && (delivery.recipient_room_id !== b.target_room_id ||
176
- delivery.session_id !== b.session_id || delivery.owner_id !== b.receiver_owner_id || delivery.membership_id !== b.membership_id ||
177
- (!isOperator(request) && !hasAdminCapability(request, b)))) return false;
178
- if (delivery.kind !== "task" && delivery.kind !== "supervision") return false;
179
- return exec(db, "UPDATE admin_deliveries SET acknowledged=1 WHERE id=? AND acknowledged=0", ack.id).changes === 1;
180
- });
181
- return json({ ok });
182
- }