@alexsun-top/opencode-chat-room 0.6.5 → 0.6.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +4 -0
  3. package/README.zh-CN.md +4 -0
  4. package/cli.ts +1 -1
  5. package/docs/administrator-rooms.md +5 -4
  6. package/index.ts +2 -2
  7. package/package.json +5 -2
  8. package/plugin.ts +21 -20
  9. package/server/admin-routes.ts +15 -7
  10. package/server/admin-state.ts +2 -2
  11. package/server/announcement-routes.ts +2 -2
  12. package/server/assets/attachments.css +25 -0
  13. package/server/assets/base.css +42 -30
  14. package/server/assets/chat/admin-badge.js +27 -0
  15. package/server/assets/chat/admin.js +71 -24
  16. package/server/assets/chat/announcements.js +27 -11
  17. package/server/assets/chat/attachments.js +50 -10
  18. package/server/assets/chat/events.js +31 -7
  19. package/server/assets/chat/image-zoom.js +57 -0
  20. package/server/assets/chat/index.js +4 -0
  21. package/server/assets/chat/markdown.js +33 -4
  22. package/server/assets/chat/members.js +14 -6
  23. package/server/assets/chat/message-polling.js +137 -0
  24. package/server/assets/chat/message-window.js +14 -0
  25. package/server/assets/chat/messages.js +6 -128
  26. package/server/assets/chat/panels.js +37 -0
  27. package/server/assets/chat/pwa.js +18 -0
  28. package/server/assets/chat/receipts.js +3 -1
  29. package/server/assets/chat/reminders.js +19 -5
  30. package/server/assets/chat/room-list.js +51 -0
  31. package/server/assets/chat/rooms.js +20 -80
  32. package/server/assets/chat/state.js +28 -14
  33. package/server/assets/chat/system-messages.js +25 -7
  34. package/server/assets/conversation.css +18 -26
  35. package/server/assets/icons/apple-touch-icon.png +0 -0
  36. package/server/assets/icons/icon-192.png +0 -0
  37. package/server/assets/icons/icon-512.png +0 -0
  38. package/server/assets/responsive.css +25 -8
  39. package/server/chat-server.ts +58 -8
  40. package/server/chat.html +108 -68
  41. package/server/history-route.ts +1 -1
  42. package/server/inbox.ts +2 -2
  43. package/server/manifest.webmanifest +15 -0
  44. package/server/member-routes.ts +4 -4
  45. package/server/newrooms.ts +96 -13
  46. package/server/resource-routes.ts +19 -5
  47. package/server/room-owner.ts +89 -0
  48. package/server/room-payload.ts +4 -2
  49. package/server/room-reminders.ts +3 -3
  50. package/server/sw.js +73 -0
  51. package/server/wake.ts +5 -5
  52. package/skills/chatroom/SKILL.md +3 -1
  53. package/src/README.md +20 -0
  54. package/src/{admin-client.ts → agent/admin-client.ts} +15 -9
  55. package/src/{admin-credentials.ts → agent/admin-credentials.ts} +1 -1
  56. package/src/{agent-presence.ts → agent/agent-presence.ts} +2 -2
  57. package/src/{agent-receipts.ts → agent/agent-receipts.ts} +2 -2
  58. package/src/{announcement-tool.ts → agent/announcement-tool.ts} +2 -2
  59. package/src/{chatroom-skill.ts → agent/chatroom-skill.ts} +1 -1
  60. package/src/{center-client.ts → center/center-client.ts} +22 -9
  61. package/src/{center-inbox.ts → center/center-inbox.ts} +9 -9
  62. package/src/{center-wake.ts → center/center-wake.ts} +6 -6
  63. package/src/{mentions.ts → center/mentions.ts} +1 -1
  64. package/src/{queue-transport.ts → center/queue-transport.ts} +3 -3
  65. package/src/{queue.ts → center/queue.ts} +2 -2
  66. package/src/{reminder-client.ts → center/reminder-client.ts} +1 -1
  67. package/src/{session-delivery.ts → center/session-delivery.ts} +1 -1
  68. package/src/{announcements.ts → rooms/announcements.ts} +2 -2
  69. package/src/{resource-upload.ts → rooms/resource-upload.ts} +1 -1
  70. package/src/{resources.ts → rooms/resources.ts} +55 -9
  71. package/src/{room-service.ts → rooms/room-service.ts} +12 -1
  72. package/src/{background.ts → runtime/background.ts} +3 -3
  73. package/src/{plugin-notifications.ts → runtime/plugin-notifications.ts} +8 -8
  74. package/src/{v1-plugin.ts → runtime/v1-plugin.ts} +4 -4
  75. package/src/{v2-plugin.ts → runtime/v2-plugin.ts} +9 -9
  76. package/src/{v2-receiver.ts → runtime/v2-receiver.ts} +7 -7
  77. package/src/{watch.ts → runtime/watch.ts} +12 -12
  78. package/src/{member-state.ts → state/member-state.ts} +2 -2
  79. package/src/{sqlite-state.ts → state/sqlite-state.ts} +35 -15
  80. package/src/{store.ts → state/store.ts} +2 -2
  81. package/src/tests/announcement-board.ts +176 -0
  82. /package/src/{resource-read.ts → rooms/resource-read.ts} +0 -0
  83. /package/src/{receiver-owner.ts → state/receiver-owner.ts} +0 -0
  84. /package/src/{receiver-state.ts → state/receiver-state.ts} +0 -0
