@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/server/chat.html CHANGED
@@ -1,5 +1,5 @@
1
1
  <!doctype html>
2
- <html lang="en">
2
+ <html lang="en" class="session-restore">
3
3
  <head>
4
4
  <meta charset="utf-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
@@ -13,9 +13,14 @@
13
13
  <body>
14
14
 
15
15
  <main id="app">
16
+ <section id="restoreView" class="restore-view" role="status" aria-live="polite">
17
+ <div class="restore-message"><span class="restore-spinner" aria-hidden="true"></span><span data-i18n="restoringSession">Restoring your session…</span></div>
18
+ <p id="restoreError" class="hint danger-text" role="alert" hidden></p>
19
+ <button id="btnRestoreRetry" class="btn ghost small" type="button" data-i18n="retry" hidden>Retry</button>
20
+ </section>
16
21
 
17
22
  <!-- Join or create a room. -->
18
- <section id="joinView" class="view">
23
+ <section id="joinView" class="view" hidden>
19
24
  <div class="join-card">
20
25
  <div class="locale-control">
21
26
  <label for="localeSelectJoin" data-i18n="languageLabel">Language</label>
@@ -75,19 +80,56 @@
75
80
  <section id="chatView" class="view" hidden>
76
81
  <aside id="roomRail" class="room-rail" aria-label="Rooms" data-i18n-aria-label="roomsLabel">
77
82
  <div class="rail-brand"><span class="brand-mark">OC</span><span data-i18n="brand">OC Chat</span></div>
78
- <div class="rail-label"><span data-i18n="existingRooms">Rooms</span><span class="rail-tools"><button id="btnNewRoom" class="icon-btn" type="button" aria-label="Create a room" data-i18n-aria-label="newRoom">+</button><button id="btnRefreshRooms" class="icon-btn" type="button" aria-label="Refresh rooms" data-i18n-aria-label="refreshRooms">↻</button></span></div>
83
+ <div class="rail-label"><span data-i18n="existingRooms">Rooms</span><span class="rail-tools"><button id="btnNewRoom" class="icon-btn" type="button" aria-label="Create a room" data-i18n-aria-label="newRoom"><svg aria-hidden="true" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg></button><button id="btnRefreshRooms" class="icon-btn" type="button" aria-label="Refresh rooms" data-i18n-aria-label="refreshRooms"><svg aria-hidden="true" viewBox="0 0 24 24"><path d="M20 7v5h-5M4 17v-5h5"/><path d="M5.6 9a7 7 0 0 1 11.8-2L20 12M4 12l2.6 5a7 7 0 0 0 11.8-2"/></svg></button></span></div>
79
84
  <form id="railRoomForm" class="rail-composer" hidden>
80
85
  <label class="field"><span class="field-label" data-i18n="newRoomNameLabel">New room name</span><input id="inRoomNameChat" class="input" maxlength="40" data-i18n-placeholder="newRoomNamePlaceholder" placeholder="e.g. Weekend movie night"></label>
81
86
  <button id="btnCreateChatRoom" class="btn primary small" type="submit" data-i18n="createRoom">Create room</button>
82
87
  </form>
83
88
  <ul id="roomListChat" class="rail-rooms"></ul>
84
89
  <p id="roomListChatEmpty" class="hint" data-i18n="noRooms" hidden></p>
85
- <div class="rail-foot"><span id="railIdentity"></span></div>
90
+ <div class="rail-foot">
91
+ <div class="anchor user-menu-anchor">
92
+ <button id="btnSettings" class="user-menu-trigger" type="button" aria-label="Your profile and settings" data-i18n-aria-label="profileMenu" aria-haspopup="dialog" aria-expanded="false" aria-controls="chatSettings">
93
+ <span id="profileAvatar" class="rail-avatar" aria-hidden="true">?</span><span id="railIdentity"></span><span class="user-menu-caret" aria-hidden="true">⌃</span>
94
+ </button>
95
+ <div class="panel user-menu-panel" id="chatSettings" role="dialog" aria-modal="false" aria-labelledby="settingsHeading" hidden>
96
+ <h3 id="settingsHeading" data-i18n="settings">Settings</h3>
97
+ <label class="field"><span class="field-label" data-i18n="languageLabel">Language</span><select id="localeSelectSettings" class="locale-select"><option value="en">English</option><option value="zh-CN">中文</option></select></label>
98
+ <label class="field"><span class="field-label" data-i18n="tokenOptional">Access token (optional)</span><input id="inTokenChat" class="input" type="password" placeholder="Enter if the server requires it" data-i18n-placeholder="tokenPlaceholder" autocomplete="off" spellcheck="false"></label>
99
+ <button class="btn ghost small" type="button" data-token-save="inTokenChat" data-i18n="save">Save</button>
100
+ <p id="tokenHint" class="hint" data-i18n="tokenRequired" hidden>The server requires an access token (401).</p>
101
+ <p class="hint" data-i18n="privacyNote">Anyone with the shared token can read direct messages and manage rooms; the server can read them too.</p>
102
+ <details class="admin-access" aria-labelledby="adminAccessHeading">
103
+ <summary id="adminAccessHeading" data-i18n="adminAccess">Administration</summary>
104
+ <label class="field"><span class="field-label" data-i18n="adminToken">Administration token</span><input id="inAdminToken" class="input" type="password" autocomplete="off" spellcheck="false"></label>
105
+ <button id="btnSaveAdminToken" class="btn ghost small" type="button" data-i18n="save">Save</button>
106
+ <p id="adminAccessError" class="hint danger-text" role="alert" hidden></p>
107
+ <button id="btnOpenAdmin" class="btn ghost small" type="button" data-i18n="openAdministration" hidden>Open administration</button>
108
+ </details>
109
+ </div>
110
+ </div>
111
+ </div>
86
112
  </aside>
