@alexsun-top/opencode-chat-room 0.7.6 → 0.7.8

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 (78) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +5 -5
  3. package/README.zh-CN.md +5 -5
  4. package/dist/cli.js +815 -192
  5. package/package.json +3 -2
  6. package/plugin.ts +15 -3
  7. package/server/assets/base.css +0 -2
  8. package/server/assets/chat/announcements.js +5 -2
  9. package/server/assets/chat/clipboard.js +30 -0
  10. package/server/assets/chat/copy-action.js +48 -0
  11. package/server/assets/chat/diagram-viewer.js +253 -0
  12. package/server/assets/chat/doc-preview.js +160 -13
  13. package/server/assets/chat/editor.js +10 -7
  14. package/server/assets/chat/events.js +26 -5
  15. package/server/assets/chat/files.js +26 -5
  16. package/server/assets/chat/history-loader.js +3 -1
  17. package/server/assets/chat/index.js +11 -1
  18. package/server/assets/chat/join-requests.js +6 -3
  19. package/server/assets/chat/locales/de.js +20 -2
  20. package/server/assets/chat/locales/es.js +20 -2
  21. package/server/assets/chat/locales/fr.js +20 -2
  22. package/server/assets/chat/locales/it.js +20 -2
  23. package/server/assets/chat/locales/ja.js +20 -2
  24. package/server/assets/chat/locales/ko.js +20 -2
  25. package/server/assets/chat/markdown.js +75 -86
  26. package/server/assets/chat/messages.js +7 -3
  27. package/server/assets/chat/palette.js +40 -18
  28. package/server/assets/chat/pwa.js +2 -0
  29. package/server/assets/chat/questions.js +6 -0
  30. package/server/assets/chat/resource-format.js +74 -0
  31. package/server/assets/chat/rooms.js +9 -1
  32. package/server/assets/chat/shortcuts.js +14 -3
  33. package/server/assets/chat/side-pane.js +136 -0
  34. package/server/assets/chat/state.js +85 -8
  35. package/server/assets/chat/system-messages.js +3 -1
  36. package/server/assets/chat/task-form.js +197 -0
  37. package/server/assets/chat/task-row.js +170 -0
  38. package/server/assets/chat/tasks.js +521 -0
  39. package/server/assets/chat/viewport.js +5 -0
  40. package/server/assets/conversation.css +25 -1
  41. package/server/assets/diagram-viewer.css +141 -0
  42. package/server/assets/doc-preview.css +24 -5
  43. package/server/assets/responsive.css +108 -14
  44. package/server/assets/tasks.css +419 -0
  45. package/server/chat-server.ts +9 -4
  46. package/server/chat.html +120 -21
  47. package/server/member-routes.ts +3 -0
  48. package/server/resource-routes.ts +3 -1
  49. package/server/sw.js +247 -4
  50. package/server/task-routes.ts +53 -0
  51. package/skills/chatroom/SKILL.md +3 -1
  52. package/src/README.md +3 -3
  53. package/src/agent/chatroom-skill.ts +8 -2
  54. package/src/agent/task-tool.ts +155 -0
  55. package/src/center/center-client.ts +44 -0
  56. package/src/rooms/resources.ts +2 -2
  57. package/src/rooms/tasks.ts +246 -0
  58. package/src/runtime/v2-plugin.ts +11 -2
  59. package/src/runtime/watch.ts +38 -5
  60. package/src/state/sqlite-state.ts +93 -8
  61. package/src/state/store.ts +2 -2
  62. package/src/tui/app.mjs +14 -4
  63. package/src/tui/http.mjs +2 -2
  64. package/src/tui/info-app.mjs +24 -15
  65. package/src/tui/join-app.mjs +3 -3
  66. package/src/tui/main.mjs +4 -4
  67. package/src/tui/markdown.mjs +31 -5
  68. package/src/tui/mentions.mjs +218 -0
  69. package/src/tui/message-app.mjs +15 -11
  70. package/src/tui/palette-app.mjs +19 -9
  71. package/src/tui/reminder-app.mjs +14 -10
  72. package/src/tui/ui-content.mjs +12 -3
  73. package/src/tui/ui-mentions.mjs +44 -0
  74. package/src/tui/ui-suggest-view.mjs +63 -0
  75. package/src/tui/ui-suggest.mjs +197 -0
  76. package/src/tui/ui-theme.mjs +2 -1
  77. package/src/tui/ui-view.mjs +2 -0
  78. package/src/tui/ui.mjs +17 -9
package/src/README.md CHANGED
@@ -6,18 +6,18 @@ takes through the plugin.
6
6
  | Folder | What lives there | Read it when |
7
7
  | --- | --- | --- |
8
8
  | `state/` | Persistence and the data model: `store.ts` (the room store), `sqlite-state.ts` (SQLite tables, join requests and pages), `sqlite.ts` (the `node:sqlite` adapter), `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, join policy), `announcements.ts`, `resources.ts` (+ upload/read helpers) | You need to change what a room is or what it holds |
9
+ | `rooms/` | The room domain: `room-service.ts` (rooms, messages, participants, join policy), `announcements.ts`, `tasks.ts`, `resources.ts` (+ upload/read helpers) | You need to change what a room is or what it holds |
10
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
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
12
  | `config/` | The shared `chatroom.json` / JSONC / YAML loader and environment precedence used by the server and every client | You are adding a configuration field or changing its precedence |
13
13
  | `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 |