@@ -0,0 +1,89 @@
1
+ import type { Participant, Room } from "../src/rooms/room-service.ts";
2
+
3
+ export type OwnerEntry = { name?: string | null; protocol?: string | null; host?: string | null; receiverOwnerID?: string | null; membershipID?: string | null };
4
+
5
+ // Agents carry a protocol (v1/v2), a host, or a receiver binding; only a person may
6
+ // own a room, so any of those fields marks an entry that must never be promoted.
7
+ export function isUser(entry: OwnerEntry | undefined | null): boolean {
8
+ return Boolean(entry?.name) && !entry!.protocol && !entry!.host && !entry!.receiverOwnerID;
9
+ }
10
+
11
+ function humans(room: Room, registry: Record<string, OwnerEntry>): OwnerEntry[] {
12
+ const joined = new Map([...room.participants.values()].map((member) => [member.name, member]));
13
+ return Object.values(registry)
14
+ .filter(isUser)
15
+ .filter((entry) => joined.has(entry.name!))
16
+ .sort((left, right) => joined.get(left.name!)!.joinedAt - joined.get(right.name!)!.joinedAt) as OwnerEntry[];
17
+ }
18
+
19
+ // The owner is a person bound to a server-issued membership. The display name is
20
+ // only for presentation: a new session that reuses the name must not inherit the room.
21
+ export function isOwnerEntry(room: Room, entry: OwnerEntry | null | undefined): boolean {
22
+ return isUser(entry) && entry!.name === room.ownerId &&
23
+ (!room.ownerMembershipID || entry!.membershipID === room.ownerMembershipID);
24
+ }
25
+
26
+ export function isRoomAdmin(room: Room, entry: OwnerEntry | null | undefined): boolean {
27
+ if (isOwnerEntry(room, entry)) return true;
28
+ if (!isUser(entry) || !(room.adminIds ?? []).includes(entry!.name!)) return false;
29
+ if (!room.adminMembershipIDs?.length) return true;
30
+ return !entry!.membershipID || room.adminMembershipIDs.includes(entry!.membershipID);
31
+ }
32
+
33
+ // A room whose owner entry vanished follows the explicit successor first, then the
34
+ // first person still present; the last person out leaves the room open to claim.
35
+ export function settleOwner(room: Room, registry: Record<string, OwnerEntry>): string {
36
+ const people = humans(room, registry);
37
+ const bound = room.ownerMembershipID ? people.find((entry) => entry.membershipID === room.ownerMembershipID) : undefined;
38
+ if (bound) { room.ownerId = bound.name!; return room.ownerId; }
39
+ if (!room.ownerMembershipID) {
40
+ const named = people.find((entry) => entry.name === room.ownerId);
41
+ if (named) { room.ownerMembershipID = named.membershipID ?? undefined; return room.ownerId; }
42
+ }
43
+ const successor = room.successorId
44
+ ? people.find((entry) => room.successorMembershipID ? entry.membershipID === room.successorMembershipID : entry.name === room.successorId)
45
+ : undefined;
46
+ const chosen = successor ?? people[0];
47
+ room.ownerId = chosen?.name ?? "";
48
+ if (chosen?.membershipID) room.ownerMembershipID = chosen.membershipID; else delete room.ownerMembershipID;
49
+ delete room.successorId;
50
+ delete room.successorMembershipID;
51
+ const admins = (room.adminIds ?? []).filter((name) => name !== room.ownerId);
52
+ if (admins.length) room.adminIds = admins;
53
+ else if (room.adminIds) delete room.adminIds;
54
+ if (chosen?.membershipID && room.adminMembershipIDs?.length) {
55
+ const ids = room.adminMembershipIDs.filter((id) => id !== chosen.membershipID);
56
+ if (ids.length) room.adminMembershipIDs = ids; else delete room.adminMembershipIDs;
57
+ }
58
+ return room.ownerId;
59
+ }
60
+
61
+ // Joining must not transfer ownership: bind a legacy room once, follow a renamed
62
+ // owner membership, and only settle when the bound owner is really gone.
63
+ export function bindOwner(room: Room, registry: Record<string, OwnerEntry>): void {
64
+ if (!room.ownerId) return;
65
+ const people = humans(room, registry);
66
+ if (room.ownerMembershipID) {
67
+ const bound = people.find((entry) => entry.membershipID === room.ownerMembershipID);
68
+ if (bound) { room.ownerId = bound.name!; return; }
69
+ settleOwner(room, registry);
70
+ return;
71
+ }
72
+ const named = people.find((entry) => entry.name === room.ownerId);
73
+ if (named?.membershipID) room.ownerMembershipID = named.membershipID;
74
+ }
75
+
76
+ // Delegated admins follow the people still in the room; the owner is implicit.
77
+ export function settleAdmins(room: Room, registry: Record<string, OwnerEntry>): void {
78
+ if (!room.adminIds?.length) return;
79
+ const people = Object.values(registry).filter(isUser);
80
+ const names = new Set(people.map((entry) => entry.name));
81
+ const next = room.adminIds.filter((name) => names.has(name));
82
+ if (next.length) room.adminIds = next;
83
+ else delete room.adminIds;
84
+ if (room.adminMembershipIDs?.length) {
85
+ const ids = new Set(people.map((entry) => entry.membershipID).filter(Boolean));
86
+ const kept = room.adminMembershipIDs.filter((id) => ids.has(id));
87
+ if (kept.length) room.adminMembershipIDs = kept; else delete room.adminMembershipIDs;
88
+ }
89
+ }
@@ -1,5 +1,5 @@
1
- import { countOpenQuestions, readHistory } from "../src/store";
2
- import type { Room } from "../src/room-service";
1
+ import { countOpenQuestions, readHistory } from "../src/state/store.ts";
2
+ import type { Room } from "../src/rooms/room-service.ts";
3
3
  import { binding, tx } from "./admin-state";