113
+ <dialog id="adminDialog" class="admin-dialog" aria-labelledby="adminHeading">
114
+ <header class="admin-dialog-head"><h2 id="adminHeading" data-i18n="administration">Administration</h2><button id="btnRefreshAdmin" class="btn ghost small" type="button" data-i18n="refreshAdmin">Refresh</button><button id="btnCloseAdmin" class="reader-close" type="button" aria-label="Close" data-i18n-aria-label="close">×</button></header>
115
+ <p id="adminStatus" class="hint" role="status" aria-live="polite"></p>
116
+ <div class="admin-columns">
117
+ <section><h3 data-i18n="designations">Designations</h3><label class="field"><span class="field-label" data-i18n="adminRoom">Admin room</span><select id="adminRoomSelect" class="admin-select"></select></label>
118
+ <label class="field"><span class="field-label" data-i18n="targetRoom">Agent room</span><select id="adminTargetRoom" class="admin-select"></select></label>
119
+ <label class="field"><span class="field-label" data-i18n="targetAgent">Registered agent</span><select id="adminTargetAgent" class="admin-select"></select></label>
120
+ <button id="btnDesignateAgent" class="btn primary small" type="button" data-i18n="designate">Designate and issue enrollment</button><div id="adminEnrollment" class="admin-enrollment" hidden></div>
121
+ <button id="btnRevokeAdmin" class="btn ghost small danger-text" type="button" data-i18n="revokeDesignation">Revoke designation</button>
122
+ </section>
123
+ <section><h3 data-i18n="globalStatus">Global status</h3><div id="adminOverview" class="admin-overview"></div><h3 data-i18n="adminTasks">Tasks</h3>
124
+ <form id="adminTaskForm"><label class="field"><span class="field-label" data-i18n="taskTargetRoom">Target room</span><select id="adminTaskRoom" class="admin-select"></select></label><label class="field"><span class="field-label" data-i18n="taskTargetAgent">Target agent</span><select id="adminTaskAgent" class="admin-select"></select></label><label class="field"><span class="field-label" data-i18n="taskText">Task</span><textarea id="adminTaskText" class="input" rows="2" maxlength="2000" required></textarea></label><button class="btn primary small" type="submit" data-i18n="dispatchTask">Dispatch task</button></form><ul id="adminTaskList" class="admin-list"></ul>
125
+ <h3 data-i18n="timers">Timers</h3><form id="adminPlanForm" class="admin-plan-form"><input id="adminPlanName" class="input" maxlength="64" required data-i18n-placeholder="planName" placeholder="Timer name"><input id="adminPlanInterval" class="input" type="number" min="60" max="2592000" value="3600" required><textarea id="adminPlanText" class="input" rows="2" maxlength="2000" required></textarea><button class="btn primary small" type="submit" data-i18n="createTimer">Create timer</button></form><ul id="adminPlanList" class="admin-list"></ul>
126
+ </section>
127
+ </div>
128
+ </dialog>
87
129
  <button id="roomDrawerBackdrop" class="room-drawer-backdrop" type="button" aria-label="Close room list" data-i18n-aria-label="closeRoomList" hidden></button>
88
130
  <header class="chat-head">
89
131
  <div class="chat-head-main">