14
- | `tui/` | The OpenTUI terminal client: `app.mjs` (headless state), `ui*.mjs` (renderables), `config.mjs`, `http.mjs`, `session.mjs`, `palette*.mjs` | You are changing the `opencode-chat-room cli` experience |
14
+ | `tui/` | The OpenTUI terminal client: `app.mjs`/`*-app.mjs` (headless state), `ui*.mjs` (renderables, mentions, inline suggestions), `config.mjs`, `http.mjs`, `session.mjs`, `palette*.mjs`, `markdown.mjs` | You are changing the `opencode-chat-room cli` experience |
15
15
  | `tests/` | Every `*.test.ts` under `src/`. Run one with `bun test src/tests/<name>.test.ts`; TUI tests run with `bun test src/tui/test` | You changed behaviour and need the proof |
16
16
 
17
17
  The entry points that the host and the CLI load stay at the repository root:
18
18
  `plugin.ts`, `cli.ts`, `index.ts`, with the HTTP server in `server/`. Join
19
19
  admission lives in `server/room-join.ts` and the approval routes in
20
- `server/join-requests.ts`.
20
+ `server/join-requests.ts`; room task routes live in `server/task-routes.ts`.
21
21
 
22
22
  Tests in `src/tests/` reach the repository root with two levels up; a test that
23
23
  spawns `server/chat-server.ts` or reads `package.json` assumes the repository
@@ -1,7 +1,13 @@
1
- import { readFileSync } from "node:fs";
1
+ import { existsSync, 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
+ // Bundled into dist/cli.js the module sits one level shallower than in src/agent,
5
+ // so try both layouts instead of hard-coding a single relative path.
6
+ const candidates = [
7
+ new URL("../../skills/chatroom/SKILL.md", import.meta.url),
8
+ new URL("../skills/chatroom/SKILL.md", import.meta.url),
9
+ ].map((url) => fileURLToPath(url));
10
+ const path = candidates.find((candidate) => existsSync(candidate)) ?? candidates[0]!;
5
11
  const source = readFileSync(path, "utf8");
6
12
  const [, metadata = "", content = source] = source.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/) ?? [];
7
13
  const description = metadata.match(/^description:\s*(.+)$/m)?.[1]?.trim();
