@alexsun-top/opencode-chat-room 0.7.5 → 0.7.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 (68) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +5 -5
  3. package/README.zh-CN.md +5 -5
  4. package/cli.ts +20 -0
  5. package/dist/cli.js +753 -164
  6. package/package.json +2 -1
  7. package/plugin.ts +15 -3
  8. package/server/assets/base.css +0 -2
  9. package/server/assets/chat/doc-preview.js +122 -0
  10. package/server/assets/chat/editor.js +10 -7
  11. package/server/assets/chat/events.js +7 -1
  12. package/server/assets/chat/files.js +14 -6
  13. package/server/assets/chat/index.js +4 -0
  14. package/server/assets/chat/locales/de.js +21 -3
  15. package/server/assets/chat/locales/es.js +21 -3
  16. package/server/assets/chat/locales/fr.js +21 -3
  17. package/server/assets/chat/locales/it.js +21 -3
  18. package/server/assets/chat/locales/ja.js +21 -3
  19. package/server/assets/chat/locales/ko.js +21 -3
  20. package/server/assets/chat/markdown.js +39 -5
  21. package/server/assets/chat/messages.js +1 -0
  22. package/server/assets/chat/palette.js +18 -9
  23. package/server/assets/chat/questions.js +1 -0
  24. package/server/assets/chat/rooms.js +6 -1
  25. package/server/assets/chat/shortcuts.js +14 -3
  26. package/server/assets/chat/state.js +42 -6
  27. package/server/assets/chat/system-messages.js +9 -1
  28. package/server/assets/chat/task-form.js +197 -0
  29. package/server/assets/chat/task-row.js +169 -0
  30. package/server/assets/chat/tasks.js +494 -0
  31. package/server/assets/doc-preview.css +158 -0
  32. package/server/assets/edit-room.css +8 -0
  33. package/server/assets/responsive.css +26 -1
  34. package/server/assets/settings.css +9 -2
  35. package/server/assets/tasks.css +422 -0
  36. package/server/chat.html +129 -33
  37. package/server/member-routes.ts +3 -0
  38. package/server/sw.js +13 -2
  39. package/server/task-routes.ts +53 -0
  40. package/skills/chatroom/SKILL.md +3 -1
  41. package/src/README.md +3 -3
  42. package/src/agent/task-tool.ts +155 -0
  43. package/src/center/center-client.ts +44 -0
  44. package/src/rooms/tasks.ts +246 -0
  45. package/src/runtime/v2-plugin.ts +11 -2
  46. package/src/state/sqlite-state.ts +67 -0
  47. package/src/tui/app.mjs +21 -4
  48. package/src/tui/http.mjs +109 -10
  49. package/src/tui/info-app.mjs +435 -0
  50. package/src/tui/info-content.mjs +198 -0
  51. package/src/tui/join-app.mjs +71 -0
  52. package/src/tui/main.mjs +23 -4
  53. package/src/tui/markdown.mjs +293 -0
  54. package/src/tui/mentions.mjs +218 -0
  55. package/src/tui/message-app.mjs +178 -0
  56. package/src/tui/message-view.mjs +128 -0
  57. package/src/tui/palette-app.mjs +91 -8
  58. package/src/tui/palette.mjs +17 -2
  59. package/src/tui/reminder-app.mjs +189 -0
  60. package/src/tui/room-settings-app.mjs +249 -0
  61. package/src/tui/ui-content.mjs +144 -94
  62. package/src/tui/ui-mentions.mjs +44 -0
  63. package/src/tui/ui-overlay-view.mjs +255 -0
  64. package/src/tui/ui-suggest-view.mjs +63 -0
  65. package/src/tui/ui-suggest.mjs +197 -0
  66. package/src/tui/ui-theme.mjs +2 -1
  67. package/src/tui/ui-view.mjs +4 -190
  68. package/src/tui/ui.mjs +111 -1