90
- <div class="room-title-row"><h1 id="roomName"></h1><button id="btnRoomsDrawer" class="chip rooms-drawer-trigger" type="button" aria-label="Open room list" data-i18n-aria-label="roomsMenu" aria-controls="roomRail" aria-expanded="false">Rooms</button></div>
132
+ <div class="room-title-row"><h1 id="roomName"></h1><button id="btnRoomsDrawer" class="chip rooms-drawer-trigger" type="button" aria-label="Open room list" data-i18n-aria-label="roomsMenu" aria-controls="roomRail" aria-expanded="false"><svg class="action-icon" aria-hidden="true" viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h16"/></svg><span class="action-label">Rooms</span></button></div>
91
133
  <p class="room-meta">
92
134
  <button type="button" id="btnCopyId" class="copy-id" aria-label="Copy room ID" data-i18n-aria-label="copyRoomId" title="Click to copy the full room ID" data-i18n-title="copyRoomIdTitle">
93
135
  <span class="mono" id="roomIdShort"></span><span class="copy-ok" data-i18n="copied">Copied</span>
@@ -95,16 +137,9 @@
95
137
  </p>
96
138
  </div>
97
139
  <div class="chat-head-actions">
98
- <div class="locale-control">
99
- <label for="localeSelectChat" data-i18n="languageLabel">Language</label>
100
- <select id="localeSelectChat" class="locale-select" aria-label="Language" data-i18n-aria-label="languageLabel">
101
- <option value="en">English</option>
102
- <option value="zh-CN">中文</option>
103
- </select>
104
- </div>
105
140
  <div class="anchor questions-anchor">
106
141
  <button class="chip questions-trigger" type="button" id="btnQuestions" aria-haspopup="true" aria-expanded="false" aria-controls="questionPanel">
107
- <span data-i18n="questions">Questions</span><span id="questionBadge" class="question-badge" hidden></span>
142
+ <svg class="action-icon" aria-hidden="true" viewBox="0 0 24 24"><path d="M9.5 9a2.5 2.5 0 1 1 4.6 1.4c-.7.9-2.1 1.3-2.1 2.8M12 17.5h.01"/><circle cx="12" cy="12" r="9"/></svg><span class="action-label" data-i18n="questions">Questions</span><span id="questionBadge" class="question-badge" hidden></span>
108
143
  </button>
109
144
  <section class="panel question-panel" id="questionPanel" aria-labelledby="questionHeading" hidden>
110
145
  <div class="question-panel-head"><h3 id="questionHeading" tabindex="-1" data-i18n="pendingQuestions">Pending questions</h3>
@@ -115,7 +150,7 @@
115
150
  </section>
116
151
  </div>
117
152
  <div class="anchor">
118
- <button class="chip" type="button" id="btnAnnouncements" aria-haspopup="true" aria-expanded="false" aria-controls="announcementPanel" data-i18n="announcements">Announcements</button>
153
+ <button class="chip" type="button" id="btnAnnouncements" aria-haspopup="true" aria-expanded="false" aria-controls="announcementPanel"><svg class="action-icon" aria-hidden="true" viewBox="0 0 24 24"><path d="M5 4h14v16H5zM8 8h8M8 12h8M8 16h5"/></svg><span class="action-label" data-i18n="announcements">Announcements</span></button>
119
154
  <section class="panel announcement-panel" id="announcementPanel" aria-labelledby="announcementHeading" hidden>
120
155
  <div class="announcement-head"><h3 id="announcementHeading" tabindex="-1" data-i18n="announcements">Announcements</h3><button type="button" id="btnRefreshAnnouncements" class="question-refresh" data-i18n="refreshQuestions">Refresh</button></div>
121
156
  <p id="announcementStatus" class="hint" role="status" aria-live="polite"></p>
@@ -129,29 +164,20 @@
129
164
  </section>
130
165
  </div>
131
166
  <div class="anchor">
132
- <button class="chip" type="button" id="btnMembers" aria-label="Members" data-i18n-aria-label="members" aria-haspopup="true" aria-expanded="false" data-i18n="members">Members</button>
167
+ <button class="chip" type="button" id="btnMembers" aria-label="Members" data-i18n-aria-label="members" aria-haspopup="true" aria-expanded="false"><svg class="action-icon" aria-hidden="true" viewBox="0 0 24 24"><circle cx="9" cy="8" r="3"/><path d="M3.5 19v-1.5a5.5 5.5 0 0 1 11 0V19zM16 5.5a3 3 0 0 1 0 5.8M17 14a4.5 4.5 0 0 1 3.5 4.4V19h-3"/></svg><span class="action-label" data-i18n="members">Members</span></button>
133
168
  <div class="panel" id="memberPanel" hidden>
134
169
  <h3 data-i18n="members">Members</h3>
135
170
  <ul id="memberList"></ul>
136
171
  <p id="memberEmpty" class="hint" data-i18n="noMembers" hidden>No members yet.</p>