@@ -0,0 +1,155 @@
1
+ import { createTask, deleteTask, listTasks, updateTask, type RoomTask } from "../rooms/tasks.ts";
2
+
3
+ export type TaskStep = string | { text: string; done?: boolean };
4
+ export type Task = Omit<RoomTask, "dueDate" | "participants" | "conclusion" | "steps"> & {
5
+ dueDate?: string;
6
+ participants?: string[];
7
+ conclusion?: string;
8
+ steps?: TaskStep[];
9
+ };
10
+ export type TaskArgs = {
11
+ action: string;
12
+ roomId?: string;
13
+ taskId?: string;
14
+ title?: string;
15
+ description?: string;
16
+ assignee?: string;
17
+ status?: string;
18
+ dueDate?: string;
19
+ participants?: string[];
20
+ conclusion?: string;
21
+ steps?: TaskStep[];
22
+ };
23
+ export type TaskEditFields = Pick<TaskArgs, "title" | "description" | "assignee" | "status" | "dueDate" | "participants" | "conclusion" | "steps">;
24
+
25
+ const EDIT_KEYS = ["title", "description", "assignee", "status", "dueDate", "participants", "conclusion", "steps"] as const;
26
+ const MAX_STEPS = 30;
27
+
28
+ function visible(value: unknown, max: number): value is string {
29
+ return typeof value === "string" && value.trim().length > 0 && Array.from(value.trim()).length <= max;
30
+ }
31
+
32
+ function calendarDate(value: string): boolean {
33
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
34
+ if (!match) return false;
35
+ const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
36
+ const date = new Date(Date.UTC(year, month - 1, day));
37
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
38
+ }
39
+
40
+ function readSteps(value: unknown): TaskStep[] | undefined {
41
+ if (!Array.isArray(value) || value.length > MAX_STEPS) return undefined;
42
+ const steps: TaskStep[] = [];
43
+ for (const item of value) {
44
+ if (typeof item === "string") {
45
+ if (!visible(item, 300)) return undefined;
46
+ steps.push(item.trim());
47
+ continue;
48
+ }
49
+ if (!item || typeof item !== "object" || Array.isArray(item)) return undefined;
50
+ const step = item as { text?: unknown; done?: unknown };
51
+ if (!visible(step.text, 300) || (step.done !== undefined && typeof step.done !== "boolean")) return undefined;
52
+ steps.push({ text: step.text.trim(), done: step.done === true });
53
+ }
54
+ return steps;
55
+ }
56
+
57
+ /** Steps normalized for display: strings become open steps, objects keep their done flag. */
58
+ function displaySteps(steps: TaskStep[] | undefined): Array<{ text: string; done: boolean }> {
59
+ return (steps ?? []).flatMap((step) => {
60
+ if (typeof step === "string") return step ? [{ text: step, done: false }] : [];
61
+ return typeof step?.text === "string" && step.text ? [{ text: step.text, done: step.done === true }] : [];
62
+ });
63
+ }
64
+
65
+ /** Model-facing parameter errors shared by the standalone tool and central client. */
66
+ export function validateTaskFields(fields: TaskEditFields, creating: boolean): string | undefined {
67
+ if (creating && (typeof fields.title !== "string" || !fields.title.trim())) return "title is required to create a task; pass a short task title";
68
+ if (fields.title !== undefined && !visible(fields.title, 200)) return "title must contain 1 to 200 characters";
69
+ if (fields.description !== undefined && (typeof fields.description !== "string" || Array.from(fields.description).length > 5000)) return "description must be a string of at most 5000 characters";
70
+ if (fields.assignee !== undefined && (typeof fields.assignee !== "string" || Array.from(fields.assignee.trim()).length > 64)) return "assignee must be a participant name of at most 64 characters";
71
+ if (fields.status !== undefined && !["todo", "doing", "done"].includes(fields.status)) return "status must be todo, doing, or done";
72
+ if (fields.dueDate !== undefined) {
73
+ if (typeof fields.dueDate !== "string") return "dueDate must be YYYY-MM-DD or empty to clear it";
74
+ if (fields.dueDate.trim() !== "" && !calendarDate(fields.dueDate.trim())) return "dueDate must be a real calendar date in YYYY-MM-DD form, for example 2026-12-31, or empty to clear it";
75
+ }
76
+ if (fields.participants !== undefined && (!Array.isArray(fields.participants) || fields.participants.length > 50 || !fields.participants.every((name) => visible(name, 64)))) return "participants must be an array of at most 50 room participant names, each 1 to 64 characters";
77
+ if (fields.conclusion !== undefined && (typeof fields.conclusion !== "string" || Array.from(fields.conclusion).length > 5000)) return "conclusion must be a string of at most 5000 characters";
78
+ if (fields.steps !== undefined && readSteps(fields.steps) === undefined) return "steps must be an array of at most 30 steps; each step is text of 1 to 300 characters or {text, done}";
79
+ return undefined;
80
+ }
81
+
82
+ /** Validated fields forwarded to the task routes; empty strings and arrays clear values. */
83
+ export function taskFields(args: TaskEditFields): Record<string, unknown> {
84
+ return {
85
+ ...(args.title !== undefined ? { title: args.title.trim() } : {}),
86
+ ...(args.description !== undefined ? { description: args.description } : {}),
87
+ ...(args.assignee !== undefined ? { assignee: args.assignee.trim() } : {}),
88
+ ...(args.status !== undefined ? { status: args.status } : {}),
89
+ ...(args.dueDate !== undefined ? { dueDate: args.dueDate.trim() } : {}),
90
+ ...(args.participants !== undefined ? { participants: args.participants.map((name) => name.trim()) } : {}),
91
+ ...(args.conclusion !== undefined ? { conclusion: args.conclusion } : {}),
92
+ ...(args.steps !== undefined ? { steps: readSteps(args.steps) } : {}),
93
+ };
94
+ }
95
+
96
+ export function formatTasks(tasks: Task[]): string {
97
+ if (!tasks.length) return "no tasks";
98
+ return tasks
99
+ .map((task) => {
100
+ const steps = displaySteps(task.steps);
101
+ const done = steps.filter((step) => step.done).length;
102
+ return `${task.id} [${task.status}] ${task.title} (creator: ${task.creatorName})` +
103
+ `${task.assignee ? ` (assignee: ${task.assignee})` : ""}` +
104
+ `${task.dueDate ? ` (due: ${task.dueDate})` : ""}` +
105
+ `${task.participants?.length ? ` (participants: ${task.participants.join(", ")})` : ""}` +
106
+ `${task.description ? `\n ${task.description}` : ""}` +
107
+ `${steps.length ? `\n steps: ${done}/${steps.length}${steps.map((step) => `\n - [${step.done ? "x" : " "}] ${step.text}`).join("")}` : ""}` +
108
+ `${task.conclusion ? `\n conclusion: ${task.conclusion}` : ""}`;
109
+ })
110
+ .join("\n");
111
+ }
112
+
113
+ const NOT_JOINED = "error: not joined; call join for this room first, and wait for approval if required";
114
+
115
+ function failure(error: string, status: number, action: string): string {
116
+ if (status === 404) {
117
+ return error === "room not found"
118
+ ? "error: room not found; run room action list to see valid room UUIDs"
119
+ : `error: ${error}; run task_list to get a task ID`;
120
+ }
121
+ if (status === 403 && (action === "task_list" || action === "task_create")) return NOT_JOINED;
122
+ if (status === 403) return `error: ${error}; only the task creator or a room administrator can edit or delete a task, and the assignee may change status or toggle existing steps`;
123
+ return `error: ${error}`;
124
+ }
125
+
126
+ /** Standalone task actions backed by the shared SQLite store; undefined for other actions. */
127
+ export async function runTaskTool(args: TaskArgs, sessionID: string): Promise<string | undefined> {
128
+ if (!args.action.startsWith("task_")) return undefined;
129
+ if (!args.roomId) return "error: roomId is required; use a room UUID from the room list, not the room name";
130
+ if (args.action === "task_list") {
131
+ const result = await listTasks(args.roomId, sessionID);
132
+ return "error" in result ? failure(result.error, result.status, args.action) : formatTasks(result.tasks);
133
+ }
134
+ if (args.action === "task_create") {
135
+ const error = validateTaskFields(args, true);
136
+ if (error) return `error: ${error}`;
137
+ const result = await createTask(args.roomId, sessionID, taskFields(args));
138
+ return "error" in result
139
+ ? failure(result.error, result.status, args.action)
140
+ : `task created: ${result.task.title} (id: ${result.task.id}, status: ${result.task.status})`;
141
+ }
142
+ if (!args.taskId) return "error: taskId is required; run task_list to get a task ID";
143
+ if (args.action === "task_delete") {
144
+ const result = await deleteTask(args.roomId, args.taskId, sessionID);
145
+ return "error" in result ? failure(result.error, result.status, args.action) : `task deleted: ${args.taskId}`;
146
+ }
147
+ if (args.action !== "task_update") return "error: unsupported task action";
148
+ const error = validateTaskFields(args, false);
149
+ if (error) return `error: ${error}`;
150
+ if (!EDIT_KEYS.some((field) => args[field] !== undefined)) return `error: at least one of ${EDIT_KEYS.join(", ")} is required to update a task`;
151
+ const result = await updateTask(args.roomId, args.taskId, sessionID, taskFields(args));
152
+ return "error" in result
153
+ ? failure(result.error, result.status, args.action)
154
+ : `task updated: ${result.task.title} (id: ${result.task.id}, status: ${result.task.status})`;
155
+ }
@@ -16,6 +16,7 @@ import {
16
16
  } from "./queue.ts";
