@alexsun-top/opencode-chat-room 0.5.0 → 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 +26 -0
- package/README.md +23 -7
- package/README.zh-CN.md +23 -7
- package/docs/administrator-rooms.md +51 -0
- package/package.json +11 -2
- package/plugin.ts +29 -12
- package/server/admin-auth.ts +16 -0
- package/server/admin-plan-routes.ts +79 -0
- package/server/admin-routes.ts +154 -0
- package/server/admin-scheduler.ts +42 -0
- package/server/admin-state.ts +61 -0
- package/server/admin-task-routes.ts +182 -0
- package/server/assets/base.css +55 -43
- package/server/assets/chat/admin.js +223 -0
- package/server/assets/chat/attachments.js +240 -0
- package/server/assets/chat/editor.js +211 -0
- package/server/assets/chat/events.js +34 -10
- package/server/assets/chat/index.js +8 -0
- package/server/assets/chat/markdown.js +1 -12
- package/server/assets/chat/members.js +1 -1
- package/server/assets/chat/mentions.js +38 -28
- package/server/assets/chat/message-window.js +18 -0
- package/server/assets/chat/messages.js +64 -46
- 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 +30 -10
- package/server/assets/chat/state.js +68 -18
- package/server/assets/conversation.css +111 -45
- package/server/assets/responsive.css +83 -28
- package/server/chat-server.ts +23 -6
- package/server/chat.html +82 -31
- package/server/inbox.ts +5 -1
- package/server/newrooms.ts +27 -10
- package/server/resource-routes.ts +3 -0
- package/server/room-reminders.ts +212 -0
- package/server/wake.ts +11 -15
- package/skills/chatroom/SKILL.md +21 -1
- package/src/admin-client.ts +130 -0
- package/src/admin-credentials.ts +58 -0
- package/src/agent-receipts.ts +13 -18
- package/src/center-client.ts +1 -1
- package/src/center-inbox.ts +2 -0
- 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 +89 -21
- package/src/store.ts +22 -8
- package/src/supervision-inbox.ts +62 -0
- package/src/v1-plugin.ts +13 -3
- package/src/v2-plugin.ts +24 -7
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { loadAdminCapability, loadTaskToken, saveAdminCapability, type AdminIdentity } from "./admin-credentials";
|
|
2
|
+
import type { CenterOpts } from "./center-client";
|
|
3
|
+
import type { QueueTransport } from "./queue-transport";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
|
|
6
|
+
export type AdminContext = { sessionID: string };
|
|
7
|
+
export type AdminArgs = {
|
|
8
|
+
action: "task_progress" | "admin_claim" | "admin_overview" | "admin_history" | "admin_dispatch" | "admin_tasks" |
|
|
9
|
+
"admin_task_update" | "admin_plans" | "admin_plan_create" | "admin_plan_update" | "admin_plan_delete";
|
|
10
|
+
roomId?: string; enrollmentKey?: string; targetRoomId?: string; targetSessionID?: string;
|
|
11
|
+
text?: string; name?: string; intervalSeconds?: number; planId?: string; taskId?: string;
|
|
12
|
+
status?: "pending" | "working" | "blocked" | "completed" | "cancelled";
|
|
13
|
+
progress?: string; paused?: boolean; limit?: number;
|
|
14
|
+
};
|
|
15
|
+
export const adminToolSchema = z.object({
|
|
16
|
+
action: z.enum(["task_progress", "admin_claim", "admin_overview", "admin_history", "admin_dispatch", "admin_tasks", "admin_task_update", "admin_plans", "admin_plan_create", "admin_plan_update", "admin_plan_delete"]),
|
|
17
|
+
roomId: z.string().optional(), enrollmentKey: z.string().optional(), targetRoomId: z.string().optional(),
|
|
18
|
+
targetSessionID: z.string().optional(), text: z.string().max(2000).optional(), name: z.string().max(64).optional(),
|
|
19
|
+
intervalSeconds: z.number().int().min(60).max(2_592_000).optional(), planId: z.string().optional(), taskId: z.string().optional(),
|
|
20
|
+
status: z.enum(["pending", "working", "blocked", "completed", "cancelled"]).optional(), progress: z.string().max(2000).optional(), paused: z.boolean().optional(),
|
|
21
|
+
limit: z.number().int().min(1).max(50).optional(),
|
|
22
|
+
});
|
|
23
|
+
export const adminToolDescription = "Administer an operator-enrolled room: overview, history, task dispatch, task progress, and plans. This tool never joins a room.";
|
|
24
|
+
const safe = (value: string) => encodeURIComponent(value);
|
|
25
|
+
|
|
26
|
+
async function send(opts: CenterOpts, path: string, method: string, body?: unknown,
|
|
27
|
+
capability?: string, sessionID?: string, ownerID?: string): Promise<Record<string, unknown>> {
|
|
28
|
+
const base = new URL(opts.center);
|
|
29
|
+
const headers: Record<string, string> = { ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}) };
|
|
30
|
+
if (body !== undefined || method === "DELETE") headers["Content-Type"] = "application/json";
|
|
31
|
+
if (capability) headers["X-Chat-Admin-Capability"] = capability;
|
|
32
|
+
if (sessionID) headers["X-Chat-Agent-Session"] = sessionID;
|
|
33
|
+
if (ownerID !== undefined) headers["X-Chat-Agent-Owner"] = ownerID;
|
|
34
|
+
const target = new URL(`${opts.center.replace(/\/+$/, "")}${path}`);
|
|
35
|
+
if (target.origin !== base.origin) throw new Error("invalid admin request origin");
|
|
36
|
+
const response = await fetch(target, {
|
|
37
|
+
method, headers, body: body === undefined ? undefined : JSON.stringify(body),
|
|
38
|
+
redirect: "error", signal: AbortSignal.timeout(10_000),
|
|
39
|
+
});
|
|
40
|
+
if (new URL(response.url || base.href).origin !== base.origin) throw new Error("admin request origin changed");
|
|
41
|
+
const data = await response.json().catch(() => ({})) as Record<string, unknown>;
|
|
42
|
+
if (!response.ok) throw Object.assign(new Error(typeof data.error === "string" ? data.error : `center error ${response.status}`), { status: response.status });
|
|
43
|
+
return data;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function protectedAdminRequest(opts: CenterOpts, path: string, method: "GET" | "POST",
|
|
47
|
+
capability: string, sessionID: string, ownerID: string, body?: unknown): Promise<Record<string, unknown>> {
|
|
48
|
+
return send(opts, path, method, body, capability, sessionID, ownerID);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function adminTool(args: AdminArgs, context: AdminContext, opts: CenterOpts,
|
|
52
|
+
transport: QueueTransport): Promise<string> {
|
|
53
|
+
if (!opts.center) return "error: admin actions require central mode";
|
|
54
|
+
if (args.action === "task_progress") {
|
|
55
|
+
if (!args.taskId || !args.status || args.progress === undefined || args.progress.length > 2000) return "error: taskId, status, and progress (up to 2000 characters) are required";
|
|
56
|
+
if (transport.protocol === "v2" && !transport.receiverOwnerID) return "error: this runtime has no verified receiver owner identity";
|
|
57
|
+
const deliveryToken = await loadTaskToken({ center: opts.center, taskId: args.taskId, sessionID: context.sessionID, ownerID: transport.receiverOwnerID ?? "" });
|
|
58
|
+
if (!deliveryToken) return "error: no task progress token for this task and session";
|
|
59
|
+
try {
|
|
60
|
+
await send(opts, `/supervision/tasks/${safe(args.taskId)}/progress`, "POST",
|
|
61
|
+
{ taskToken: deliveryToken, status: args.status, progress: args.progress }, undefined, context.sessionID, transport.receiverOwnerID ?? "");
|
|
62
|
+
return "task progress updated";
|
|
63
|
+
} catch (error) {
|
|
64
|
+
const message = error instanceof Error ? error.message : "task progress update failed";
|
|
65
|
+
return `error: ${message.replaceAll(deliveryToken, "[redacted]")}`;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const roomId = args.roomId?.trim();
|
|
69
|
+
if (!roomId) return "error: roomId is required";
|
|
70
|
+
const ownerID = transport.receiverOwnerID;
|
|
71
|
+
if (args.action === "admin_claim") {
|
|
72
|
+
if (!args.enrollmentKey?.trim()) return "error: enrollmentKey is required";
|
|
73
|
+
if (transport.protocol === "v2" && !ownerID) return "error: this runtime has no verified receiver owner identity";
|
|
74
|
+
const identity: AdminIdentity = { center: opts.center, roomId, sessionID: context.sessionID, ownerID: ownerID ?? "" };
|
|
75
|
+
try {
|
|
76
|
+
const result = await send(opts, `/admin/rooms/${safe(roomId)}/claim`, "POST", {
|
|
77
|
+
sessionID: context.sessionID, receiverOwnerID: ownerID ?? "", enrollmentKey: args.enrollmentKey,
|
|
78
|
+
});
|
|
79
|
+
if (typeof result.capability !== "string" || !result.capability) throw new Error("invalid admin claim response");
|
|
80
|
+
await saveAdminCapability(identity, result.capability);
|
|
81
|
+
return "admin room enrolled for this agent session";
|
|
82
|
+
} catch (error) {
|
|
83
|
+
const status = (error as { status?: unknown })?.status;
|
|
84
|
+
const detail = typeof status === "number" ? ` (HTTP ${status})` : "";
|
|
85
|
+
return `error: admin claim failed${detail}. If enrollment expired or saving failed, ask the operator to reset enrollment.`;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if (transport.protocol === "v2" && !ownerID) return "error: this runtime has no verified receiver owner identity";
|
|
89
|
+
const identity: AdminIdentity = { center: opts.center, roomId, sessionID: context.sessionID, ownerID: ownerID ?? "" };
|
|
90
|
+
const capability = await loadAdminCapability(identity);
|
|
91
|
+
if (!capability) return "error: no admin binding for this session; ask the operator to enroll this agent";
|
|
92
|
+
const root = `/admin/rooms/${safe(roomId)}`;
|
|
93
|
+
const request = (route: string, method: string, body?: unknown) =>
|
|
94
|
+
send(opts, `${root}${route}`, method, body, capability, context.sessionID, ownerID ?? "");
|
|
95
|
+
try {
|
|
96
|
+
let result: Record<string, unknown>;
|
|
97
|
+
switch (args.action) {
|
|
98
|
+
case "admin_overview": result = await request("/overview", "GET"); break;
|
|
99
|
+
case "admin_history": {
|
|
100
|
+
if (!args.targetRoomId) return "error: targetRoomId is required";
|
|
101
|
+
const query = new URLSearchParams();
|
|
102
|
+
query.set("targetRoomId", args.targetRoomId);
|
|
103
|
+
query.set("limit", String(Math.min(50, Math.max(1, args.limit ?? 20))));
|
|
104
|
+
result = await request(`/history?${query}`, "GET"); break;
|
|
105
|
+
}
|
|
106
|
+
case "admin_dispatch":
|
|
107
|
+
if (!args.targetRoomId || !args.targetSessionID || !args.text?.trim()) return "error: targetRoomId, targetSessionID, and text are required";
|
|
108
|
+
result = await request("/tasks", "POST", { targetRoomId: args.targetRoomId, targetSessionID: args.targetSessionID, text: args.text.trim() }); break;
|
|
109
|
+
case "admin_tasks": result = await request("/tasks", "GET"); break;
|
|
110
|
+
case "admin_task_update":
|
|
111
|
+
if (!args.taskId || !args.status) return "error: taskId and status are required";
|
|
112
|
+
result = await request(`/tasks/${safe(args.taskId)}`, "PATCH", { status: args.status, ...(args.progress === undefined ? {} : { progress: args.progress }) }); break;
|
|
113
|
+
case "admin_plans": result = await request("/plans", "GET"); break;
|
|
114
|
+
case "admin_plan_create":
|
|
115
|
+
if (!args.name?.trim() || !args.text?.trim() || !args.intervalSeconds) return "error: name, intervalSeconds, and text are required";
|
|
116
|
+
result = await request("/plans", "POST", { name: args.name.trim(), intervalSeconds: args.intervalSeconds, text: args.text.trim() }); break;
|
|
117
|
+
case "admin_plan_update":
|
|
118
|
+
if (!args.planId || args.paused === undefined) return "error: planId and paused are required";
|
|
119
|
+
result = await request(`/plans/${safe(args.planId)}`, "PATCH", { paused: args.paused }); break;
|
|
120
|
+
case "admin_plan_delete":
|
|
121
|
+
if (!args.planId) return "error: planId is required";
|
|
122
|
+
result = await request(`/plans/${safe(args.planId)}`, "DELETE"); break;
|
|
123
|
+
default: return "error: unsupported admin action";
|
|
124
|
+
}
|
|
125
|
+
return JSON.stringify(result);
|
|
126
|
+
} catch (error) {
|
|
127
|
+
const message = error instanceof Error ? error.message : "admin request failed";
|
|
128
|
+
return `error: ${capability ? message.replaceAll(capability, "[redacted]") : message}`;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, rename, chmod, writeFile, rm } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { statePath } from "./store";
|
|
5
|
+
|
|
6
|
+
export type AdminIdentity = { center: string; roomId: string; sessionID: string; ownerID: string };
|
|
7
|
+
export type TaskIdentity = { center: string; taskId: string; sessionID: string; ownerID: string };
|
|
8
|
+
const keyOf = (identity: AdminIdentity) => createHash("sha256").update(JSON.stringify([
|
|
9
|
+
new URL(identity.center).origin, identity.roomId, identity.sessionID, identity.ownerID,
|
|
10
|
+
])).digest("hex");
|
|
11
|
+
|
|
12
|
+
function credentialPath(identity: AdminIdentity): string {
|
|
13
|
+
return path.join(path.dirname(statePath()), "admin-capabilities", `${keyOf(identity)}.json`);
|
|
14
|
+
}
|
|
15
|
+
function taskPath(identity: TaskIdentity): string {
|
|
16
|
+
const key = createHash("sha256").update(JSON.stringify([
|
|
17
|
+
new URL(identity.center).origin, identity.taskId, identity.sessionID, identity.ownerID,
|
|
18
|
+
])).digest("hex");
|
|
19
|
+
return path.join(path.dirname(statePath()), "supervision-tokens", `${key}.json`);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function persist(file: string, content: unknown): Promise<void> {
|
|
23
|
+
const directory = path.dirname(file);
|
|
24
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
25
|
+
await chmod(directory, 0o700);
|
|
26
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
27
|
+
try {
|
|
28
|
+
await writeFile(temporary, JSON.stringify(content), { mode: 0o600, flag: "wx" });
|
|
29
|
+
await chmod(temporary, 0o600);
|
|
30
|
+
await rename(temporary, file);
|
|
31
|
+
await chmod(file, 0o600);
|
|
32
|
+
} finally { await rm(temporary, { force: true }); }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function loadAdminCapability(identity: AdminIdentity): Promise<string | undefined> {
|
|
36
|
+
try {
|
|
37
|
+
const file = credentialPath(identity);
|
|
38
|
+
const content = JSON.parse(await readFile(file, "utf8")) as { capability?: unknown; origin?: unknown };
|
|
39
|
+
return content.origin === new URL(identity.center).origin && typeof content.capability === "string"
|
|
40
|
+
? content.capability : undefined;
|
|
41
|
+
} catch { return undefined; }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function saveAdminCapability(identity: AdminIdentity, capability: string): Promise<void> {
|
|
45
|
+
const file = credentialPath(identity);
|
|
46
|
+
await persist(file, { origin: new URL(identity.center).origin, capability });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function loadTaskToken(identity: TaskIdentity): Promise<string | undefined> {
|
|
50
|
+
try {
|
|
51
|
+
const data = JSON.parse(await readFile(taskPath(identity), "utf8")) as { origin?: unknown; taskToken?: unknown };
|
|
52
|
+
return data.origin === new URL(identity.center).origin && typeof data.taskToken === "string" ? data.taskToken : undefined;
|
|
53
|
+
} catch { return undefined; }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function saveTaskToken(identity: TaskIdentity, taskToken: string): Promise<void> {
|
|
57
|
+
await persist(taskPath(identity), { origin: new URL(identity.center).origin, taskToken });
|
|
58
|
+
}
|
package/src/agent-receipts.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { acquireDeliveryLease, deleteReceiptCandidate, markReceiptCandidateReady
|
|
|
5
5
|
|
|
6
6
|
// shortcut: expire unobserved proofs after seven days; increase if hosts may stay disconnected longer.
|
|
7
7
|
const UNOBSERVED_TTL = 7 * 24 * 60 * 60_000;
|
|
8
|
-
type Item = { id?: string; text: string; senderId?: string; createdAt?: number };
|
|
8
|
+
type Item = { id?: string; text: string; senderId?: string; createdAt?: number; answerQuestionExcerpt?: string };
|
|
9
9
|
type CappedItem = Item & { senderId: string; createdAt: number };
|
|
10
10
|
export type ReceiptCandidate = {
|
|
11
11
|
admissionID: string; sessionID: string; roomID: string; membershipID: string;
|
|
@@ -38,25 +38,20 @@ export function prepareReceiptCandidate(input: {
|
|
|
38
38
|
if (cappedItems.length !== input.items.length) return undefined;
|
|
39
39
|
const closing = input.prompt.lastIndexOf("\n</notification>");
|
|
40
40
|
if (closing < 0) return undefined;
|
|
41
|
-
const
|
|
41
|
+
const rendered = formatNotificationLines(cappedItems);
|
|
42
|
+
const block = `\n${rendered.lines.join("\n")}\n</notification>`;
|
|
43
|
+
if (!input.prompt.endsWith(block)) return undefined;
|
|
44
|
+
const displayedCounts = new Map<string, number>();
|
|
45
|
+
for (const line of rendered.lines.filter((value) => value.startsWith("- ["))) displayedCounts.set(line, (displayedCounts.get(line) ?? 0) + 1);
|
|
46
|
+
const candidateCounts = new Map<string, number>();
|
|
42
47
|
for (const item of cappedItems) {
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
renderedCounts.set(key, (renderedCounts.get(key) ?? 0) + 1);
|
|
48
|
+
const line = `- [${timeOf(item.createdAt)}] ${item.senderId}: ${item.text}`;
|
|
49
|
+
candidateCounts.set(line, (candidateCounts.get(line) ?? 0) + 1);
|
|
46
50
|
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
const prefix = `\n- [${timeOf(item.createdAt)}] ${item.senderId}: `;
|
|
52
|
-
const line = tail.lastIndexOf(prefix);
|
|
53
|
-
if (line < 0) break;
|
|
54
|
-
const displayedText = tail.slice(line + prefix.length);
|
|
55
|
-
if (displayedText.includes("\n")) break;
|
|
56
|
-
if (displayedText === item.text && renderedCounts.get(`${prefix}${item.text}`) === 1 && !formatNotificationLines([item]).capped) evidenceItems.push(item);
|
|
57
|
-
tail = tail.slice(0, line);
|
|
58
|
-
}
|
|
59
|
-
evidenceItems.reverse();
|
|
51
|
+
evidenceItems = rendered.visibleIndices.map((index) => cappedItems[index]!).filter((item) => {
|
|
52
|
+
const line = `- [${timeOf(item.createdAt)}] ${item.senderId}: ${item.text}`;
|
|
53
|
+
return candidateCounts.get(line) === 1 && displayedCounts.get(line) === 1 && !formatNotificationLines([item]).capped;
|
|
54
|
+
});
|
|
60
55
|
}
|
|
61
56
|
if (!evidenceItems.length) return undefined;
|
|
62
57
|
const candidate: ReceiptCandidate = {
|
package/src/center-client.ts
CHANGED
|
@@ -247,7 +247,7 @@ export async function centerAction(
|
|
|
247
247
|
if (!result.member) {
|
|
248
248
|
return "error: not joined";
|
|
249
249
|
}
|
|
250
|
-
const items = Array.isArray(result.items) ? result.items : [];
|
|
250
|
+
const items = (Array.isArray(result.items) ? result.items : []).filter((item) => item.senderSessionID !== sessionID);
|
|
251
251
|
if (items.length === 0) {
|
|
252
252
|
return "no new messages";
|
|
253
253
|
}
|
package/src/center-inbox.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { explicitlyAddresses } from "./mentions";
|
|
|
13
13
|
import { claimBackgroundAttempt } from "./receiver-state";
|
|
14
14
|
import { prepareReceiptCandidate, receiptDestination } from "./agent-receipts";
|
|
15
15
|
import { serializeSessionPush } from "./session-delivery";
|
|
16
|
+
import { checkSupervisionInbox } from "./supervision-inbox";
|
|
16
17
|
export { serializeSessionPush } from "./session-delivery";
|
|
17
18
|
import {
|
|
18
19
|
sendAsyncNotification,
|
|
@@ -68,6 +69,7 @@ export async function checkCenterInbox(
|
|
|
68
69
|
items = [...merged.values()].sort((a, b) => a.createdAt - b.createdAt);
|
|
69
70
|
}
|
|
70
71
|
await pushItemsToSession(opts, sessionID, items, transport, queued, qualified);
|
|
72
|
+
await checkSupervisionInbox(opts, sessionID, transport);
|
|
71
73
|
});
|
|
72
74
|
} catch {
|
|
73
75
|
// The next inbox poll retries failed delivery.
|
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
formatNotificationLines,
|
|
6
6
|
loadRegistry,
|
|
7
7
|
loadRooms,
|
|
8
|
+
readQuestionExcerpt,
|
|
8
9
|
statePath,
|
|
9
10
|
timeOf,
|
|
10
11
|
} from "./store";
|
|
@@ -74,6 +75,9 @@ export function createNotifier(deps: {
|
|
|
74
75
|
batch: NotifyBatch,
|
|
75
76
|
transport: QueueTransport,
|
|
76
77
|
): Promise<NotifyAttempt | undefined> {
|
|
78
|
+
batch = { ...batch, messages: await Promise.all(batch.messages.map(async (message) => message.answerToMessageID
|
|
79
|
+
? { ...message, answerQuestionExcerpt: await readQuestionExcerpt(batch.roomId, message.answerToMessageID) }
|
|
80
|
+
: message)) };
|
|
77
81
|
const [registry, rooms] = await Promise.all([loadRegistry(), loadRooms()]);
|
|
78
82
|
const entry = registry[batch.roomId]?.[sessionID];
|
|
79
83
|
const roomKind = batch.roomKind ?? rooms.find((room) => room.id === batch.roomId)?.kind ?? "group";
|
package/src/queue.ts
CHANGED
|
@@ -9,6 +9,7 @@ export type QueueItem = {
|
|
|
9
9
|
text: string;
|
|
10
10
|
createdAt: number;
|
|
11
11
|
roomKind?: "group" | "direct";
|
|
12
|
+
answerQuestionExcerpt?: string;
|
|
12
13
|
};
|
|
13
14
|
|
|
14
15
|
export type QueueBody = {
|
|
@@ -52,6 +53,7 @@ export function queueAdmissionId(
|
|
|
52
53
|
item.text,
|
|
53
54
|
item.createdAt,
|
|
54
55
|
item.roomKind ?? "",
|
|
56
|
+
item.answerQuestionExcerpt ?? "",
|
|
55
57
|
]),
|
|
56
58
|
});
|
|
57
59
|
return `msg_${createHash("sha256").update(fingerprint).digest("hex")}`;
|
|
@@ -80,14 +82,17 @@ export function getOrCreatePendingAdmission(
|
|
|
80
82
|
): PendingAdmission {
|
|
81
83
|
const now = Date.now();
|
|
82
84
|
const existing = readPendingAdmission<PendingAdmission>(sessionID, roomId, now);
|
|
85
|
+
const id = queueAdmissionId(sessionID, roomId, items, prompt);
|
|
86
|
+
const retriesOriginal = existing?.state === "pending" && existing.items.length < items.length &&
|
|
87
|
+
queueAdmissionId(sessionID, roomId, existing.items) === queueAdmissionId(sessionID, roomId, items.slice(0, existing.items.length));
|
|
83
88
|
if (
|
|
84
89
|
existing &&
|
|
85
|
-
(existing.state
|
|
90
|
+
(existing.state === "admitted" ? maxTs <= existing.maxTs : existing.id === id || retriesOriginal)
|
|
86
91
|
) {
|
|
87
92
|
return existing;
|
|
88
93
|
}
|
|
89
94
|
const admission: PendingAdmission = {
|
|
90
|
-
id
|
|
95
|
+
id,
|
|
91
96
|
createdAt: now,
|
|
92
97
|
prompt,
|
|
93
98
|
itemCount: items.length,
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { request, type CenterOpts } from "./center-client";
|
|
2
|
+
|
|
3
|
+
type Schedule =
|
|
4
|
+
| { type: "once"; at: string; timezone?: string }
|
|
5
|
+
| { type: "cron"; expression: string; timezone?: string };
|
|
6
|
+
type ReminderArgs = {
|
|
7
|
+
action: string;
|
|
8
|
+
roomId?: string;
|
|
9
|
+
reminderId?: string;
|
|
10
|
+
schedule?: Schedule;
|
|
11
|
+
text?: string;
|
|
12
|
+
paused?: boolean;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export async function runReminderTool(
|
|
16
|
+
opts: CenterOpts,
|
|
17
|
+
args: ReminderArgs,
|
|
18
|
+
sessionID: string,
|
|
19
|
+
): Promise<string> {
|
|
20
|
+
if (!opts.center) return "error: reminders require central server mode";
|
|
21
|
+
if (!args.roomId) return "error: roomId is required";
|
|
22
|
+
const root = `/rooms/${encodeURIComponent(args.roomId)}/reminders`;
|
|
23
|
+
try {
|
|
24
|
+
if (args.action === "reminder_list") {
|
|
25
|
+
const result = await request(opts, `${root}?sessionID=${encodeURIComponent(sessionID)}`, "GET");
|
|
26
|
+
return JSON.stringify(result, null, 2);
|
|
27
|
+
}
|
|
28
|
+
if (args.action === "reminder_create") {
|
|
29
|
+
if (!args.schedule) return "error: schedule is required";
|
|
30
|
+
if (!args.text?.trim()) return "error: text is required";
|
|
31
|
+
const result = await request(opts, root, "POST", { sessionID, schedule: args.schedule, text: args.text });
|
|
32
|
+
return JSON.stringify(result, null, 2);
|
|
33
|
+
}
|
|
34
|
+
if (!args.reminderId) return "error: reminderId is required";
|
|
35
|
+
const child = `${root}/${encodeURIComponent(args.reminderId)}`;
|
|
36
|
+
if (args.action === "reminder_update") {
|
|
37
|
+
const fields = { ...(args.schedule ? { schedule: args.schedule } : {}), ...(args.text !== undefined ? { text: args.text } : {}), ...(args.paused !== undefined ? { paused: args.paused } : {}) };
|
|
38
|
+
if (!Object.keys(fields).length) return "error: at least one of schedule, text, or paused is required";
|
|
39
|
+
const result = await request(opts, child, "PATCH", { sessionID, ...fields });
|
|
40
|
+
return JSON.stringify(result, null, 2);
|
|
41
|
+
}
|
|
42
|
+
if (args.action === "reminder_delete") {
|
|
43
|
+
const result = await request(opts, child, "DELETE", { sessionID });
|
|
44
|
+
return JSON.stringify(result, null, 2);
|
|
45
|
+
}
|
|
46
|
+
return "error: unsupported reminder action";
|
|
47
|
+
} catch (error) {
|
|
48
|
+
return `error: ${error instanceof Error ? error.message : String(error)}`;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -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;
|