@alexsun-top/opencode-chat-room 0.7.8 → 0.8.1
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 +43 -1
- package/LICENSE +21 -0
- package/README.md +77 -36
- package/README.zh-CN.md +82 -41
- package/cli.ts +27 -1
- package/dist/cli.js +6905 -2764
- package/package.json +33 -3
- package/packages/chat-room-channeld/README.md +315 -0
- package/packages/chat-room-channeld/dist/feishu-adapter.js +1262 -0
- package/packages/chat-room-channeld/dist/mock-adapter.js +295 -0
- package/packages/chat-room-channeld/src/adapter.ts +509 -0
- package/packages/chat-room-channeld/src/cli.ts +124 -0
- package/packages/chat-room-channeld/src/config.ts +269 -0
- package/packages/chat-room-channeld/src/delivery.ts +163 -0
- package/packages/chat-room-channeld/src/feishu-adapter.ts +303 -0
- package/packages/chat-room-channeld/src/feishu-card.ts +27 -0
- package/packages/chat-room-channeld/src/feishu-inbound.ts +158 -0
- package/packages/chat-room-channeld/src/feishu-live.ts +355 -0
- package/packages/chat-room-channeld/src/feishu-send.ts +342 -0
- package/packages/chat-room-channeld/src/feishu-ws-frames.ts +173 -0
- package/packages/chat-room-channeld/src/framing.ts +128 -0
- package/packages/chat-room-channeld/src/host-helpers.ts +52 -0
- package/packages/chat-room-channeld/src/host.ts +627 -0
- package/packages/chat-room-channeld/src/inbound.ts +26 -0
- package/packages/chat-room-channeld/src/ingest-gate.ts +108 -0
- package/packages/chat-room-channeld/src/log.ts +26 -0
- package/packages/chat-room-channeld/src/mock-adapter.ts +206 -0
- package/packages/chat-room-channeld/src/protocol.ts +75 -0
- package/packages/chat-room-channeld/src/published.ts +37 -0
- package/packages/chat-room-channeld/src/rules.ts +127 -0
- package/packages/chat-room-channeld/src/state.ts +502 -0
- package/packages/chat-room-channeld/src/stats.ts +209 -0
- package/plugin.ts +22 -5
- package/server/addressing-routes.ts +130 -0
- package/server/admin-state.ts +13 -13
- package/server/app.ts +95 -0
- package/server/assets/NOTICE.txt +3 -2
- package/server/assets/SHIKI-LICENSE +22 -0
- package/server/assets/base.css +24 -10
- package/server/assets/chat/announcements.js +70 -7
- package/server/assets/chat/doc-preview.js +187 -39
- package/server/assets/chat/events.js +3 -0
- package/server/assets/chat/files.js +46 -4
- package/server/assets/chat/forward.js +69 -0
- package/server/assets/chat/index.js +4 -0
- package/server/assets/chat/integration-editor.js +163 -0
- package/server/assets/chat/integration-values.js +124 -0
- package/server/assets/chat/integrations.js +498 -0
- package/server/assets/chat/locales/de.js +45 -4
- package/server/assets/chat/locales/es.js +45 -4
- package/server/assets/chat/locales/fr.js +45 -4
- package/server/assets/chat/locales/it.js +45 -4
- package/server/assets/chat/locales/ja.js +45 -4
- package/server/assets/chat/locales/ko.js +45 -4
- package/server/assets/chat/markdown-footnotes.js +115 -0
- package/server/assets/chat/markdown.js +46 -43
- package/server/assets/chat/messages.js +5 -5
- package/server/assets/chat/office-preview.js +69 -0
- package/server/assets/chat/palette.js +1 -1
- package/server/assets/chat/panels.js +36 -0
- package/server/assets/chat/recall.js +58 -7
- package/server/assets/chat/receipts.js +15 -3
- package/server/assets/chat/reminders.js +69 -8
- package/server/assets/chat/replies.js +7 -1
- package/server/assets/chat/resource-format.js +11 -0
- package/server/assets/chat/settings.js +30 -2
- package/server/assets/chat/shiki.js +87 -0
- package/server/assets/chat/side-pane.js +9 -3
- package/server/assets/chat/state.js +107 -11
- package/server/assets/chat/system-events.js +32 -0
- package/server/assets/chat/system-messages.js +23 -12
- package/server/assets/chat/task-row.js +0 -6
- package/server/assets/chat/tasks.js +121 -33
- package/server/assets/code-highlight.css +74 -62
- package/server/assets/conversation.css +126 -25
- package/server/assets/doc-preview.css +36 -3
- package/server/assets/files.css +5 -0
- package/server/assets/fluent-icons.svg +2 -0
- package/server/assets/monaco/LICENSE +21 -0
- package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
- package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
- package/server/assets/monaco/editor.worker.js +45 -0
- package/server/assets/monaco/integration-rules.css +1 -0
- package/server/assets/monaco/integration-rules.js +1297 -0
- package/server/assets/monaco/json.worker.js +77 -0
- package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
- package/server/assets/office/docx.bundle.js +33 -0
- package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
- package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
- package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
- package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
- package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
- package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
- package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
- package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
- package/server/assets/{HIGHLIGHT-LICENSE → office/licenses/zrender-LICENSE.txt} +2 -2
- package/server/assets/office/pptx.bundle.js +104 -0
- package/server/assets/office/xlsx.bundle.js +141 -0
- package/server/assets/recall.css +5 -4
- package/server/assets/responsive.css +52 -8
- package/server/assets/settings.css +73 -1
- package/server/assets/shiki.bundle.js +152 -0
- package/server/assets/tasks.css +57 -7
- package/server/channel-integration.ts +519 -0
- package/server/channel-settings.ts +77 -0
- package/server/channels.ts +557 -0
- package/server/chat-server.ts +33 -558
- package/server/chat.html +195 -22
- package/server/http-server.ts +3 -182
- package/server/resource-routes.ts +16 -16
- package/server/routes/inbox.ts +100 -0
- package/server/routes/pages.ts +83 -0
- package/server/routes/questions.ts +39 -0
- package/server/routes/room-actions.ts +162 -0
- package/server/routes/rooms.ts +160 -0
- package/server/startup.ts +84 -0
- package/server/sw.js +5 -2
- package/server/task-routes.ts +1 -1
- package/skills/chatroom/SKILL.md +1 -1
- package/src/center/center-client.ts +71 -1
- package/src/config/file-config.ts +29 -42
- package/src/platform/http-server.ts +182 -0
- package/src/protocol/addressing.ts +21 -0
- package/src/protocol/config.ts +58 -0
- package/src/protocol/room.ts +51 -0
- package/src/rooms/resources.ts +26 -16
- package/src/rooms/room-service.ts +2 -48
- package/src/rooms/storage.ts +329 -0
- package/src/rooms/tasks.ts +21 -5
- package/src/runtime/v2-plugin.ts +8 -2
- package/src/runtime/watch.ts +4 -3
- package/src/state/pg-database.ts +183 -0
- package/src/state/pg-migrate.ts +175 -0
- package/src/state/pg-sql.mjs +175 -0
- package/src/state/pg-worker.mjs +148 -0
- package/src/state/sqlite-announcements.ts +25 -0
- package/src/state/sqlite-database.ts +121 -0
- package/src/state/sqlite-legacy.ts +90 -0
- package/src/state/sqlite-members.ts +155 -0
- package/src/state/sqlite-messages.ts +288 -0
- package/src/state/sqlite-resources.ts +39 -0
- package/src/state/sqlite-rooms.ts +87 -0
- package/src/state/sqlite-schema.ts +80 -0
- package/src/state/sqlite-state-store.ts +33 -0
- package/src/state/sqlite-state.ts +15 -866
- package/src/state/sqlite-tasks.ts +65 -0
- package/src/state/sqlite-transaction.ts +13 -0
- package/src/state/sqlite.ts +21 -1
- package/src/state/store.ts +13 -3
- package/src/tui/app.mjs +32 -19
- package/src/tui/config.mjs +12 -4
- package/src/tui/http.mjs +16 -2
- package/src/tui/i18n.mjs +38 -0
- package/src/tui/info-app.mjs +50 -51
- package/src/tui/info-content.mjs +79 -44
- package/src/tui/join-app.mjs +9 -9
- package/src/tui/locales/en.mjs +349 -0
- package/src/tui/locales/zh-CN.mjs +349 -0
- package/src/tui/main.mjs +85 -37
- package/src/tui/markdown.mjs +3 -2
- package/src/tui/mentions.mjs +3 -1
- package/src/tui/message-app.mjs +22 -21
- package/src/tui/message-view.mjs +2 -1
- package/src/tui/palette-app.mjs +9 -8
- package/src/tui/palette.mjs +30 -24
- package/src/tui/prefs.mjs +92 -0
- package/src/tui/reminder-app.mjs +18 -17
- package/src/tui/room-settings-app.mjs +30 -28
- package/src/tui/settings-app.mjs +153 -0
- package/src/tui/ui-content.mjs +65 -86
- package/src/tui/ui-help.mjs +73 -0
- package/src/tui/ui-overlay-view.mjs +23 -7
- package/src/tui/ui-suggest.mjs +6 -5
- package/src/tui/ui-theme.mjs +37 -33
- package/src/tui/ui-view.mjs +22 -7
- package/src/tui/ui.mjs +15 -3
- package/src/web/editor.worker.ts +1 -0
- package/src/web/integration-rules-editor.ts +439 -0
- package/src/web/integration-rules.ts +22 -0
- package/src/web/integration-schema.ts +228 -0
- package/src/web/json.worker.ts +1 -0
- package/src/web/office-viewer.ts +221 -0
- package/server/assets/highlight-10.7.3.min.js +0 -1358
|
@@ -1,53 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { JoinPolicy, Message, Participant, Room } from "../protocol/room.ts";
|
|
2
3
|
|
|
3
|
-
export type Participant
|
|
4
|
-
id: string;
|
|
5
|
-
name: string;
|
|
6
|
-
joinedAt: number;
|
|
7
|
-
};
|
|
8
|
-
|
|
9
|
-
export type Message = {
|
|
10
|
-
id: string;
|
|
11
|
-
roomId: string;
|
|
12
|
-
senderId: string;
|
|
13
|
-
senderSessionID?: string;
|
|
14
|
-
text: string;
|
|
15
|
-
createdAt: number;
|
|
16
|
-
isQuestion?: boolean;
|
|
17
|
-
answerToMessageID?: string;
|
|
18
|
-
answeredByMessageID?: string;
|
|
19
|
-
// Soft recall: the original text stays in storage for member reveal, while
|
|
20
|
-
// read paths expose the message as a tombstone.
|
|
21
|
-
recalledAt?: number;
|
|
22
|
-
recalledBy?: string;
|
|
23
|
-
};
|
|
24
|
-
|
|
25
|
-
export type JoinPolicy = "open" | "approval";
|
|
26
|
-
|
|
27
|
-
export type Room = {
|
|
28
|
-
id: string;
|
|
29
|
-
name: string;
|
|
30
|
-
description?: string;
|
|
31
|
-
// Absent means "open" so rooms created before approvals existed stay open.
|
|
32
|
-
joinPolicy?: JoinPolicy;
|
|
33
|
-
ownerId: string;
|
|
34
|
-
// Server-issued membership binding for the owner and the explicitly chosen successor.
|
|
35
|
-
// Display names remain the public identity; the membership IDs guard against name reuse.
|
|
36
|
-
ownerMembershipID?: string;
|
|
37
|
-
successorId?: string;
|
|
38
|
-
successorMembershipID?: string;
|
|
39
|
-
// Humans authorized by the owner or another admin; the owner is always an admin.
|
|
40
|
-
adminIds?: string[];
|
|
41
|
-
// Server-issued membership bindings matching adminIds, so a same-name session
|
|
42
|
-
// does not inherit delegation. Missing for legacy rooms; names are the fallback.
|
|
43
|
-
adminMembershipIDs?: string[];
|
|
44
|
-
participants: Map<string, Participant>;
|
|
45
|
-
messages: Message[];
|
|
46
|
-
createdAt: number;
|
|
47
|
-
kind?: "group" | "direct";
|
|
48
|
-
directSessionIDs?: string[];
|
|
49
|
-
directPair?: string;
|
|
50
|
-
};
|
|
4
|
+
export type { JoinPolicy, Message, Participant, Room };
|
|
51
5
|
|
|
52
6
|
export type RoomErrorCode =
|
|
53
7
|
| "ROOM_NOT_FOUND"
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
// Resource object storage. Local disk is the default; S3 is opt-in and never
|
|
2
|
+
// falls back silently to local files after a failed S3 operation.
|
|
3
|
+
import { createReadStream, promises as fs } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { Readable } from "node:stream";
|
|
6
|
+
import type { S3Client } from "@aws-sdk/client-s3";
|
|
7
|
+
import { databasePath } from "../state/store.ts";
|
|
8
|
+
|
|
9
|
+
export type ResourceStorage = {
|
|
10
|
+
ready(): Promise<void>;
|
|
11
|
+
put(key: string, filePath: string, contentType: string): Promise<void>;
|
|
12
|
+
open(key: string, start?: number, end?: number): Promise<{ stream: ReadableStream<Uint8Array>; size: number } | undefined>;
|
|
13
|
+
delete(key: string): Promise<void>;
|
|
14
|
+
deletePrefix(prefix: string): Promise<void>;
|
|
15
|
+
exists(key: string): Promise<boolean>;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export type S3StorageConfig = {
|
|
19
|
+
kind: "s3";
|
|
20
|
+
bucket: string;
|
|
21
|
+
accessKeyId: string;
|
|
22
|
+
secretAccessKey: string;
|
|
23
|
+
endpoint?: string;
|
|
24
|
+
region: string;
|
|
25
|
+
forcePathStyle: boolean;
|
|
26
|
+
prefix: string;
|
|
27
|
+
localCache: boolean;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export type StorageConfig = { kind: "local" } | S3StorageConfig;
|
|
31
|
+
|
|
32
|
+
export class StorageConflictError extends Error {
|
|
33
|
+
constructor(message = "storage key already exists") { super(message); this.name = "StorageConflictError"; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
type S3ClientLike = { send(command: any): Promise<any> };
|
|
37
|
+
type StorageDependencies = { client?: S3ClientLike; localRoot?: () => string };
|
|
38
|
+
|
|
39
|
+
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;
|
|
40
|
+
|
|
41
|
+
export function defaultLocalRoot(): string {
|
|
42
|
+
return path.join(path.dirname(databasePath()), "resources");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function resourceStorageKey(roomID: string, id: string): string {
|
|
46
|
+
if (!uuid.test(roomID) || !uuid.test(id)) throw new Error("invalid resource storage key");
|
|
47
|
+
return `${roomID}/${id}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function assertKeySegments(key: string): string[] {
|
|
51
|
+
const segments = key.split("/");
|
|
52
|
+
if (!segments.length || segments.some((segment) => !uuid.test(segment))) throw new Error("invalid resource storage key");
|
|
53
|
+
return segments;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function parseBoolean(value: string | undefined, name: string): boolean | undefined {
|
|
57
|
+
if (value === undefined || value === "") return undefined;
|
|
58
|
+
const normalized = value.trim().toLowerCase();
|
|
59
|
+
if (normalized === "1" || normalized === "true") return true;
|
|
60
|
+
if (normalized === "0" || normalized === "false") return false;
|
|
61
|
+
throw new Error(`${name} must be true or false`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function storageConfig(env: NodeJS.ProcessEnv = process.env): StorageConfig {
|
|
65
|
+
const kind = (env.CHAT_ROOM_STORAGE ?? "local").trim().toLowerCase();
|
|
66
|
+
if (kind === "local") return { kind: "local" };
|
|
67
|
+
if (kind !== "s3") throw new Error('CHAT_ROOM_STORAGE must be "local" or "s3"');
|
|
68
|
+
const required = ["CHAT_ROOM_S3_BUCKET", "CHAT_ROOM_S3_ACCESS_KEY_ID", "CHAT_ROOM_S3_SECRET_ACCESS_KEY"] as const;
|
|
69
|
+
for (const name of required) {
|
|
70
|
+
if (!env[name]?.trim()) throw new Error(`${name} is required when CHAT_ROOM_STORAGE=s3`);
|
|
71
|
+
}
|
|
72
|
+
const endpoint = env.CHAT_ROOM_S3_ENDPOINT?.trim() || undefined;
|
|
73
|
+
const prefix = (env.CHAT_ROOM_S3_PREFIX?.trim() || "chat-room").replace(/^\/+|\/+$/g, "") || "chat-room";
|
|
74
|
+
const cacheFlag = (env.CHAT_ROOM_S3_LOCAL_CACHE ?? "").trim().toLowerCase();
|
|
75
|
+
return {
|
|
76
|
+
kind: "s3",
|
|
77
|
+
bucket: env.CHAT_ROOM_S3_BUCKET!.trim(),
|
|
78
|
+
accessKeyId: env.CHAT_ROOM_S3_ACCESS_KEY_ID!.trim(),
|
|
79
|
+
secretAccessKey: env.CHAT_ROOM_S3_SECRET_ACCESS_KEY!,
|
|
80
|
+
endpoint,
|
|
81
|
+
region: env.CHAT_ROOM_S3_REGION?.trim() || "us-east-1",
|
|
82
|
+
forcePathStyle: parseBoolean(env.CHAT_ROOM_S3_FORCE_PATH_STYLE, "CHAT_ROOM_S3_FORCE_PATH_STYLE") ?? Boolean(endpoint),
|
|
83
|
+
prefix,
|
|
84
|
+
localCache: !["0", "false", "off"].includes(cacheFlag),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function asWebStream(stream: Readable): ReadableStream<Uint8Array> {
|
|
89
|
+
return Readable.toWeb(stream) as unknown as ReadableStream<Uint8Array>;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function isMissingFile(error: unknown): boolean {
|
|
93
|
+
return (error as NodeJS.ErrnoException)?.code === "ENOENT";
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function statusOf(error: unknown): number | undefined {
|
|
97
|
+
return (error as { $metadata?: { httpStatusCode?: number } })?.$metadata?.httpStatusCode;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function errorCode(error: unknown): string {
|
|
101
|
+
const value = error as { name?: unknown; Code?: unknown };
|
|
102
|
+
return typeof value?.Code === "string" ? value.Code : typeof value?.name === "string" ? value.name : "";
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function isNotFound(error: unknown): boolean {
|
|
106
|
+
return statusOf(error) === 404 || errorCode(error) === "NoSuchKey" || errorCode(error) === "NotFound";
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function isPreconditionFailed(error: unknown): boolean {
|
|
110
|
+
return statusOf(error) === 412 || errorCode(error) === "PreconditionFailed" ||
|
|
111
|
+
(statusOf(error) === 409 && errorCode(error) === "ConditionalRequestConflict");
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Some S3-compatible stores reject conditional PutObject. Only these errors
|
|
115
|
+
// retry without If-None-Match after a HeadObject precheck.
|
|
116
|
+
function isConditionalUnsupported(error: unknown): boolean {
|
|
117
|
+
return statusOf(error) === 501 || errorCode(error) === "NotImplemented" ||
|
|
118
|
+
(statusOf(error) === 400 && /if-none-match/i.test(String((error as Error)?.message ?? "")));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function createLocalStorage(localRoot: () => string): ResourceStorage {
|
|
122
|
+
const target = (key: string) => path.join(localRoot(), ...assertKeySegments(key));
|
|
123
|
+
return {
|
|
124
|
+
async ready() { await fs.mkdir(localRoot(), { recursive: true, mode: 0o700 }); },
|
|
125
|
+
async put(key, filePath) {
|
|
126
|
+
const destination = target(key);
|
|
127
|
+
await fs.mkdir(path.dirname(destination), { recursive: true, mode: 0o700 });
|
|
128
|
+
try { await fs.link(filePath, destination); }
|
|
129
|
+
catch (error) {
|
|
130
|
+
if ((error as NodeJS.ErrnoException).code === "EEXIST") throw new StorageConflictError();
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
async open(key, start, end) {
|
|
135
|
+
const file = target(key);
|
|
136
|
+
let info;
|
|
137
|
+
try { info = await fs.stat(file); }
|
|
138
|
+
catch (error) { if (isMissingFile(error)) return undefined; throw error; }
|
|
139
|
+
const stream = start === undefined ? createReadStream(file) : createReadStream(file, { start, end });
|
|
140
|
+
return { stream: asWebStream(stream), size: info.size };
|
|
141
|
+
},
|
|
142
|
+
async delete(key) { await fs.rm(target(key), { force: true }); },
|
|
143
|
+
async deletePrefix(prefix) { await fs.rm(target(prefix), { recursive: true, force: true }); },
|
|
144
|
+
async exists(key) {
|
|
145
|
+
try { await fs.stat(target(key)); return true; }
|
|
146
|
+
catch (error) { if (isMissingFile(error)) return false; throw error; }
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
let sdkModule: Promise<typeof import("@aws-sdk/client-s3")> | undefined;
|
|
152
|
+
const s3Sdk = () => (sdkModule ??= import("@aws-sdk/client-s3"));
|
|
153
|
+
|
|
154
|
+
function createS3Storage(config: S3StorageConfig, deps: StorageDependencies): ResourceStorage {
|
|
155
|
+
const cacheRoot = deps.localRoot ?? defaultLocalRoot;
|
|
156
|
+
const cachePath = (key: string) => path.join(cacheRoot(), ...assertKeySegments(key));
|
|
157
|
+
const objectKey = (key: string) => `${config.prefix}/${key}`;
|
|
158
|
+
let clientPromise: Promise<S3ClientLike> | undefined;
|
|
159
|
+
const client = () => (clientPromise ??= (async () => {
|
|
160
|
+
if (deps.client) return deps.client;
|
|
161
|
+
const { S3Client: Client } = await s3Sdk();
|
|
162
|
+
return new Client({
|
|
163
|
+
region: config.region,
|
|
164
|
+
...(config.endpoint ? { endpoint: config.endpoint } : {}),
|
|
165
|
+
forcePathStyle: config.forcePathStyle,
|
|
166
|
+
credentials: { accessKeyId: config.accessKeyId, secretAccessKey: config.secretAccessKey },
|
|
167
|
+
}) as unknown as S3Client;
|
|
168
|
+
})());
|
|
169
|
+
|
|
170
|
+
async function removeObject(key: string): Promise<void> {
|
|
171
|
+
const { DeleteObjectCommand } = await s3Sdk();
|
|
172
|
+
await (await client()).send(new DeleteObjectCommand({ Bucket: config.bucket, Key: objectKey(key) }));
|
|
173
|
+
await fs.rm(cachePath(key), { force: true });
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function headSize(key: string): Promise<number | undefined> {
|
|
177
|
+
try {
|
|
178
|
+
const { HeadObjectCommand } = await s3Sdk();
|
|
179
|
+
const output = await (await client()).send(new HeadObjectCommand({ Bucket: config.bucket, Key: objectKey(key) }));
|
|
180
|
+
return typeof output?.ContentLength === "number" ? output.ContentLength : undefined;
|
|
181
|
+
} catch (error) {
|
|
182
|
+
if (isNotFound(error)) return undefined;
|
|
183
|
+
throw error;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function objectExists(key: string): Promise<boolean> {
|
|
188
|
+
const { HeadObjectCommand } = await s3Sdk();
|
|
189
|
+
try {
|
|
190
|
+
await (await client()).send(new HeadObjectCommand({ Bucket: config.bucket, Key: objectKey(key) }));
|
|
191
|
+
return true;
|
|
192
|
+
} catch (error) {
|
|
193
|
+
if (isNotFound(error)) return false;
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async function putObject(key: string, filePath: string, contentType: string, conditional: boolean): Promise<void> {
|
|
199
|
+
const { PutObjectCommand } = await s3Sdk();
|
|
200
|
+
const info = await fs.stat(filePath);
|
|
201
|
+
await (await client()).send(new PutObjectCommand({
|
|
202
|
+
Bucket: config.bucket,
|
|
203
|
+
Key: objectKey(key),
|
|
204
|
+
Body: createReadStream(filePath),
|
|
205
|
+
ContentLength: info.size,
|
|
206
|
+
ContentType: contentType,
|
|
207
|
+
...(conditional ? { IfNoneMatch: "*" } : {}),
|
|
208
|
+
}));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return {
|
|
212
|
+
async ready() {
|
|
213
|
+
try {
|
|
214
|
+
const { HeadBucketCommand } = await s3Sdk();
|
|
215
|
+
await (await client()).send(new HeadBucketCommand({ Bucket: config.bucket }));
|
|
216
|
+
} catch (error) {
|
|
217
|
+
const detail = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
218
|
+
throw new Error(`S3 storage is not ready: HeadBucket failed for bucket "${config.bucket}": ${detail}`);
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
async put(key, filePath, contentType) {
|
|
222
|
+
try {
|
|
223
|
+
await putObject(key, filePath, contentType, true);
|
|
224
|
+
} catch (error) {
|
|
225
|
+
if (isPreconditionFailed(error)) throw new StorageConflictError();
|
|
226
|
+
if (!isConditionalUnsupported(error)) throw error;
|
|
227
|
+
// shortcut: stores without conditional PUT leave a small precheck/write race.
|
|
228
|
+
if (await objectExists(key)) throw new StorageConflictError();
|
|
229
|
+
await putObject(key, filePath, contentType, false);
|
|
230
|
+
}
|
|
231
|
+
if (!config.localCache) {
|
|
232
|
+
await fs.rm(cachePath(key), { force: true });
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
const cache = cachePath(key);
|
|
236
|
+
try {
|
|
237
|
+
await fs.mkdir(path.dirname(cache), { recursive: true, mode: 0o700 });
|
|
238
|
+
await fs.link(filePath, cache);
|
|
239
|
+
} catch (error) {
|
|
240
|
+
// Keep any pre-existing cache file that won the race; only remove the
|
|
241
|
+
// S3 object this attempt just wrote.
|
|
242
|
+
const { DeleteObjectCommand } = await s3Sdk();
|
|
243
|
+
await (await client()).send(new DeleteObjectCommand({ Bucket: config.bucket, Key: objectKey(key) })).catch(() => {});
|
|
244
|
+
if ((error as NodeJS.ErrnoException).code === "EEXIST") throw new StorageConflictError();
|
|
245
|
+
throw error;
|
|
246
|
+
}
|
|
247
|
+
},
|
|
248
|
+
async open(key, start, end) {
|
|
249
|
+
if (config.localCache) {
|
|
250
|
+
const cache = cachePath(key);
|
|
251
|
+
try {
|
|
252
|
+
const info = await fs.stat(cache);
|
|
253
|
+
const stream = start === undefined ? createReadStream(cache) : createReadStream(cache, { start, end });
|
|
254
|
+
return { stream: asWebStream(stream), size: info.size };
|
|
255
|
+
} catch (error) { if (!isMissingFile(error)) throw error; }
|
|
256
|
+
}
|
|
257
|
+
let range: string | undefined;
|
|
258
|
+
if (start !== undefined) {
|
|
259
|
+
if (!Number.isSafeInteger(start) || start < 0 || (end !== undefined && (!Number.isSafeInteger(end) || end < start))) throw new Error("invalid storage range");
|
|
260
|
+
let last = end;
|
|
261
|
+
if (last === undefined) {
|
|
262
|
+
const total = await headSize(key);
|
|
263
|
+
if (total === undefined) return undefined;
|
|
264
|
+
last = total - 1;
|
|
265
|
+
}
|
|
266
|
+
if (last < start) throw new Error("invalid storage range");
|
|
267
|
+
range = `bytes=${start}-${last}`;
|
|
268
|
+
} else if (end !== undefined) {
|
|
269
|
+
throw new Error("invalid storage range");
|
|
270
|
+
}
|
|
271
|
+
let body: Readable;
|
|
272
|
+
let size: number | undefined;
|
|
273
|
+
try {
|
|
274
|
+
const { GetObjectCommand } = await s3Sdk();
|
|
275
|
+
const output = await (await client()).send(new GetObjectCommand({ Bucket: config.bucket, Key: objectKey(key), ...(range ? { Range: range } : {}) }));
|
|
276
|
+
if (!output?.Body) return undefined;
|
|
277
|
+
body = output.Body as Readable;
|
|
278
|
+
size = range ? Number(/^bytes\s+\d+-\d+\/(\d+)$/.exec(String(output.ContentRange ?? ""))?.[1]) : Number(output.ContentLength);
|
|
279
|
+
} catch (error) {
|
|
280
|
+
if (isNotFound(error)) return undefined;
|
|
281
|
+
throw error;
|
|
282
|
+
}
|
|
283
|
+
// Do not guess the total from the range length: ask HeadObject when the
|
|
284
|
+
// range response omits ContentRange.
|
|
285
|
+
if (!Number.isSafeInteger(size) || size === undefined || size < 0) size = await headSize(key);
|
|
286
|
+
if (!Number.isSafeInteger(size) || size === undefined || size < 0) throw new Error("S3 storage did not report the object size");
|
|
287
|
+
return { stream: asWebStream(body), size };
|
|
288
|
+
},
|
|
289
|
+
async delete(key) { await removeObject(key); },
|
|
290
|
+
async deletePrefix(prefix) {
|
|
291
|
+
const { ListObjectsV2Command, DeleteObjectsCommand } = await s3Sdk();
|
|
292
|
+
const listingPrefix = `${config.prefix}/${prefix}/`;
|
|
293
|
+
let token: string | undefined;
|
|
294
|
+
do {
|
|
295
|
+
const page = await (await client()).send(new ListObjectsV2Command({ Bucket: config.bucket, Prefix: listingPrefix, ContinuationToken: token }));
|
|
296
|
+
const objects = (page?.Contents ?? []).map((entry: { Key?: string }) => entry.Key).filter((key: unknown): key is string => typeof key === "string");
|
|
297
|
+
for (let index = 0; index < objects.length; index += 1000) {
|
|
298
|
+
const batch = objects.slice(index, index + 1000);
|
|
299
|
+
if (batch.length) await (await client()).send(new DeleteObjectsCommand({ Bucket: config.bucket, Delete: { Objects: batch.map((Key: string) => ({ Key })), Quiet: true } }));
|
|
300
|
+
}
|
|
301
|
+
token = page?.IsTruncated ? page.NextContinuationToken : undefined;
|
|
302
|
+
} while (token);
|
|
303
|
+
await fs.rm(cachePath(prefix), { recursive: true, force: true });
|
|
304
|
+
},
|
|
305
|
+
async exists(key) {
|
|
306
|
+
if (config.localCache) {
|
|
307
|
+
try { await fs.stat(cachePath(key)); return true; }
|
|
308
|
+
catch (error) { if (!isMissingFile(error)) throw error; }
|
|
309
|
+
}
|
|
310
|
+
try {
|
|
311
|
+
const { HeadObjectCommand } = await s3Sdk();
|
|
312
|
+
await (await client()).send(new HeadObjectCommand({ Bucket: config.bucket, Key: objectKey(key) }));
|
|
313
|
+
return true;
|
|
314
|
+
} catch (error) {
|
|
315
|
+
if (isNotFound(error)) return false;
|
|
316
|
+
throw error;
|
|
317
|
+
}
|
|
318
|
+
},
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export function createStorage(config: StorageConfig, deps: StorageDependencies = {}): ResourceStorage {
|
|
323
|
+
return config.kind === "local" ? createLocalStorage(deps.localRoot ?? defaultLocalRoot) : createS3Storage(config, deps);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
let singleton: ResourceStorage | undefined;
|
|
327
|
+
export function resourceStorage(): ResourceStorage {
|
|
328
|
+
return (singleton ??= createStorage(storageConfig()));
|
|
329
|
+
}
|
package/src/rooms/tasks.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
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 {
|
|
3
|
+
import { ROOM_TASK_STATUSES, countRoomTasks, deleteCompletedRoomTasks, deleteRoomTask, insertRoomTask, listRoomTasks, patchRoomTask, readRoomTask, type RoomTask, type RoomTaskPatch, type RoomTaskStatus, type RoomTaskStep } from "../state/sqlite-state.ts";
|
|
4
|
+
import type { StateDatabase } from "../state/sqlite.ts";
|
|
5
5
|
import { databasePath } from "../state/store.ts";
|
|
6
6
|
import { withStateTransaction } from "../state/sqlite-state.ts";
|
|
7
7
|
|
|
8
8
|
export type { RoomTask, RoomTaskStatus };
|
|
9
9
|
export type TaskFailure = { status: 400 | 403 | 404 | 409; error: string };
|
|
10
|
-
export type TaskListResult = { tasks: RoomTask[] } | TaskFailure;
|
|
10
|
+
export type TaskListResult = { tasks: RoomTask[]; limit: number } | TaskFailure;
|
|
11
11
|
export type TaskWriteResult = { task: RoomTask } | TaskFailure;
|
|
12
12
|
export type TaskDeleteResult = { ok: true } | TaskFailure;
|
|
13
13
|
export type TaskClearResult = { ok: true; count: number } | TaskFailure;
|
|
@@ -22,8 +22,20 @@ const MAX_CONCLUSION = 5000;
|
|
|
22
22
|
const MAX_PARTICIPANTS = 50;
|
|
23
23
|
const MAX_STEPS = 30;
|
|
24
24
|
const MAX_STEP_TEXT = 300;
|
|
25
|
+
const DEFAULT_MAX_ROOM_TASKS = 10;
|
|
25
26
|
const invalid = (error: string): TaskFailure => ({ status: 400, error });
|
|
26
27
|
|
|
28
|
+
/** The per-room task limit, read from CHAT_ROOM_MAX_ROOM_TASKS on every use. */
|
|
29
|
+
export function maxRoomTasks(env: NodeJS.ProcessEnv = process.env): number {
|
|
30
|
+
const raw = env.CHAT_ROOM_MAX_ROOM_TASKS?.trim();
|
|
31
|
+
if (!raw) return DEFAULT_MAX_ROOM_TASKS;
|
|
32
|
+
const limit = Number(raw);
|
|
33
|
+
if (!/^\d+$/.test(raw) || !Number.isSafeInteger(limit) || limit < 1) {
|
|
34
|
+
throw new Error("CHAT_ROOM_MAX_ROOM_TASKS must be a positive integer");
|
|
35
|
+
}
|
|
36
|
+
return limit;
|
|
37
|
+
}
|
|
38
|
+
|
|
27
39
|
type Context = { room: RoleRoom; entry: RoleEntry; name: string; participants: Set<string> };
|
|
28
40
|
type RoomRow = {
|
|
29
41
|
kind: string; owner_id: string; owner_membership_id: string | null;
|
|
@@ -36,7 +48,7 @@ type MemberRow = {
|
|
|
36
48
|
|
|
37
49
|
// The session must be a current participant and a registry entry; roles come
|
|
38
50
|
// from the stored room, never from a client-supplied name.
|
|
39
|
-
function context(db:
|
|
51
|
+
function context(db: StateDatabase, roomID: string, sessionID: string): Context | TaskFailure {
|
|
40
52
|
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
53
|
if (!room) return { status: 404, error: "room not found" };
|
|
42
54
|
if (room.kind === "direct") return { status: 409, error: "tasks are not available in direct rooms" };
|
|
@@ -121,7 +133,7 @@ export function listTasks(roomID: string, sessionID: string): Promise<TaskListRe
|
|
|
121
133
|
return withStateTransaction(databasePath(), (db) => {
|
|
122
134
|
const ctx = context(db, roomID, sessionID);
|
|
123
135
|
if (isFailure(ctx)) return ctx;
|
|
124
|
-
return { tasks: listRoomTasks(db, roomID) };
|
|
136
|
+
return { tasks: listRoomTasks(db, roomID), limit: maxRoomTasks() };
|
|
125
137
|
});
|
|
126
138
|
}
|
|
127
139
|
|
|
@@ -143,6 +155,10 @@ export function createTask(roomID: string, sessionID: string, input: TaskFields)
|
|
|
143
155
|
if (conclusion === undefined) return invalid(`conclusion must be a string of at most ${MAX_CONCLUSION} characters`);
|
|
144
156
|
const steps = input.steps === undefined ? [] : readSteps(input.steps);
|
|
145
157
|
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`);
|
|
158
|
+
const limit = maxRoomTasks();
|
|
159
|
+
if (countRoomTasks(db, roomID) >= limit) {
|
|
160
|
+
return { status: 409, error: `room task limit reached (${limit}); delete a completed task before adding another` };
|
|
161
|
+
}
|
|
146
162
|
const now = Date.now();
|
|
147
163
|
const task: RoomTask = {
|
|
148
164
|
id: randomUUID(), roomId: roomID, title, description, assignee, status: "todo",
|
package/src/runtime/v2-plugin.ts
CHANGED
|
@@ -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;
|
|
84
|
+
description: "Chat room operations: create, join, join_status, leave and list rooms; send and poll messages; get_message fetches one message by ID (recalled messages come back as tombstones); catch_up pages messages after a seq cursor and is read-only (no read receipt or wake); send accepts parentMessageId to reply. 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,13 +169,19 @@ 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", "task_list", "task_create", "task_update", "task_delete"]),
|
|
172
|
+
action: z.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "get_message", "catch_up", "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
|
+
messageId: z.string().optional().describe("For get_message: the full message ID returned by send, poll, or catch_up."),
|
|
175
176
|
resourceId: z.string().optional(),
|
|
176
177
|
filePath: z.string().optional().describe("Local regular file to upload; central mode only; requires host read permission."),
|
|
177
178
|
text: z.string().max(5000).optional(),
|
|
178
179
|
isQuestion: z.boolean().optional(),
|
|
180
|
+
parentMessageId: z.string().optional().describe("For send: the ID of the message this one answers or replies to."),
|
|
181
|
+
replyToMessageID: z.string().optional().describe("Legacy alias of parentMessageId for send."),
|
|
182
|
+
clientMessageID: z.string().max(100).optional().describe("For send: idempotency key; retrying with the same ID and parent creates one message."),
|
|
183
|
+
afterSeq: z.number().int().min(0).optional().describe("For catch_up: return messages with seq greater than this cursor; omit to start at 0."),
|
|
184
|
+
limit: z.number().int().min(1).max(200).optional().describe("For catch_up: page size from 1 to 200; the server default is 50."),
|
|
179
185
|
announcementName: z.string().optional().describe("Name of a room announcement; distinct from participant or room name."),
|
|
180
186
|
content: z.string().optional().describe("Announcement content, at most 5000 Unicode characters."),
|
|
181
187
|
taskId: z.string().optional().describe("Task UUID from task_list; required for task_update and task_delete."),
|
package/src/runtime/watch.ts
CHANGED
|
@@ -18,7 +18,7 @@ import { pollOwnedSessions } from "./v2-receiver.ts";
|
|
|
18
18
|
import { pollKnownSessions } from "../../plugin.ts";
|
|
19
19
|
import { locallyOwnedSessions, reportAgentPresence } from "../agent/agent-presence.ts";
|
|
20
20
|
import { flushReceiptCandidates, receiptDestination } from "../agent/agent-receipts.ts";
|
|
21
|
-
import { startServer } from "
|
|
21
|
+
import { startServer } from "../platform/http-server.ts";
|
|
22
22
|
|
|
23
23
|
type WatchRecord = { phase: "starting" | "running"; token: string; nonce: string; instanceID: string; pid: number; port?: number; createdAt?: number };
|
|
24
24
|
function canonicalPath(value: string): string {
|
|
@@ -242,7 +242,8 @@ export async function watchStatus(): Promise<"running" | "stopped" | "unavailabl
|
|
|
242
242
|
return await control(record) ? "running" : "unavailable";
|
|
243
243
|
}
|
|
244
244
|
|
|
245
|
-
|
|
245
|
+
// readyTimeoutMs is a test seam so the timeout cleanup can be exercised quickly.
|
|
246
|
+
export async function startWatcher(beforePublish?: () => Promise<void>, readyTimeoutMs = 20_000): Promise<string> {
|
|
246
247
|
await privateDirectory();
|
|
247
248
|
const own: WatchRecord = { phase: "starting", token: randomBytes(32).toString("base64url"), nonce: randomBytes(16).toString("hex"), instanceID: randomBytes(16).toString("hex"), pid: process.pid, createdAt: Date.now() };
|
|
248
249
|
const reservation = await reserveWatcher(own, beforePublish);
|
|
@@ -269,7 +270,7 @@ export async function startWatcher(beforePublish?: () => Promise<void>): Promise
|
|
|
269
270
|
});
|
|
270
271
|
child.once("error", (error) => { childError = error; });
|
|
271
272
|
child.unref();
|
|
272
|
-
const deadline = Date.now() +
|
|
273
|
+
const deadline = Date.now() + readyTimeoutMs;
|
|
273
274
|
while (Date.now() < deadline) {
|
|
274
275
|
if (childError) { await removeRecord(own.token, own.nonce); releaseWatcherClaim(profile(), own.instanceID); throw childError; }
|
|
275
276
|
const record = await readRecord();
|