@alexsun-top/opencode-chat-room 0.5.2 → 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.
@@ -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-enrolled 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;
@@ -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
- }
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
  }
@@ -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 {
@@ -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
@@ -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
- }
@@ -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
- }