137
172
  </div>
138
173
  </div>
139
- <div class="anchor">
140
- <button class="chip profile-trigger" type="button" id="btnSettings" aria-label="Your profile and settings" data-i18n-aria-label="profileMenu" aria-haspopup="dialog" aria-expanded="false" aria-controls="chatSettings"><span id="profileAvatar" class="rail-avatar" aria-hidden="true">?</span></button>
141
- <div class="panel" id="chatSettings" role="dialog" aria-modal="false" aria-labelledby="settingsHeading" hidden>
142
- <h3 id="settingsHeading" data-i18n="settings">Settings</h3>
143
- <label class="field mobile-locale"><span class="field-label" data-i18n="languageLabel">Language</span><select id="localeSelectSettings" class="locale-select"><option value="en">English</option><option value="zh-CN">中文</option></select></label>
144
- <label class="field">
145
- <span class="field-label" data-i18n="tokenOptional">Access token (optional)</span>
146
- <input id="inTokenChat" class="input" type="password" placeholder="Enter if the server requires it" data-i18n-placeholder="tokenPlaceholder" autocomplete="off" spellcheck="false">
147
- </label>
148
- <button class="btn ghost small" type="button" data-token-save="inTokenChat" data-i18n="save">Save</button>
149
- <p id="tokenHint" class="hint" data-i18n="tokenRequired" hidden>The server requires an access token (401).</p>
150
- <p class="hint" data-i18n="privacyNote">Anyone with the shared token can read direct messages and manage rooms; the server can read them too.</p>
174
+ <div class="anchor room-options-anchor">
175
+ <button class="chip" type="button" id="btnRoomOptions" aria-haspopup="true" aria-expanded="false" aria-controls="roomOptions"><svg class="action-icon" aria-hidden="true" viewBox="0 0 24 24"><circle cx="5" cy="12" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/></svg><span class="action-label" data-i18n="roomOptions">Options</span></button>
176
+ <div class="panel room-options-panel" id="roomOptions" hidden>
177
+ <button class="menu-action" type="button" id="btnLeave" data-i18n="leave">Leave room</button>
178
+ <button class="menu-action danger-text" type="button" id="btnDeleteRoom" data-i18n="deleteRoom">Delete room</button>
151
179
  </div>
152
180
  </div>
153
- <button class="chip danger" type="button" id="btnDeleteRoom" aria-label="Delete room" data-i18n-aria-label="deleteRoom" data-i18n="deleteRoom">Delete room</button>
154
- <button class="chip" type="button" id="btnLeave" aria-label="Leave room" data-i18n-aria-label="leave" data-i18n="leave">Leave</button>
155
181
  </div>
156
182
  </header>
157
183
 
@@ -182,7 +208,14 @@
182
208
  <footer class="composer">
183
209
  <p id="sendError" class="send-error" role="alert" hidden></p>
184
210
  <div id="mentionPicker" class="mention-picker" role="listbox" aria-label="Choose a member to mention" data-i18n-aria-label="mentionMembers" hidden></div>
211
+ <section id="attachmentTray" class="attachment-tray" aria-label="Attachments" data-i18n-aria-label="attachments" hidden>
212
+ <p id="attachmentVolatile" class="attachment-volatile" data-i18n="attachmentVolatile" hidden></p>
213
+ <ul id="attachmentList" class="attachment-list"></ul>
214
+ <p id="attachmentStatus" class="attachment-status" role="status" aria-live="polite"></p>
215
+ </section>
185
216
  <div class="composer-row">
217
+ <button class="attachment-button" type="button" id="btnAddAttachments" aria-label="Add files" data-i18n-aria-label="addFiles" aria-controls="attachmentPicker" disabled><svg aria-hidden="true" viewBox="0 0 24 24"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.82-2.83l8.49-8.48"/></svg></button>
218
+ <input id="attachmentPicker" type="file" multiple hidden>
186
219
  <textarea id="msgInput" class="input" rows="1" maxlength="2000" placeholder="Type a message, Enter to send, Shift+Enter for a new line" data-i18n-placeholder="messagePlaceholder" autocomplete="off" aria-autocomplete="list" aria-controls="mentionPicker" aria-expanded="false" disabled></textarea>
187
220
  <button class="btn primary" type="button" id="btnSend" data-i18n="send" disabled>Send</button>
188
221
  </div>
@@ -191,6 +224,7 @@
191
224
  <p id="draftCount" class="draft-count">0 / 2000</p>
192
225
  </div>
193
226
  </footer>
