@alexsun-top/opencode-chat-room 0.5.1 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +15 -7
- package/README.zh-CN.md +15 -7
- package/package.json +4 -2
- package/plugin.ts +19 -4
- package/server/assets/base.css +10 -0
- package/server/assets/chat/admin.js +37 -10
- package/server/assets/chat/attachments.js +1 -1
- package/server/assets/chat/editor.js +211 -0
- package/server/assets/chat/events.js +7 -5
- package/server/assets/chat/index.js +4 -0
- package/server/assets/chat/mentions.js +38 -28
- package/server/assets/chat/message-window.js +18 -0
- package/server/assets/chat/messages.js +48 -56
- package/server/assets/chat/questions.js +113 -41
- package/server/assets/chat/receipts.js +0 -1
- package/server/assets/chat/reminders.js +101 -0
- package/server/assets/chat/replies.js +149 -0
- package/server/assets/chat/rooms.js +9 -6
- package/server/assets/chat/state.js +27 -9
- package/server/assets/conversation.css +30 -9
- package/server/assets/responsive.css +10 -4
- package/server/chat-server.ts +21 -2
- package/server/chat.html +23 -6
- package/server/inbox.ts +5 -1
- package/server/room-reminders.ts +212 -0
- package/server/wake.ts +6 -3
- package/skills/chatroom/SKILL.md +9 -1
- package/src/agent-receipts.ts +13 -18
- package/src/plugin-notifications.ts +4 -0
- package/src/queue.ts +7 -2
- package/src/reminder-client.ts +50 -0
- package/src/resource-read.ts +118 -0
- package/src/resources.ts +1 -1
- package/src/sqlite-state.ts +43 -3
- package/src/store.ts +22 -8
- package/src/v2-plugin.ts +11 -5
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { promises as fs } from "node:fs";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
type Options = { center: string; token: string };
|
|
7
|
+
type Permission = { ask(input: { permission: string; patterns: string[]; always: string[]; metadata: Record<string, unknown> }): Promise<void> };
|
|
8
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
9
|
+
const limit = 512 * 1024 * 1024;
|
|
10
|
+
|
|
11
|
+
export class ResourceReadError extends Error {
|
|
12
|
+
constructor(readonly code: "permission_denied" | "size_limit" | "not_found" | "aborted" | "network" | "save_failed", message: string) { super(message); }
|
|
13
|
+
}
|
|
14
|
+
export function resourceReadFailure(error: unknown): string {
|
|
15
|
+
return error instanceof ResourceReadError ? error.message : "resource read failed";
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function readAgentResource(opts: Options, roomID: string, id: string, permission: Permission, signal?: AbortSignal) {
|
|
19
|
+
if (!opts.center) throw new Error("resource viewing requires CHAT_ROOM_SERVER_URL (central server mode)");
|
|
20
|
+
if (!uuid.test(roomID) || !uuid.test(id)) throw new Error("invalid roomId or resourceId");
|
|
21
|
+
const base = new URL(opts.center);
|
|
22
|
+
if (!/^https?:$/.test(base.protocol) || base.username || base.password) throw new Error("invalid chat server URL");
|
|
23
|
+
await ask(permission, "webfetch", [base.origin], { url: base.origin });
|
|
24
|
+
const headers: Record<string, string> = opts.token ? { Authorization: `Bearer ${opts.token}` } : {};
|
|
25
|
+
const root = `${base.origin}${base.pathname.replace(/\/$/, "")}`;
|
|
26
|
+
const requestSignal = combineSignal(signal, 30_000);
|
|
27
|
+
let configuredLimit: number | undefined;
|
|
28
|
+
try {
|
|
29
|
+
const response = await fetchSafe(`${root}/resources/config`, { headers, redirect: "error", signal: requestSignal }, signal);
|
|
30
|
+
if (response.ok) {
|
|
31
|
+
const config = await response.json() as { maxFileSizeBytes?: number };
|
|
32
|
+
if (Number.isSafeInteger(config.maxFileSizeBytes) && config.maxFileSizeBytes! > 0) configuredLimit = config.maxFileSizeBytes;
|
|
33
|
+
}
|
|
34
|
+
} catch (error) { if (error instanceof ResourceReadError && error.code === "aborted") throw error; }
|
|
35
|
+
const allowed = Math.min(limit, configuredLimit ?? limit);
|
|
36
|
+
const limitNote = configuredLimit ? `server limit ${Math.min(limit, configuredLimit)} bytes` : "512 MiB safety cap (server limit unavailable)";
|
|
37
|
+
const endpoint = `${root}/rooms/${roomID}/resources/${id}`;
|
|
38
|
+
const metadataResponse = await fetchSafe(endpoint, { headers, redirect: "error", signal: requestSignal }, signal);
|
|
39
|
+
if (metadataResponse.status === 404) throw new ResourceReadError("not_found", "resource not found in this room");
|
|
40
|
+
if (!metadataResponse.ok) throw new ResourceReadError("network", "could not retrieve resource metadata");
|
|
41
|
+
const metadata = await metadataResponse.json() as { resource?: { id?: string; roomID?: string; mimeType?: string; size?: number; name?: string } };
|
|
42
|
+
const resource = metadata.resource;
|
|
43
|
+
if (resource && Number.isSafeInteger(resource.size) && resource.size! > allowed) throw new ResourceReadError("size_limit", `resource exceeds the ${limitNote}`);
|
|
44
|
+
if (!resource || resource.id !== id || resource.roomID !== roomID || typeof resource.name !== "string" || typeof resource.mimeType !== "string" || !Number.isSafeInteger(resource.size) || resource.size! < 0) throw new ResourceReadError("network", "resource metadata is invalid");
|
|
45
|
+
const verified: Resource = { id: resource.id!, roomID: resource.roomID!, name: resource.name, mimeType: resource.mimeType, size: resource.size! };
|
|
46
|
+
return saveResource(permission, headers, endpoint, verified, allowed, signal, limitNote);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
type Resource = { id: string; roomID: string; mimeType: string; size: number; name: string };
|
|
50
|
+
async function saveResource(permission: Permission, headers: Record<string, string>, endpoint: string, resource: Resource, allowed: number, signal: AbortSignal | undefined, limitNote: string): Promise<string> {
|
|
51
|
+
const tmp = os.tmpdir();
|
|
52
|
+
await ask(permission, "external_directory", [tmp], { filepath: tmp });
|
|
53
|
+
const directory = await fs.mkdtemp(path.join(tmp, "opencode-chat-room-"));
|
|
54
|
+
const extension = path.extname(resource.name).toLowerCase();
|
|
55
|
+
const filename = `${randomUUID()}${/^\.[a-z0-9]{1,10}$/.test(extension) ? extension : ".bin"}`;
|
|
56
|
+
const filepath = path.join(directory, filename);
|
|
57
|
+
try {
|
|
58
|
+
await fs.chmod(directory, 0o700);
|
|
59
|
+
await ask(permission, "edit", [filepath], { filepath });
|
|
60
|
+
await ask(permission, "read", [filepath], { filepath });
|
|
61
|
+
const response = await fetchSafe(`${endpoint}/content`, { headers, redirect: "error", signal: combineSignal(signal, 30 * 60_000) }, signal);
|
|
62
|
+
if (response.status === 404) throw new ResourceReadError("not_found", "resource not found in this room");
|
|
63
|
+
if (response.status === 413) throw new ResourceReadError("size_limit", "resource exceeds the server download limit");
|
|
64
|
+
if (!response.ok || !response.body) throw new ResourceReadError("network", "could not retrieve resource content");
|
|
65
|
+
const file = await fs.open(filepath, "wx", 0o600);
|
|
66
|
+
try { await streamToFile(response.body, file, Math.min(allowed, resource.size), signal); }
|
|
67
|
+
finally { await file.close(); }
|
|
68
|
+
const info = await fs.stat(filepath);
|
|
69
|
+
if (info.size !== resource.size) throw new Error("resource size does not match metadata");
|
|
70
|
+
return `Saved ${safeDisplayName(resource.name)} (${resource.mimeType}, ${info.size} bytes) to ${filepath}; used ${limitNote}. The private temporary file remains until you remove it or the operating system cleans temporary files.`;
|
|
71
|
+
} catch (error) {
|
|
72
|
+
await fs.rm(directory, { recursive: true, force: true }).catch(() => {});
|
|
73
|
+
if (error instanceof ResourceReadError) throw error;
|
|
74
|
+
if (signal?.aborted || (error instanceof Error && error.name === "AbortError")) throw new ResourceReadError("aborted", "resource download was canceled");
|
|
75
|
+
throw new ResourceReadError("save_failed", "could not save resource to private temporary storage");
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function streamToFile(body: ReadableStream<Uint8Array>, file: Awaited<ReturnType<typeof fs.open>>, limitBytes: number, signal?: AbortSignal): Promise<void> {
|
|
80
|
+
const reader = body.getReader(); let size = 0;
|
|
81
|
+
try {
|
|
82
|
+
while (true) {
|
|
83
|
+
const { done, value } = await reader.read(); if (done) break;
|
|
84
|
+
size += value.byteLength;
|
|
85
|
+
if (size > limitBytes) throw new ResourceReadError("size_limit", "resource exceeds the configured safe limit");
|
|
86
|
+
let offset = 0;
|
|
87
|
+
while (offset < value.byteLength) {
|
|
88
|
+
let result;
|
|
89
|
+
try { result = await file.write(value, offset, value.byteLength - offset); }
|
|
90
|
+
catch { throw new ResourceReadError("save_failed", "could not write resource to private temporary storage"); }
|
|
91
|
+
if (!result.bytesWritten) throw new Error("temporary file write made no progress");
|
|
92
|
+
offset += result.bytesWritten;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
} catch (error) {
|
|
96
|
+
await reader.cancel().catch(() => {});
|
|
97
|
+
if (error instanceof ResourceReadError) throw error;
|
|
98
|
+
if (signal?.aborted || (error instanceof Error && error.name === "AbortError")) throw new ResourceReadError("aborted", "resource download was canceled");
|
|
99
|
+
throw new ResourceReadError("network", "resource download was interrupted");
|
|
100
|
+
}
|
|
101
|
+
finally { reader.releaseLock(); }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function combineSignal(signal: AbortSignal | undefined, timeout: number): AbortSignal {
|
|
105
|
+
return signal ? AbortSignal.any([signal, AbortSignal.timeout(timeout)]) : AbortSignal.timeout(timeout);
|
|
106
|
+
}
|
|
107
|
+
async function ask(permission: Permission, action: string, patterns: string[], metadata: Record<string, unknown>): Promise<void> {
|
|
108
|
+
try { await permission.ask({ permission: action, patterns, always: [], metadata }); }
|
|
109
|
+
catch { throw new ResourceReadError("permission_denied", `host denied ${action} permission for resource download`); }
|
|
110
|
+
}
|
|
111
|
+
async function fetchSafe(url: string, init: RequestInit, signal?: AbortSignal): Promise<Response> {
|
|
112
|
+
try { return await fetch(url, init); }
|
|
113
|
+
catch (error) {
|
|
114
|
+
if (signal?.aborted || (error instanceof Error && error.name === "AbortError")) throw new ResourceReadError("aborted", "resource download was canceled");
|
|
115
|
+
throw new ResourceReadError("network", "resource server request failed or timed out");
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function safeDisplayName(name: string): string { return path.basename(name).replace(/[\u0000-\u001f\u007f]/g, "_").slice(0, 255) || "attachment"; }
|
package/src/resources.ts
CHANGED
|
@@ -13,7 +13,7 @@ const storageDir = () => path.join(path.dirname(databasePath()), "resources");
|
|
|
13
13
|
const roomDirectory = (roomID: string) => path.join(storageDir(), roomID);
|
|
14
14
|
|
|
15
15
|
export function maxResourceBytes(): number {
|
|
16
|
-
const mb = Number(process.env.CHAT_ROOM_MAX_FILE_SIZE_MB ?? "
|
|
16
|
+
const mb = Number(process.env.CHAT_ROOM_MAX_FILE_SIZE_MB ?? "500");
|
|
17
17
|
const bytes = mb * 1024 * 1024;
|
|
18
18
|
if (!Number.isFinite(mb) || mb <= 0 || !Number.isSafeInteger(bytes)) throw new Error("CHAT_ROOM_MAX_FILE_SIZE_MB must be a positive finite number");
|
|
19
19
|
return bytes;
|
package/src/sqlite-state.ts
CHANGED
|
@@ -43,6 +43,19 @@ export async function initializeAdminSchema(file: string): Promise<void> {
|
|
|
43
43
|
});
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
export async function initializeReminderSchema(file: string): Promise<void> {
|
|
47
|
+
await withStateTransaction(file, db => db.exec(`CREATE TABLE IF NOT EXISTS room_reminders(
|
|
48
|
+
id TEXT PRIMARY KEY, room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
|
|
49
|
+
creator_session_id TEXT NOT NULL, text TEXT NOT NULL, schedule_type TEXT NOT NULL,
|
|
50
|
+
at TEXT, expression TEXT, timezone TEXT, paused INTEGER NOT NULL DEFAULT 0,
|
|
51
|
+
next_run_at INTEGER NOT NULL, created_at INTEGER NOT NULL, last_error TEXT);`));
|
|
52
|
+
await withStateTransaction(file, db => {
|
|
53
|
+
const columns = db.query("PRAGMA table_info(room_reminders)").all() as Array<{ name: string }>;
|
|
54
|
+
if (!columns.some(column => column.name === "initiator")) db.exec("ALTER TABLE room_reminders ADD COLUMN initiator TEXT NOT NULL DEFAULT ''");
|
|
55
|
+
if (!columns.some(column => column.name === "last_error")) db.exec("ALTER TABLE room_reminders ADD COLUMN last_error TEXT");
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
46
59
|
async function initialize(file: string): Promise<Database> {
|
|
47
60
|
mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
48
61
|
chmodSync(path.dirname(file), 0o700);
|
|
@@ -347,6 +360,33 @@ export async function answerQuestion(file: string, roomID: string, questionID: s
|
|
|
347
360
|
});
|
|
348
361
|
}
|
|
349
362
|
|
|
363
|
+
export async function sendReply(file: string, roomID: string, targetID: string, sessionID: string, text: string): Promise<{ status: "ok"; message: Message } | { status: "missing" | "member" | "target" | "question" }> {
|
|
364
|
+
const db = await openStateDatabase(file);
|
|
365
|
+
return immediate(db, () => {
|
|
366
|
+
if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return { status: "missing" };
|
|
367
|
+
const member = db.query("SELECT g.name,r.kind FROM registry g JOIN rooms r ON r.id=g.room_id JOIN participants p ON p.room_id=g.room_id AND p.id=CASE WHEN r.kind='direct' THEN g.session_id ELSE g.name END WHERE g.room_id=? AND g.session_id=?").get(roomID, sessionID) as { name: string; kind: string } | null;
|
|
368
|
+
if (!member) return { status: "member" };
|
|
369
|
+
const target = db.query("SELECT is_question FROM messages WHERE room_id=? AND id=?").get(roomID, targetID) as { is_question: number } | null;
|
|
370
|
+
if (!target) return { status: "target" };
|
|
371
|
+
if (target.is_question) return { status: "question" };
|
|
372
|
+
const tail = db.query("SELECT created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1").get(roomID) as { created_at: number } | null;
|
|
373
|
+
const message: Message = { id: randomUUID(), roomId: roomID, senderId: member.kind === "direct" ? sessionID : member.name, senderSessionID: sessionID, text, createdAt: Math.max(Date.now(), (tail?.created_at ?? 0) + 1), answerToMessageID: targetID };
|
|
374
|
+
db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to) VALUES(?,?,?,?,?,?,0,?)").run(message.id, roomID, message.senderId, sessionID, text, message.createdAt, targetID);
|
|
375
|
+
return { status: "ok", message };
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function questionExcerpt(text: string): string {
|
|
380
|
+
const chars = Array.from(text);
|
|
381
|
+
return chars.length <= 200 ? text : `${chars.slice(0, 100).join("")}…${chars.slice(-100).join("")}`;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
export async function readQuestionExcerpt(file: string, roomID: string, questionID: string): Promise<string | undefined> {
|
|
385
|
+
const db = await openStateDatabase(file);
|
|
386
|
+
const row = db.query("SELECT text FROM messages WHERE room_id=? AND id=? AND is_question=1").get(roomID, questionID) as { text: string } | null;
|
|
387
|
+
return row ? questionExcerpt(row.text) : undefined;
|
|
388
|
+
}
|
|
389
|
+
|
|
350
390
|
export async function readUnreadPage(file: string, roomID: string, afterTs: number, limit = 100, sessionID?: string, senderName?: string, newest = false): Promise<Page<Message>> {
|
|
351
391
|
const db = await openStateDatabase(file);
|
|
352
392
|
const take = Math.min(200, Math.max(1, limit));
|
|
@@ -364,8 +404,8 @@ export async function readInboxPage(file: string, sessionID: string, roomFilter:
|
|
|
364
404
|
return db.transaction(() => {
|
|
365
405
|
const take = Math.min(200, Math.max(1, limit));
|
|
366
406
|
const members = db.query("SELECT room_id,last_queued_ts FROM registry WHERE session_id=? AND (? IS NULL OR room_id=?)").all(sessionID, roomFilter, roomFilter) as Array<{ room_id: string; last_queued_ts: number | null }>;
|
|
367
|
-
const rows = db.query(`SELECT m.id,m.room_id,m.sender_id,m.sender_session_id,m.text,m.created_at,m.is_question,m.answer_to,m.answered_by,r.name AS room_name,r.kind AS room_kind
|
|
368
|
-
FROM messages m JOIN registry g ON g.room_id=m.room_id JOIN rooms r ON r.id=m.room_id
|
|
407
|
+
const rows = db.query(`SELECT m.id,m.room_id,m.sender_id,m.sender_session_id,m.text,m.created_at,m.is_question,m.answer_to,m.answered_by,r.name AS room_name,r.kind AS room_kind,q.text AS answer_question_text
|
|
408
|
+
FROM messages m JOIN registry g ON g.room_id=m.room_id JOIN rooms r ON r.id=m.room_id LEFT JOIN messages q ON q.room_id=m.room_id AND q.id=m.answer_to AND q.is_question=1
|
|
369
409
|
WHERE g.session_id=? AND (? IS NULL OR m.room_id=?) AND
|
|
370
410
|
m.created_at > coalesce(?,CASE WHEN ? THEN max(coalesce(g.last_read_ts,0),coalesce(g.last_queued_ts,0)) ELSE coalesce(g.last_read_ts,0) END) AND
|
|
371
411
|
(?=0 OR (m.sender_session_id IS NOT NULL AND m.sender_session_id!=?) OR (m.sender_session_id IS NULL AND m.sender_id!=g.name))
|
|
@@ -374,7 +414,7 @@ export async function readInboxPage(file: string, sessionID: string, roomFilter:
|
|
|
374
414
|
const hasMore = rows.length > take;
|
|
375
415
|
const items = rows.slice(0, take).map((row) => {
|
|
376
416
|
const message = rowMessage(row);
|
|
377
|
-
return { ...message, roomName: String(row.room_name), roomKind: (row.room_kind === "direct" ? "direct" : "group") as "direct" | "group" };
|
|
417
|
+
return { ...message, ...(row.answer_question_text !== null ? { answerQuestionExcerpt: questionExcerpt(String(row.answer_question_text)) } : {}), roomName: String(row.room_name), roomKind: (row.room_kind === "direct" ? "direct" : "group") as "direct" | "group" };
|
|
378
418
|
});
|
|
379
419
|
const queuedTs = Object.fromEntries(members.map((member) => [member.room_id, member.last_queued_ts ?? 0]));
|
|
380
420
|
return { member: members.length > 0, items, queuedTs, hasMore };
|
package/src/store.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import os from "node:os";
|
|
6
6
|
import RoomService, { type Message, type Room } from "./room-service";
|
|
7
|
-
import { answerQuestion as sqliteAnswerQuestion, readHistoryPage, readInboxPage as sqliteInboxPage, readMessageReceipts, readQuestions as sqliteReadQuestions, readSqliteState, readUnreadPage, writeMessageReceipts, writePresenceState, writeSqliteState, type HistoryMessage } from "./sqlite-state";
|
|
7
|
+
import { answerQuestion as sqliteAnswerQuestion, sendReply as sqliteSendReply, readHistoryPage, readInboxPage as sqliteInboxPage, readMessageReceipts, readQuestionExcerpt as sqliteQuestionExcerpt, readQuestions as sqliteReadQuestions, readSqliteState, readUnreadPage, writeMessageReceipts, writePresenceState, writeSqliteState, type HistoryMessage } from "./sqlite-state";
|
|
8
8
|
|
|
9
9
|
export function statePath(): string {
|
|
10
10
|
// JSON path remains the migration source; SQLite lives beside it.
|
|
@@ -36,6 +36,8 @@ export async function readHistory(roomID: string, beforeSeq?: number, limit = 10
|
|
|
36
36
|
}
|
|
37
37
|
export async function readQuestions(roomID: string): Promise<Message[]> { return sqliteReadQuestions(databasePath(), roomID); }
|
|
38
38
|
export async function answerQuestion(roomID: string, questionID: string, sessionID: string, text: string) { return sqliteAnswerQuestion(databasePath(), roomID, questionID, sessionID, text); }
|
|
39
|
+
export async function sendReply(roomID: string, targetID: string, sessionID: string, text: string) { return sqliteSendReply(databasePath(), roomID, targetID, sessionID, text); }
|
|
40
|
+
export async function readQuestionExcerpt(roomID: string, questionID: string) { return sqliteQuestionExcerpt(databasePath(), roomID, questionID); }
|
|
39
41
|
|
|
40
42
|
export async function loadRooms(): Promise<Room[]> {
|
|
41
43
|
return (await readSqliteState(databasePath())).rooms;
|
|
@@ -109,20 +111,32 @@ const MAX_LINES = 20;
|
|
|
109
111
|
// lines were folded or message text was truncated; callers must not advance
|
|
110
112
|
// the watermark until a full poll confirms it.
|
|
111
113
|
export function formatNotificationLines(
|
|
112
|
-
items: ReadonlyArray<{ createdAt: number; senderId: string; text: string }>,
|
|
113
|
-
): { lines: string[]; capped: boolean } {
|
|
114
|
-
const
|
|
114
|
+
items: ReadonlyArray<{ createdAt: number; senderId: string; text: string; answerQuestionExcerpt?: string }>,
|
|
115
|
+
): { lines: string[]; capped: boolean; visibleIndices: number[] } {
|
|
116
|
+
const visible: Array<{ item: typeof items[number]; index: number }> = [];
|
|
117
|
+
let lineCount = 0;
|
|
118
|
+
for (let index = items.length - 1; index >= 0; index--) {
|
|
119
|
+
const item = items[index]!;
|
|
120
|
+
const required = item.answerQuestionExcerpt ? 2 : 1;
|
|
121
|
+
if (lineCount + required > MAX_LINES) break;
|
|
122
|
+
visible.unshift({ item, index });
|
|
123
|
+
lineCount += required;
|
|
124
|
+
}
|
|
125
|
+
const countCapped = visible.length < items.length;
|
|
115
126
|
const textCapped = items.some((it) => it.text.length > MAX_LINE);
|
|
116
127
|
const capped = countCapped || textCapped;
|
|
117
|
-
const lines =
|
|
128
|
+
const lines = visible.flatMap(({ item: it }) => {
|
|
118
129
|
const text =
|
|
119
130
|
it.text.length > MAX_LINE ? `${it.text.slice(0, MAX_LINE)}\u2026` : it.text;
|
|
120
|
-
return
|
|
131
|
+
return [
|
|
132
|
+
...(it.answerQuestionExcerpt ? [` ↳ Answer to: “${it.answerQuestionExcerpt.replace(/[\r\n]+/g, " ")}”`] : []),
|
|
133
|
+
`- [${timeOf(it.createdAt)}] ${it.senderId}: ${text}`,
|
|
134
|
+
];
|
|
121
135
|
});
|
|
122
136
|
if (countCapped) {
|
|
123
|
-
lines.unshift(`\u2026 and ${items.length -
|
|
137
|
+
lines.unshift(`\u2026 and ${items.length - visible.length} earlier messages`);
|
|
124
138
|
}
|
|
125
|
-
return { lines, capped };
|
|
139
|
+
return { lines, capped, visibleIndices: visible.map(({ index }) => index) };
|
|
126
140
|
}
|
|
127
141
|
|
|
128
142
|
export function authHeader(): string {
|
package/src/v2-plugin.ts
CHANGED
|
@@ -20,7 +20,7 @@ export type V2Runtime = {
|
|
|
20
20
|
export function createV2Setup(deps: {
|
|
21
21
|
runtime(directory: string, transport: QueueTransport): V2Runtime;
|
|
22
22
|
run<T>(runtime: V2Runtime, callback: () => T): T;
|
|
23
|
-
execute(args: z.infer<ReturnType<typeof roomSchema>>, sessionID: string, permissionContext: { directory: string; worktree?: string; ask(input: { permission: string; patterns: string[]; always: string[]; metadata: Record<string, unknown> }): Promise<void> }): Promise<string>;
|
|
23
|
+
execute(args: z.infer<ReturnType<typeof roomSchema>>, sessionID: string, permissionContext: { directory: string; worktree?: string; signal?: AbortSignal; ask(input: { permission: string; patterns: string[]; always: string[]; metadata: Record<string, unknown> }): Promise<void> }): Promise<string>;
|
|
24
24
|
admin?: (args: z.infer<typeof adminToolSchema>, sessionID: string, transport: QueueTransport, center: CenterOptions) => Promise<string>;
|
|
25
25
|
observe(runtime: V2Runtime, sessionID: string): Promise<void>;
|
|
26
26
|
poll(sessions: ReadonlySet<string>, transport: QueueTransport, center: CenterOptions): Promise<void>;
|
|
@@ -80,7 +80,7 @@ export function createV2Setup(deps: {
|
|
|
80
80
|
});
|
|
81
81
|
toolRegistration = await context.tool.transform((editor) => editor.add({
|
|
82
82
|
name: "room",
|
|
83
|
-
description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements;
|
|
83
|
+
description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements; manage reminders. Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup.",
|
|
84
84
|
options: { codemode: false },
|
|
85
85
|
input: roomSchema(),
|
|
86
86
|
execute: async (args, toolContext) => {
|
|
@@ -90,6 +90,7 @@ export function createV2Setup(deps: {
|
|
|
90
90
|
const permissionContext = {
|
|
91
91
|
directory: context.location.directory,
|
|
92
92
|
worktree: context.location.directory,
|
|
93
|
+
signal: toolContext.signal,
|
|
93
94
|
ask: (input: { permission: string; patterns: string[]; always: string[]; metadata: Record<string, unknown> }) => context.permission.assert({
|
|
94
95
|
sessionID: toolContext.sessionID,
|
|
95
96
|
agent: toolContext.agent,
|
|
@@ -100,7 +101,8 @@ export function createV2Setup(deps: {
|
|
|
100
101
|
source: { type: "tool", messageID: toolContext.messageID, id: toolContext.id },
|
|
101
102
|
}),
|
|
102
103
|
};
|
|
103
|
-
|
|
104
|
+
const result = await deps.execute(args, toolContext.sessionID, permissionContext);
|
|
105
|
+
return { content: [{ type: "text", text: result }] };
|
|
104
106
|
});
|
|
105
107
|
},
|
|
106
108
|
}));
|
|
@@ -148,16 +150,20 @@ export function createV2Setup(deps: {
|
|
|
148
150
|
};
|
|
149
151
|
}
|
|
150
152
|
|
|
151
|
-
function roomSchema() {
|
|
153
|
+
export function roomSchema() {
|
|
152
154
|
return z.object({
|
|
153
|
-
action: z.enum(["create", "join", "leave", "list", "send", "poll", "members", "upload_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete"]),
|
|
155
|
+
action: z.enum(["create", "join", "leave", "list", "send", "poll", "members", "upload_resource", "read_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete"]),
|
|
154
156
|
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."),
|
|
155
157
|
roomId: z.string().optional(),
|
|
158
|
+
resourceId: z.string().optional(),
|
|
156
159
|
filePath: z.string().optional().describe("Local regular file to upload; central mode only; requires host read permission."),
|
|
157
160
|
text: z.string().max(2000).optional(),
|
|
158
161
|
isQuestion: z.boolean().optional(),
|
|
159
162
|
announcementName: z.string().optional().describe("Name of a room announcement; distinct from participant or room name."),
|
|
160
163
|
content: z.string().optional().describe("Announcement content, at most 5000 Unicode characters."),
|
|
164
|
+
reminderId: z.string().optional(),
|
|
165
|
+
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(),
|
|
166
|
+
paused: z.boolean().optional(),
|
|
161
167
|
}).superRefine((args, ctx) => {
|
|
162
168
|
if (args.action === "join" && !args.name?.trim()) {
|
|
163
169
|
ctx.addIssue({ code: "custom", path: ["name"], message: "name is required to join a room" });
|