17
17
  import type { InboxItem } from "./center-inbox.ts";
18
18
  import { assertDeliveryLease } from "./session-delivery.ts";
19
+ import { formatTasks, taskFields, validateTaskFields, type Task } from "../agent/task-tool.ts";
19
20
  export { queueAdmissionId } from "./queue.ts";
20
21
  export { createQueueTransport, sendAsyncNotification, sendQueue } from "./queue-transport.ts";
21
22
  export type { QueueTransport, PushResult } from "./queue-transport.ts";
@@ -165,6 +166,15 @@ export async function centerAction(
165
166
  text?: string;
166
167
  announcementName?: string;
167
168
  content?: string;
169
+ taskId?: string;
170
+ title?: string;
171
+ description?: string;
172
+ assignee?: string;
173
+ status?: string;
174
+ dueDate?: string;
175
+ participants?: string[];
176
+ conclusion?: string;
177
+ steps?: Array<string | { text: string; done?: boolean }>;
168
178
  isQuestion?: boolean;
169
179
  receiverOwnerID?: string;
170
180
  protocol?: "v1" | "v2";
@@ -291,6 +301,40 @@ export async function centerAction(
291
301
  await request(opts, path, "DELETE", { sessionID });
292
302
  return `announcement deleted: ${args.announcementName}`;
293
303
  }
304
+ case "task_list": {
305
+ if (!args.roomId) return "error: roomId is required; use a room UUID from the room list, not the room name";
306
+ const result = await request(opts, `/rooms/${encodeURIComponent(args.roomId)}/tasks?sessionID=${encodeURIComponent(sessionID)}`, "GET") as { tasks?: Task[] };
307
+ return formatTasks(Array.isArray(result.tasks) ? result.tasks : []);
308
+ }
309
+ case "task_create": {
310
+ if (!args.roomId) return "error: roomId is required; use a room UUID from the room list, not the room name";
311
+ const error = validateTaskFields(args, true);
312
+ if (error) return `error: ${error}`;
313
+ const result = await request(opts, `/rooms/${encodeURIComponent(args.roomId)}/tasks`, "POST", {
314
+ sessionID,
315
+ ...taskFields(args),
316
+ }) as { task: Task };
317
+ return `task created: ${result.task.title} (id: ${result.task.id}, status: ${result.task.status})`;
318
+ }
319
+ case "task_update": {
320
+ if (!args.roomId) return "error: roomId is required; use a room UUID from the room list, not the room name";
321
+ if (!args.taskId) return "error: taskId is required; run task_list to get a task ID";
322
+ const error = validateTaskFields(args, false);
323
+ if (error) return `error: ${error}`;
324
+ const fields = taskFields(args);
325
+ if (!Object.keys(fields).length) return "error: at least one of title, description, assignee, status, dueDate, participants, conclusion, or steps is required to update a task";
326
+ const result = await request(opts, `/rooms/${encodeURIComponent(args.roomId)}/tasks/${encodeURIComponent(args.taskId)}`, "PATCH", {
327
+ sessionID,
328
+ ...fields,
329
+ }) as { task: Task };
330
+ return `task updated: ${result.task.title} (id: ${result.task.id}, status: ${result.task.status})`;
331
+ }
332
+ case "task_delete": {
333
+ if (!args.roomId) return "error: roomId is required; use a room UUID from the room list, not the room name";
334
+ if (!args.taskId) return "error: taskId is required; run task_list to get a task ID";
335
+ await request(opts, `/rooms/${encodeURIComponent(args.roomId)}/tasks/${encodeURIComponent(args.taskId)}`, "DELETE", { sessionID });
336
+ return `task deleted: ${args.taskId}`;
337
+ }
294
338
  case "send": {
295
339
  if (!args.roomId) {
296
340
  return "error: roomId is required; use a room UUID from the room list, not the room name";
@@ -134,9 +134,9 @@ export function resourcePath(resource: Pick<Resource, "id" | "roomID">): string
134
134
  if (!uuid.test(resource.roomID) || !uuid.test(resource.id)) throw new ResourceError(404, "resource not found");
135
135
  return path.join(roomDirectory(resource.roomID), resource.id);
136
136
  }
137
- export async function listRoomResources(roomID: string, limit = 500, offset = 0): Promise<{ items: Resource[]; total: number }> {
137
+ export async function listRoomResources(roomID: string, limit = 500, offset = 0, beforeID?: string): Promise<{ items: Resource[]; total: number }> {
138
138
  if (!uuid.test(roomID)) throw new ResourceError(404, "room not found");
139
- return listResources(databasePath(), roomID, limit, offset);
139
+ return listResources(databasePath(), roomID, limit, offset, beforeID);
140
140
  }
141
141
  export async function findResource(roomID: string, id: string): Promise<Resource | undefined> {
142
142
  if (!uuid.test(id)) return undefined;
@@ -0,0 +1,246 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { isRoomAdmin, type RoleEntry, type RoleRoom } from "../state/roles.ts";
3
+ import { ROOM_TASK_STATUSES, deleteCompletedRoomTasks, deleteRoomTask, insertRoomTask, listRoomTasks, patchRoomTask, readRoomTask, type RoomTask, type RoomTaskPatch, type RoomTaskStatus, type RoomTaskStep } from "../state/sqlite-state.ts";
4
+ import type { Database } from "../state/sqlite.ts";
5
+ import { databasePath } from "../state/store.ts";
6
+ import { withStateTransaction } from "../state/sqlite-state.ts";
7
+
8
+ export type { RoomTask, RoomTaskStatus };
9
+ export type TaskFailure = { status: 400 | 403 | 404 | 409; error: string };
10
+ export type TaskListResult = { tasks: RoomTask[] } | TaskFailure;
11
+ export type TaskWriteResult = { task: RoomTask } | TaskFailure;
12
+ export type TaskDeleteResult = { ok: true } | TaskFailure;
13
+ export type TaskClearResult = { ok: true; count: number } | TaskFailure;
14
+ export type TaskFields = {
15
+ title?: unknown; description?: unknown; assignee?: unknown; status?: unknown;
16
+ dueDate?: unknown; participants?: unknown; conclusion?: unknown; steps?: unknown;
17
+ };
18
+
19
+ const MAX_TITLE = 200;
20
+ const MAX_DESCRIPTION = 5000;
21
+ const MAX_CONCLUSION = 5000;
22
+ const MAX_PARTICIPANTS = 50;
23
+ const MAX_STEPS = 30;
24
+ const MAX_STEP_TEXT = 300;
25
+ const invalid = (error: string): TaskFailure => ({ status: 400, error });
26
+
27
+ type Context = { room: RoleRoom; entry: RoleEntry; name: string; participants: Set<string> };
28
+ type RoomRow = {
29
+ kind: string; owner_id: string; owner_membership_id: string | null;
30
+ admin_names: string | null; admin_membership_ids: string | null;
31
+ };
32
+ type MemberRow = {
33
+ name: string; protocol: string | null; host: string | null;
34
+ receiver_owner_id: string | null; membership_id: string | null;
35
+ };
36
+
37
+ // The session must be a current participant and a registry entry; roles come
38
+ // from the stored room, never from a client-supplied name.
39
+ function context(db: Database, roomID: string, sessionID: string): Context | TaskFailure {
40
+ const room = db.query("SELECT kind,owner_id,owner_membership_id,admin_names,admin_membership_ids FROM rooms WHERE id=?").get(roomID) as RoomRow | null;
41
+ if (!room) return { status: 404, error: "room not found" };
42
+ if (room.kind === "direct") return { status: 409, error: "tasks are not available in direct rooms" };
43
+ const member = db.query("SELECT g.name,g.protocol,g.host,g.receiver_owner_id,g.membership_id FROM registry g JOIN participants p ON p.room_id=g.room_id AND p.id=g.name WHERE g.room_id=? AND g.session_id=?")
44
+ .get(roomID, sessionID) as MemberRow | null;
45
+ if (!member) return { status: 403, error: "not a room member" };
46
+ const roleRoom: RoleRoom = {
47
+ ownerId: room.owner_id,
48
+ ...(room.owner_membership_id ? { ownerMembershipID: room.owner_membership_id } : {}),
49
+ ...(room.admin_names ? { adminIds: JSON.parse(room.admin_names) as string[] } : {}),
50
+ ...(room.admin_membership_ids ? { adminMembershipIDs: JSON.parse(room.admin_membership_ids) as string[] } : {}),
51
+ };
52
+ const entry: RoleEntry = {
53
+ name: member.name,
54
+ ...(member.protocol ? { protocol: member.protocol } : {}),
55
+ ...(member.host ? { host: member.host } : {}),
56
+ ...(member.receiver_owner_id ? { receiverOwnerID: member.receiver_owner_id } : {}),
57
+ ...(member.membership_id ? { membershipID: member.membership_id } : {}),
58
+ };
59
+ const participants = new Set((db.query("SELECT name FROM participants WHERE room_id=?").all(roomID) as Array<{ name: string }>).map((row) => row.name));
60
+ return { room: roleRoom, entry, name: member.name, participants };
61
+ }
62
+
63
+ const isFailure = (value: Context | TaskFailure): value is TaskFailure => "status" in value;
64
+
65
+ function readTitle(value: unknown): string | undefined {
66
+ if (typeof value !== "string") return undefined;
67
+ const title = value.trim();
68
+ return title && Array.from(title).length <= MAX_TITLE ? title : undefined;
69
+ }
70
+
71
+ function readDescription(value: unknown): string | undefined {
72
+ return typeof value === "string" && Array.from(value).length <= MAX_DESCRIPTION ? value : undefined;
73
+ }
74
+
75
+ function readDueDate(value: unknown): string | undefined {
76
+ if (typeof value !== "string") return undefined;
77
+ if (value === "") return "";
78
+ if (value.length !== 10) return undefined;
79
+ const date = new Date(`${value}T00:00:00Z`);
80
+ return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value ? value : undefined;
81
+ }
82
+
83
+ function readParticipants(value: unknown, participants: Set<string>): string[] | undefined {
84
+ if (!Array.isArray(value) || value.length > MAX_PARTICIPANTS) return undefined;
85
+ const names: string[] = [];
86
+ for (const name of value) {
87
+ if (typeof name !== "string" || !participants.has(name) || names.includes(name)) return undefined;
88
+ names.push(name);
89
+ }
90
+ return names;
91
+ }
92
+
93
+ function readConclusion(value: unknown): string | undefined {
94
+ return typeof value === "string" && Array.from(value).length <= MAX_CONCLUSION ? value : undefined;
95
+ }
96
+
97
+ function readStepText(value: unknown): string | undefined {
98
+ return typeof value === "string" && value.trim().length > 0 && Array.from(value).length <= MAX_STEP_TEXT ? value : undefined;
99
+ }
100
+
101
+ function readSteps(value: unknown): RoomTaskStep[] | undefined {
102
+ if (!Array.isArray(value) || value.length > MAX_STEPS) return undefined;
103
+ const steps: RoomTaskStep[] = [];
104
+ for (const item of value) {
105
+ if (typeof item === "string") {
106
+ const text = readStepText(item);
107
+ if (text === undefined) return undefined;
108
+ steps.push({ text, done: false });
109
+ continue;
110
+ }
111
+ if (typeof item !== "object" || item === null || Array.isArray(item)) return undefined;
112
+ const text = readStepText((item as { text?: unknown }).text);
113
+ const done = (item as { done?: unknown }).done;
114
+ if (text === undefined || typeof done !== "boolean") return undefined;
115
+ steps.push({ text, done });
116
+ }
117
+ return steps;
118
+ }
119
+
120
+ export function listTasks(roomID: string, sessionID: string): Promise<TaskListResult> {
121
+ return withStateTransaction(databasePath(), (db) => {
122
+ const ctx = context(db, roomID, sessionID);
123
+ if (isFailure(ctx)) return ctx;
124
+ return { tasks: listRoomTasks(db, roomID) };
125
+ });
126
+ }
127
+
128
+ export function createTask(roomID: string, sessionID: string, input: TaskFields): Promise<TaskWriteResult> {
129
+ return withStateTransaction(databasePath(), (db) => {
130
+ const ctx = context(db, roomID, sessionID);
131
+ if (isFailure(ctx)) return ctx;
132
+ const title = readTitle(input.title);
133
+ if (!title) return invalid(`title must contain 1 to ${MAX_TITLE} characters`);
134
+ const description = input.description === undefined ? "" : readDescription(input.description);
135
+ if (description === undefined) return invalid(`description must be a string of at most ${MAX_DESCRIPTION} characters`);
136
+ const assignee = input.assignee === undefined ? "" : input.assignee;
137
+ if (typeof assignee !== "string" || (assignee !== "" && !ctx.participants.has(assignee))) return invalid("assignee must be a current participant name");
138
+ const dueDate = input.dueDate === undefined ? "" : readDueDate(input.dueDate);
139
+ if (dueDate === undefined) return invalid("dueDate must be empty or a valid YYYY-MM-DD calendar date");
140
+ const participants = input.participants === undefined ? [] : readParticipants(input.participants, ctx.participants);
141
+ if (participants === undefined) return invalid(`participants must be at most ${MAX_PARTICIPANTS} unique current participant names`);
142
+ const conclusion = input.conclusion === undefined ? "" : readConclusion(input.conclusion);
143
+ if (conclusion === undefined) return invalid(`conclusion must be a string of at most ${MAX_CONCLUSION} characters`);
144
+ const steps = input.steps === undefined ? [] : readSteps(input.steps);
145
+ if (steps === undefined) return invalid(`steps must be at most ${MAX_STEPS} items, each text 1 to ${MAX_STEP_TEXT} characters with a boolean done`);
146
+ const now = Date.now();
147
+ const task: RoomTask = {
148
+ id: randomUUID(), roomId: roomID, title, description, assignee, status: "todo",
149
+ creatorName: ctx.name, creatorSessionID: sessionID, createdAt: now, updatedAt: now,
150
+ dueDate, participants, conclusion, steps,
151
+ };
152
+ insertRoomTask(db, task);
153
+ return { task };
154
+ });
155
+ }
156
+
157
+ export function updateTask(roomID: string, taskID: string, sessionID: string, input: TaskFields): Promise<TaskWriteResult> {
158
+ return withStateTransaction(databasePath(), (db) => {
159
+ const ctx = context(db, roomID, sessionID);
160
+ if (isFailure(ctx)) return ctx;
161
+ const task = readRoomTask(db, roomID, taskID);
162
+ if (!task) return { status: 404, error: "task not found" };
163
+ const patch: RoomTaskPatch = {};
164
+ if (input.title !== undefined) {
165
+ const title = readTitle(input.title);
166
+ if (!title) return invalid(`title must contain 1 to ${MAX_TITLE} characters`);
167
+ patch.title = title;
168
+ }
169
+ if (input.description !== undefined) {
170
+ const description = readDescription(input.description);
171
+ if (description === undefined) return invalid(`description must be a string of at most ${MAX_DESCRIPTION} characters`);
172
+ patch.description = description;
173
+ }
174
+ if (input.assignee !== undefined) {
175
+ // Keep an existing assignee valid after they leave so editing another
176
+ // field does not fail; assigning a different person still requires membership.
177
+ const assignee = input.assignee;
178
+ if (typeof assignee !== "string") return invalid("assignee must be a current participant name");
179
+ if (assignee !== "" && !ctx.participants.has(assignee) && assignee !== task.assignee) return invalid("assignee must be a current participant name");
180
+ patch.assignee = assignee;
181
+ }
182
+ if (input.status !== undefined) {
183
+ if (typeof input.status !== "string" || !ROOM_TASK_STATUSES.includes(input.status as RoomTaskStatus)) return invalid("status must be todo, doing, or done");
184
+ patch.status = input.status as RoomTaskStatus;
185
+ }
186
+ if (input.dueDate !== undefined) {
187
+ const dueDate = readDueDate(input.dueDate);
188
+ if (dueDate === undefined) return invalid("dueDate must be empty or a valid YYYY-MM-DD calendar date");
189
+ patch.dueDate = dueDate;
190
+ }
191
+ if (input.participants !== undefined) {
192
+ // A participant who left the room stays valid on an existing task so
193
+ // editing another field cannot silently drop them.
194
+ const allowed = new Set([...ctx.participants, ...task.participants]);
195
+ const participants = readParticipants(input.participants, allowed);
196
+ if (participants === undefined) return invalid(`participants must be at most ${MAX_PARTICIPANTS} unique participant names`);
197
+ patch.participants = participants;
198
+ }
199
+ if (input.conclusion !== undefined) {
200
+ const conclusion = readConclusion(input.conclusion);
201
+ if (conclusion === undefined) return invalid(`conclusion must be a string of at most ${MAX_CONCLUSION} characters`);
202
+ patch.conclusion = conclusion;
203
+ }
204
+ if (input.steps !== undefined) {
205
+ const steps = readSteps(input.steps);
206
+ if (steps === undefined) return invalid(`steps must be at most ${MAX_STEPS} items, each text 1 to ${MAX_STEP_TEXT} characters with a boolean done`);
207
+ patch.steps = steps;
208
+ }
209
+ if (!Object.keys(patch).length) return invalid("at least one task field is required");
210
+ const admin = isRoomAdmin(ctx.room, ctx.entry);
211
+ const creator = task.creatorSessionID === sessionID;
212
+ const assignee = task.assignee !== "" && task.assignee === ctx.name;
213
+ const contentChanged = patch.title !== undefined || patch.description !== undefined || patch.assignee !== undefined ||
214
+ patch.dueDate !== undefined || patch.participants !== undefined || patch.conclusion !== undefined;
215
+ const stepsChanged = patch.steps !== undefined && (patch.steps.length !== task.steps.length ||
216
+ patch.steps.some((step, index) => step.text !== task.steps[index]!.text));
217
+ if (!admin && !creator && (!assignee || contentChanged || stepsChanged)) {
218
+ return { status: 403, error: "only the creator or a room admin may edit task fields; the assignee may change status or toggle step done values" };
219
+ }
220
+ const updated = patchRoomTask(db, roomID, taskID, patch, Date.now());
221
+ return updated ? { task: updated } : { status: 404, error: "task not found" };
222
+ });
223
+ }
224
+
225
+ export function deleteTask(roomID: string, taskID: string, sessionID: string): Promise<TaskDeleteResult> {
226
+ return withStateTransaction(databasePath(), (db) => {
227
+ const ctx = context(db, roomID, sessionID);
228
+ if (isFailure(ctx)) return ctx;
229
+ const task = readRoomTask(db, roomID, taskID);
230
+ if (!task) return { status: 404, error: "task not found" };
231
+ if (task.creatorSessionID !== sessionID && !isRoomAdmin(ctx.room, ctx.entry)) {
232
+ return { status: 403, error: "not allowed to delete this task" };
233
+ }
234
+ deleteRoomTask(db, roomID, taskID);
235
+ return { ok: true };
236
+ });
237
+ }
238
+
239
+ export function clearCompletedTasks(roomID: string, sessionID: string): Promise<TaskClearResult> {
240
+ return withStateTransaction(databasePath(), (db) => {
241
+ const ctx = context(db, roomID, sessionID);
242
+ if (isFailure(ctx)) return ctx;
243
+ const admin = isRoomAdmin(ctx.room, ctx.entry);
244
+ return { ok: true, count: deleteCompletedRoomTasks(db, roomID, admin ? undefined : sessionID) };
245
+ });
246
+ }
@@ -81,7 +81,7 @@ export function createV2Setup(deps: {
81
81
  });
82
82
  toolRegistration = await context.tool.transform((editor) => editor.add({
83
83
  name: "room",
84
- description: "Chat room operations: create, join, join_status, leave and list rooms; send and poll messages; list members and announcements; manage reminders. In an approval room join returns pending: you are not a member yet; call join_status to check whether an administrator approved you. Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media; upload_resource returns a [[resource:UUID]] marker, and the attachment renders only when that exact marker is included in a send message. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup. delete_resource removes an uploaded file; servers allow human room administrators any resource and agents only their own uploads.",
84
+ description: "Chat room operations: create, join, join_status, leave and list rooms; send and poll messages; list members, announcements and tasks; create, update and delete room tasks; manage reminders. In an approval room join returns pending: you are not a member yet; call join_status to check whether an administrator approved you. Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media; upload_resource returns a [[resource:UUID]] marker, and the attachment renders only when that exact marker is included in a send message. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup. delete_resource removes an uploaded file; servers allow human room administrators any resource and agents only their own uploads.",
85
85
  options: { codemode: false },
86
86
  input: roomSchema(),
87
87
  execute: async (args, toolContext) => {
@@ -169,7 +169,7 @@ export function createV2Setup(deps: {
169
169
 
170
170
  export function roomSchema() {
171
171
  return z.object({
172
- action: z.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "members", "upload_resource", "read_resource", "delete_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete"]),
172
+ action: z.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "members", "upload_resource", "read_resource", "delete_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete", "task_list", "task_create", "task_update", "task_delete"]),
173
173
  name: z.string().max(64).optional().describe("For join: your own participant display name, NOT the room name (required). For create: the new room name."),
174
174
  roomId: z.string().optional(),
175
175
  resourceId: z.string().optional(),
@@ -178,6 +178,15 @@ export function roomSchema() {
178
178
  isQuestion: z.boolean().optional(),
179
179
  announcementName: z.string().optional().describe("Name of a room announcement; distinct from participant or room name."),
180
180
  content: z.string().optional().describe("Announcement content, at most 5000 Unicode characters."),
181
+ taskId: z.string().optional().describe("Task UUID from task_list; required for task_update and task_delete."),
182
+ title: z.string().optional().describe("Task title, 1 to 200 characters; required for task_create."),
183
+ description: z.string().optional().describe("Task description, at most 5000 characters."),
184
+ assignee: z.string().optional().describe("Participant display name responsible for the task; empty leaves it unassigned."),
185
+ status: z.enum(["todo", "doing", "done"]).optional().describe("Task status; the assignee may change only this field."),
186
+ dueDate: z.string().optional().describe("Task due date as YYYY-MM-DD; empty clears it."),
187
+ participants: z.array(z.string()).optional().describe("Task participants as room participant display names; empty clears them."),
188
+ conclusion: z.string().optional().describe("Task conclusion, at most 5000 characters; empty clears it."),
189
+ steps: z.array(z.union([z.string(), z.object({ text: z.string(), done: z.boolean().optional() })])).optional().describe("Task checklist, at most 30 steps; each is text of 1 to 300 characters or {text, done}; empty clears them."),
181
190
  reminderId: z.string().optional(),
182
191
  schedule: z.discriminatedUnion("type", [z.object({ type: z.literal("once"), at: z.string(), timezone: z.string().refine((value) => { try { new Intl.DateTimeFormat("en", { timeZone: value }); return true; } catch { return false; } }, "timezone must be an IANA timezone").optional() }), z.object({ type: z.literal("cron"), expression: z.string().regex(/^\S+\s+\S+\s+\S+\s+\S+\s+\S+$/), timezone: z.string().refine((value) => { try { new Intl.DateTimeFormat("en", { timeZone: value }); return true; } catch { return false; } }, "timezone must be an IANA timezone").optional() })]).optional(),
183
192
  paused: z.boolean().optional(),
@@ -1,6 +1,6 @@
1
1
  import { Buffer } from "node:buffer";
2
2
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
3
- import { realpathSync } from "node:fs";
3
+ import { existsSync, realpathSync } from "node:fs";
4
4
  import { appendFile, chmod, link, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
5
5
  import { spawn } from "node:child_process";
6
6
  import { fileURLToPath } from "node:url";
@@ -212,6 +212,26 @@ function sameController(value: unknown, record: WatchRecord, status: string): bo
212
212
  body.instanceID === record.instanceID && body.nonce === record.nonce;
213
213
  }
214
214
 
215
+ // Run the same entry script that started this process. A relative ../cli.ts
216
+ // only exists in the source layout; inside dist/cli.js it would point outside
217
+ // the package (and Node cannot run a .ts daemon from node_modules).
218
+ function cliEntryPath(): string {
219
+ // Installed packages run through a bin shim (node_modules/.bin/...), so resolve
220
+ // the symlink before checking the file name; the shim itself is not cli.js.
221
+ const argv = process.argv[1];
222
+ if (argv) {
223
+ let resolved = path.resolve(argv);
224
+ try { resolved = realpathSync(resolved); } catch { /* keep the resolved path */ }
225
+ if (/^cli\.(?:ts|js)$/.test(path.basename(resolved))) return resolved;
226
+ }
227
+ const candidates = [
228
+ fileURLToPath(new URL("../../dist/cli.js", import.meta.url)),
229
+ fileURLToPath(new URL("../../cli.ts", import.meta.url)),
230
+ fileURLToPath(new URL("../cli.js", import.meta.url)),
231
+ ];
232
+ return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0]!;
233
+ }
234
+
215
235
  export async function watchStatus(): Promise<"running" | "stopped" | "unavailable" | "starting"> {
216
236
  const record = await readRecord();
217
237
  if (!record) {
@@ -241,9 +261,9 @@ export async function startWatcher(beforePublish?: () => Promise<void>): Promise
241
261
  }
242
262
  throw new Error("watcher state exists or is starting; no process was signaled");
243
263
  }
244
- const cli = fileURLToPath(new URL("../../cli.ts", import.meta.url));
264
+ const cli = cliEntryPath();
245
265
  let childError: Error | undefined;
246
- const child = spawn(process.execPath, [path.resolve(cli), "watch", "run"], {
266
+ const child = spawn(process.execPath, [cli, "watch", "run"], {
247
267
  detached: true, stdio: "ignore",
248
268
  env: { ...process.env, CHAT_ROOM_WATCH_CONTROL_TOKEN: own.token, CHAT_ROOM_WATCH_START_NONCE: own.nonce, CHAT_ROOM_WATCH_INSTANCE_ID: own.instanceID },
249
269
  });
@@ -251,7 +271,7 @@ export async function startWatcher(beforePublish?: () => Promise<void>): Promise
251
271
  child.unref();
252
272
  const deadline = Date.now() + 20_000;
253
273
  while (Date.now() < deadline) {
254
- if (childError) { await removeRecord(own.token, own.nonce); releaseWatcherClaim(profile(), own.instanceID); throw childError; }
274
+ if (childError) { await removeRecord(own.token, own.nonce); releaseWatcherClaim(profile(), own.instanceID); throw childError; }
255
275
  const record = await readRecord();
256
276
  if (record?.token === own.token && record.nonce === own.nonce && record.phase === "running" && await control(record)) {
257
277
  return "watcher started";
@@ -263,7 +283,20 @@ export async function startWatcher(beforePublish?: () => Promise<void>): Promise
263
283
  }
264
284
  await new Promise((resolve) => setTimeout(resolve, 100));
265
285
  }
266
- throw new Error("watcher did not become ready; its process was not signaled");
286
+ // Leaving the child alive would keep the pid claim and block every later
287
+ // start, so stop it and release this attempt instead of only throwing.
288
+ child.kill("SIGTERM");
289
+ if (child.exitCode === null) {
290
+ // Give the dying daemon a bounded moment to finish its shutdown sweep so a
291
+ // new start cannot overlap it while the old pid still holds leases.
292
+ await Promise.race([
293
+ new Promise((resolve) => child.once("exit", resolve)),
294
+ new Promise((resolve) => setTimeout(resolve, 1000)),
295
+ ]);
296
+ }
297
+ await removeRecord(own.token, own.nonce);
298
+ releaseWatcherClaim(profile(), own.instanceID);
299
+ throw new Error("watcher did not become ready; its process was stopped");
267
300
  }
268
301
 
269
302
  export async function stopWatcher(): Promise<string> {