227
+ <div id="attachmentDropOverlay" class="attachment-drop-overlay" role="status" aria-live="polite" data-i18n="dropFilesHere" hidden></div>
194
228
  </section>
195
229
 
196
230
  </main>
@@ -1,9 +1,12 @@
1
1
  import RoomService, { RoomError, type Room } from "../src/room-service";
2
- import { writeState } from "../src/store";
2
+ import { databasePath, writeState } from "../src/store";
3
+ import { writeSqliteStateWithDatabase } from "../src/sqlite-state";
4
+ import { isOperator } from "./admin-auth";
3
5
  import { clearPendingAdmission } from "../src/queue";
4
6
  import { removeRoomResources } from "../src/resources";
5
7
 
6
8
  const json = (body: unknown, status = 200) => Response.json(body, { status });
9
+ class ProtectedRoomDeletion extends Error {}
7
10
  const serializeRoom = (room: Room) => ({ ...room, participants: [...room.participants.values()], messages: room.messages, kind: room.kind ?? "group" });
8
11
  const mutate = <T>(fn: (service: RoomService, registry: import("../src/store").Registry) => T) => writeState(fn);
9
12
  async function objectBody(req: Request): Promise<Record<string, unknown> | undefined> {
@@ -71,15 +74,29 @@ export async function roomManagement(req: Request, url: URL): Promise<Response |
71
74
  const body = await objectBody(req);
72
75
  if (!body) return json({ error: "JSON object body is required" }, 400);
73
76
  const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
74
- if (!sessionID || sessionID.length > 128) return json({ error: "sessionID is required" }, 400);
75
- const sessions = await mutate((svc, registry) => {
76
- svc.getRoom(roomId);
77
- if (!registry[roomId]?.[sessionID]) throw new RoomError("NOT_JOINED", "actor is not a room member");
78
- const removed = Object.keys(registry[roomId]);
79
- svc.deleteRoom(roomId);
80
- delete registry[roomId];
81
- return removed;
82
- });
77
+ if (body.sessionID !== undefined && (typeof body.sessionID !== "string" || sessionID.length > 128)) return json({ error: "invalid sessionID" }, 400);
78
+ if (!sessionID && !isOperator(req)) return json({ error: "sessionID is required" }, 400);
79
+ let sessions: string[];
80
+ try {
81
+ sessions = await writeSqliteStateWithDatabase(databasePath(), (svc, registry, db) => {
82
+ svc.getRoom(roomId);
83
+ const hasAdminSchema = db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='admin_rooms'").get();
84
+ const protectedRoom = Boolean(hasAdminSchema && db.query("SELECT 1 FROM admin_rooms WHERE room_id=? OR target_room_id=? LIMIT 1").get(roomId, roomId));
85
+ const operator = isOperator(req);
86
+ if (protectedRoom && !operator) throw new ProtectedRoomDeletion();
87
+ // Only an operator may bypass membership when deleting an admin room or its target.
88
+ if (!protectedRoom || !operator) {
89
+ if (!registry[roomId]?.[sessionID]) throw new RoomError("NOT_JOINED", "actor is not a room member");
90
+ }
91
+ const removed = Object.keys(registry[roomId] ?? {});
92
+ svc.deleteRoom(roomId);
93
+ delete registry[roomId];
94
+ return removed;
95
+ });
96
+ } catch (error) {
97
+ if (error instanceof ProtectedRoomDeletion) return json({ error: "operator token required to delete a designated admin or target room" }, 403);
98
+ throw error;
99
+ }
83
100
  await removeRoomResources(roomId).catch(() => console.error("failed to clean deleted room resources", roomId));
84
101
  for (const sid of sessions) clearPendingAdmission(sid, roomId, Number.MAX_SAFE_INTEGER);
85
102
  return json({ ok: true });
@@ -12,6 +12,9 @@ function contentDisposition(name: string, inline: boolean): string {
12
12
  }
13
13
 
14
14
  export async function resourceRoutes(req: Request, url: URL): Promise<Response | undefined> {
15
+ if (req.method === "GET" && url.pathname === "/resources/config") {
16
+ return Response.json({ maxFileSizeBytes: maxResourceBytes() }, { headers: { "Cache-Control": "no-store" } });
17
+ }
15
18
  const upload = url.pathname.match(/^\/rooms\/([^/]+)\/resources$/);
16
19
  const item = url.pathname.match(/^\/rooms\/([^/]+)\/resources\/([^/]+)(\/content)?$/);
17
20
  if ((!upload || req.method !== "POST") && (!item || req.method !== "GET")) return undefined;
package/server/wake.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import os from "node:os";
2
2
  import type { Message } from "../src/room-service";
3
- import { authHeader, formatNotificationLines, formatServeWakePrompt, readState, writeState, type RegistryEntry } from "../src/store";
4
- import { admissionMatches, clearPendingAdmission, getOrCreatePendingAdmission, markPendingAdmissionAdmitted, pendingAdmission, rejectPendingAdmission, type QueueBody, type QueueItem } from "../src/queue";
3
+ import { formatNotificationLines, formatServeWakePrompt, readState, writeState, type RegistryEntry } from "../src/store";
4
+ import { clearPendingAdmission, getOrCreatePendingAdmission, markPendingAdmissionAdmitted, pendingAdmission, rejectPendingAdmission, type QueueItem } from "../src/queue";
5
+ import { sendAsyncNotification } from "../src/queue-transport";
5
6
  import { readInbox, type InboxItem } from "./inbox";
6
7
  import { explicitlyAddresses } from "../src/mentions";
7
8
 
@@ -70,21 +71,13 @@ async function deliverWake(
70
71
  : formatServeWakePrompt(roomName, roomId, lines);
71
72
  const admission = getOrCreatePendingAdmission(sid, roomId, delta as QueueItem[], prompt,
72
73
  delta.reduce((max, item) => Math.max(max, item.createdAt), 0), capped);
73
- const body: QueueBody = { id: admission.id, prompt: { text: admission.prompt }, delivery: "steer", resume: true };
74
74
  const directory = entry.directory ?? process.env.OPENCODE_DIRECTORY;
75
- const auth = authHeader();
76
75
  try {
77
- const response = await fetch(`${serveWakeUrl.replace(/\/+$/, "")}/api/session/${encodeURIComponent(sid)}/prompt`, {
78
- method: "POST",
79
- headers: { "Content-Type": "application/json", ...(auth ? { Authorization: auth } : {}),
80
- ...(directory ? { "x-opencode-directory": encodeURIComponent(directory) } : {}) },
81
- body: JSON.stringify(body), signal: AbortSignal.timeout(10_000),
82
- });
83
- const data = await response.json().catch(() => undefined);
84
- if (response.ok && admissionMatches(data, body, sid)) {
76
+ const result = await sendAsyncNotification({ serverUrl: serveWakeUrl, directory, protocol: "v1" }, sid, admission.prompt);
77
+ if (result === "delivered") {
85
78
  markPendingAdmissionAdmitted(sid, roomId, admission.id);
86
79
  touchActive(sid);
87
80
  await confirmQueued(admission.maxTs);
88
- } else if (response.status !== 404) rejectPendingAdmission(sid, roomId, admission.id);
81
+ } else if (result === "rejected") rejectPendingAdmission(sid, roomId, admission.id);
89
82
  } catch { /* The periodic inbox poll retries delivery. */ }
90
83
  }
@@ -85,6 +85,18 @@ The plugin requests host file-read permissions and returns resource metadata and
85
85
 
86
86
  Respect permission denials and do not upload secrets or unrelated files. A local path is read on the machine running the plugin, not on the central server; remote URLs are not upload paths. The server sets the single-file size limit, defaulting to 100 MiB. Images, audio, and video may preview in the browser; other formats are offered as downloads. Resource markers refer to the room where the file was uploaded, not arbitrary filesystem paths or public links.
87
87
 
88
+ ## Administrator supervision
89
+
90
+ The separate `admin` tool supports operator-enrolled administrator rooms in central mode. A normal room token, a mention, or room membership does not grant administrator privileges. Do not attempt to appoint yourself or another Agent.
91
+
92
+ When the user privately supplies an enrollment instruction, call `admin` with `action: "admin_claim"`, `roomId`, and `enrollmentKey` in that designated session. Never post the enrollment key in a room. The plugin stores the resulting capability privately; do not request, copy, or expose it. If enrollment fails, ask the operator to reset it.
93
+
94
+ For a designated supervisor, `admin_overview` lists rooms, members, tasks, and plans. Use `admin_dispatch` with the administrator `roomId`, `targetRoomId`, `targetSessionID`, and `text` to assign work to an existing Agent without joining its room. Use `admin_history` for bounded target-room history and `admin_tasks` to inspect assignments. Room names or display names are not substitutes for target session IDs.
95
+
96
+ Workers receiving an assignment can call `admin` with `action: "task_progress"`, `taskId`, `status`, and `progress`. Supported states are `pending`, `working`, `blocked`, `completed`, and `cancelled`. Report actual progress and blockers; a received steer is not evidence that work is complete. Do not join the administrator room to report progress.
97
+
98
+ Use `admin_plan_create`, `admin_plans`, `admin_plan_update`, and `admin_plan_delete` for recurring supervision authorized by the user. Timers persist on the server and coalesce offline reminders; they do not guarantee execution while the host is unavailable. Check task reports and concrete evidence before declaring completion. Pause or delete a plan when its purpose ends.
99
+
88
100
  ## Testing and subagents
89
101
 
90
102
  Debug only in newly created temporary rooms whose names start with `__Test_`, preferably on an isolated local center. Never join an existing room for testing. Delete temporary rooms and clean up test identities and processes afterward.
@@ -0,0 +1,130 @@
1
+ import { loadAdminCapability, loadTaskToken, saveAdminCapability, type AdminIdentity } from "./admin-credentials";
2
+ import type { CenterOpts } from "./center-client";
3
+ import type { QueueTransport } from "./queue-transport";
4
+ import { z } from "zod";
5
+
6
+ export type AdminContext = { sessionID: string };
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;
14
+ };
15
+ 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"]),
17
+ 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
+ limit: z.number().int().min(1).max(50).optional(),
22
+ });
23
+ export const adminToolDescription = "Administer an operator-enrolled room: overview, history, task dispatch, task progress, and plans. This tool never joins a room.";
24
+ const safe = (value: string) => encodeURIComponent(value);
25
+
26
+ async function send(opts: CenterOpts, path: string, method: string, body?: unknown,
27
+ capability?: string, sessionID?: string, ownerID?: string): Promise<Record<string, unknown>> {
28
+ const base = new URL(opts.center);
29
+ const headers: Record<string, string> = { ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}) };
30
+ if (body !== undefined || method === "DELETE") headers["Content-Type"] = "application/json";
31
+ if (capability) headers["X-Chat-Admin-Capability"] = capability;
32
+ if (sessionID) headers["X-Chat-Agent-Session"] = sessionID;
33
+ if (ownerID !== undefined) headers["X-Chat-Agent-Owner"] = ownerID;
34
+ const target = new URL(`${opts.center.replace(/\/+$/, "")}${path}`);
35
+ if (target.origin !== base.origin) throw new Error("invalid admin request origin");
36
+ const response = await fetch(target, {
37
+ method, headers, body: body === undefined ? undefined : JSON.stringify(body),
38
+ redirect: "error", signal: AbortSignal.timeout(10_000),
39
+ });
40
+ if (new URL(response.url || base.href).origin !== base.origin) throw new Error("admin request origin changed");
41
+ const data = await response.json().catch(() => ({})) as Record<string, unknown>;
42
+ if (!response.ok) throw Object.assign(new Error(typeof data.error === "string" ? data.error : `center error ${response.status}`), { status: response.status });
43
+ return data;
44
+ }
45
+
46
+ export function protectedAdminRequest(opts: CenterOpts, path: string, method: "GET" | "POST",
47
+ capability: string, sessionID: string, ownerID: string, body?: unknown): Promise<Record<string, unknown>> {
48
+ return send(opts, path, method, body, capability, sessionID, ownerID);
49
+ }
50
+
51
+ export async function adminTool(args: AdminArgs, context: AdminContext, opts: CenterOpts,
52
+ transport: QueueTransport): Promise<string> {
53
+ 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
+ const roomId = args.roomId?.trim();
69
+ if (!roomId) return "error: roomId is required";
70
+ const ownerID = transport.receiverOwnerID;
71
+ if (args.action === "admin_claim") {
72
+ if (!args.enrollmentKey?.trim()) return "error: enrollmentKey is required";
73
+ if (transport.protocol === "v2" && !ownerID) return "error: this runtime has no verified receiver owner identity";
74
+ const identity: AdminIdentity = { center: opts.center, roomId, sessionID: context.sessionID, ownerID: ownerID ?? "" };
75
+ try {
76
+ const result = await send(opts, `/admin/rooms/${safe(roomId)}/claim`, "POST", {
77
+ sessionID: context.sessionID, receiverOwnerID: ownerID ?? "", enrollmentKey: args.enrollmentKey,
78
+ });
79
+ if (typeof result.capability !== "string" || !result.capability) throw new Error("invalid admin claim response");
80
+ await saveAdminCapability(identity, result.capability);
81
+ return "admin room enrolled for this agent session";
82
+ } catch (error) {
83
+ const status = (error as { status?: unknown })?.status;
84
+ const detail = typeof status === "number" ? ` (HTTP ${status})` : "";
85
+ return `error: admin claim failed${detail}. If enrollment expired or saving failed, ask the operator to reset enrollment.`;
86
+ }
87
+ }
88
+ if (transport.protocol === "v2" && !ownerID) return "error: this runtime has no verified receiver owner identity";
89
+ const identity: AdminIdentity = { center: opts.center, roomId, sessionID: context.sessionID, ownerID: ownerID ?? "" };
90
+ const capability = await loadAdminCapability(identity);
91
+ if (!capability) return "error: no admin binding for this session; ask the operator to enroll this agent";
92
+ const root = `/admin/rooms/${safe(roomId)}`;
93
+ const request = (route: string, method: string, body?: unknown) =>
94
+ send(opts, `${root}${route}`, method, body, capability, context.sessionID, ownerID ?? "");
95
+ try {
96
+ let result: Record<string, unknown>;
97
+ switch (args.action) {
98
+ case "admin_overview": result = await request("/overview", "GET"); break;
99
+ case "admin_history": {
100
+ if (!args.targetRoomId) return "error: targetRoomId is required";
101
+ const query = new URLSearchParams();
102
+ query.set("targetRoomId", args.targetRoomId);
103
+ query.set("limit", String(Math.min(50, Math.max(1, args.limit ?? 20))));
104
+ result = await request(`/history?${query}`, "GET"); break;
105
+ }
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
+ default: return "error: unsupported admin action";
124
+ }
125
+ return JSON.stringify(result);
126
+ } catch (error) {
127
+ const message = error instanceof Error ? error.message : "admin request failed";
128
+ return `error: ${capability ? message.replaceAll(capability, "[redacted]") : message}`;
129
+ }
130
+ }
@@ -0,0 +1,58 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, rename, chmod, writeFile, rm } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { statePath } from "./store";
5
+
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
+ const keyOf = (identity: AdminIdentity) => createHash("sha256").update(JSON.stringify([
9
+ new URL(identity.center).origin, identity.roomId, identity.sessionID, identity.ownerID,
10
+ ])).digest("hex");
11
+
12
+ function credentialPath(identity: AdminIdentity): string {
13
+ return path.join(path.dirname(statePath()), "admin-capabilities", `${keyOf(identity)}.json`);
14
+ }
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
+ async function persist(file: string, content: unknown): Promise<void> {
23
+ const directory = path.dirname(file);
24
+ await mkdir(directory, { recursive: true, mode: 0o700 });
25
+ await chmod(directory, 0o700);
26
+ const temporary = `${file}.${randomUUID()}.tmp`;
27
+ try {
28
+ await writeFile(temporary, JSON.stringify(content), { mode: 0o600, flag: "wx" });
29
+ await chmod(temporary, 0o600);
30
+ await rename(temporary, file);
31
+ await chmod(file, 0o600);
32
+ } finally { await rm(temporary, { force: true }); }
33
+ }
34
+
35
+ export async function loadAdminCapability(identity: AdminIdentity): Promise<string | undefined> {
36
+ try {
37
+ const file = credentialPath(identity);
38
+ const content = JSON.parse(await readFile(file, "utf8")) as { capability?: unknown; origin?: unknown };
39
+ return content.origin === new URL(identity.center).origin && typeof content.capability === "string"
40
+ ? content.capability : undefined;
41
+ } catch { return undefined; }
42
+ }
43
+
44
+ export async function saveAdminCapability(identity: AdminIdentity, capability: string): Promise<void> {
45
+ const file = credentialPath(identity);
46
+ await persist(file, { origin: new URL(identity.center).origin, capability });
47
+ }
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
+ }
@@ -247,7 +247,7 @@ export async function centerAction(
247
247
  if (!result.member) {
248
248
  return "error: not joined";
249
249
  }
250
- const items = Array.isArray(result.items) ? result.items : [];
250
+ const items = (Array.isArray(result.items) ? result.items : []).filter((item) => item.senderSessionID !== sessionID);
251
251
  if (items.length === 0) {
252
252
  return "no new messages";
253
253
  }
@@ -13,6 +13,7 @@ import { explicitlyAddresses } from "./mentions";
13
13
  import { claimBackgroundAttempt } from "./receiver-state";
14
14
  import { prepareReceiptCandidate, receiptDestination } from "./agent-receipts";
15
15
  import { serializeSessionPush } from "./session-delivery";
16
+ import { checkSupervisionInbox } from "./supervision-inbox";
16
17
  export { serializeSessionPush } from "./session-delivery";
17
18
  import {
18
19
  sendAsyncNotification,
@@ -68,6 +69,7 @@ export async function checkCenterInbox(
68
69
  items = [...merged.values()].sort((a, b) => a.createdAt - b.createdAt);
69
70
  }
70
71
  await pushItemsToSession(opts, sessionID, items, transport, queued, qualified);
72
+ await checkSupervisionInbox(opts, sessionID, transport);
71
73
  });
72
74
  } catch {
73
75
  // The next inbox poll retries failed delivery.