@alexsun-top/opencode-chat-room 0.5.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +8 -0
- package/README.zh-CN.md +8 -0
- package/docs/administrator-rooms.md +51 -0
- package/package.json +8 -1
- package/plugin.ts +10 -8
- package/server/admin-auth.ts +16 -0
- package/server/admin-plan-routes.ts +79 -0
- package/server/admin-routes.ts +154 -0
- package/server/admin-scheduler.ts +42 -0
- package/server/admin-state.ts +61 -0
- package/server/admin-task-routes.ts +182 -0
- package/server/assets/base.css +45 -43
- package/server/assets/chat/admin.js +196 -0
- package/server/assets/chat/attachments.js +240 -0
- package/server/assets/chat/events.js +27 -5
- package/server/assets/chat/index.js +4 -0
- package/server/assets/chat/markdown.js +1 -12
- package/server/assets/chat/members.js +1 -1
- package/server/assets/chat/messages.js +32 -6
- package/server/assets/chat/rooms.js +21 -4
- package/server/assets/chat/state.js +43 -11
- package/server/assets/conversation.css +82 -37
- package/server/assets/responsive.css +74 -25
- package/server/chat-server.ts +2 -4
- package/server/chat.html +63 -29
- package/server/newrooms.ts +27 -10
- package/server/resource-routes.ts +3 -0
- package/server/wake.ts +6 -13
- package/skills/chatroom/SKILL.md +12 -0
- package/src/admin-client.ts +130 -0
- package/src/admin-credentials.ts +58 -0
- package/src/center-client.ts +1 -1
- package/src/center-inbox.ts +2 -0
- package/src/sqlite-state.ts +46 -18
- package/src/supervision-inbox.ts +62 -0
- package/src/v1-plugin.ts +13 -3
- package/src/v2-plugin.ts +13 -2
package/src/sqlite-state.ts
CHANGED
|
@@ -10,7 +10,7 @@ type State = { rooms: Room[]; registry: Registry };
|
|
|
10
10
|
type Page<T> = { items: T[]; hasMore: boolean };
|
|
11
11
|
const databases = new Map<string, Promise<Database>>();
|
|
12
12
|
|
|
13
|
-
function
|
|
13
|
+
export function openStateDatabase(file: string): Promise<Database> {
|
|
14
14
|
const known = databases.get(file);
|
|
15
15
|
if (known) return known;
|
|
16
16
|
const pending = initialize(file);
|
|
@@ -19,6 +19,30 @@ function open(file: string): Promise<Database> {
|
|
|
19
19
|
return pending;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
export async function withStateTransaction<T>(file: string, callback: (db: Database) => T): Promise<T> {
|
|
23
|
+
const db = await openStateDatabase(file);
|
|
24
|
+
return immediate(db, () => callback(db));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function initializeAdminSchema(file: string): Promise<void> {
|
|
28
|
+
await withStateTransaction(file, db => {
|
|
29
|
+
db.exec(`CREATE TABLE IF NOT EXISTS admin_rooms(room_id TEXT PRIMARY KEY REFERENCES rooms(id) ON DELETE CASCADE,target_room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,session_id TEXT NOT NULL,receiver_owner_id TEXT NOT NULL,membership_id TEXT NOT NULL,generation INTEGER NOT NULL,enrollment_hash TEXT NOT NULL,enrollment_expires INTEGER NOT NULL,capability_hash TEXT,created_at INTEGER NOT NULL);
|
|
30
|
+
CREATE TABLE IF NOT EXISTS admin_tasks(id TEXT PRIMARY KEY,admin_room_id TEXT NOT NULL REFERENCES admin_rooms(room_id) ON DELETE CASCADE,admin_generation INTEGER NOT NULL DEFAULT 1,target_room_id TEXT NOT NULL,target_session_id TEXT NOT NULL,target_owner_id TEXT NOT NULL DEFAULT '',target_membership_id TEXT NOT NULL DEFAULT '',text TEXT NOT NULL,status TEXT NOT NULL,progress TEXT NOT NULL,delivery_token_hash TEXT NOT NULL DEFAULT '',created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL);
|
|
31
|
+
CREATE TABLE IF NOT EXISTS admin_plans(id TEXT PRIMARY KEY,admin_room_id TEXT NOT NULL REFERENCES admin_rooms(room_id) ON DELETE CASCADE,name TEXT NOT NULL,interval_seconds INTEGER NOT NULL,text TEXT NOT NULL,paused INTEGER NOT NULL,next_run_at INTEGER NOT NULL,created_at INTEGER NOT NULL);
|
|
32
|
+
CREATE TABLE IF NOT EXISTS admin_deliveries(id TEXT PRIMARY KEY,admin_room_id TEXT NOT NULL REFERENCES admin_rooms(room_id) ON DELETE CASCADE,generation INTEGER NOT NULL,recipient_room_id TEXT NOT NULL DEFAULT '',session_id TEXT NOT NULL,owner_id TEXT NOT NULL,membership_id TEXT NOT NULL,kind TEXT NOT NULL,text TEXT NOT NULL,task_id TEXT,task_token TEXT,admission_id TEXT NOT NULL,created_at INTEGER NOT NULL,acknowledged INTEGER NOT NULL DEFAULT 0,UNIQUE(admin_room_id,kind,task_id));
|
|
33
|
+
CREATE INDEX IF NOT EXISTS admin_delivery_target ON admin_deliveries(session_id,owner_id,acknowledged);`);
|
|
34
|
+
const taskColumns = db.query("PRAGMA table_info(admin_tasks)").all() as Array<{ name: string }>;
|
|
35
|
+
if (!taskColumns.some(column => column.name === "delivery_token_hash")) db.exec("ALTER TABLE admin_tasks ADD COLUMN delivery_token_hash TEXT NOT NULL DEFAULT ''");
|
|
36
|
+
if (!taskColumns.some(column => column.name === "admin_generation")) db.exec("ALTER TABLE admin_tasks ADD COLUMN admin_generation INTEGER NOT NULL DEFAULT 1");
|
|
37
|
+
if (!taskColumns.some(column => column.name === "target_owner_id")) db.exec("ALTER TABLE admin_tasks ADD COLUMN target_owner_id TEXT NOT NULL DEFAULT ''");
|
|
38
|
+
if (!taskColumns.some(column => column.name === "target_membership_id")) db.exec("ALTER TABLE admin_tasks ADD COLUMN target_membership_id TEXT NOT NULL DEFAULT ''");
|
|
39
|
+
const deliveryColumns = db.query("PRAGMA table_info(admin_deliveries)").all() as Array<{ name: string }>;
|
|
40
|
+
if (!deliveryColumns.some(column => column.name === "task_token")) db.exec("ALTER TABLE admin_deliveries ADD COLUMN task_token TEXT");
|
|
41
|
+
if (!deliveryColumns.some(column => column.name === "recipient_room_id")) db.exec("ALTER TABLE admin_deliveries ADD COLUMN recipient_room_id TEXT NOT NULL DEFAULT ''");
|
|
42
|
+
db.exec("UPDATE admin_deliveries SET admission_id='msg_' || substr(admission_id,7) WHERE admission_id LIKE 'admin:%'");
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
22
46
|
async function initialize(file: string): Promise<Database> {
|
|
23
47
|
mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
24
48
|
chmodSync(path.dirname(file), 0o700);
|
|
@@ -51,16 +75,16 @@ async function initialize(file: string): Promise<Database> {
|
|
|
51
75
|
|
|
52
76
|
export type Announcement = { roomID: string; name: string; content: string; updatedAt: number };
|
|
53
77
|
export async function listAnnouncements(file: string, roomID: string): Promise<Announcement[]> {
|
|
54
|
-
const db = await
|
|
78
|
+
const db = await openStateDatabase(file);
|
|
55
79
|
if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return [];
|
|
56
80
|
return db.query("SELECT room_id AS roomID,name,content,updated_at AS updatedAt FROM announcements WHERE room_id=? ORDER BY name").all(roomID) as Announcement[];
|
|
57
81
|
}
|
|
58
82
|
export async function getAnnouncement(file: string, roomID: string, name: string): Promise<Announcement | undefined> {
|
|
59
|
-
const db = await
|
|
83
|
+
const db = await openStateDatabase(file);
|
|
60
84
|
return db.query("SELECT room_id AS roomID,name,content,updated_at AS updatedAt FROM announcements WHERE room_id=? AND name=?").get(roomID, name) as Announcement | undefined;
|
|
61
85
|
}
|
|
62
86
|
export async function putAnnouncement(file: string, roomID: string, name: string, content: string, updatedAt: number): Promise<Announcement | undefined> {
|
|
63
|
-
const db = await
|
|
87
|
+
const db = await openStateDatabase(file);
|
|
64
88
|
return immediate(db, () => {
|
|
65
89
|
if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return undefined;
|
|
66
90
|
db.query("INSERT INTO announcements(room_id,name,content,updated_at) VALUES(?,?,?,?) ON CONFLICT(room_id,name) DO UPDATE SET content=excluded.content,updated_at=excluded.updated_at").run(roomID, name, content, updatedAt);
|
|
@@ -68,13 +92,13 @@ export async function putAnnouncement(file: string, roomID: string, name: string
|
|
|
68
92
|
});
|
|
69
93
|
}
|
|
70
94
|
export async function deleteAnnouncement(file: string, roomID: string, name: string): Promise<boolean> {
|
|
71
|
-
const db = await
|
|
95
|
+
const db = await openStateDatabase(file);
|
|
72
96
|
return immediate(db, () => db.query("DELETE FROM announcements WHERE room_id=? AND name=?").run(roomID, name).changes > 0);
|
|
73
97
|
}
|
|
74
98
|
|
|
75
99
|
export type StoredResource = { id: string; roomID: string; name: string; mimeType: string; size: number; createdAt: number };
|
|
76
100
|
export async function putResource(file: string, resource: StoredResource): Promise<boolean> {
|
|
77
|
-
const db = await
|
|
101
|
+
const db = await openStateDatabase(file);
|
|
78
102
|
return immediate(db, () => {
|
|
79
103
|
if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(resource.roomID)) return false;
|
|
80
104
|
db.query("INSERT INTO resources(id,room_id,name,mime_type,size,created_at) VALUES(?,?,?,?,?,?)")
|
|
@@ -83,7 +107,7 @@ export async function putResource(file: string, resource: StoredResource): Promi
|
|
|
83
107
|
});
|
|
84
108
|
}
|
|
85
109
|
export async function getResource(file: string, roomID: string, id: string): Promise<StoredResource | undefined> {
|
|
86
|
-
const db = await
|
|
110
|
+
const db = await openStateDatabase(file);
|
|
87
111
|
const row = db.query("SELECT id,room_id AS roomID,name,mime_type AS mimeType,size,created_at AS createdAt FROM resources WHERE room_id=? AND id=?")
|
|
88
112
|
.get(roomID, id) as StoredResource | null;
|
|
89
113
|
return row ?? undefined;
|
|
@@ -279,12 +303,16 @@ function readState(db: Database): State {
|
|
|
279
303
|
|
|
280
304
|
export type HistoryMessage = Message & { seq: number };
|
|
281
305
|
export async function writeSqliteState<T>(file: string, callback: (service: RoomService, registry: Registry) => T): Promise<T> {
|
|
282
|
-
|
|
306
|
+
return writeSqliteStateWithDatabase(file, (service, registry) => callback(service, registry));
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export async function writeSqliteStateWithDatabase<T>(file: string, callback: (service: RoomService, registry: Registry, db: Database) => T): Promise<T> {
|
|
310
|
+
const db = await openStateDatabase(file);
|
|
283
311
|
return immediate(db, () => {
|
|
284
312
|
const state = readState(db);
|
|
285
313
|
const service = new RoomService();
|
|
286
314
|
service.hydrate(state.rooms);
|
|
287
|
-
const result = callback(service, state.registry);
|
|
315
|
+
const result = callback(service, state.registry, db);
|
|
288
316
|
if (result && typeof (result as { then?: unknown }).then === "function") throw new Error("writeState callback must be synchronous");
|
|
289
317
|
persistState(db, service.listRooms(), state.registry);
|
|
290
318
|
return result;
|
|
@@ -292,17 +320,17 @@ export async function writeSqliteState<T>(file: string, callback: (service: Room
|
|
|
292
320
|
}
|
|
293
321
|
|
|
294
322
|
export async function readSqliteState(file: string): Promise<State> {
|
|
295
|
-
const db = await
|
|
323
|
+
const db = await openStateDatabase(file);
|
|
296
324
|
return db.transaction(() => readState(db)).deferred();
|
|
297
325
|
}
|
|
298
326
|
|
|
299
327
|
export async function readQuestions(file: string, roomID: string): Promise<Message[]> {
|
|
300
|
-
const db = await
|
|
328
|
+
const db = await openStateDatabase(file);
|
|
301
329
|
return (db.query("SELECT id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by FROM messages WHERE room_id=? AND is_question=1 AND answered_by IS NULL ORDER BY seq").all(roomID) as Array<Record<string, string | number | null>>).map(rowMessage);
|
|
302
330
|
}
|
|
303
331
|
|
|
304
332
|
export async function answerQuestion(file: string, roomID: string, questionID: string, sessionID: string, text: string): Promise<{ status: "ok"; answer: Message } | { status: "missing" | "member" | "question" | "answered" }> {
|
|
305
|
-
const db = await
|
|
333
|
+
const db = await openStateDatabase(file);
|
|
306
334
|
return immediate(db, () => {
|
|
307
335
|
if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return { status: "missing" };
|
|
308
336
|
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;
|
|
@@ -320,7 +348,7 @@ export async function answerQuestion(file: string, roomID: string, questionID: s
|
|
|
320
348
|
}
|
|
321
349
|
|
|
322
350
|
export async function readUnreadPage(file: string, roomID: string, afterTs: number, limit = 100, sessionID?: string, senderName?: string, newest = false): Promise<Page<Message>> {
|
|
323
|
-
const db = await
|
|
351
|
+
const db = await openStateDatabase(file);
|
|
324
352
|
const take = Math.min(200, Math.max(1, limit));
|
|
325
353
|
const rows = db.query(`SELECT id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by FROM messages WHERE room_id=? AND created_at>? AND
|
|
326
354
|
(? IS NULL OR (sender_session_id IS NOT NULL AND sender_session_id!=?) OR (sender_session_id IS NULL AND sender_id!=?))
|
|
@@ -332,7 +360,7 @@ export async function readUnreadPage(file: string, roomID: string, afterTs: numb
|
|
|
332
360
|
}
|
|
333
361
|
|
|
334
362
|
export async function readInboxPage(file: string, sessionID: string, roomFilter: string | null, excludeSelf: boolean, limit = 100, afterTs?: number) {
|
|
335
|
-
const db = await
|
|
363
|
+
const db = await openStateDatabase(file);
|
|
336
364
|
return db.transaction(() => {
|
|
337
365
|
const take = Math.min(200, Math.max(1, limit));
|
|
338
366
|
const members = db.query("SELECT room_id,last_queued_ts FROM registry WHERE session_id=? AND (? IS NULL OR room_id=?)").all(sessionID, roomFilter, roomFilter) as Array<{ room_id: string; last_queued_ts: number | null }>;
|
|
@@ -354,7 +382,7 @@ export async function readInboxPage(file: string, sessionID: string, roomFilter:
|
|
|
354
382
|
}
|
|
355
383
|
|
|
356
384
|
export async function readHistoryPage(file: string, roomID: string, beforeSeq?: number, limit = 100, excludeSessionID?: string, excludeName = ""): Promise<{ messages: HistoryMessage[]; nextBeforeSeq: number | null; hasMore: boolean }> {
|
|
357
|
-
const db = await
|
|
385
|
+
const db = await openStateDatabase(file);
|
|
358
386
|
const take = Math.min(200, Math.max(1, limit));
|
|
359
387
|
const rows = db.query(`SELECT seq,id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by FROM messages WHERE room_id=? ${beforeSeq === undefined ? "" : "AND seq<? "}AND
|
|
360
388
|
(? IS NULL OR (sender_session_id IS NOT NULL AND sender_session_id!=?) OR (sender_session_id IS NULL AND sender_id!=?))
|
|
@@ -366,7 +394,7 @@ export async function readHistoryPage(file: string, roomID: string, beforeSeq?:
|
|
|
366
394
|
}
|
|
367
395
|
|
|
368
396
|
export async function readMessageReceipts(file: string, roomID: string, messageIDs?: string[]): Promise<MessageReceipt[] | undefined> {
|
|
369
|
-
const db = await
|
|
397
|
+
const db = await openStateDatabase(file);
|
|
370
398
|
return db.transaction(() => {
|
|
371
399
|
if (messageIDs && (!messageIDs.length || messageIDs.length > 500 || messageIDs.some((id) => !id))) return undefined;
|
|
372
400
|
const requested = messageIDs ? [...new Set(messageIDs)] : undefined;
|
|
@@ -385,7 +413,7 @@ export async function readMessageReceipts(file: string, roomID: string, messageI
|
|
|
385
413
|
export async function writeMessageReceipts(file: string, roomID: string, sessionID: string, messageIDs: string[], evidence: ReceiptEvidence, identity: ReceiptIdentity, readAt: number, readThroughTs?: number): Promise<ReceiptWriteResult> {
|
|
386
414
|
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: [] };
|
|
387
415
|
const ids = [...new Set(messageIDs)];
|
|
388
|
-
const db = await
|
|
416
|
+
const db = await openStateDatabase(file);
|
|
389
417
|
return immediate(db, () => {
|
|
390
418
|
const member = db.query("SELECT membership_id,server_url,api_prefix,protocol,name,receiver_owner_id,host FROM registry WHERE room_id=? AND session_id=?").get(roomID, sessionID) as Record<string, string | null> | null;
|
|
391
419
|
if (!member || member.membership_id !== identity.membershipID || !receiptOwnerMatches({
|
|
@@ -411,7 +439,7 @@ export async function writeMessageReceipts(file: string, roomID: string, session
|
|
|
411
439
|
}
|
|
412
440
|
|
|
413
441
|
export async function writePresenceState(file: string, reports: PresenceReport[], ownerID: string | undefined, sequence: number | undefined, now: number): Promise<{ stale: boolean; updatedSessionIDs: string[] }> {
|
|
414
|
-
const db = await
|
|
442
|
+
const db = await openStateDatabase(file);
|
|
415
443
|
return immediate(db, () => {
|
|
416
444
|
if (ownerID && sequence !== undefined) {
|
|
417
445
|
const current = db.query("SELECT last_sequence FROM presence_sequences WHERE owner_id=?").get(ownerID) as { last_sequence: number } | null;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { request, type CenterOpts } from "./center-client";
|
|
2
|
+
import { sendAsyncNotification, sendQueue, type QueueTransport } from "./queue-transport";
|
|
3
|
+
import { loadAdminCapability, saveTaskToken } from "./admin-credentials";
|
|
4
|
+
import { protectedAdminRequest } from "./admin-client";
|
|
5
|
+
|
|
6
|
+
type Delivery = { id: string; admissionID?: string; adminRoomId?: string; kind: "task" | "supervision"; text: string; taskId?: string; taskToken?: string; targetRoomId?: string };
|
|
7
|
+
type Inbox = { deliveries?: Delivery[]; supervisionRoomIds?: string[] };
|
|
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>`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async function push(opts: CenterOpts, sessionID: string, ownerID: string, transport: QueueTransport,
|
|
19
|
+
item: Delivery, capability?: string): Promise<void> {
|
|
20
|
+
const text = promptText(item, capability ?? item.taskToken);
|
|
21
|
+
const admissionID = item.admissionID ?? item.id;
|
|
22
|
+
const result = transport.protocol === "v1" ? await sendAsyncNotification(transport, sessionID, text)
|
|
23
|
+
: await sendQueue(transport, sessionID, text, admissionID, "steer");
|
|
24
|
+
if (result !== "delivered") return;
|
|
25
|
+
const body = { id: item.id, sessionID, receiverOwnerID: ownerID };
|
|
26
|
+
if (capability) await protectedAdminRequest(opts, "/supervision/ack", "POST", capability, sessionID, ownerID, body);
|
|
27
|
+
else await request(opts, "/supervision/ack", "POST", body);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function checkSupervisionInbox(opts: CenterOpts, sessionID: string, transport: QueueTransport): Promise<void> {
|
|
31
|
+
if (!opts.center || (transport.protocol === "v2" && !transport.receiverOwnerID)) return;
|
|
32
|
+
const ownerID = transport.receiverOwnerID ?? "";
|
|
33
|
+
let inbox: Inbox;
|
|
34
|
+
try {
|
|
35
|
+
const query = new URLSearchParams({ sessionID, receiverOwnerID: ownerID });
|
|
36
|
+
inbox = await request(opts, `/supervision/inbox?${query}`, "GET") as Inbox;
|
|
37
|
+
} catch { return; }
|
|
38
|
+
if (!inbox || typeof inbox !== "object") return;
|
|
39
|
+
|
|
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
|
+
const hintedRooms = Array.isArray(inbox.supervisionRoomIds)
|
|
48
|
+
? [...new Set(inbox.supervisionRoomIds.filter((room): room is string => typeof room === "string" && !!room))].slice(0, 50)
|
|
49
|
+
: [];
|
|
50
|
+
for (const roomId of hintedRooms) {
|
|
51
|
+
const capability = await loadAdminCapability({ center: opts.center, roomId, sessionID, ownerID });
|
|
52
|
+
if (!capability) continue;
|
|
53
|
+
try {
|
|
54
|
+
const query = new URLSearchParams({ sessionID, receiverOwnerID: ownerID, adminRoomId: roomId });
|
|
55
|
+
const result = await protectedAdminRequest(opts, `/supervision/inbox?${query}`, "GET", capability, sessionID, ownerID) as Inbox;
|
|
56
|
+
for (const item of (Array.isArray(result.deliveries) ? result.deliveries : []).slice(0, 50)) {
|
|
57
|
+
if (item?.kind !== "supervision" || item.adminRoomId !== roomId || !item.id || typeof item.text !== "string") continue;
|
|
58
|
+
try { await push(opts, sessionID, ownerID, transport, item, capability); } catch { /* Retry with the same server-issued ID next sweep. */ }
|
|
59
|
+
}
|
|
60
|
+
} catch { /* A room's protected feed does not block other admin rooms or task delivery. */ }
|
|
61
|
+
}
|
|
62
|
+
}
|
package/src/v1-plugin.ts
CHANGED
|
@@ -9,6 +9,7 @@ export function createV1Server(deps: {
|
|
|
9
9
|
runtime(input: PluginInput, transport: QueueTransport): V2Runtime;
|
|
10
10
|
run<T>(runtime: V2Runtime, callback: () => T): T;
|
|
11
11
|
room: ToolDefinition;
|
|
12
|
+
admin?: ToolDefinition;
|
|
12
13
|
observe(runtime: V2Runtime, sessionID: string): Promise<void>;
|
|
13
14
|
checkInbox(runtime: V2Runtime, sessionID: string): Promise<void>;
|
|
14
15
|
wake(runtime: V2Runtime, sessions: ReadonlySet<string>): Promise<void>;
|
|
@@ -22,10 +23,16 @@ export function createV1Server(deps: {
|
|
|
22
23
|
protocol: "v1" as const,
|
|
23
24
|
};
|
|
24
25
|
const runtime = deps.runtime(input, transport);
|
|
26
|
+
const adminTool = deps.admin;
|
|
25
27
|
let timer: ReturnType<typeof setInterval> | undefined;
|
|
26
28
|
if (deps.central) {
|
|
27
|
-
void deps.run(runtime, () =>
|
|
28
|
-
|
|
29
|
+
const sweep = (pollInbox: boolean) => void deps.run(runtime, async () => {
|
|
30
|
+
await deps.wake(runtime, sessions).catch(() => {});
|
|
31
|
+
if (!pollInbox) return;
|
|
32
|
+
for (const sessionID of [...sessions]) await deps.checkInbox(runtime, sessionID).catch(() => {});
|
|
33
|
+
});
|
|
34
|
+
sweep(false);
|
|
35
|
+
timer = setInterval(() => sweep(true), 10000);
|
|
29
36
|
}
|
|
30
37
|
const room = {
|
|
31
38
|
...deps.room,
|
|
@@ -37,7 +44,10 @@ export function createV1Server(deps: {
|
|
|
37
44
|
}),
|
|
38
45
|
};
|
|
39
46
|
return {
|
|
40
|
-
tool: { room
|
|
47
|
+
tool: { room, ...(adminTool ? { admin: {
|
|
48
|
+
...adminTool,
|
|
49
|
+
execute: (args, context) => deps.run(runtime, () => adminTool.execute(args, context)),
|
|
50
|
+
} } : {}) },
|
|
41
51
|
config: async (cfg: Config & { skills?: { paths?: string[]; urls?: string[] } }) => {
|
|
42
52
|
cfg.skills ??= {};
|
|
43
53
|
cfg.skills.paths = [...new Set([...(cfg.skills.paths ?? []), bundledSkillsPath])];
|
package/src/v2-plugin.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { receiverOwnerID } from "./receiver-owner";
|
|
|
6
6
|
import { attachV2Receiver } from "./v2-receiver";
|
|
7
7
|
import { observeReceiptContext, receiptDestination } from "./agent-receipts";
|
|
8
8
|
import { chatroomSkill } from "./chatroom-skill";
|
|
9
|
+
import { adminToolDescription, adminToolSchema } from "./admin-client";
|
|
9
10
|
|
|
10
11
|
type CenterOptions = { center: string; token: string; directory?: string };
|
|
11
12
|
export type V2Runtime = {
|
|
@@ -20,6 +21,7 @@ export function createV2Setup(deps: {
|
|
|
20
21
|
runtime(directory: string, transport: QueueTransport): V2Runtime;
|
|
21
22
|
run<T>(runtime: V2Runtime, callback: () => T): T;
|
|
22
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>;
|
|
24
|
+
admin?: (args: z.infer<typeof adminToolSchema>, sessionID: string, transport: QueueTransport, center: CenterOptions) => Promise<string>;
|
|
23
25
|
observe(runtime: V2Runtime, sessionID: string): Promise<void>;
|
|
24
26
|
poll(sessions: ReadonlySet<string>, transport: QueueTransport, center: CenterOptions): Promise<void>;
|
|
25
27
|
resolveOwner?: () => Promise<string | undefined>;
|
|
@@ -43,6 +45,7 @@ export function createV2Setup(deps: {
|
|
|
43
45
|
};
|
|
44
46
|
const runtime = deps.runtime(directory, transport);
|
|
45
47
|
let toolRegistration: { dispose(): Promise<void> } | undefined;
|
|
48
|
+
let adminRegistration: { dispose(): Promise<void> } | undefined;
|
|
46
49
|
let commandRegistration: { dispose(): Promise<void> } | undefined;
|
|
47
50
|
let promptRegistration: { dispose(): Promise<void> } | undefined;
|
|
48
51
|
let contextRegistration: { dispose(): Promise<void> } | undefined;
|
|
@@ -101,6 +104,14 @@ export function createV2Setup(deps: {
|
|
|
101
104
|
});
|
|
102
105
|
},
|
|
103
106
|
}));
|
|
107
|
+
if (deps.admin) adminRegistration = await context.tool.transform((editor) => editor.add({
|
|
108
|
+
name: "admin",
|
|
109
|
+
description: adminToolDescription,
|
|
110
|
+
options: { codemode: false },
|
|
111
|
+
input: adminToolSchema,
|
|
112
|
+
execute: async (args, toolContext) => ({ content: [{ type: "text", text: await deps.run(runtime,
|
|
113
|
+
() => deps.admin!(args, toolContext.sessionID, transport, runtime.center)) }] }),
|
|
114
|
+
}));
|
|
104
115
|
commandRegistration = await context.command.transform((editor) => editor.add({
|
|
105
116
|
name: "room",
|
|
106
117
|
description: "Chat room operations",
|
|
@@ -127,12 +138,12 @@ export function createV2Setup(deps: {
|
|
|
127
138
|
});
|
|
128
139
|
} catch (error) {
|
|
129
140
|
releaseReceiver?.();
|
|
130
|
-
await dispose(toolRegistration, commandRegistration, promptRegistration, contextRegistration, skillRegistration);
|
|
141
|
+
await dispose(toolRegistration, adminRegistration, commandRegistration, promptRegistration, contextRegistration, skillRegistration);
|
|
131
142
|
throw error;
|
|
132
143
|
}
|
|
133
144
|
return async () => {
|
|
134
145
|
releaseReceiver?.();
|
|
135
|
-
await dispose(toolRegistration, commandRegistration, promptRegistration, contextRegistration, skillRegistration);
|
|
146
|
+
await dispose(toolRegistration, adminRegistration, commandRegistration, promptRegistration, contextRegistration, skillRegistration);
|
|
136
147
|
};
|
|
137
148
|
};
|
|
138
149
|
}
|