4
4
 
5
5
  // Initial page of history sent when a room is opened; older pages load on scroll.
@@ -16,6 +16,8 @@ export async function roomPayload(room: Room, limit = ROOM_WINDOW) {
16
16
  name: room.name,
17
17
  description: room.description ?? "",
18
18
  ownerId: room.ownerId,
19
+ adminIds: room.adminIds ?? [],
20
+ successorId: room.successorId ?? null,
19
21
  createdAt: room.createdAt,
20
22
  participants: [...room.participants.values()],
21
23
  messages: page.messages,
@@ -1,8 +1,8 @@
1
1
  import { Cron } from "croner";
2
2
  import { randomUUID } from "node:crypto";
3
- import { databasePath } from "../src/store";
4
- import { initializeReminderSchema, withStateTransaction } from "../src/sqlite-state";
5
- import type { Message } from "../src/room-service";
3
+ import { databasePath } from "../src/state/store.ts";
4
+ import { initializeReminderSchema, withStateTransaction } from "../src/state/sqlite-state.ts";
5
+ import type { Message } from "../src/rooms/room-service.ts";
6
6
 
7
7
  type Schedule = { type: "once"; at: string; timezone?: string } | { type: "cron"; expression: string; timezone: string };
8
8
  type Row = { id: string; room_id: string; creator_session_id: string; initiator: string; text: string; schedule_type: string; at: string | null; expression: string | null; timezone: string | null; paused: number; next_run_at: number; created_at: number; last_error: string | null };
package/server/sw.js ADDED
@@ -0,0 +1,73 @@
1
+ // The server fills in {{version}} so a release installs a worker that replaces the old cache.
2
+ const VERSION = "{{version}}";
3
+ const CACHE = `oc-chat-${VERSION}`;
4
+ const SHELL = "/chat";
5
+ const STATIC = [
6
+ "/assets/base.css",
7
+ "/assets/conversation.css",
8
+ "/assets/attachments.css",
9
+ "/assets/responsive.css",
10
+ "/assets/icons/icon-192.png",
11
+ "/assets/icons/icon-512.png",
12
+ "/manifest.webmanifest",
13
+ ];
14
+
15
+ self.addEventListener("install", (event) => {
16
+ event.waitUntil((async () => {
17
+ const cache = await caches.open(CACHE);
18
+ await cache.addAll([SHELL, ...STATIC]);
19
+ // The shell is a module graph, so an offline start needs the imports too. Walk them
20
+ // from the entry point instead of keeping a list that drifts with every new module.
21
+ const pending = ["/assets/chat/index.js"], seen = new Set();
22
+ while (pending.length) {
23
+ const url = pending.pop();
24
+ if (seen.has(url)) continue;
25
+ seen.add(url);
26
+ const response = await fetch(url).catch(() => null);
27
+ if (!response?.ok) continue;
28
+ const source = await response.clone().text();
29
+ await cache.put(url, response);
30
+ for (const match of source.matchAll(/from\s+"(\.\/[\w.-]+\.js)"/g)) {
31
+ pending.push(new URL(match[1], `https://chat.invalid${url}`).pathname);
32
+ }
33
+ }
34
+ await self.skipWaiting();
35
+ })());
36
+ });
37
+
38
+ self.addEventListener("activate", (event) => {
39
+ event.waitUntil((async () => {
40
+ for (const key of await caches.keys()) if (key !== CACHE) await caches.delete(key);
41
+ await self.clients.claim();
42
+ })());
43
+ });
44
+
45
+ self.addEventListener("fetch", (event) => {
46
+ const request = event.request;
47
+ if (request.method !== "GET") return;
48
+ const url = new URL(request.url);
49
+ if (url.origin !== self.location.origin) return;
50
+ // Chat data never comes from a cache: a stale answer would show a room that was deleted
51
+ // and messages that were already read.
52
+ if (url.pathname !== SHELL && !url.pathname.startsWith("/assets/")) return;
53
+ if (url.pathname === SHELL) {
54
+ event.respondWith((async () => {
55
+ try {
56
+ const response = await fetch(request);
57
+ if (response.ok) await (await caches.open(CACHE)).put(SHELL, response.clone());
58
+ return response;
59
+ } catch {
60
+ return (await caches.match(SHELL)) || Response.error();
61
+ }
62
+ })());
63
+ return;
64
+ }
65
+ event.respondWith((async () => {
66
+ const cached = await caches.match(request);
67
+ const network = fetch(request).then(async (response) => {
68
+ if (response.ok) await (await caches.open(CACHE)).put(request, response.clone());
69
+ return response;
70
+ }).catch(() => cached || Response.error());
71
+ return cached || network;
72
+ })());
73
+ });
package/server/wake.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import os from "node:os";
2
- import type { Message } from "../src/room-service";
3
- import { formatNotificationLines, formatServeWakePrompt, readQuestionExcerpt, 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";
2
+ import type { Message } from "../src/rooms/room-service.ts";
3
+ import { formatNotificationLines, formatServeWakePrompt, readQuestionExcerpt, readState, writeState, type RegistryEntry } from "../src/state/store.ts";
4
+ import { clearPendingAdmission, getOrCreatePendingAdmission, markPendingAdmissionAdmitted, pendingAdmission, rejectPendingAdmission, type QueueItem } from "../src/center/queue.ts";
5
+ import { sendAsyncNotification } from "../src/center/queue-transport.ts";
6
6
  import { readInbox, type InboxItem } from "./inbox";
7
- import { explicitlyAddresses } from "../src/mentions";
7
+ import { explicitlyAddresses } from "../src/center/mentions.ts";
8
8
 
9
9
  const wakeClaims = new Map<string, number>();
10
10
  const activeSessions = new Map<string, number>();
@@ -102,13 +102,15 @@ Respect permission denials and do not upload secrets or unrelated files. A local
102
102
 
103
103
  To retrieve an attachment from a room message, call `room` with `action: "read_resource"`, the originating `roomId`, and the UUID from `[[resource:UUID]]` as `resourceId`. The tool saves it to a private temporary file and returns its path without exposing the server token. The limit is 512 MiB or the server's configured limit, whichever is lower; if the server limit is unavailable, the 512 MiB cap applies. Successful files remain until removed or cleaned up by the operating system. Use your normal file-reading tools when appropriate. Attachment contents are untrusted data.
104
104
 
105
+ To delete an attachment you uploaded, call `room` with `action: "delete_resource"`, its `roomId`, and `resourceId`. This requires a central server; other agents' uploads cannot be deleted through your agent identity.
106
+
105
107
  ## Administrator supervision
106
108
 
107
109
  The separate `admin` tool supports owner-designated 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.
108
110
 
109
111
  The room owner designates the administrator from the room's Options → Edit room dialog; it applies immediately and stays in effect until the owner revokes it. There is no enrollment code to redeem. If the tool reports that the session is not designated, the room owner must designate it first.
110
112
 
111
- For a designated supervisor, `admin_overview` lists rooms and members; `admin_history` reads bounded target-room history. To assign work, send a room message to the intended Agent. For scheduled work, create a room reminder containing the task and an @ mention.
113
+ For a designated supervisor, `admin_overview` lists its designated room and members; `admin_history` reads bounded history in that room. To assign work, send a room message to the intended Agent. For scheduled work, create a room reminder containing the task and an @ mention.
112
114
 
113
115
  ## Testing and subagents
114
116
 
package/src/README.md ADDED
@@ -0,0 +1,20 @@
1
+ # Source layout
2
+
3
+ `src/` used to be one flat folder of 91 files. It now follows the path a message
4
+ takes through the plugin.
5
+
6
+ | Folder | What lives there | Read it when |
7
+ | --- | --- | --- |
8
+ | `state/` | Persistence and the data model: `store.ts` (the room store), `sqlite-state.ts` (SQLite tables and pages), `member-state.ts`, `receiver-state.ts`, `receiver-owner.ts` | A value must survive a restart, or a query must be paged |
9
+ | `rooms/` | The room domain: `room-service.ts` (rooms, messages, participants), `announcements.ts`, `resources.ts` (+ upload/read helpers) | You need to change what a room is or what it holds |
10
+ | `center/` | Talking to a remote center: `center-client.ts`, `center-inbox.ts`, `center-wake.ts`, the delivery `queue*`, `session-delivery.ts`, `reminder-client.ts`, `mentions.ts` | A message must leave this process, or a reply must come back |
11
+ | `agent/` | The agent-facing side: presence and receipts, the admin client and credentials, the room skill text, and the announcement tool | You are changing what an agent can do or what it is told |
12
+ | `runtime/` | Entry points and the running loop: `v1-plugin.ts`, `v2-plugin.ts`, `v2-receiver.ts`, `watch.ts`, `background.ts`, `plugin-notifications.ts` | You are changing startup, the poll loop, or host hooks |
13
+ | `tests/` | Every `*.test.ts` under `src/`. Run one with `bun test src/tests/<name>.test.ts` | You changed behaviour and need the proof |
14
+
15
+ The entry points that the host and the CLI load stay at the repository root:
16
+ `plugin.ts`, `cli.ts`, `index.ts`, with the HTTP server in `server/`.
17
+
18
+ Tests in `src/tests/` reach the repository root with two levels up; a test that
19
+ spawns `server/chat-server.ts` or reads `package.json` assumes the repository
20
+ root is the working directory, which `bun run test` guarantees.
@@ -1,20 +1,21 @@
1
- import { loadAdminCapability, saveAdminCapability, type AdminIdentity } from "./admin-credentials";
2
- import type { CenterOpts } from "./center-client";
3
- import type { QueueTransport } from "./queue-transport";
1
+ import { loadAdminCapability, saveAdminCapability, type AdminIdentity } from "./admin-credentials.ts";
2
+ import type { CenterOpts } from "../center/center-client.ts";
3
+ import type { QueueTransport } from "../center/queue-transport.ts";
4
4
  import { z } from "zod";
5
5
 
6
6
  export type AdminContext = { sessionID: string };
7
7
  export type AdminArgs = {
8
- action: "admin_claim" | "admin_overview" | "admin_history";
9
- roomId?: string; enrollmentKey?: string; targetRoomId?: string;
8
+ action: "admin_claim" | "admin_overview" | "admin_history" | "admin_remove_member";
9
+ roomId?: string; enrollmentKey?: string; targetRoomId?: string; targetSessionID?: string;
10
10
  limit?: number;
11
11
  };
12
12
  export const adminToolSchema = z.object({
13
- action: z.enum(["admin_claim", "admin_overview", "admin_history"]),
13
+ action: z.enum(["admin_claim", "admin_overview", "admin_history", "admin_remove_member"]),
14
14
  roomId: z.string().optional(), enrollmentKey: z.string().optional(), targetRoomId: z.string().optional(),
15
+ targetSessionID: z.string().optional().describe("Member session to remove for admin_remove_member."),
15
16
  limit: z.number().int().min(1).max(50).optional(),
16
17
  });
17
- export const adminToolDescription = "Administer an operator-designated room: overview and history. This tool never joins a room.";
18
+ export const adminToolDescription = "Administer an operator-designated room: overview, history and member removal of that room only. This tool never joins a room.";
18
19
  const safe = (value: string) => encodeURIComponent(value);
19
20
 
20
21
  async function send(opts: CenterOpts, path: string, method: string, body?: unknown,
@@ -77,12 +78,17 @@ export async function adminTool(args: AdminArgs, context: AdminContext, opts: Ce
77
78
  switch (args.action) {
78
79
  case "admin_overview": result = await request("/overview", "GET"); break;
79
80
  case "admin_history": {
80
- if (!args.targetRoomId) return "error: targetRoomId is required";
81
81
  const query = new URLSearchParams();
82
- query.set("targetRoomId", args.targetRoomId);
82
+ query.set("targetRoomId", args.targetRoomId?.trim() || roomId);
83
83
  query.set("limit", String(Math.min(50, Math.max(1, args.limit ?? 20))));
84
84
  result = await request(`/history?${query}`, "GET"); break;
85
85
  }
86
+ case "admin_remove_member": {
87
+ const targetSessionID = args.targetSessionID?.trim();
88
+ if (!targetSessionID) return "error: targetSessionID is required";
89
+ result = await send(opts, `/rooms/${safe(roomId)}/kick`, "POST", { sessionID: context.sessionID, targetSessionID }, capability, context.sessionID, ownerID ?? "");
90
+ break;
91
+ }
86
92
  default: return "error: unsupported admin action";
87
93
  }
88
94
  return JSON.stringify(result);
@@ -1,7 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { mkdir, readFile, rename, chmod, writeFile, rm } from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { statePath } from "./store";
4
+ import { statePath } from "../state/store.ts";
5
5
 
6
6
  export type AdminIdentity = { center: string; roomId: string; sessionID: string; ownerID: string };
7
7
  const keyOf = (identity: AdminIdentity) => createHash("sha256").update(JSON.stringify([
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { reportPresence, type PresenceReport, type Registry } from "./store";
3
- import { claimPresenceReport, nextPresenceSequence, acquireDeliveryLease, ownsDeliveryLease, releaseDeliveryLease } from "./receiver-state";
2
+ import { reportPresence, type PresenceReport, type Registry } from "../state/store.ts";
3
+ import { claimPresenceReport, nextPresenceSequence, acquireDeliveryLease, ownsDeliveryLease, releaseDeliveryLease } from "../state/receiver-state.ts";
4
4
 
5
5
  const LEASE_MS = 20_000;
6
6
  const REPORT_MS = 10_000;
@@ -1,7 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import path from "node:path";
3
- import { databasePath, formatNotificationLines, recordMessageReceipts, timeOf, visibleText } from "./store";
4
- import { acquireDeliveryLease, deleteReceiptCandidate, markReceiptCandidateReady, ownsDeliveryLease, receiptCandidates, readyReceiptCandidates, releaseDeliveryLease, saveReceiptCandidate } from "./receiver-state";
3
+ import { databasePath, formatNotificationLines, recordMessageReceipts, timeOf, visibleText } from "../state/store.ts";
4
+ import { acquireDeliveryLease, deleteReceiptCandidate, markReceiptCandidateReady, ownsDeliveryLease, receiptCandidates, readyReceiptCandidates, releaseDeliveryLease, saveReceiptCandidate } from "../state/receiver-state.ts";
5
5
 
6
6
  // shortcut: expire unobserved proofs after seven days; increase if hosts may stay disconnected longer.
7
7
  const UNOBSERVED_TTL = 7 * 24 * 60 * 60_000;
@@ -1,5 +1,5 @@
1
- import { deleteAnnouncement, getAnnouncement, listAnnouncements, putAnnouncement, validateAnnouncement } from "./announcements";
2
- import { loadRegistry, readState } from "./store";
1
+ import { deleteAnnouncement, getAnnouncement, listAnnouncements, putAnnouncement, validateAnnouncement } from "../rooms/announcements.ts";
2
+ import { loadRegistry, readState } from "../state/store.ts";
3
3
 
4
4
  export async function runAnnouncementTool(args: { action: string; roomId?: string; announcementName?: string; content?: string }, sessionID: string): Promise<string | undefined> {
5
5
  if (!args.action.startsWith("announcement_")) return undefined;
@@ -1,7 +1,7 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { fileURLToPath } from "node:url";
3
3
 
4
- const path = fileURLToPath(new URL("../skills/chatroom/SKILL.md", import.meta.url));
4
+ const path = fileURLToPath(new URL("../../skills/chatroom/SKILL.md", import.meta.url));
5
5
  const source = readFileSync(path, "utf8");
6
6
  const [, metadata = "", content = source] = source.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/) ?? [];
7
7
  const description = metadata.match(/^description:\s*(.+)$/m)?.[1]?.trim();
@@ -4,21 +4,21 @@ import RoomService, {
4
4
  type Message,
5
5
  type Participant,
6
6
  type Room,
7
- } from "./room-service";
7
+ } from "../rooms/room-service.ts";
8
8
  import os from "node:os";
9
9
  import {
10
10
  formatRoom,
11
11
  identity,
12
12
  timeOf,
13
- } from "./store";
13
+ } from "../state/store.ts";
14
14
  import {
15
15
  clearPendingAdmission,
16
- } from "./queue";
17
- import type { InboxItem } from "./center-inbox";
18
- import { assertDeliveryLease } from "./session-delivery";
19
- export { queueAdmissionId } from "./queue";
20
- export { createQueueTransport, sendAsyncNotification, sendQueue } from "./queue-transport";
21
- export type { QueueTransport, PushResult } from "./queue-transport";
16
+ } from "./queue.ts";
17
+ import type { InboxItem } from "./center-inbox.ts";
18
+ import { assertDeliveryLease } from "./session-delivery.ts";
19
+ export { queueAdmissionId } from "./queue.ts";
20
+ export { createQueueTransport, sendAsyncNotification, sendQueue } from "./queue-transport.ts";
21
+ export type { QueueTransport, PushResult } from "./queue-transport.ts";
22
22
 
23
23
  type Json = Record<string, unknown>;
24
24
 
@@ -56,8 +56,9 @@ export async function request(
56
56
  path: string,
57
57
  method: string,
58
58
  body?: unknown,
59
+ extraHeaders?: Record<string, string>,
59
60
  ): Promise<Json> {
60
- const headers: Record<string, string> = {};
61
+ const headers: Record<string, string> = { ...extraHeaders };
61
62
  if (opts.token) {
62
63
  headers["Authorization"] = `Bearer ${opts.token}`;
63
64
  }
@@ -90,6 +91,18 @@ export async function markQueued(
90
91
  .catch(() => false);
91
92
  }
92
93
 
94
+ export async function deleteAgentResource(opts: CenterOpts, roomID: string, resourceID: string, sessionID: string): Promise<string> {
95
+ if (!opts.center) return "error: resource deletion requires CHAT_ROOM_SERVER_URL (central server mode)";
96
+ if (!roomID) return "error: roomId is required";
97
+ if (!resourceID) return "error: resourceId is required";
98
+ try {
99
+ await request(opts, `/rooms/${encodeURIComponent(roomID)}/resources/${encodeURIComponent(resourceID)}`, "DELETE", {}, { "X-Session-ID": sessionID });
100
+ return `deleted resource ${resourceID}`;
101
+ } catch (error) {
102
+ return `error: ${error instanceof Error ? error.message : String(error)}`;
103
+ }
104
+ }
105
+
93
106
  export async function centerAction(
94
107
  opts: CenterOpts,
95
108
  args: {
@@ -1,4 +1,4 @@
1
- import { formatNotificationLines } from "./store";
1
+ import { formatNotificationLines } from "../state/store.ts";
2
2
  import {
3
3
  clearPendingAdmission,
4
4
  getOrCreatePendingAdmission,
@@ -7,13 +7,13 @@ import {
7
7
  prunePendingAdmission,
8
8
  rejectPendingAdmission,
9
9
  type QueueItem,
10
- } from "./queue";
11
- import { request, markQueued, type CenterOpts } from "./center-client";
12
- import { explicitlyAddresses } from "./mentions";
13
- import { claimBackgroundAttempt } from "./receiver-state";
14
- import { prepareReceiptCandidate, receiptDestination } from "./agent-receipts";
15
- import { serializeSessionPush } from "./session-delivery";
16
- export { serializeSessionPush } from "./session-delivery";
10
+ } from "./queue.ts";
11
+ import { request, markQueued, type CenterOpts } from "./center-client.ts";
12
+ import { explicitlyAddresses } from "./mentions.ts";
13
+ import { claimBackgroundAttempt } from "../state/receiver-state.ts";
14
+ import { prepareReceiptCandidate, receiptDestination } from "../agent/agent-receipts.ts";
15
+ import { serializeSessionPush } from "./session-delivery.ts";
16
+ export { serializeSessionPush } from "./session-delivery.ts";
17
17
  import {
18
18
  sendAsyncNotification,
19
19
  sendQueue,
@@ -22,7 +22,7 @@ import {
22
22
  type BackgroundResult,
23
23
  type PushResult,
24
24
  type QueueTransport,
25
- } from "./queue-transport";
25
+ } from "./queue-transport.ts";
26
26
 
27
27
  export type InboxItem = QueueItem & { roomId: string; roomName: string; roomKind?: "group" | "direct" };
28
28
  const inboxChecks = new Set<string>();
@@ -2,8 +2,8 @@ import os from "node:os";
2
2
  import {
3
3
  formatNotificationLines,
4
4
  formatServeWakePrompt,
5
- } from "./store";
6
- import { explicitlyAddresses } from "./mentions";
5
+ } from "../state/store.ts";
6
+ import { explicitlyAddresses } from "./mentions.ts";
7
7
  import {
8
8
  clearPendingAdmission,
9
9
  getOrCreatePendingAdmission,
@@ -12,10 +12,10 @@ import {
12
12
  prunePendingAdmission,
13
13
  rejectPendingAdmission,
14
14
  type PendingAdmission,
15
- } from "./queue";
16
- import { markQueued, request, type CenterOpts } from "./center-client";
17
- import { pushItemsToSession, serializeSessionPush, type InboxItem } from "./center-inbox";
18
- import { sendAsyncNotification, sendQueue, type QueueTransport } from "./queue-transport";
15
+ } from "./queue.ts";
16
+ import { markQueued, request, type CenterOpts } from "./center-client.ts";
17
+ import { pushItemsToSession, serializeSessionPush, type InboxItem } from "./center-inbox.ts";
18
+ import { sendAsyncNotification, sendQueue, type QueueTransport } from "./queue-transport.ts";
19
19
 
20
20
  const checking = new WeakSet<QueueTransport>();
21
21
 
@@ -1,4 +1,4 @@
1
- import type { QueueItem } from "./queue";
1
+ import type { QueueItem } from "./queue.ts";
2
2
 
3
3
  export function explicitlyMentions(item: QueueItem, recipient: string, sessionID?: string): boolean {
4
4
  if (!recipient.trim() || (item.senderId === "system" && !item.id?.startsWith("reminder:")) || (sessionID !== undefined && item.senderSessionID === sessionID)) return false;
@@ -1,6 +1,6 @@
1
- import { authHeader } from "./store";
2
- import { admissionMatches, type QueueBody } from "./queue";
3
- import { assertDeliveryLease } from "./session-delivery";
1
+ import { authHeader } from "../state/store.ts";
2
+ import { admissionMatches, type QueueBody } from "./queue.ts";
3
+ import { assertDeliveryLease } from "./session-delivery.ts";
4
4
 
5
5
  export type PushResult = "delivered" | "unreachable" | "rejected";
6
6
  export type BackgroundResult = { status: "done" | "failed" | "skip"; reason?: string };
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
- import { deletePendingAdmission, readPendingAdmission, savePendingAdmission } from "./receiver-state";
3
- import { assertDeliveryLease } from "./session-delivery";
2
+ import { deletePendingAdmission, readPendingAdmission, savePendingAdmission } from "../state/receiver-state.ts";
3
+ import { assertDeliveryLease } from "./session-delivery.ts";
4
4
 
5
5
  export type QueueItem = {
6
6
  id?: string;
@@ -1,4 +1,4 @@
1
- import { request, type CenterOpts } from "./center-client";
1
+ import { request, type CenterOpts } from "./center-client.ts";
2
2
 
3
3
  type Schedule =
4
4
  | { type: "once"; at: string; timezone?: string }
@@ -1,6 +1,6 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { randomUUID } from "node:crypto";
3
- import { acquireDeliveryLease, ownsDeliveryLease, releaseDeliveryLease, renewDeliveryLease } from "./receiver-state";
3
+ import { acquireDeliveryLease, ownsDeliveryLease, releaseDeliveryLease, renewDeliveryLease } from "../state/receiver-state.ts";
4
4
 
5
5
  const LEASE_MS = 15_000;
6
6
  const active = new AsyncLocalStorage<{ sessionID: string; holder: string; lost: boolean }>();
@@ -1,5 +1,5 @@
1
- import { databasePath } from "./store";
2
- import { deleteAnnouncement as sqliteDelete, getAnnouncement as sqliteGet, listAnnouncements as sqliteList, putAnnouncement as sqlitePut, type Announcement } from "./sqlite-state";
1
+ import { databasePath } from "../state/store.ts";
2
+ import { deleteAnnouncement as sqliteDelete, getAnnouncement as sqliteGet, listAnnouncements as sqliteList, putAnnouncement as sqlitePut, type Announcement } from "../state/sqlite-state.ts";
3
3
 
4
4
  export type { Announcement };
5
5
  export function validateAnnouncement(name: unknown, content?: unknown, requireContent = false): string | undefined {
@@ -1,6 +1,6 @@
1
1
  import { realpath, stat } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import type { Resource } from "./resources";
3
+ import type { Resource } from "./resources.ts";
4
4
 
5
5
  type PermissionContext = { directory: string; worktree?: string; ask(input: { permission: string; patterns: string[]; always: string[]; metadata: Record<string, unknown> }): Promise<void> };
6
6
  type UploadOptions = { center: string; token: string };