@@ -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";
@@ -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(),
@@ -86,6 +86,8 @@ async function initialize(file: string): Promise<Database> {
86
86
  CREATE TABLE IF NOT EXISTS registry(room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,session_id TEXT NOT NULL,server_url TEXT NOT NULL,api_prefix TEXT NOT NULL,protocol TEXT,name TEXT NOT NULL,last_read_ts INTEGER,last_queued_ts INTEGER,directory TEXT,host TEXT,receiver_owner_id TEXT,membership_id TEXT,work_state TEXT,last_seen_at INTEGER,PRIMARY KEY(room_id,session_id));`);
87
87
  db.exec("CREATE TABLE IF NOT EXISTS announcements(room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,name TEXT NOT NULL,content TEXT NOT NULL,updated_at INTEGER NOT NULL,PRIMARY KEY(room_id,name))");
88
88
  db.exec("CREATE TABLE IF NOT EXISTS resources(id TEXT PRIMARY KEY,room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,name TEXT NOT NULL,mime_type TEXT NOT NULL,size INTEGER NOT NULL,created_at INTEGER NOT NULL,uploader_session_id TEXT,uploader_name TEXT)");
89
+ db.exec("CREATE TABLE IF NOT EXISTS room_tasks(id TEXT PRIMARY KEY,room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,title TEXT NOT NULL,description TEXT NOT NULL DEFAULT '',assignee TEXT NOT NULL DEFAULT '',status TEXT NOT NULL CHECK(status IN ('todo','doing','done')),creator_name TEXT NOT NULL,creator_session_id TEXT NOT NULL,created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL,due_date TEXT NOT NULL DEFAULT '',participants TEXT NOT NULL DEFAULT '[]',conclusion TEXT NOT NULL DEFAULT '',steps TEXT NOT NULL DEFAULT '[]')");
90
+ db.exec("CREATE INDEX IF NOT EXISTS room_tasks_room_status_created ON room_tasks(room_id,status,created_at,id)");
89
91
  await ensureRoomColumns(db);
90
92
  await migrate(db, file);
91
93
  db.exec("PRAGMA busy_timeout=50;");
@@ -151,6 +153,66 @@ export async function removeResource(file: string, roomID: string, id: string):
151
153
  const db = await openStateDatabase(file);
152
154
  return immediate(db, () => db.query("DELETE FROM resources WHERE room_id=? AND id=?").run(roomID, id).changes > 0);
153
155
  }
156
+
157
+ // --- Room tasks (group rooms only; HTTP permissions live in rooms/tasks.ts) ---
158
+ export const ROOM_TASK_STATUSES = ["todo", "doing", "done"] as const;
159
+ export type RoomTaskStatus = (typeof ROOM_TASK_STATUSES)[number];
160
+ export type RoomTaskStep = { text: string; done: boolean };
161
+ export type RoomTask = {
162
+ id: string; roomId: string; title: string; description: string; assignee: string;
163
+ status: RoomTaskStatus; creatorName: string; creatorSessionID: string;
164
+ createdAt: number; updatedAt: number; dueDate: string; participants: string[];
165
+ conclusion: string; steps: RoomTaskStep[];
166
+ };
167
+ type RoomTaskRow = Omit<RoomTask, "status" | "participants" | "steps"> & { status: string; participants: string; steps: string };
168
+ const ROOM_TASK_COLUMNS = "id,room_id AS roomId,title,description,assignee,status,creator_name AS creatorName,creator_session_id AS creatorSessionID,created_at AS createdAt,updated_at AS updatedAt,due_date AS dueDate,participants,conclusion,steps";
169
+ const jsonArray = <T>(value: string): T[] => {
170
+ try { const parsed = JSON.parse(value) as unknown; return Array.isArray(parsed) ? parsed as T[] : []; }
171
+ catch { return []; }
172
+ };
173
+ const roomTask = (row: RoomTaskRow): RoomTask => ({
174
+ ...row, status: row.status as RoomTaskStatus,
175
+ participants: jsonArray<string>(row.participants), steps: jsonArray<RoomTaskStep>(row.steps),
176
+ });
177
+
178
+ export function listRoomTasks(db: Database, roomID: string): RoomTask[] {
179
+ return (db.query(`SELECT ${ROOM_TASK_COLUMNS} FROM room_tasks WHERE room_id=? ORDER BY created_at,id`).all(roomID) as RoomTaskRow[]).map(roomTask);
180
+ }
181
+
182
+ export function readRoomTask(db: Database, roomID: string, id: string): RoomTask | undefined {
183
+ const row = db.query(`SELECT ${ROOM_TASK_COLUMNS} FROM room_tasks WHERE room_id=? AND id=?`).get(roomID, id) as RoomTaskRow | null;
184
+ return row ? roomTask(row) : undefined;
185
+ }
186
+
187
+ export function insertRoomTask(db: Database, task: RoomTask): void {
188
+ db.query("INSERT INTO room_tasks(id,room_id,title,description,assignee,status,creator_name,creator_session_id,created_at,updated_at,due_date,participants,conclusion,steps) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
189
+ .run(task.id, task.roomId, task.title, task.description, task.assignee, task.status, task.creatorName, task.creatorSessionID,
190
+ task.createdAt, task.updatedAt, task.dueDate, JSON.stringify(task.participants), task.conclusion, JSON.stringify(task.steps));
191
+ }
192
+
193
+ export type RoomTaskPatch = Partial<Pick<RoomTask, "title" | "description" | "assignee" | "status" | "dueDate" | "participants" | "conclusion" | "steps">>;
194
+
195
+ export function patchRoomTask(db: Database, roomID: string, id: string, patch: RoomTaskPatch, updatedAt: number): RoomTask | undefined {
196
+ const sets: string[] = [], values: string[] = [];
197
+ for (const [column, value] of [["title", patch.title], ["description", patch.description], ["assignee", patch.assignee], ["status", patch.status], ["due_date", patch.dueDate], ["conclusion", patch.conclusion]] as const) {
198
+ if (value !== undefined) { sets.push(`${column}=?`); values.push(value); }
199
+ }
200
+ if (patch.participants !== undefined) { sets.push("participants=?"); values.push(JSON.stringify(patch.participants)); }
201
+ if (patch.steps !== undefined) { sets.push("steps=?"); values.push(JSON.stringify(patch.steps)); }
202
+ db.query(`UPDATE room_tasks SET ${sets.map((set) => `${set},`).join("")}updated_at=? WHERE room_id=? AND id=?`)
203
+ .run(...values, updatedAt, roomID, id);
204
+ return readRoomTask(db, roomID, id);
205
+ }
206
+
207
+ export function deleteRoomTask(db: Database, roomID: string, id: string): boolean {
208
+ return db.query("DELETE FROM room_tasks WHERE room_id=? AND id=?").run(roomID, id).changes > 0;
209
+ }
210
+
211
+ export function deleteCompletedRoomTasks(db: Database, roomID: string, creatorSessionID?: string): number {
212
+ return creatorSessionID === undefined
213
+ ? db.query("DELETE FROM room_tasks WHERE room_id=? AND status='done'").run(roomID).changes
214
+ : db.query("DELETE FROM room_tasks WHERE room_id=? AND status='done' AND creator_session_id=?").run(roomID, creatorSessionID).changes;
215
+ }
154
216
  async function ensureRoomColumns(db: Database): Promise<void> {
155
217
  await immediate(db, () => {
156
218
  const messageColumns = db.query("PRAGMA table_info(messages)").all() as Array<{ name: string }>;
@@ -161,6 +223,11 @@ async function ensureRoomColumns(db: Database): Promise<void> {
161
223
  if (!messageColumns.some((column) => column.name === "recalled_by")) db.exec("ALTER TABLE messages ADD COLUMN recalled_by TEXT");
162
224
  db.exec("CREATE INDEX IF NOT EXISTS messages_pending_questions ON messages(room_id,is_question,answered_by,seq)");
163
225
  db.exec("CREATE INDEX IF NOT EXISTS messages_room_recalled ON messages(room_id,recalled_at)");
226
+ const taskColumns = db.query("PRAGMA table_info(room_tasks)").all() as Array<{ name: string }>;
227
+ if (!taskColumns.some((column) => column.name === "due_date")) db.exec("ALTER TABLE room_tasks ADD COLUMN due_date TEXT NOT NULL DEFAULT ''");
228
+ if (!taskColumns.some((column) => column.name === "participants")) db.exec("ALTER TABLE room_tasks ADD COLUMN participants TEXT NOT NULL DEFAULT '[]'");
229
+ if (!taskColumns.some((column) => column.name === "conclusion")) db.exec("ALTER TABLE room_tasks ADD COLUMN conclusion TEXT NOT NULL DEFAULT ''");
230
+ if (!taskColumns.some((column) => column.name === "steps")) db.exec("ALTER TABLE room_tasks ADD COLUMN steps TEXT NOT NULL DEFAULT '[]'");
164
231
  db.exec("CREATE TABLE IF NOT EXISTS room_recall_versions(room_id TEXT PRIMARY KEY REFERENCES rooms(id) ON DELETE CASCADE,version INTEGER NOT NULL)");
165
232
  db.exec(`CREATE TABLE IF NOT EXISTS room_join_requests(
166
233
  room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
package/src/tui/app.mjs CHANGED
@@ -2,6 +2,12 @@
2
2
  // the reducer can be tested against a fake api. Palette methods are attached
3
3
  // from palette-app.mjs.
4
4
  import { attachPalette } from "./palette-app.mjs";
5
+ import { attachInfo } from "./info-app.mjs";
6
+ import { attachReminders } from "./reminder-app.mjs";
7
+ import { attachRoomSettings } from "./room-settings-app.mjs";
8
+ import { attachMessageActions } from "./message-app.mjs";
9
+ import { attachJoinRequests } from "./join-app.mjs";
10
+ import { canonicalizeMentions } from "./mentions.mjs";
5
11
  import { mergeMessages, messageStamp, oldestSeq } from "./messages.mjs";
6
12
 
7
13
  const BACKOFF_MS = [1000, 2000, 4000, 8000, 15000];
@@ -16,12 +22,16 @@ const normalizeRoom = (room) => ({
16
22
  });
17
23
 
18
24
  export class ChatApp {
19
- constructor({ api, sessionID, participant, host = "", autoPoll = true, schedule = (fn, ms) => setTimeout(fn, ms) }) {
25
+ constructor({ api, sessionID, participant, host = "", autoPoll = true, settings = {}, downloadDir = process.cwd(), schedule = (fn, ms) => setTimeout(fn, ms) }) {
20
26
  this.api = api;
21
27
  this.sessionID = sessionID;
22
28
  this.participant = participant;
23
29
  this.autoPoll = autoPoll;
24
30
  this.schedule = schedule;
31
+ this.settings = { ...settings };
32
+ this.token = this.settings.token ?? "";
33
+ delete this.settings.token;
34
+ this.downloadDir = downloadDir;
25
35
  this.closed = false;
26
36
  this.pollToken = 0;
27
37
  this.timers = new Set();
@@ -35,6 +45,7 @@ export class ChatApp {
35
45
  this.state = {
36
46
  host,
37
47
  participant,
48
+ theme: "dark",
38
49
  connection: "connecting",
39
50
  rooms: [],
40
51
  selected: 0,
@@ -319,13 +330,14 @@ export class ChatApp {
319
330
  }
320
331
 
321
332
  async send() {
322
- const text = String(this.state.draft ?? "").trim();
323
- if (!text) return;
333
+ const raw = String(this.state.draft ?? "").trim();
334
+ if (!raw) return;
324
335
  const room = this.state.current;
325
336
  if (!room || !this.state.joined) {
326
337
  this.setStatus("join a room before sending", "error");
327
338
  return;
328
339
  }
340
+ const text = canonicalizeMentions(raw, room.participants);
329
341
  this.state.draft = "";
330
342
  this.touch();
331
343
  try {
@@ -338,7 +350,7 @@ export class ChatApp {
338
350
  this.setStatus("sent", "success");
339
351
  this.markRead();
340
352
  } catch (error) {
341
- if (!this.state.draft) this.state.draft = text;
353
+ if (!this.state.draft) this.state.draft = raw;
342
354
  this.setStatus(`send failed: ${errorText(error)}`, "error");
343
355
  }
344
356
  }
@@ -411,6 +423,11 @@ export class ChatApp {
411
423
  }
412
424
 
413
425
  attachPalette(ChatApp);
426
+ attachInfo(ChatApp);
427
+ attachReminders(ChatApp);
428
+ attachRoomSettings(ChatApp);
429
+ attachMessageActions(ChatApp);
430
+ attachJoinRequests(ChatApp);
414
431
 
415
432
  export function createApp(options) {
416
433
  return new ChatApp(options);